package com.kri.notihub.server.scheduler; import com.kri.common.feature.datetime.DateTimeUtil; import com.kri.common.feature.util.StringUtil; import com.kri.notihub.server.common.consts.NotihubConst; import com.kri.notihub.server.common.enums.SendStatusType; import com.kri.notihub.server.common.enums.SendType; import com.kri.notihub.server.persistence.entity.BizLogEntity; import com.kri.notihub.server.persistence.entity.TBulkSendEntity; import com.kri.notihub.server.persistence.entity.TSendEntity; import com.kri.notihub.server.persistence.repository.BizLogRepository; import com.kri.notihub.server.persistence.repository.BulkSendRepository; import com.kri.notihub.server.persistence.repository.SendRepository; import com.kri.notihub.server.service.BizppurioSendCursorStore; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.PageRequest; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @RequiredArgsConstructor public class BizLogResultScheduler { private final BizppurioSendCursorStore cursorStore; private final SendRepository sendRepository; private final BizLogRepository bizLogRepository; private final BulkSendRepository bulkSendRepository; @Scheduled(fixedDelay = 60 * 1_000) // 나중에 증가시킬 것 @Transactional(transactionManager = "transactionManager") public void syncSmsResults() { TimeWindow window = buildWindow(1L); // hours는 추후 파라미터화 List sendTyList = List.of(SendType.SMS.getCode(), SendType.LMS_MMS.getCode(), SendType.KKO_AT.getCode()); while (true) { List batch = fetchRefreshTargets(sendTyList, window, 1000); if (batch.isEmpty()) { return; } BulkContext bulkCtx = loadBulkContext(batch); BatchResult result = applyResultsAndCollectDeltas(batch, bulkCtx); persistChanges(result, bulkCtx); } } private TimeWindow buildWindow(long hours) { LocalDateTime toDt = LocalDateTime.now(); return new TimeWindow(toDt.minusHours(hours), toDt); } private List fetchRefreshTargets(List sendTyList, TimeWindow window, int size) { return sendRepository.findSendListToRefreshWithinHours( sendTyList, SendStatusType.STANDBY.getCode(), window.from(), window.to(), PageRequest.of(0, size) ); } /** * batch에서 bulkKey 수집 + bulk 엔티티 로딩 + Map 인덱싱 */ private BulkContext loadBulkContext(List batch) { Set bulkKeys = extractBulkKeys(batch); if (bulkKeys.isEmpty()) { return new BulkContext(Set.of(), Map.of()); } List bulkEntities = bulkSendRepository.findByBulkSendKeyIn(new ArrayList<>(bulkKeys)); Map bulkMap = bulkEntities.stream() .collect(Collectors.toMap( TBulkSendEntity::getBulkSendKey, Function.identity(), (a, b) -> a )); return new BulkContext(bulkKeys, bulkMap); } private Set extractBulkKeys(List batch) { return batch.stream() .map(TSendEntity::getBulkSendKey) .filter(k -> k != null && !k.isBlank()) .collect(Collectors.toSet()); } /** * BizLog 반영 + send/bulk delta 수집 */ private BatchResult applyResultsAndCollectDeltas(List batch, BulkContext bulkCtx) { Map successDelta = new HashMap<>(); Map failDelta = new HashMap<>(); List updatedSends = new ArrayList<>(); for (TSendEntity s : batch) { if (!isResultPending(s)) { continue; } Short beforeStatus = s.getSendStatus(); bizLogRepository.findTopByCmidOrderByReportTimeDesc(s.getCmid()).ifPresent(log -> { applySmsResultFromBizLog(s, log); updatedSends.add(s); accumulateBulkDeltaIfNeeded(s, beforeStatus, bulkCtx.bulkMap(), successDelta, failDelta); }); } return new BatchResult(updatedSends, successDelta, failDelta); } private boolean isResultPending(TSendEntity s) { if (s == null) { return false; } Short resultCode = s.getResultCode(); return resultCode != null && (resultCode == NotihubConst.SMS_STANDBY || resultCode == NotihubConst.LMS_MMS_STANDBY || resultCode == NotihubConst.KKO_AT_STANDBY); } /** * STANDBY -> SUCCESS/FAIL 전이일 때만 bulk delta 누적 */ private void accumulateBulkDeltaIfNeeded( TSendEntity s, Short beforeStatus, Map bulkMap, Map successDelta, Map failDelta ) { String key = s.getBulkSendKey(); if (StringUtil.isNullOrBlank(key)) { return; } if (!bulkMap.containsKey(key)) { return; } if (!Objects.equals(beforeStatus, SendStatusType.STANDBY.getCode())) { return; } if (Objects.equals(s.getSendStatus(), SendStatusType.SUCCESS.getCode())) { successDelta.merge(key, 1, Integer::sum); } else if (Objects.equals(s.getSendStatus(), SendStatusType.FAIL.getCode())) { failDelta.merge(key, 1, Integer::sum); } } /** * 저장 + cursor + bulk 카운트 반영 */ private void persistChanges(BatchResult result, BulkContext bulkCtx) { LocalDateTime now = DateTimeUtil.nowKstLocalDateTime(); if (!result.updatedSends().isEmpty()) { sendRepository.saveAll(result.updatedSends()); sendRepository.flush(); // 마지막 갱신 sendIdx 기록(현재 로직 유지) cursorStore.set(result.updatedSends().get(result.updatedSends().size() - 1).getSendIdx()); } if (bulkCtx.bulkMap().isEmpty()) { return; } applyBulkCountDeltas(bulkCtx.bulkMap(), result.successDelta(), result.failDelta(), now); bulkSendRepository.saveAll(bulkCtx.bulkMap().values()); } private void applyBulkCountDeltas( Map bulkMap, Map successDelta, Map failDelta, LocalDateTime now ) { Set touched = new HashSet<>(); successDelta.forEach((k, d) -> { TBulkSendEntity e = bulkMap.get(k); if (e != null) { int cur = e.getSuccesCnt() == null ? 0 : e.getSuccesCnt(); e.setSuccesCnt(cur + d); touched.add(k); } }); failDelta.forEach((k, d) -> { TBulkSendEntity e = bulkMap.get(k); if (e != null) { int cur = e.getFailCnt() == null ? 0 : e.getFailCnt(); e.setFailCnt(cur + d); touched.add(k); } }); // 완료 처리: trgt_cnt <= succes_cnt + fail_cnt 되는 순간 complete_dt 세팅 for (String k : touched) { TBulkSendEntity e = bulkMap.get(k); if (e == null) { continue; } if (e.getCompleteDt() != null) { continue; // 이미 완료면 재세팅 방지 } int trgt = e.getTrgtCnt() == null ? 0 : e.getTrgtCnt(); int success = e.getSuccesCnt() == null ? 0 : e.getSuccesCnt(); int fail = e.getFailCnt() == null ? 0 : e.getFailCnt(); if (trgt <= (success + fail)) { e.setCompleteDt(now); } } } private void applySmsResultFromBizLog(TSendEntity s, BizLogEntity log) { // ReportDt(LocalDateTime) 반영 // BizLogEntity.reportTime 타입이 Date면 LocalDateTime 변환 로직으로 바꾸세요. s.setReportDt(log.getReportTime()); short callStatus = safeParseShort(log.getCallStatus(), NotihubConst.SMS_NOT_RESULT); if (callStatus == NotihubConst.SMS_SUCCESS || callStatus == NotihubConst.LMS_MMS_SUCCESS || callStatus == NotihubConst.KKO_AT_SUCCESS) { s.setSendStatus(SendStatusType.SUCCESS.getCode()); s.setResultCode(callStatus); } else { s.setSendStatus(SendStatusType.FAIL.getCode()); s.setResultCode(callStatus); // “그 외 실패”이지만, 실제 코드 보존이 운영/분석에 유리 } } private short safeParseShort(String v, short fallback) { if (v == null || v.isBlank()) { return fallback; } try { return Short.parseShort(v.trim()); } catch (Exception e) { return fallback; } } private record TimeWindow(LocalDateTime from, LocalDateTime to) { } private record BulkContext(Set bulkKeys, Map bulkMap) { } private record BatchResult(List updatedSends, Map successDelta, Map failDelta) { } }