package com.kri.notihub.server.scheduler; import com.kri.common.feature.datetime.DateTimeUtil; 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.common.external.pringo.dto.PringoSendRequestDto; import com.kri.notihub.server.dto.send.DestInfoDto; import com.kri.notihub.server.dto.send.SendInternalResultDto; import com.kri.notihub.server.persistence.entity.TSendEntity; import com.kri.notihub.server.persistence.repository.SendRepository; import com.kri.notihub.server.service.SendEmailService; import com.kri.notihub.server.service.SendResultService; import java.time.LocalDateTime; import java.util.List; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.PageRequest; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor @Slf4j public class SendReservationEmailScheduler { private final SendEmailService sendEmlService; private final SendRepository sendRepository; private final SendResultService resultService; @Scheduled(cron = "${kri.email.reservation-send.cron:0 */5 * * * *}") public void sendReservationEmail() { LocalDateTime now = DateTimeUtil.nowKstLocalDateTime(); while (true) { List reservationList = sendRepository.findReservedSendEmail( SendType.EMAIL.getCode(), NotihubConst.EMAIL_STANDBY, now, PageRequest.of(0, 1000) ); if (reservationList.isEmpty()) { return; } for (TSendEntity s : reservationList) { TSendEntity claimed = sendEmlService.claimReservedEmail(s.getSendIdx()); if (claimed == null) { continue; } SendInternalResultDto sendResult; try { PringoSendRequestDto pringoReq = sendEmlService.buildPringoSendRequest( claimed.getSendEml(), claimed.getSendNm(), claimed.getMsgTitle(), claimed.getMsgBody(), claimed.getTmplatIdx(), claimed.getAtchFl(), DestInfoDto.from(claimed)); sendResult = sendEmlService.sendPringoEmail(pringoReq); } catch (Exception ex) { log.warn("Reserved email preparation failed (sendIdx={})", claimed.getSendIdx()); sendResult = SendInternalResultDto.of(claimed.getCmid(), SendStatusType.FAIL, NotihubConst.EMAIL_SEND_FAIL); } TSendEntity persisted = resultService.record(claimed.getSendIdx(), sendResult.cmid(), sendResult.status(), sendResult.resultCode(), null); if (persisted != null) { sendEmlService.afterPersistSendEntities(List.of(persisted)); } } } } }