From c3ec5444c25e28b990ebb1c6a8a765624e9f9e04 Mon Sep 17 00:00:00 2001
From: kimhobeen <sksjsksh32@naver.com>
Date: Mon, 2 Oct 2023 15:16:22 +0900
Subject: [PATCH] =?UTF-8?q?:recycle:=20refactor=20:=20=EC=A0=95=EC=82=B0?=
 =?UTF-8?q?=EA=B2=B0=EA=B3=BC=20=EB=B0=98=ED=99=98=EA=B0=92=20=EB=B3=80?=
 =?UTF-8?q?=EA=B2=BD=20#494?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .../snippets/adjustment/adjustment.adoc       |  13 -
 .../controller/AdjustmentController.java      |  14 +-
 .../adjustment/service/AdjustmentService.java | 222 +++++++++++-------
 .../dto/response/MonthAdjustmentResponse.java |   9 +-
 .../batch/adjustment/AdjustmentJobConfig.java |   4 +
 .../controller/AdjustmentControllerTest.java  | 108 ++-------
 6 files changed, 177 insertions(+), 193 deletions(-)
 create mode 100644 Server/src/main/java/com/server/global/batch/adjustment/AdjustmentJobConfig.java

diff --git a/Server/src/docs/asciidoc/snippets/adjustment/adjustment.adoc b/Server/src/docs/asciidoc/snippets/adjustment/adjustment.adoc
index f8f66b50..efca296c 100644
--- a/Server/src/docs/asciidoc/snippets/adjustment/adjustment.adoc
+++ b/Server/src/docs/asciidoc/snippets/adjustment/adjustment.adoc
@@ -24,19 +24,6 @@ include::{snippets}/adjustment/adjustment/http-response.adoc[]
 ==== Response Fields
 include::{snippets}/adjustment/adjustment/response-fields.adoc[]
 
-[[Adjustment-total]]
-== 특정 월의 정산 총 금액 및 월별 정산 내역
-=== HTTP Request
-include::{snippets}/adjustment/calculateamount/http-request.adoc[]
-==== Request Headers
-include::{snippets}/adjustment/calculateamount/request-headers.adoc[]
-==== Request Query Parameters
-include::{snippets}/adjustment/calculateamount/request-parameters.adoc[]
-=== HTTP Response
-include::{snippets}/adjustment/calculateamount/http-response.adoc[]
-==== Response Fields
-include::{snippets}/adjustment/calculateamount/response-fields.adoc[]
-
 [[Adjustment-totalyear]]
 == 특정 연도의 정산 총 금액 및 월별 정산 내역
 === HTTP Request
diff --git a/Server/src/main/java/com/server/domain/adjustment/controller/AdjustmentController.java b/Server/src/main/java/com/server/domain/adjustment/controller/AdjustmentController.java
index 9a41b5a1..9ae763c2 100644
--- a/Server/src/main/java/com/server/domain/adjustment/controller/AdjustmentController.java
+++ b/Server/src/main/java/com/server/domain/adjustment/controller/AdjustmentController.java
@@ -2,11 +2,8 @@
 
 import com.server.domain.adjustment.controller.dto.request.AccountUpdateApiRequest;
 import com.server.domain.adjustment.service.AdjustmentService;
-import com.server.domain.adjustment.service.dto.response.AccountResponse;
-import com.server.domain.adjustment.service.dto.response.ToTalAdjustmentResponse;
-import com.server.domain.adjustment.service.dto.response.VideoAdjustmentResponse;
+import com.server.domain.adjustment.service.dto.response.*;
 import com.server.domain.order.controller.dto.request.AdjustmentSort;
-import com.server.domain.adjustment.service.dto.response.AdjustmentResponse;
 import com.server.global.annotation.LoginId;
 import com.server.global.exception.businessexception.orderexception.AdjustmentDateException;
 import com.server.global.reponse.ApiPageResponse;
@@ -65,16 +62,13 @@ public ResponseEntity<ApiSingleResponse<List<VideoAdjustmentResponse>>> calculat
     }
 
     @GetMapping("/total-adjustment")
