|
| 1 | +package com.swyp.picke.domain.admin.adfit; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.databind.JsonNode; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import java.math.BigDecimal; |
| 6 | +import java.net.URI; |
| 7 | +import java.time.Instant; |
| 8 | +import java.time.LocalDate; |
| 9 | +import java.time.temporal.ChronoUnit; |
| 10 | +import java.util.ArrayList; |
| 11 | +import java.util.HashMap; |
| 12 | +import java.util.List; |
| 13 | +import java.util.Map; |
| 14 | +import lombok.extern.slf4j.Slf4j; |
| 15 | +import org.springframework.beans.factory.annotation.Value; |
| 16 | +import org.springframework.beans.factory.annotation.Autowired; |
| 17 | +import org.springframework.stereotype.Component; |
| 18 | +import org.springframework.util.StringUtils; |
| 19 | +import org.springframework.web.util.UriComponentsBuilder; |
| 20 | + |
| 21 | +@Slf4j |
| 22 | +@Component |
| 23 | +public class AdfitAccountReportClient { |
| 24 | + private static final String REPORT_URL = |
| 25 | + "https://adfit.kakao.com/api/v2/report/accountTotal/periodicIndicators"; |
| 26 | + |
| 27 | + private final String sessionCookie; |
| 28 | + private final AdfitHttpTransport transport; |
| 29 | + private final ObjectMapper objectMapper; |
| 30 | + |
| 31 | + @Autowired |
| 32 | + public AdfitAccountReportClient( |
| 33 | + @Value("${picke.adfit.session-cookie:${ADFIT_SESSION_COOKIE:}}") String sessionCookie, |
| 34 | + AdfitHttpTransport transport) { |
| 35 | + this(sessionCookie, transport, new ObjectMapper()); |
| 36 | + } |
| 37 | + |
| 38 | + AdfitAccountReportClient(String sessionCookie, AdfitHttpTransport transport, ObjectMapper objectMapper) { |
| 39 | + this.sessionCookie = sessionCookie; |
| 40 | + this.transport = transport; |
| 41 | + this.objectMapper = objectMapper; |
| 42 | + } |
| 43 | + |
| 44 | + public AdfitReport.AccountReport fetch(LocalDate from, LocalDate to, long expectedDays) { |
| 45 | + validateRange(from, to); |
| 46 | + List<AdfitReport.AccountDay> emptyDays = nullDays(from, to); |
| 47 | + if (!StringUtils.hasText(sessionCookie)) { |
| 48 | + return report(AdfitAccountReportStatus.NOT_CONFIGURED, null, expectedDays, null, emptyDays); |
| 49 | + } |
| 50 | + |
| 51 | + AdfitHttpResponse response = transport.get(uri(from, to), sessionCookie); |
| 52 | + if (response.statusCode() == 401 || response.statusCode() == 403 || response.statusCode() == 419 |
| 53 | + || response.isRedirect() |
| 54 | + || looksLikeHtml(response.body())) { |
| 55 | + return report(AdfitAccountReportStatus.RECONNECT_REQUIRED, null, expectedDays, null, emptyDays); |
| 56 | + } |
| 57 | + if (response.statusCode() < 200 || response.statusCode() >= 300 || !response.isJson()) { |
| 58 | + return report(AdfitAccountReportStatus.UNAVAILABLE, null, expectedDays, null, emptyDays); |
| 59 | + } |
| 60 | + |
| 61 | + try { |
| 62 | + List<AdfitReport.AccountDay> days = parseDays(response.body(), from, to); |
| 63 | + BigDecimal revenue = days.stream() |
| 64 | + .map(AdfitReport.AccountDay::revenue) |
| 65 | + .filter(value -> value != null) |
| 66 | + .reduce(BigDecimal.ZERO, BigDecimal::add); |
| 67 | + long reportedDays = days.stream().filter(day -> day.revenue() != null).count(); |
| 68 | + return new AdfitReport.AccountReport(AdfitAccountReportStatus.CONNECTED, Instant.now(), |
| 69 | + reportedDays, expectedDays, reportedDays == 0 ? null : revenue, null, null, days); |
| 70 | + } catch (Exception e) { |
| 71 | + log.warn("[AdFit] 계정 수익 보고서 응답 파싱 실패: {}", e.getClass().getSimpleName()); |
| 72 | + return report(AdfitAccountReportStatus.UNAVAILABLE, null, expectedDays, null, emptyDays); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + private URI uri(LocalDate from, LocalDate to) { |
| 77 | + return UriComponentsBuilder.fromUriString(REPORT_URL) |
| 78 | + .queryParam("dayType", "DAY") |
| 79 | + .queryParam("startDate", from) |
| 80 | + .queryParam("endDate", to) |
| 81 | + .build() |
| 82 | + .toUri(); |
| 83 | + } |
| 84 | + |
| 85 | + private List<AdfitReport.AccountDay> parseDays(String body, LocalDate from, LocalDate to) throws Exception { |
| 86 | + JsonNode root = objectMapper.readTree(body); |
| 87 | + if (!root.isArray()) { |
| 88 | + throw new IllegalArgumentException("AdFit report root must be an array."); |
| 89 | + } |
| 90 | + |
| 91 | + Map<LocalDate, AdfitReport.AccountDay> byDate = new HashMap<>(); |
| 92 | + for (JsonNode node : root) { |
| 93 | + LocalDate date = LocalDate.parse(requiredText(node, "reportDate")); |
| 94 | + if (date.isBefore(from) || date.isAfter(to)) { |
| 95 | + throw new IllegalArgumentException("AdFit report date is out of range."); |
| 96 | + } |
| 97 | + if (!node.has("profit")) { |
| 98 | + throw new IllegalArgumentException("AdFit report profit is missing."); |
| 99 | + } |
| 100 | + AdfitReport.AccountDay day = new AdfitReport.AccountDay(date, decimalOrNull(node, "profit"), |
| 101 | + decimalOrNull(node, "ctr"), decimalOrNull(node, "ecpm"), |
| 102 | + decimalOrNull(node, "fillRate"), decimalOrNull(node, "winFillRate")); |
| 103 | + if (byDate.putIfAbsent(date, day) != null) { |
| 104 | + throw new IllegalArgumentException("AdFit report date is duplicated."); |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + List<AdfitReport.AccountDay> days = new ArrayList<>(); |
| 109 | + LocalDate cursor = to; |
| 110 | + while (!cursor.isBefore(from)) { |
| 111 | + days.add(byDate.getOrDefault(cursor, |
| 112 | + new AdfitReport.AccountDay(cursor, null, null, null, null, null))); |
| 113 | + cursor = cursor.minusDays(1); |
| 114 | + } |
| 115 | + return days; |
| 116 | + } |
| 117 | + |
| 118 | + private String requiredText(JsonNode node, String field) { |
| 119 | + JsonNode value = node.get(field); |
| 120 | + if (value == null || value.isNull() || !value.isTextual()) { |
| 121 | + throw new IllegalArgumentException("AdFit report " + field + " is invalid."); |
| 122 | + } |
| 123 | + return value.asText(); |
| 124 | + } |
| 125 | + |
| 126 | + private BigDecimal decimalOrNull(JsonNode node, String field) { |
| 127 | + JsonNode value = node.get(field); |
| 128 | + if (value == null || value.isNull()) { |
| 129 | + return null; |
| 130 | + } |
| 131 | + if (!value.isNumber()) { |
| 132 | + throw new IllegalArgumentException("AdFit report " + field + " is invalid."); |
| 133 | + } |
| 134 | + return value.decimalValue(); |
| 135 | + } |
| 136 | + |
| 137 | + private List<AdfitReport.AccountDay> nullDays(LocalDate from, LocalDate to) { |
| 138 | + List<AdfitReport.AccountDay> days = new ArrayList<>(); |
| 139 | + LocalDate cursor = to; |
| 140 | + while (!cursor.isBefore(from)) { |
| 141 | + days.add(new AdfitReport.AccountDay(cursor, null, null, null, null, null)); |
| 142 | + cursor = cursor.minusDays(1); |
| 143 | + } |
| 144 | + return days; |
| 145 | + } |
| 146 | + |
| 147 | + private AdfitReport.AccountReport report(AdfitAccountReportStatus status, Instant fetchedAt, |
| 148 | + long expectedDays, BigDecimal revenue, |
| 149 | + List<AdfitReport.AccountDay> days) { |
| 150 | + return new AdfitReport.AccountReport(status, fetchedAt, 0, expectedDays, revenue, null, null, days); |
| 151 | + } |
| 152 | + |
| 153 | + private void validateRange(LocalDate from, LocalDate to) { |
| 154 | + long expected = ChronoUnit.DAYS.between(from, to) + 1; |
| 155 | + if (expected < 1 || expected > 366) { |
| 156 | + throw new IllegalArgumentException("조회 기간은 1일부터 366일까지입니다."); |
| 157 | + } |
| 158 | + } |
| 159 | + |
| 160 | + private boolean looksLikeHtml(String body) { |
| 161 | + return body != null && body.stripLeading().startsWith("<"); |
| 162 | + } |
| 163 | +} |
0 commit comments