-    public ResponseEntity<ApiSingleResponse<ToTalAdjustmentResponse>> calculateAmount(
-            @RequestParam(required = false) @Min(value = 1) @Max(value = 12) Integer month,
+    public ResponseEntity<ApiSingleResponse<List<MonthAdjustmentResponse>>> calculateAmount(
             @RequestParam(required = false) @Min(value = 2020) Integer year,
             @LoginId Long loginMemberId) {
 
-        checkValidDate(month, year);
-
-        ToTalAdjustmentResponse total = adjustmentService.totalAdjustment(loginMemberId, month, year);
+        List<MonthAdjustmentResponse> total = adjustmentService.totalAdjustment(loginMemberId, year);
 
-        return ResponseEntity.ok(ApiSingleResponse.ok(total, getAdjustmentMessage(month, year) + " 정산 내역"));
+        return ResponseEntity.ok(ApiSingleResponse.ok(total, getAdjustmentMessage(null, year) + " 정산 내역"));
     }
 
     @GetMapping("/account")
diff --git a/Server/src/main/java/com/server/domain/adjustment/service/AdjustmentService.java b/Server/src/main/java/com/server/domain/adjustment/service/AdjustmentService.java
index cc1de9c5..ea10ca62 100644
--- a/Server/src/main/java/com/server/domain/adjustment/service/AdjustmentService.java
+++ b/Server/src/main/java/com/server/domain/adjustment/service/AdjustmentService.java
@@ -46,12 +46,7 @@ public Page<AdjustmentResponse> adjustment(Long loginMemberId, int page, int siz
         return datas.map(AdjustmentResponse::of);
     }
 
-    public Integer calculateAmount(Long loginMemberId, Integer month, Integer year) {
-
-        return adjustmentRepository.calculateAmount(loginMemberId, month, year);
-    }
-
-    public ToTalAdjustmentResponse totalAdjustment(Long loginMemberId, Integer month, Integer year) {
+    public List<MonthAdjustmentResponse> totalAdjustment(Long loginMemberId, Integer year) {
 
         List<Adjustment> monthlyData = adjustmentRepository.findMonthlyData(loginMemberId, year);
 
@@ -59,87 +54,10 @@ public ToTalAdjustmentResponse totalAdjustment(Long loginMemberId, Integer month
                 .map(MonthAdjustmentResponse::of)
                 .collect(Collectors.toList());
 
-        //최근 2달 데이터 넣기
-        addCurrentMonthData(monthAdjustmentResponses);
-
-        //필요한 데이터 세팅
-        return getTotalAdjustment(monthAdjustmentResponses, monthlyData, month, year);
-    }
-
-    private void addCurrentMonthData(List<MonthAdjustmentResponse> monthAdjustmentResponses) {
-
-        LocalDate now = LocalDate.now();
-        int month = now.getMonthValue();
-        int year = now.getYear();
-
-        //이번달 데이터 세팅
-        int amount = adjustmentRepository.calculateAmount(1L, month, year);
-        monthAdjustmentResponses.add(MonthAdjustmentResponse.of(year, month, amount));
-
-        //지난달 데이터가 있는지 확인
-        if (month == 1) {
-            month = 12;
-            year -= 1;
-        } else {
-            month -= 1;
-        }
-
-        boolean hasLastMonth = false;
-
-        for(MonthAdjustmentResponse monthAdjustmentResponse : monthAdjustmentResponses) {
-            if (monthAdjustmentResponse.isSameMonthAndYear(year, month)) {
-                hasLastMonth = true;
-                break;
-            }
-        }
+        //없는 데이터 넣기
+        addAdditionalMonthData(monthAdjustmentResponses, year);
 
-        //지난달 데이터가 없다면 세팅
-        if (!hasLastMonth) {
-            amount = adjustmentRepository.calculateAmount(1L, month, year);
-            monthAdjustmentResponses.add(MonthAdjustmentResponse.of(year, month, amount));
-        }
-    }
-
-    private ToTalAdjustmentResponse getTotalAdjustment(List<MonthAdjustmentResponse> monthAdjustmentResponses,
-                                                       List<Adjustment> monthlyData,
-                                                       Integer month,
-                                                       Integer year) {
-
-        int amount = 0;
-        AdjustmentStatus status = AdjustmentStatus.NO_ADJUSTMENT;
-        String reason = null;
-
-        if(year == null) {
-
-            amount = adjustmentRepository.calculateAmount(1L, null, null);
-            status = AdjustmentStatus.TOTAL;
-
-            return ToTalAdjustmentResponse.of(amount, status, reason, monthAdjustmentResponses);
-        }
-
-        if(month == null) {
-
-            amount = adjustmentRepository.calculateAmount(1L, null, year);
-            status = AdjustmentStatus.TOTAL;
-
-            return ToTalAdjustmentResponse.of(amount, status, reason, monthAdjustmentResponses);
-        }
-
-        for(MonthAdjustmentResponse monthAdjustmentResponse : monthAdjustmentResponses) {
-            if (monthAdjustmentResponse.isSameMonthAndYear(month, year)) {
-                amount = monthAdjustmentResponse.getAmount();
-                status = AdjustmentStatus.NOT_ADJUSTED;
-            }
-        }
-
-        for(Adjustment adjustment : monthlyData) {
-            if (adjustment.isSameMonthAndYear(month, year)) {
-                status = adjustment.getAdjustmentStatus();
-                reason = adjustment.getReason() == null ? status.getDescription() : adjustment.getReason();
-            }
-        }
-
-        return ToTalAdjustmentResponse.of(amount, status, reason, monthAdjustmentResponses);
+        return monthAdjustmentResponses;
     }
 
     public AccountResponse getAccount(Long loginMemberId) {
@@ -176,6 +94,138 @@ private Account getAccountOrNull(Long loginMemberId) {
         return accountRepository.findByMemberId(loginMemberId).orElse(null);
     }
 
+    private void addAdditionalMonthData(List<MonthAdjustmentResponse> monthAdjustmentResponses, Integer year) {
+
+        LocalDate now = LocalDate.now();
+        int currentMonth = now.getMonthValue();
+        int currentYear = now.getYear();
+
+        if(year == null) {
+
+            //이번달 데이터 세팅
+            int amount = adjustmentRepository.calculateAmount(1L, currentMonth, currentYear);
+            monthAdjustmentResponses.add(MonthAdjustmentResponse.of(currentYear, currentMonth, amount, AdjustmentStatus.NOT_ADJUSTED));
+
+            //지난달 데이터가 있는지 확인
+            if (currentMonth == 1) {
+                currentMonth = 12;
+                currentYear -= 1;
+            } else {
+                currentMonth -= 1;
+            }
+
+            boolean hasLastMonth = false;
+
+            for(MonthAdjustmentResponse monthAdjustmentResponse : monthAdjustmentResponses) {
+                if (monthAdjustmentResponse.isSameMonthAndYear(currentYear, currentMonth)) {
+                    hasLastMonth = true;
+                    break;
+                }
+            }
+
+            //지난달 데이터가 없다면 세팅
+            if (!hasLastMonth) {
+                amount = adjustmentRepository.calculateAmount(1L, currentMonth, currentYear);
+                monthAdjustmentResponses.add(MonthAdjustmentResponse.of(currentYear, currentMonth, amount, AdjustmentStatus.NOT_ADJUSTED));
+            }
+
+            //2023년부터 빈 데이터를 확인해서 0원으로 넣어주기
+            for(int i = 2023; i <= currentYear; i++) {
+                for(int j = 1; j <= 12; j++) {
+                    boolean hasData = false;
+                    for(MonthAdjustmentResponse monthAdjustmentResponse : monthAdjustmentResponses) {
+                        if (monthAdjustmentResponse.isSameMonthAndYear(i, j)) {
+                            hasData = true;
+                            break;
+                        }
+                    }
+                    if(!hasData) {
+                        monthAdjustmentResponses.add(MonthAdjustmentResponse.of(i, j, 0, AdjustmentStatus.NO_ADJUSTMENT));
+                    }
+                }
+            }
+        }else if(year.equals(currentYear)) {
+
+            //이번달 데이터 세팅
+            int amount = adjustmentRepository.calculateAmount(1L, currentMonth, currentYear);
+            monthAdjustmentResponses.add(MonthAdjustmentResponse.of(currentYear, currentMonth, amount, AdjustmentStatus.NOT_ADJUSTED));
+
+            boolean hasLastMonth = false;
+
+            //지난달 데이터가 올해인지 확인
+            if (currentMonth == 1) {
+                hasLastMonth = true;
+            } else {
+                currentMonth -= 1;
+            }
+
+            if(!hasLastMonth) {
+
+                for(MonthAdjustmentResponse monthAdjustmentResponse : monthAdjustmentResponses) {
+                    if (monthAdjustmentResponse.isSameMonthAndYear(currentYear, currentMonth)) {
+                        hasLastMonth = true;
+                        break;
+                    }
+                }
+            }
+
+            //지난달 데이터가 없다면 세팅
+            if (!hasLastMonth) {
+                amount = adjustmentRepository.calculateAmount(1L, currentMonth, currentYear);
+                monthAdjustmentResponses.add(MonthAdjustmentResponse.of(currentYear, currentMonth, amount, AdjustmentStatus.NOT_ADJUSTED));
+            }
+
+            //빈 데이터를 확인해서 0원으로 넣어주기
+            for (int j = 1; j <= 12; j++) {
+                boolean hasData = false;
+                for (MonthAdjustmentResponse monthAdjustmentResponse : monthAdjustmentResponses) {
+                    if (monthAdjustmentResponse.isSameMonthAndYear(year, j)) {
+                        hasData = true;
+                        break;
+                    }
+                }
+                if (!hasData) {
+                    monthAdjustmentResponses.add(MonthAdjustmentResponse.of(year, j, 0, AdjustmentStatus.NO_ADJUSTMENT));
+                }
+            }
+        }else {
+            //현재 월이 1월이라면 지난달 12월 데이터 넣어주기
+            if(currentMonth == 1 && currentYear == year + 1) {
+
+                boolean hasLastMonth = false;
+
+                for(MonthAdjustmentResponse monthAdjustmentResponse : monthAdjustmentResponses) {
+                    if (monthAdjustmentResponse.isSameMonthAndYear(year, 12)) {
+                        hasLastMonth = true;
+                        break;
+                    }
+                }
+
+                //지난달 데이터가 없다면 세팅
+                if (!hasLastMonth) {
+                    int amount = adjustmentRepository.calculateAmount(1L, 12, year);
+                    monthAdjustmentResponses.add(MonthAdjustmentResponse.of(year, 12, amount, AdjustmentStatus.NOT_ADJUSTED));
+                }
+            }
+
+            //빈 데이터를 확인해서 0원으로 넣어주기
+            for (int j = 1; j <= 12; j++) {
+                boolean hasData = false;
+                for (MonthAdjustmentResponse monthAdjustmentResponse : monthAdjustmentResponses) {
+                    if (monthAdjustmentResponse.isSameMonthAndYear(year, j)) {
+                        hasData = true;
+                        break;
+                    }
+                }
+                if (!hasData) {
+                    monthAdjustmentResponses.add(MonthAdjustmentResponse.of(year, j, 0, AdjustmentStatus.NO_ADJUSTMENT));
+                }
+            }
+        }
+
+
+    }
+
     private Member verifiedMember(Long memberId) {
         return memberRepository.findById(memberId)
                 .orElseThrow(MemberNotFoundException::new);
diff --git a/Server/src/main/java/com/server/domain/adjustment/service/dto/response/MonthAdjustmentResponse.java b/Server/src/main/java/com/server/domain/adjustment/service/dto/response/MonthAdjustmentResponse.java
index 0f7ee770..dc056c54 100644
--- a/Server/src/main/java/com/server/domain/adjustment/service/dto/response/MonthAdjustmentResponse.java
+++ b/Server/src/main/java/com/server/domain/adjustment/service/dto/response/MonthAdjustmentResponse.java
@@ -1,6 +1,7 @@
 package com.server.domain.adjustment.service.dto.response;
 
 import com.server.domain.adjustment.domain.Adjustment;
+import com.server.domain.adjustment.domain.AdjustmentStatus;
 import lombok.AllArgsConstructor;
 import lombok.Builder;
 import lombok.Getter;
@@ -13,20 +14,26 @@ public class MonthAdjustmentResponse {
     private Integer year;
     private Integer month;
     private Integer amount;
+    private String reason;
+    private AdjustmentStatus adjustmentStatus;
 
     public static MonthAdjustmentResponse of(Adjustment adjustment) {
         return MonthAdjustmentResponse.builder()
                 .year(adjustment.getAdjustmentYear())
                 .month(adjustment.getAdjustmentMonth())
                 .amount(adjustment.getAmount())
+                .reason(adjustment.getReason())
+                .adjustmentStatus(adjustment.getAdjustmentStatus())
                 .build();
     }
 
-    public static MonthAdjustmentResponse of(int year, int month, int amount) {
+    public static MonthAdjustmentResponse of(int year, int month, int amount, AdjustmentStatus adjustmentStatus) {
         return MonthAdjustmentResponse.builder()
                 .year(year)
                 .month(month)
                 .amount(amount)
+                .reason(adjustmentStatus.getDescription())
+                .adjustmentStatus(adjustmentStatus)
                 .build();
     }
 
diff --git a/Server/src/main/java/com/server/global/batch/adjustment/AdjustmentJobConfig.java b/Server/src/main/java/com/server/global/batch/adjustment/AdjustmentJobConfig.java
new file mode 100644
index 00000000..e259c5a0
--- /dev/null
+++ b/Server/src/main/java/com/server/global/batch/adjustment/AdjustmentJobConfig.java
@@ -0,0 +1,4 @@
+package com.server.global.batch.adjustment;
+
+public class AdjustmentJobConfig {
+}
diff --git a/Server/src/test/java/com/server/domain/adjustment/controller/AdjustmentControllerTest.java b/Server/src/test/java/com/server/domain/adjustment/controller/AdjustmentControllerTest.java
index d8da2c6d..d05916d6 100644
--- a/Server/src/test/java/com/server/domain/adjustment/controller/AdjustmentControllerTest.java
+++ b/Server/src/test/java/com/server/domain/adjustment/controller/AdjustmentControllerTest.java
@@ -96,67 +96,15 @@ void adjustment() throws Exception {
         );
     }
 
-    @Test
-    @DisplayName("연/월별 총 판매 금액 조회 API - 특정 달")
-    void calculateAmount() throws Exception {
-        //given
-        int month = 9;
-        int year = 2023;
-
-        ToTalAdjustmentResponse response = createToTalAdjustmentResponse(9, 2023);
-
-        given(adjustmentService.totalAdjustment(anyLong(), anyInt(), anyInt()))
-                .willReturn(response);
-
-        String apiResponse = objectMapper.writeValueAsString(ApiSingleResponse.ok(response, year + "년 " + month + "월 정산 내역"));
-
-        //when
-        ResultActions actions = mockMvc.perform(
-                get(BASE_URL + "/total-adjustment")
-                        .header(AUTHORIZATION, TOKEN)
-                        .param("month", String.valueOf(month))
-                        .param("year", String.valueOf(year))
-        );
-
-        //then
-        actions
-                .andDo(print())
-                .andExpect(status().isOk())
-                .andExpect(content().string(apiResponse));
-
-        //restDocs
-        actions.andDo(
-                documentHandler.document(
-                        requestHeaders(
-                                headerWithName(AUTHORIZATION).description("액세스 토큰")
-                        ),
-                        requestParameters(
-                                parameterWithName("month").description("정산 월").optional(),
-                                parameterWithName("year").description("정산 년도").optional()
-                        ),
-                        singleResponseFields(
-                                fieldWithPath("data").description("정산 내역"),
-                                fieldWithPath("data.amount").description("정산 금액"),
-                                fieldWithPath("data.adjustmentStatus").description(generateLinkCode(AdjustmentStatus.class)),
-                                fieldWithPath("data.reason").description("정산 실패 시 사유"),
-                                fieldWithPath("data.monthData").description("월별 정산 내역"),
-                                fieldWithPath("data.monthData[].month").description("월"),
-                                fieldWithPath("data.monthData[].year").description("년"),
-                                fieldWithPath("data.monthData[].amount").description("정산 금액")
-                        )
-                )
-        );
-    }
-
     @Test
     @DisplayName("연/월별 총 판매 금액 조회 API - 전체 연도")
     void calculateAmountYear() throws Exception {
         //given
         int year = 2023;
 
-        ToTalAdjustmentResponse response = createToTalAdjustmentResponse(null, 2023);
+        List<MonthAdjustmentResponse> response = createToTalAdjustmentResponse(2023);
 
-        given(adjustmentService.totalAdjustment(anyLong(), isNull(), anyInt()))
+        given(adjustmentService.totalAdjustment(anyLong(), anyInt()))
                 .willReturn(response);
 
         String apiResponse = objectMapper.writeValueAsString(ApiSingleResponse.ok(response, year + "년 정산 내역"));
@@ -185,13 +133,11 @@ void calculateAmountYear() throws Exception {
                         ),
                         singleResponseFields(
                                 fieldWithPath("data").description("정산 내역"),
-                                fieldWithPath("data.amount").description("정산 금액"),
-                                fieldWithPath("data.adjustmentStatus").description(generateLinkCode(AdjustmentStatus.class)),
-                                fieldWithPath("data.reason").description("정산 실패 시 사유"),
-                                fieldWithPath("data.monthData").description("월별 정산 내역"),
-                                fieldWithPath("data.monthData[].month").description("월"),
-                                fieldWithPath("data.monthData[].year").description("년"),
-                                fieldWithPath("data.monthData[].amount").description("정산 금액")
+                                fieldWithPath("data[].month").description("월"),
+                                fieldWithPath("data[].year").description("년"),
+                                fieldWithPath("data[].amount").description("정산 금액"),
+                                fieldWithPath("data[].adjustmentStatus").description(generateLinkCode(AdjustmentStatus.class)),
+                                fieldWithPath("data[].reason").description("정산 상태에 대한 사유")
                         )
                 )
         );
@@ -367,35 +313,31 @@ void calculateVideoRate() throws Exception {
         );
     }
 
-    private ToTalAdjustmentResponse createToTalAdjustmentResponse(Integer month, Integer year) {
+    private List<MonthAdjustmentResponse> createToTalAdjustmentResponse(Integer year) {
 
         List<MonthAdjustmentResponse> monthAdjustmentResponses = new ArrayList<>();
 
-        if(month != null) {
-            for(int i = 1; i <= month; i++) {
-                monthAdjustmentResponses.add(MonthAdjustmentResponse.builder()
-                        .month(i)
-                        .year(year)
-                        .amount(10000)
-                        .build());
-            }
-        }
-        else {
-
-            for(int i = 1; i <= 9; i++) {
-                monthAdjustmentResponses.add(MonthAdjustmentResponse.builder()
-                        .month(i)
-                        .year(year)
-                        .amount(10000)
-                        .build());
-            }
+        for(int i = 1; i <= 9; i++) {
+            monthAdjustmentResponses.add(MonthAdjustmentResponse.builder()
+                    .month(i)
+                    .year(year)
+                    .amount(10000)
+                    .adjustmentStatus(AdjustmentStatus.ADJUSTED)
+                    .reason(AdjustmentStatus.ADJUSTED.getDescription())
+                    .build());
         }
 
-        if(month == null || year == null) {
-            return ToTalAdjustmentResponse.of(90000, AdjustmentStatus.TOTAL, "이유", monthAdjustmentResponses);
+        for(int i = 10; i <= 12; i++) {
+            monthAdjustmentResponses.add(MonthAdjustmentResponse.builder()
+                    .month(i)
+                    .year(year)
+                    .amount(0)
+                    .adjustmentStatus(AdjustmentStatus.NO_ADJUSTMENT)
+                    .reason(AdjustmentStatus.NO_ADJUSTMENT.getDescription())
+                    .build());
         }
 
-        return ToTalAdjustmentResponse.of(10000, AdjustmentStatus.NO_ADJUSTMENT, "이유", monthAdjustmentResponses);
+        return monthAdjustmentResponses;
     }
 
     private List<AdjustmentResponse> createAdjustmentResponse(int size) {