261022_01_ENH: 예약 발송 취소 구현, record로 전환 가능한 Class Dto record로 전환, KKO 템플릿 등록시 사용 준비도 등록가능 템플릿으로 지정

This commit is contained in:
2026-10-22 12:33:32 +09:00
parent 7a1501d551
commit f2a9d6bfc6
58 changed files with 1090 additions and 1057 deletions

View File

@@ -2,11 +2,17 @@ package com.kri.notihub.server.common.consts;
import com.kri.notihub.server.common.enums.SendType;
import java.util.List;
import java.util.Set;
import lombok.NoArgsConstructor;
@NoArgsConstructor
public final class NotihubConst {
// send_status=CANCELED와 함께 사용하는 NotiHub 내부 코드
public static final short EMAIL_CANCELED = 108;
public static final short BIZPPURIO_CANCELED = 9998;
public static final String CANCELED_LABEL = "예약 취소";
public static final String NATION_CODE = "82";
public static final int OUTSOURCE_USER_ROLE = 4000;
public static final int CHUNK_SIZE = 5_000;
@@ -32,5 +38,6 @@ public final class NotihubConst {
public static final short LMS_MMS_SUCCESS = 6600;
public static final short KKO_AT_STANDBY = 7900;
public static final short KKO_AT_SUCCESS = 7000;
public static final Set<String> KKO_TEMPLATE_AVAILABLE_STATUSES = Set.of("A", "R"); // 정상, 사용준비
}

View File

@@ -12,6 +12,7 @@ public enum SendStatusType implements CodeEnum<Short> {
STANDBY((short) 0),
SUCCESS((short) 1),
CANCELED((short) 8),
FAIL((short) 9);
private final Short code;

View File

@@ -1,17 +1,12 @@
package com.kri.notihub.server.common.external.intranet.dto;
import lombok.Getter;
import lombok.Setter;
public record IntranetProjectBaseInfoDto(
String childSn,
@Getter
@Setter
public class IntranetProjectBaseInfoDto {
String title,
private String childSn;
String researchTeam,
private String title;
private String researchTeam;
private String researchTeamName;
String researchTeamName
) {
}

View File

@@ -224,10 +224,7 @@ public class PringoApiClient {
private static final class PringoJsonReturnErrorDtoBuilder {
static PringoReturnErrorDto noResultFallback() {
PringoReturnErrorDto e = new PringoReturnErrorDto();
e.setResult("0");
e.setMsg("응답이 비어 있습니다.");
return e;
return new PringoReturnErrorDto(null, null, "0", "응답이 비어 있습니다.");
}
}
}

View File

@@ -1,26 +1,21 @@
package com.kri.notihub.server.common.external.pringo.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class PringoReturnErrorDto {
public record PringoReturnErrorDto(
String type,
private String type;
@JsonProperty("typeAlias")
String typeAlias,
@JsonProperty("typeAlias")
private String typeAlias;
/**
* 예: "0"
*/
private String result;
private String msg;
/**
* 예: "0"
*/
String result,
String msg
) {
public boolean isNoResult() {
return "0".equals(result);
}
}
}

View File

@@ -1,44 +1,39 @@
package com.kri.notihub.server.common.external.pringo.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class PringoReturnItemDto {
public record PringoReturnItemDto(
@JsonProperty("No")
Integer no,
@JsonProperty("No")
private Integer no;
@JsonProperty("return_key")
Long returnKey,
@JsonProperty("return_key")
private Long returnKey;
@JsonProperty("email")
String email,
@JsonProperty("email")
private String email;
/**
* "O" / "X"
*/
@JsonProperty("open")
String open,
/**
* "O" / "X"
*/
@JsonProperty("open")
private String open;
/**
* "O" / "X"
*/
@JsonProperty("send_success")
String sendSuccess,
/**
* "O" / "X"
*/
@JsonProperty("send_success")
private String sendSuccess;
/**
* "yyyy-MM-dd HH:mm:ss" (문자열로 보관 권장)
*/
@JsonProperty("send_time")
String sendTime,
/**
* "yyyy-MM-dd HH:mm:ss" (문자열로 보관 권장)
*/
@JsonProperty("send_time")
private String sendTime;
/**
* ex) "250"
*/
@JsonProperty("status")
private String status;
}
/**
* ex) "250"
*/
@JsonProperty("status")
String status
) {
}

View File

@@ -1,29 +1,20 @@
package com.kri.notihub.server.common.external.pringo.dto;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PringoReturnResponseDto {
/**
* 조회 결과 row들(성공 시)
*/
private List<PringoReturnItemDto> itemList;
/**
* 조회 실패/없음(실패 시)
*/
private PringoReturnErrorDto error;
public record PringoReturnResponseDto(
/**
* 조회 결과 row들(성공 시)
*/
List<PringoReturnItemDto> itemList,
/**
* 조회 실패/없음(실패 시)
*/
PringoReturnErrorDto error
) {
public boolean isSuccess() {
return itemList != null && !itemList.isEmpty();
}
@@ -31,4 +22,4 @@ public class PringoReturnResponseDto {
public boolean isNoResult() {
return error != null && error.isNoResult();
}
}
}

View File

@@ -2,34 +2,29 @@ package com.kri.notihub.server.common.external.pringo.dto;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class PringoSendResponseDto {
public record PringoSendResponseDto(
String type,
private String type;
@JsonProperty("typeAlias")
String typeAlias,
@JsonProperty("typeAlias")
private String typeAlias;
/**
* Success: 1, failure: -1. Keep String because the API can return numeric or string values.
*/
@JsonProperty("result")
String result,
/**
* Success: 1, failure: -1. Keep String because the API can return numeric or string values.
*/
@JsonProperty("result")
private String result;
@JsonProperty("msg")
private String msg;
/**
* Pringo send response key. Accepts the legacy misspelled key for compatibility.
*/
@JsonProperty("return_key")
@JsonAlias("retrun_key")
private Long returnKey;
@JsonProperty("msg")
String msg,
/**
* Pringo send response key. Accepts the legacy misspelled key for compatibility.
*/
@JsonProperty("return_key")
@JsonAlias("retrun_key")
Long returnKey
) {
public boolean isSuccess() {
return "1".equals(result);
}

View File

@@ -118,10 +118,10 @@ public class ReportController {
@Valid @RequestBody SendCostSummaryRequestDto req
) {
ReportExcelResponseDto result = reportService.getSendCostSummaryWithItrntPrjctExcel(req);
byte[] bytes = Base64.getDecoder().decode(result.getFileBase64());
byte[] bytes = Base64.getDecoder().decode(result.fileBase64());
String contentDisposition = "attachment; filename*=UTF-8''" +
URLEncoder.encode(result.getFileName(), StandardCharsets.UTF_8).replace("+", "%20");
URLEncoder.encode(result.fileName(), StandardCharsets.UTF_8).replace("+", "%20");
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)

View File

@@ -0,0 +1,38 @@
package com.kri.notihub.server.controller;
import com.kri.common.feature.web.RequestUserContext;
import com.kri.notihub.server.dto.send.SendCancelBulkRequestDto;
import com.kri.notihub.server.dto.send.SendCancelSingleRequestDto;
import com.kri.notihub.server.dto.send.SendCancelResponseDto;
import com.kri.notihub.server.service.SendCancelService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/send/cancel")
@RequiredArgsConstructor
@Tag(name = "Send Cancel", description = "예약 발송 취소")
public class SendCancelController {
private final SendCancelService sendCancelService;
@PostMapping("/single")
@Operation(summary = "단건 예약 취소")
public SendCancelResponseDto cancelSingle(
@Valid @RequestBody SendCancelSingleRequestDto request, RequestUserContext ctx) {
return sendCancelService.cancelSingle(request.sendIdx(), ctx);
}
@PostMapping("/bulk")
@Operation(summary = "벌크의 남은 예약 건 취소", description = "이미 시작된 건은 유지하고 취소 가능한 건만 처리")
public SendCancelResponseDto cancelBulk(
@Valid @RequestBody SendCancelBulkRequestDto request, RequestUserContext ctx) {
return sendCancelService.cancelBulk(request.bulkSendKey(), ctx);
}
}

View File

@@ -51,7 +51,7 @@ public class TemplateController {
produces = MediaType.APPLICATION_JSON_VALUE)
public KkoTemplateListResponseDto getKkoTemplateList(
@Valid @RequestBody KkoTemplateListRequestDto request) {
return kkoTemplateService.getList(request.getKeyword());
return kkoTemplateService.getList(request.keyword());
}
@Operation(summary = "외부 알림톡 템플릿 상세 조회")
@@ -59,7 +59,7 @@ public class TemplateController {
produces = MediaType.APPLICATION_JSON_VALUE)
public KkoTemplateDetailDto getKkoTemplateDetail(
@Valid @RequestBody KkoTemplateDetailRequestDto request) {
return kkoTemplateService.getDetail(request.getTemplateCode());
return kkoTemplateService.getDetail(request.templateCode());
}

View File

@@ -2,11 +2,7 @@ package com.kri.notihub.server.dto.email;
import java.util.Objects;
public record EmailAttachmentDto(
String fileName,
String contentType,
byte[] content
) {
public record EmailAttachmentDto(String fileName, String contentType, byte[] content) {
public EmailAttachmentDto {
Objects.requireNonNull(fileName, "fileName is required");

View File

@@ -80,12 +80,32 @@ public class BulkSendInfoDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private LocalDateTime regDt;
@Schema(description = "벌크 취소 요청자")
private String cancelUser;
@Schema(description = "벌크 취소 요청 일시. 수신자 추가 등록 마감 기준")
private LocalDateTime cancelDt;
@Schema(description = "현재 취소 상태인 건수")
private long canceledCount;
@Schema(description = "취소 상태: NONE, PARTIAL, ALL")
private String cancellationStatus;
public void applyCanceledCount(long count, long targetCount) {
canceledCount = count;
cancellationStatus = count == 0 ? "NONE"
: count == targetCount ? "ALL" : "PARTIAL";
}
public static BulkSendInfoDto from(TBulkSendEntity entity) {
if (entity == null) {
return null;
}
return BulkSendInfoDto.builder()
.cancelUser(entity.getCancelUser())
.cancelDt(entity.getCancelDt())
.bulkSendKey(entity.getBulkSendKey())
.reqstSvc(entity.getReqstSvc())
.prjctCd(entity.getPrjctCd())

View File

@@ -2,17 +2,13 @@ package com.kri.notihub.server.dto.report;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Builder
public class ReportExcelResponseDto {
public record ReportExcelResponseDto(
@Schema(description = "프론트가 저장용으로 쓸 파일명")
String fileName,
@Schema(description = "프론트가 저장용으로 쓸 파일명")
private String fileName;
@Schema(description = "엑셀 파일 (xlsx)의 Base64 문자열 (hasErrorFile == true일 때만 세팅)")
private String fileBase64;
@Schema(description = "엑셀 파일 (xlsx)의 Base64 문자열 (hasErrorFile == true일 때만 세팅)")
String fileBase64
) {
}

View File

@@ -3,25 +3,17 @@ package com.kri.notihub.server.dto.report;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import java.time.LocalDate;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "발송 비용 프로젝트별 요약 요청")
public class SendCostSummaryRequestDto {
public record SendCostSummaryRequestDto(
@Schema(description = "조회 시작 일시")
@NotNull
LocalDate startDt,
@Schema(description = "조회 시작 일시")
@NotNull
private LocalDate startDt;
@Schema(description = "조회 종료 일시")
@NotNull
private LocalDate endDt;
@Schema(description = "조회 종료 일시")
@NotNull
LocalDate endDt
) {
}

View File

@@ -5,46 +5,37 @@ import com.kri.notihub.server.common.enums.SendCorpType;
import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.common.external.intranet.dto.IntranetProjectBaseInfoDto;
import java.math.BigDecimal;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class SendCostSummaryWithItrntPrjctExcelDto {
public record SendCostSummaryWithItrntPrjctExcelDto(
@ExcelColumn(header = "요청 서비스", order = 0)
String reqstSvc,
@ExcelColumn(header = "요청 서비스", order = 0)
private String reqstSvc;
@ExcelColumn(header = "인트라넷 프로젝트 코드", order = 1)
String itrntPrjctCd,
@ExcelColumn(header = "인트라넷 프로젝트 코드", order = 1)
private String itrntPrjctCd;
@ExcelColumn(header = "프로젝트 명", order = 2)
String title,
@ExcelColumn(header = "프로젝트 명", order = 2)
private String title;
@ExcelColumn(header = "연구팀 명", order = 3)
String researchTeamName,
@ExcelColumn(header = "연구팀 명", order = 3)
private String researchTeamName;
@ExcelColumn(header = "발송 타입", order = 4)
String sendTy,
@ExcelColumn(header = "발송 타입", order = 4)
private String sendTy;
@ExcelColumn(header = "발송 업체", order = 5)
String sendCorp,
@ExcelColumn(header = "발송 업체", order = 5)
private String sendCorp;
@ExcelColumn(header = "발송 건수", order = 6)
Long sendCnt,
@ExcelColumn(header = "발송 건수", order = 6)
private Long sendCnt;
@ExcelColumn(header = "단가", order = 7)
private BigDecimal unitPrice;
@ExcelColumn(header = "총 비용", order = 8)
private BigDecimal totalPrice;
@ExcelColumn(header = "단가", order = 7)
BigDecimal unitPrice,
@ExcelColumn(header = "총 비용", order = 8)
BigDecimal totalPrice
) {
public static SendCostSummaryWithItrntPrjctExcelDto from(
SendCostSummaryWithItrntPrjctDto source) {
if (source == null) {
@@ -56,8 +47,8 @@ public class SendCostSummaryWithItrntPrjctExcelDto {
return SendCostSummaryWithItrntPrjctExcelDto.builder()
.reqstSvc(source.getReqstSvc())
.itrntPrjctCd(source.getItrntPrjctCd())
.title(projectInfo != null ? projectInfo.getTitle() : null)
.researchTeamName(projectInfo != null ? projectInfo.getResearchTeamName() : null)
.title(projectInfo != null ? projectInfo.title() : null)
.researchTeamName(projectInfo != null ? projectInfo.researchTeamName() : null)
.sendTy(getSendTypeLabel(source.getSendTy()))
.sendCorp(getSendCorpLabel(source.getSendCorp()))
.sendCnt(source.getSendCnt())

View File

@@ -2,6 +2,7 @@ package com.kri.notihub.server.dto.report;
import com.kri.common.feature.excel.ExcelColumn;
import com.kri.notihub.server.common.enums.SendStatusType;
import com.kri.notihub.server.common.consts.NotihubConst;
import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.persistence.entity.TSendEntity;
import com.kri.notihub.server.persistence.entity.TSendResultCodeEntity;
@@ -11,123 +12,121 @@ import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.List;
import lombok.AllArgsConstructor;
import java.util.Objects;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "발송 정보")
public class SendInfoDto {
public record SendInfoDto(
@Size(max = 32)
@NotBlank
@Schema(description = "CMID")
String cmid,
@Size(max = 32)
@NotBlank
@Schema(description = "CMID")
private String cmid;
@Size(max = 32)
@Schema(description = "대량발송 키")
String bulkSendKey,
@Size(max = 32)
@Schema(description = "대량발송 키")
private String bulkSendKey;
@NotNull
@Schema(description = "발송 타입 코드")
Short sendTyCode,
@NotNull
@Schema(description = "발송 타입 코드")
private Short sendTyCode;
@NotNull
@Schema(description = "발송 타입 라벨")
String sendTyLabel,
@NotNull
@Schema(description = "발송 타입 라벨")
private String sendTyLabel;
@NotNull
@Schema(description = "예약 여부")
Boolean resve,
@NotNull
@Schema(description = "예약 여부")
private Boolean resve;
@NotNull
@Schema(description = "발송 상태")
Short sendStatusCode,
@NotNull
@Schema(description = "발송 상태")
private Short sendStatusCode;
@NotNull
@ExcelColumn(header = "발송 상태", order = 0)
@Schema(description = "발송 상태 라벨")
String sendStatusLabel,
@NotNull
@ExcelColumn(header = "발송 상태", order = 0)
@Schema(description = "발송 상태 라벨")
private String sendStatusLabel;
@NotNull
@Schema(description = "결과 코드")
Short resultCode,
@NotNull
@Schema(description = "결과 코드")
private Short resultCode;
@NotNull
@ExcelColumn(header = "발송 결과", order = 1)
@Schema(description = "결과 라벨")
String resultLabel,
@NotNull
@ExcelColumn(header = "발송 결과", order = 1)
@Schema(description = "결과 라벨")
private String resultLabel;
@Size(max = 16)
@NotBlank
@Schema(description = "요청 서비스")
String reqstSvc,
@Size(max = 16)
@NotBlank
@Schema(description = "요청 서비스")
private String reqstSvc;
@Size(max = 32)
@NotBlank
@Schema(description = "프로젝트 코드")
String prjctCd,
@Size(max = 32)
@NotBlank
@Schema(description = "프로젝트 코드")
private String prjctCd;
@Schema(description = "템플릿 인덱스")
Long tmplatIdx,
@Schema(description = "템플릿 인덱스")
private Long tmplatIdx;
@Size(max = 64)
@ExcelColumn(header = "발신지", order = 2)
@Schema(description = "발신지(EMAIL이면 sendEml, 아니면 sendTel)")
String sendFrom,
@Size(max = 64)
@ExcelColumn(header = "발신지", order = 2)
@Schema(description = "발신지(EMAIL이면 sendEml, 아니면 sendTel)")
private String sendFrom;
@Size(max = 32)
@ExcelColumn(header = "발신자명", order = 3)
@Schema(description = "발신자명")
String sendNm,
@Size(max = 32)
@ExcelColumn(header = "발신자명", order = 3)
@Schema(description = "발신자명")
private String sendNm;
@NotNull
@ExcelColumn(header = "발송 일시", order = 4)
@Schema(description = "발송 일시")
LocalDateTime sendDt,
@NotNull
@ExcelColumn(header = "발송 일시", order = 4)
@Schema(description = "발송 일시")
private LocalDateTime sendDt;
@Size(max = 128)
@NotBlank
@ExcelColumn(header = "SID", order = 5)
@Schema(description = "SID")
String sid,
@Size(max = 128)
@NotBlank
@ExcelColumn(header = "SID", order = 5)
@Schema(description = "SID")
private String sid;
@Size(max = 64)
@ExcelColumn(header = "수신지", order = 6)
@Schema(description = "수신지(EMAIL이면 destEml, 아니면 destTel)")
String destTo,
@Size(max = 64)
@ExcelColumn(header = "수신지", order = 6)
@Schema(description = "수신지(EMAIL이면 destEml, 아니면 destTel)")
private String destTo;
@Size(max = 32)
@ExcelColumn(header = "수신자명", order = 7)
@Schema(description = "수신자명")
String destNm,
@Size(max = 32)
@ExcelColumn(header = "수신자명", order = 7)
@Schema(description = "수신자명")
private String destNm;
@ExcelColumn(header = "발송 결과 확인 일시", order = 8)
@Schema(description = "리포트 일시")
LocalDateTime reportDt,
@ExcelColumn(header = "발송 결과 확인 일시", order = 8)
@Schema(description = "리포트 일시")
private LocalDateTime reportDt;
@Size(max = 32)
@NotBlank
@Schema(description = "등록 회사")
String regCmpn,
@Size(max = 32)
@NotBlank
@Schema(description = "등록 회사")
private String regCmpn;
@Size(max = 32)
@NotBlank
@ExcelColumn(header = "발송 요청자", order = 9)
@Schema(description = "등록자")
String regUser,
@Size(max = 32)
@NotBlank
@ExcelColumn(header = "발송 요청자", order = 9)
@Schema(description = "등록자")
private String regUser;
@NotNull
@ExcelColumn(header = "발송 요청 일시", order = 10)
@Schema(description = "등록일시")
LocalDateTime regDt,
@NotNull
@ExcelColumn(header = "발송 요청 일시", order = 10)
@Schema(description = "등록일시")
private LocalDateTime regDt;
@ExcelColumn(header = "취소 처리자", order = 11)
String cancelUser,
@ExcelColumn(header = "취소 처리 일시", order = 12)
LocalDateTime cancelDt
) {
public static SendInfoDto from(TSendEntity entity, List<TSendResultCodeEntity> resultCodeEntity) {
if (entity == null) {
return null;
@@ -146,15 +145,19 @@ public class SendInfoDto {
.orElse(null); // 없으면 null
return SendInfoDto.builder()
.cancelUser(entity.getCancelUser())
.cancelDt(entity.getCancelDt())
.cmid(entity.getCmid())
.bulkSendKey(entity.getBulkSendKey())
.sendTyCode(entity.getSendTy())
.sendTyLabel(SendType.fromCode(entity.getSendTy()).name())
.resve(entity.isResve())
.sendStatusCode(entity.getSendStatus())
.sendStatusLabel(SendStatusType.fromCode(entity.getSendStatus()).name())
.sendStatusLabel(Objects.equals(entity.getSendStatus(), SendStatusType.CANCELED.getCode())
? NotihubConst.CANCELED_LABEL : SendStatusType.fromCode(entity.getSendStatus()).name())
.resultCode(entity.getResultCode())
.resultLabel(resultViewLabel)
.resultLabel(Objects.equals(entity.getSendStatus(), SendStatusType.CANCELED.getCode())
? NotihubConst.CANCELED_LABEL : resultViewLabel)
.reqstSvc(entity.getReqstSvc())
.prjctCd(entity.getPrjctCd())
.tmplatIdx(entity.getTmplatIdx())

View File

@@ -5,38 +5,29 @@ import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "발송 결과 코드")
public class SendResultCodeDto {
public record SendResultCodeDto(
@NotNull
@Schema(description = "결과 코드")
Short resultCode,
@NotNull
@Schema(description = "결과 코드")
private Short resultCode;
@NotNull
@Schema(description = "결과 타입")
Short resultTy,
@NotNull
@Schema(description = "결과 타입")
private Short resultTy;
@Size(max = 128)
@NotBlank
@Schema(description = "결과 라벨")
private String resultLabel;
@Size(max = 128)
@NotBlank
@Schema(description = "결과 표시 라벨")
private String resultViewLabel;
@Size(max = 128)
@NotBlank
@Schema(description = "결과 라벨")
String resultLabel,
@Size(max = 128)
@NotBlank
@Schema(description = "결과 표시 라벨")
String resultViewLabel
) {
public static SendResultCodeDto from(TSendResultCodeEntity entity) {
if (entity == null) {
return null;

View File

@@ -1,6 +1,8 @@
package com.kri.notihub.server.dto.report;
import com.kri.notihub.server.persistence.entity.TSendEntity;
import com.kri.notihub.server.common.consts.NotihubConst;
import com.kri.notihub.server.common.enums.SendStatusType;
import com.kri.notihub.server.persistence.entity.TSendResultCodeEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
@@ -9,107 +11,107 @@ import jakarta.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "발송 결과 정보")
public class SendResultInfoDto {
public record SendResultInfoDto(
@Schema(description = "발송 이력 ID")
Long sendIdx,
@Schema(description = "CMID")
private String cmid;
@Schema(description = "취소 처리자")
String cancelUser,
@Schema(description = "대량 발송 키")
private String bulkSendKey;
@Schema(description = "취소 처리 일시. 실제 발송 결과가 확인된 뒤에도 이력 유지")
LocalDateTime cancelDt,
@Schema(description = "인트라넷 프로젝트 코드")
private String itrntPrjctCd;
@Schema(description = "CMID")
String cmid,
@Schema(description = "요청 서비스")
private String reqstSvc;
@Schema(description = "대량 발송 키")
String bulkSendKey,
@Schema(description = "프로젝트 코드")
private String prjctCd;
@Schema(description = "인트라넷 프로젝트 코드")
String itrntPrjctCd,
@Schema(description = "리스트 아이디")
private String sid;
@Schema(description = "요청 서비스")
String reqstSvc,
@NotNull
@Schema(description = "발송 타입")
private Short sendTy;
@Schema(description = "프로젝트 코드")
String prjctCd,
@NotNull
@Schema(description = "예약 여부")
private Boolean resve;
@Schema(description = "리스트 아이디")
String sid,
@NotNull
@Schema(description = "결과 코드")
private Short resultCode;
@NotNull
@Schema(description = "발송 타입")
Short sendTy,
@Size(max = 128)
@Schema(description = "결과 라벨")
private String resultLabel;
@NotNull
@Schema(description = "예약 여부")
Boolean resve,
@Size(max = 128)
@Schema(description = "결과 표시 라벨")
private String resultViewLabel;
@NotNull
@Schema(description = "결과 코드")
Short resultCode,
@Schema(description = "템플릿 인덱스")
private Long tmplatIdx;
@Size(max = 128)
@Schema(description = "결과 라벨")
String resultLabel,
@Size(max = 64)
@Schema(description = "카카오 템플릿 코드")
private String kkoTmplatCd;
@Size(max = 128)
@Schema(description = "결과 표시 라벨")
String resultViewLabel,
@Size(max = 64)
@Schema(description = "발신 이메일")
private String sendEml;
@Schema(description = "템플릿 인덱스")
Long tmplatIdx,
@Size(max = 16)
@Schema(description = "발신 전화번호")
private String sendTel;
@Size(max = 64)
@Schema(description = "카카오 템플릿 코드")
String kkoTmplatCd,
@Size(max = 32)
@Schema(description = "발신자명")
private String sendNm;
@Size(max = 64)
@Schema(description = "발신 이메일")
String sendEml,
@NotNull
@Schema(description = "발송 일시")
private LocalDateTime sendDt;
@Size(max = 16)
@Schema(description = "발신 전화번호")
String sendTel,
@Size(max = 64)
@Schema(description = "수신 이메일")
private String destEml;
@Size(max = 32)
@Schema(description = "발신자명")
String sendNm,
@Size(max = 32)
@Schema(description = "수신자명")
private String destNm;
@NotNull
@Schema(description = "발송 일시")
LocalDateTime sendDt,
@Size(max = 16)
@Schema(description = "수신 전화번호")
private String destTel;
@Size(max = 64)
@Schema(description = "수신 이메일")
String destEml,
@Size(max = 32)
@NotBlank
@Schema(description = "등록 회사")
private String regCmpn;
@Size(max = 32)
@Schema(description = "수신자명")
String destNm,
@Size(max = 32)
@NotBlank
@Schema(description = "등록자")
private String regUser;
@Size(max = 16)
@Schema(description = "수신 전화번호")
String destTel,
@NotNull
@Schema(description = "등록 일시")
private LocalDateTime regDt;
@Size(max = 32)
@NotBlank
@Schema(description = "등록 회사")
String regCmpn,
@Size(max = 32)
@NotBlank
@Schema(description = "등록자")
String regUser,
@NotNull
@Schema(description = "등록 일시")
LocalDateTime regDt
) {
public static SendResultInfoDto from(TSendEntity entity) {
return from(entity, null);
}
@@ -121,8 +123,12 @@ public class SendResultInfoDto {
}
TSendResultCodeEntity resultCode = findResultCode(entity, resultCodeEntity);
boolean canceled = Objects.equals(entity.getSendStatus(), SendStatusType.CANCELED.getCode());
return SendResultInfoDto.builder()
.sendIdx(entity.getSendIdx())
.cancelUser(entity.getCancelUser())
.cancelDt(entity.getCancelDt())
.cmid(entity.getCmid())
.bulkSendKey(entity.getBulkSendKey())
.itrntPrjctCd(entity.getItrntPrjctCd())
@@ -132,8 +138,10 @@ public class SendResultInfoDto {
.sendTy(entity.getSendTy())
.resve(entity.isResve())
.resultCode(entity.getResultCode())
.resultLabel(resultCode != null ? resultCode.getResultLabel() : null)
.resultViewLabel(resultCode != null ? resultCode.getResultViewLabel() : null)
.resultLabel(canceled ? NotihubConst.CANCELED_LABEL
: resultCode != null ? resultCode.getResultLabel() : null)
.resultViewLabel(canceled ? NotihubConst.CANCELED_LABEL
: resultCode != null ? resultCode.getResultViewLabel() : null)
.tmplatIdx(entity.getTmplatIdx())
.kkoTmplatCd(entity.getKkoTmplatCd())
.sendEml(entity.getSendEml())

View File

@@ -2,36 +2,28 @@ package com.kri.notihub.server.dto.report;
import io.swagger.v3.oas.annotations.media.Schema;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import lombok.Builder;
@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Schema(description = "발송 결과 정보")
public class SendResultLastWithSidDto {
public record SendResultLastWithSidDto(
@Schema(description = "리스트 아이디")
String sid,
@Schema(description = "리스트 아이디")
private String sid;
@Schema(description = "마지막 결과 코드")
Short lastResultCode,
@Schema(description = "마지막 결과 코드")
private Short lastResultCode;
@Schema(description = "마지막 결과 라벨")
String lastResultLabel,
@Schema(description = "마지막 결과 라벨")
private String lastResultLabel;
@Schema(description = "마지막 결과 표시 라벨")
String lastResultViewLabel,
@Schema(description = "마지막 결과 표시 라벨")
private String lastResultViewLabel;
@Schema(description = "마지막 발송 일시")
LocalDateTime lastSendDt,
@Schema(description = "마지막 발송 일시")
private LocalDateTime lastSendDt;
@Schema(description = "총 발송 Count")
private Integer totalSendCount;
@Schema(description = "총 발송 Count")
Integer totalSendCount
) {
}

View File

@@ -30,6 +30,9 @@ public class SendResultSummaryDto {
@Schema(description = "대기중 카운트")
private Long standByCount;
@Schema(description = "현재 취소 상태인 건수")
private Long canceledCount;
@Schema(description = "전체 카운트")
private Long totalCount;
}

View File

@@ -1,38 +1,28 @@
package com.kri.notihub.server.dto.report;
import io.swagger.v3.oas.annotations.media.Schema;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "발송 축약 결과 요청")
public class SendResultSummaryRequestDto {
public record SendResultSummaryRequestDto(
@Schema(description = "대량발송 키")
String bulkSendKey,
@Schema(description = "대량발송 키")
private String bulkSendKey;
@Schema(description = "인트라넷 프로젝트 코드")
String itrntPrjctCd,
@Schema(description = "인트라넷 프로젝트 코드")
private String itrntPrjctCd;
@Schema(description = "요청 서비스")
String reqstSvc,
@Schema(description = "요청 서비스")
private String reqstSvc;
@Schema(description = "프로젝트 코드")
String prjctCd,
@Schema(description = "프로젝트 코드")
private String prjctCd;
@Schema(description = "발송일시 조회 시작")
private LocalDateTime sendStartDt;
@Schema(description = "발송일시 조회 종료")
private LocalDateTime sendEndDt;
@Schema(description = "발송일시 조회 시작")
LocalDateTime sendStartDt,
@Schema(description = "발송일시 조회 종료")
LocalDateTime sendEndDt
) {
}

View File

@@ -1,23 +1,16 @@
package com.kri.notihub.server.dto.send;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BizppurioCursorResponseDto {
@Schema(description = "SMS 결과 반영 스케줄러 커서(send_idx)")
private Long cursor;
public record BizppurioCursorResponseDto(
@Schema(description = "SMS 결과 반영 스케줄러 커서(send_idx)")
Long cursor
) {
public static BizppurioCursorResponseDto of(long cursor) {
return BizppurioCursorResponseDto.builder()
.cursor(cursor)
.build();
}
}
}

View File

@@ -1,29 +1,22 @@
package com.kri.notihub.server.dto.send;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BulkSendResponseDto {
public record BulkSendResponseDto(
@Schema(description = "bulkSendKey")
String bulkSendKey,
@Schema(description = "bulkSendKey")
private String bulkSendKey;
@Schema(description = "요청 건수")
Integer requestCount,
@Schema(description = "요청 건수")
private Integer requestCount;
@Schema(description = "발송 접수 건수(대기 또는 즉시 성공)")
private Integer acceptCount;
@Schema(description = "발송 접수 실패 건수")
private Integer failCount;
@Schema(description = "발송 접수 건수(대기 또는 즉시 성공)")
Integer acceptCount,
@Schema(description = "발송 접수 실패 건수")
Integer failCount
) {
public static BulkSendResponseDto of(String bulkSendKey, Integer requestCount,
Integer acceptCount, Integer failCount) {
return BulkSendResponseDto.builder()

View File

@@ -5,39 +5,30 @@ import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Size;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "수신 정보")
public class DestInfoDto {
public record DestInfoDto(
@Schema(description = "리스트 아이디")
String sid,
@Schema(description = "리스트 아이디")
private String sid;
@Size(max = 64)
@Email
@Schema(description = "수신 이메일 (이메일 발송에서 사용)")
String destEml,
@Size(max = 64)
@Email
@Schema(description = "수신 이메일 (이메일 발송에서 사용)")
private String destEml;
@Size(max = 16)
@Schema(description = "수신 전화번호 (문자 발송에서 사용)")
String destTel,
@Size(max = 16)
@Schema(description = "수신 전화번호 (문자 발송에서 사용)")
private String destTel;
@Size(max = 32)
@Schema(description = "수신자 이름")
private String destNm;
@Schema(description = "수신 파라미터 (템플릿 내용 파싱용)")
private Map<String, String> msgParam;
@Size(max = 32)
@Schema(description = "수신자 이름")
String destNm,
@Schema(description = "수신 파라미터 (템플릿 내용 파싱용)")
Map<String, String> msgParam
) {
public static DestInfoDto from(TSendEntity entity) {
return DestInfoDto.builder()
.sid(entity.getSid())

View File

@@ -5,30 +5,23 @@ import com.kri.common.feature.datetime.DateTimeUtil;
import io.swagger.v3.oas.annotations.media.Schema;
import java.time.Instant;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class EmailPollQueueItemDto {
public record EmailPollQueueItemDto(
@Schema(description = "Pringo return_key(cmid)")
String cmid,
@Schema(description = "Pringo return_key(cmid)")
private String cmid;
@Schema(description = "폴링 시도 횟수(0부터 시작)")
Integer attempt,
@Schema(description = "폴링 시도 횟수(0부터 시작)")
private Integer attempt;
@Schema(description = "구동까지 남은 시간(ms)")
private Long remainingMs;
@Schema(description = "구동 예상 시간(KST LocalDateTime)")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime triggerAt;
@Schema(description = "구동까지 남은 시간(ms)")
Long remainingMs,
@Schema(description = "구동 예상 시간(KST LocalDateTime)")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
LocalDateTime triggerAt
) {
public static EmailPollQueueItemDto of(String cmid, int attempt, long remainingMs,
long triggerAtEpochMs) {
return EmailPollQueueItemDto.builder()

View File

@@ -2,23 +2,16 @@ package com.kri.notihub.server.dto.send;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class EmailPollQueueResponseDto {
@Schema(description = "Queue size (snapshot)")
private Integer size;
@Schema(description = "Queue에 있는 작업 내용 (snapshot)")
private List<EmailPollQueueItemDto> items;
public record EmailPollQueueResponseDto(
@Schema(description = "Queue size (snapshot)")
Integer size,
@Schema(description = "Queue에 있는 작업 내용 (snapshot)")
List<EmailPollQueueItemDto> items
) {
public static EmailPollQueueResponseDto of(List<EmailPollQueueItemDto> items) {
return EmailPollQueueResponseDto.builder()
.size(items != null ? items.size() : 0)

View File

@@ -0,0 +1,11 @@
package com.kri.notihub.server.dto.send;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record SendCancelBulkRequestDto(
@NotBlank
@Size(max = 32)
String bulkSendKey
) {
}

View File

@@ -0,0 +1,14 @@
package com.kri.notihub.server.dto.send;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
@Schema(description = "싱글/벌크 예약 취소 결과. 문자·알림톡은 큐 제거 기준이며 미발송을 보장하지 않음")
@Builder
public record SendCancelResponseDto(
long targetCount,
long canceledCount,
long alreadyCanceledCount,
long notCancelableCount
) {
}

View File

@@ -0,0 +1,11 @@
package com.kri.notihub.server.dto.send;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
public record SendCancelSingleRequestDto(
@NotNull
@Positive
Long sendIdx
) {
}

View File

@@ -2,26 +2,17 @@ package com.kri.notihub.server.dto.send;
import com.kri.notihub.server.common.enums.SendStatusType;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "이메일/문자 발송 결과")
public class SendInternalResultDto {
public record SendInternalResultDto(
String cmid,
private String cmid;
private SendStatusType status;
private Short resultCode;
SendStatusType status,
Short resultCode
) {
public static SendInternalResultDto of(String cmid, SendStatusType status, short resultCode) {
return SendInternalResultDto.builder()
.cmid(cmid)

View File

@@ -2,32 +2,34 @@ package com.kri.notihub.server.dto.send;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "단건 발송 접수 결과")
public class SendSingleResponseDto {
public record SendSingleResponseDto(
@Schema(description = "발송 이력 ID")
Long sendIdx,
@Schema(description = "발송 고유 키")
String cmid,
@Schema(description = "템플릿 목적별 추가 응답 정보")
Map<String, Object> data
) {
public static final String VERIFICATION_ID_KEY = "verificationId";
public static final String EXPIRE_DT_KEY = "expireDt";
@Schema(description = "발송 고유 키")
private String cmid;
@Builder.Default
@Schema(description = "템플릿 목적별 추가 응답 정보")
private Map<String, Object> data = Map.of();
public static SendSingleResponseDto of(String cmid, Map<String, Object> data) {
public static SendSingleResponseDto of(Long sendIdx, String cmid, Map<String, Object> data) {
return SendSingleResponseDto.builder()
.sendIdx(sendIdx)
.cmid(cmid)
.data(data == null ? Map.of() : Map.copyOf(data))
.build();
}
public static class SendSingleResponseDtoBuilder {
private Map<String, Object> data = Map.of();
}
}

View File

@@ -3,33 +3,29 @@ package com.kri.notihub.server.dto.template;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class KkoTemplateDetailDto {
private String templateCode;
private String templateName;
private String templateContent;
private String templatePreviewMessage;
private String templateMessageType;
private String templateEmphasizeType;
private String inspectionStatus;
private String status;
private Boolean block;
private Boolean dormant;
private String templateExtra;
private String templateImageName;
private String templateImageUrl;
private String templateTitle;
private String templateSubtitle;
private String templateHeader;
private JsonNode templateItemHighlight;
private JsonNode templateItem;
private JsonNode templateRepresentLink;
private List<JsonNode> buttons;
private List<JsonNode> quickReplies;
public record KkoTemplateDetailDto(
String templateCode,
String templateName,
String templateContent,
String templatePreviewMessage,
String templateMessageType,
String templateEmphasizeType,
String inspectionStatus,
String status,
Boolean block,
Boolean dormant,
String templateExtra,
String templateImageName,
String templateImageUrl,
String templateTitle,
String templateSubtitle,
String templateHeader,
JsonNode templateItemHighlight,
JsonNode templateItem,
JsonNode templateRepresentLink,
List<JsonNode> buttons,
List<JsonNode> quickReplies
) {
}

View File

@@ -3,19 +3,11 @@ package com.kri.notihub.server.dto.template;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class KkoTemplateDetailRequestDto {
@NotBlank
@Size(max = 30)
@Pattern(regexp = "[A-Za-z0-9_-]+")
private String templateCode;
public record KkoTemplateDetailRequestDto(
@NotBlank
@Size(max = 30)
@Pattern(regexp = "[A-Za-z0-9_-]+")
String templateCode
) {
}

View File

@@ -1,21 +1,12 @@
package com.kri.notihub.server.dto.template;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
public class KkoTemplateListRequestDto {
@Size(min = 2, max = 50)
private String keyword;
public KkoTemplateListRequestDto(String keyword) {
setKeyword(keyword);
}
public void setKeyword(String keyword) {
this.keyword = keyword == null || keyword.isBlank() ? null : keyword.trim();
public record KkoTemplateListRequestDto(
@Size(min = 2, max = 50)
String keyword
) {
public KkoTemplateListRequestDto {
keyword = keyword == null || keyword.isBlank() ? null : keyword.trim();
}
}

View File

@@ -1,19 +1,11 @@
package com.kri.notihub.server.dto.template;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class KkoTemplateListResponseDto {
private int totalCount;
private int totalPage;
private int currentPage;
private List<KkoTemplateSummaryDto> list;
public record KkoTemplateListResponseDto(
int totalCount,
int totalPage,
int currentPage,
List<KkoTemplateSummaryDto> list
) {
}

View File

@@ -1,21 +1,13 @@
package com.kri.notihub.server.dto.template;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class KkoTemplateSummaryDto {
private String templateCode;
private String templateName;
private String serviceStatus;
private String createdAt;
private String modifiedAt;
public record KkoTemplateSummaryDto(
String templateCode,
String templateName,
String serviceStatus,
String createdAt,
String modifiedAt
) {
}

View File

@@ -3,29 +3,20 @@ package com.kri.notihub.server.dto.template;
import com.kri.notihub.server.common.enums.TemplatePurpose;
import com.kri.notihub.server.persistence.entity.TTmplatEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "템플릿 요약 정보")
public class TemplateSummaryDto {
public record TemplateSummaryDto(
@Schema(description = "템플릿 고유 키")
Long tmplatIdx,
@Schema(description = "템플릿 고유 키")
private Long tmplatIdx;
@Schema(description = "템플릿 명")
private String tmplatNm;
@Schema(description = "템플릿 목적")
private TemplatePurpose tmplatPurpose;
@Schema(description = "템플릿 명")
String tmplatNm,
@Schema(description = "템플릿 목적")
TemplatePurpose tmplatPurpose
) {
public static TemplateSummaryDto from(TTmplatEntity entity) {
return TemplateSummaryDto.builder()
.tmplatIdx(entity.getTmplatIdx())

View File

@@ -4,29 +4,25 @@ import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Schema(description = "휴대전화번호 인증 요청")
public class PhoneVerificationRequestDto {
public record PhoneVerificationRequestDto(
@NotBlank
@Pattern(
regexp = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$",
message = "verificationId는 UUID 형식이어야 합니다."
)
@Schema(description = "인증 발급 UUID")
String verificationId,
@NotBlank
@Pattern(
regexp = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$",
message = "verificationId는 UUID 형식이어야 합니다."
)
@Schema(description = "인증 발급 UUID")
private String verificationId;
@NotBlank
@Size(max = 16)
@Schema(description = "인증 대상 휴대전화번호")
String sendTel,
@NotBlank
@Size(max = 16)
@Schema(description = "인증 대상 휴대전화번호")
private String sendTel;
@NotBlank
@Pattern(regexp = "^[0-9]{6}$", message = "verificationCode는 숫자 6자리여야 합니다.")
@Schema(description = "6자리 인증번호")
private String verificationCode;
@NotBlank
@Pattern(regexp = "^[0-9]{6}$", message = "verificationCode는 숫자 6자리여야 합니다.")
@Schema(description = "6자리 인증번호")
String verificationCode
) {
}

View File

@@ -3,27 +3,20 @@ package com.kri.notihub.server.dto.verification;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "휴대전화번호 인증 결과")
public class PhoneVerificationResponseDto {
public record PhoneVerificationResponseDto(
String verificationId,
private String verificationId;
String sendTel,
private String sendTel;
private boolean verified;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime verifiedDt;
boolean verified,
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
LocalDateTime verifiedDt
) {
public static PhoneVerificationResponseDto of(
String verificationId,
String sendTel,

View File

@@ -86,6 +86,25 @@ public class TBulkSendEntity extends BaseUuidEntity {
@Column(name = "reg_dt", nullable = false)
private LocalDateTime regDt;
@Column(name = "cancel_user", length = 32)
private String cancelUser;
@Column(name = "cancel_dt")
private LocalDateTime cancelDt;
public void completeIfSettled(long canceledCount, LocalDateTime now) {
long registered = value(sendCnt);
boolean registrationClosed = cancelDt != null || registered >= value(trgtCnt);
if (registrationClosed && registered <= value(succesCnt) + value(failCnt) + canceledCount
&& completeDt == null) {
completeDt = now;
}
}
private long value(Integer count) {
return count == null ? 0 : count;
}
public static TBulkSendEntity from(BulkSendCreateRequestDto req, LocalDateTime now) {
return TBulkSendEntity.builder()

View File

@@ -173,6 +173,12 @@ public class TSendEntity {
@Column(name = "reg_dt", nullable = false)
private LocalDateTime regDt;
@Column(name = "cancel_user", length = 32)
private String cancelUser;
@Column(name = "cancel_dt")
private LocalDateTime cancelDt;
public static TSendEntity from(
SendRequestSingleDto req,
TemplateDto tmplat,
@@ -240,13 +246,13 @@ public class TSendEntity {
}
return TSendEntity.builder()
.cmid(sendResult.getCmid())
.cmid(sendResult.cmid())
.bulkSendKey(bulkSendKey)
.sendTy(sendTy)
.resve(resve)
.sendCorp(sendCorp)
.sendStatus(sendResult.getStatus().getCode())
.resultCode(sendResult.getResultCode())
.sendStatus(sendResult.status().getCode())
.resultCode(sendResult.resultCode())
.itrntPrjctCd(tmplat.getItrntPrjctCd())
.reqstSvc(reqstSvc)
.prjctCd(prjctCd)
@@ -259,13 +265,13 @@ public class TSendEntity {
.sendTel(basic.getSendTel())
.sendNm(basic.getSendNm())
.sendDt(sendDt)
.sid(dest.getSid())
.sid(dest.sid())
.msgTitle(msgTitle)
.msgBody(msgBody)
.msgParam(dest.getMsgParam() != null ? dest.getMsgParam() : Map.of())
.destEml(dest.getDestEml())
.destTel(dest.getDestTel())
.destNm(dest.getDestNm())
.msgParam(dest.msgParam() != null ? dest.msgParam() : Map.of())
.destEml(dest.destEml())
.destTel(dest.destTel())
.destNm(dest.destNm())
.regCmpn(regCmpn)
.regUser(regUser)
.regDt(regDt)

View File

@@ -2,7 +2,14 @@ package com.kri.notihub.server.persistence.repository;
import com.kri.notihub.server.persistence.entity.BizMsgEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
public interface BizMsgRepository extends JpaRepository<BizMsgEntity, String> {
// 사전 조회가 아닌 실제 DELETE 결과로 큐 제거 성공 여부를 판단한다.
@Modifying
@Query("delete from BizMsgEntity m where m.cmid = :cmid and m.status = 0")
int deleteWaiting(String cmid);
}

View File

@@ -4,10 +4,16 @@ import com.kri.notihub.server.persistence.entity.TBulkSendEntity;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import jakarta.persistence.LockModeType;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
public interface BulkSendRepository extends JpaRepository<TBulkSendEntity, String> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select b from TBulkSendEntity b where b.bulkSendKey = :bulkSendKey")
Optional<TBulkSendEntity> findForUpdate(String bulkSendKey);
List<TBulkSendEntity> findByBulkSendKeyIn(List<String> bulkSendKeyList);
@Query("""

View File

@@ -12,6 +12,8 @@ import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import jakarta.persistence.LockModeType;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
@@ -19,6 +21,29 @@ import org.springframework.transaction.annotation.Transactional;
public interface SendRepository extends JpaRepository<TSendEntity, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select s from TSendEntity s where s.sendIdx = :sendIdx")
Optional<TSendEntity> findForUpdate(Long sendIdx);
@Query("select s.sendIdx from TSendEntity s where s.bulkSendKey = :bulkSendKey "
+ "and s.sendIdx > :afterIdx order by s.sendIdx")
List<Long> findBulkSendIds(String bulkSendKey, Long afterIdx, Pageable pageable);
long countByBulkSendKeyAndSendStatus(String bulkSendKey, Short sendStatus);
interface CancellationCount {
String getBulkSendKey();
Long getCanceledCount();
Long getTargetCount();
}
@Query("select s.bulkSendKey as bulkSendKey, "
+ "sum(case when s.sendStatus = 8 then 1L else 0L end) as canceledCount, "
+ "count(s) as targetCount "
+ "from TSendEntity s where s.bulkSendKey in :bulkSendKeys "
+ "group by s.bulkSendKey")
List<CancellationCount> countCanceledByBulkSendKeys(List<String> bulkSendKeys);
Optional<TSendEntity> findByCmid(String cmid);
@Query("""
@@ -32,9 +57,9 @@ public interface SendRepository extends JpaRepository<TSendEntity, Long> {
@Query("""
select s
from TSendEntity s
where s.sendStatus = :sendStatus
where (s.sendStatus = :sendStatus or s.sendStatus = 8)
and s.sendTy in :sendTyList
and s.resultCode in :resultCodes
and (s.resultCode in :resultCodes or s.sendStatus = 8)
and s.sendDt <= :now
and exists (
select 1
@@ -57,6 +82,8 @@ public interface SendRepository extends JpaRepository<TSendEntity, Long> {
where s.sendTy = :sendTy
and s.resultCode = :resultCode
and s.resve = true
and s.sendStatus = 0
and s.cancelDt is null
and s.sendDt <= :now
order by s.sendIdx asc
""")
@@ -73,6 +100,8 @@ public interface SendRepository extends JpaRepository<TSendEntity, Long> {
where s.sendTy = :sendTy
and s.resultCode = :resultCode
and s.resve = false
and s.sendStatus = 0
and s.cancelDt is null
and s.bulkSendKey is not null
and s.sendDt <= :now
order by s.sendIdx asc
@@ -91,6 +120,8 @@ public interface SendRepository extends JpaRepository<TSendEntity, Long> {
set s.resultCode = :sendingResultCode
where s.sendIdx = :sendIdx
and s.resultCode = :standbyResultCode
and s.sendStatus = 0
and s.cancelDt is null
""")
int markEmailSending(
Long sendIdx,
@@ -105,6 +136,8 @@ public interface SendRepository extends JpaRepository<TSendEntity, Long> {
set s.resultCode = :standbyResultCode
where s.sendTy = :sendTy
and s.resultCode = :sendingResultCode
and s.sendStatus = 0
and s.cancelDt is null
and s.resve = false
and s.bulkSendKey is not null
and s.sendDt <= :staleBefore
@@ -146,8 +179,8 @@ public interface SendRepository extends JpaRepository<TSendEntity, Long> {
select new com.kri.notihub.server.dto.report.SendResultLastWithSidDto(
s.sid,
s.resultCode,
src.resultLabel,
src.resultViewLabel,
case when s.sendStatus = 8 then '예약 취소' else src.resultLabel end,
case when s.sendStatus = 8 then '예약 취소' else src.resultViewLabel end,
s.sendDt,
cast((
select count(sc)
@@ -159,10 +192,11 @@ public interface SendRepository extends JpaRepository<TSendEntity, Long> {
) as integer)
)
from TSendEntity s
join TSendResultCodeEntity src
left join TSendResultCodeEntity src
on s.sendCorp = src.id.sendCorp
and s.resultCode = src.id.resultCode
where s.sid in :sids
and (src.id.resultCode is not null or s.sendStatus = 8)
and s.prjctCd = :prjctCd
and s.reqstSvc = :reqstSvc
and s.sendTy in :sendTys
@@ -188,16 +222,18 @@ public interface SendRepository extends JpaRepository<TSendEntity, Long> {
select new com.kri.notihub.server.dto.report.SendResultSummaryDto(
s.sendTy,
s.sendCorp,
sum(case when src.resultCodeType = 1 then 1L else 0L end),
sum(case when src.resultCodeType = 0 then 1L else 0L end),
sum(case when src.resultCodeType = 9 then 1L else 0L end),
sum(case when s.sendStatus <> 8 and src.resultCodeType = 1 then 1L else 0L end),
sum(case when s.sendStatus <> 8 and src.resultCodeType = 0 then 1L else 0L end),
sum(case when s.sendStatus <> 8 and src.resultCodeType = 9 then 1L else 0L end),
sum(case when s.sendStatus = 8 then 1L else 0L end),
count(s)
)
from TSendEntity s
join TSendResultCodeEntity src
left join TSendResultCodeEntity src
on s.sendCorp = src.id.sendCorp
and s.resultCode = src.id.resultCode
where (:bulkSendKey is null or s.bulkSendKey = :bulkSendKey)
and (src.id.resultCode is not null or s.sendStatus = 8)
and (:itrntPrjctCd is null or s.itrntPrjctCd = :itrntPrjctCd)
and (:reqstSvc is null or s.reqstSvc = :reqstSvc)
and (:prjctCd is null or s.prjctCd = :prjctCd)

View File

@@ -1,33 +1,20 @@
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.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 com.kri.notihub.server.service.SendResultService;
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 java.util.stream.Stream;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
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
@@ -36,254 +23,51 @@ public class BizLogResultScheduler {
private final BizppurioSendCursorStore cursorStore;
private final SendRepository sendRepository;
private final BizLogRepository bizLogRepository;
private final BulkSendRepository bulkSendRepository;
private final SendResultService resultService;
@Value("${kri.sms.result-sync.batch-size:1000}")
private int resultSyncBatchSize;
@Scheduled(fixedDelayString = "${kri.sms.result-sync.fixed-delay-ms:60000}")
@Transactional(transactionManager = "transactionManager")
public void syncSmsResults() {
List<Short> sendTyList = Stream.concat(
NotihubConst.SMS_TYPE_CODE_LIST.stream(),
List<Short> types = Stream.concat(NotihubConst.SMS_TYPE_CODE_LIST.stream(),
NotihubConst.KKO_TYPE_CODE_LIST.stream()).toList();
List<Short> resultCodes = List.of(
NotihubConst.SMS_STANDBY,
NotihubConst.LMS_MMS_STANDBY,
NotihubConst.KKO_AT_STANDBY
);
List<Short> codes = List.of(NotihubConst.SMS_STANDBY,
NotihubConst.LMS_MMS_STANDBY, NotihubConst.KKO_AT_STANDBY);
while (true) {
List<TSendEntity> batch = fetchRefreshTargets(sendTyList, resultCodes, resultSyncBatchSize);
if (batch.isEmpty()) {
List<TSendEntity> sends = sendRepository.findSendListToRefresh(types,
SendStatusType.STANDBY.getCode(), codes, DateTimeUtil.nowKstLocalDateTime(),
PageRequest.of(0, Math.max(1, resultSyncBatchSize)));
if (sends.isEmpty()) {
return;
}
BulkContext bulkCtx = loadBulkContext(batch);
BatchResult result = applyResultsAndCollectDeltas(batch, bulkCtx);
persistChanges(result, bulkCtx);
if (result.updatedSends().isEmpty()) {
boolean updated = false;
for (TSendEntity send : sends) {
var log = bizLogRepository.findTopByCmidOrderByReportTimeDesc(send.getCmid());
if (log.isEmpty()) {
continue;
}
short code = parseCode(log.get().getCallStatus());
SendStatusType status = code == NotihubConst.SMS_SUCCESS
|| code == NotihubConst.LMS_MMS_SUCCESS || code == NotihubConst.KKO_AT_SUCCESS
? SendStatusType.SUCCESS : SendStatusType.FAIL;
if (resultService.record(send.getSendIdx(), null, status, code,
log.get().getReportTime()) != null) {
cursorStore.set(send.getSendIdx());
updated = true;
}
}
if (!updated) {
return;
}
}
}
private List<TSendEntity> fetchRefreshTargets(List<Short> sendTyList, List<Short> resultCodes,
int size) {
return sendRepository.findSendListToRefresh(
sendTyList,
SendStatusType.STANDBY.getCode(),
resultCodes,
LocalDateTime.now(),
PageRequest.of(0, size)
);
}
/**
* batch에서 bulkKey 수집 + bulk 엔티티 로딩 + Map 인덱싱
*/
private BulkContext loadBulkContext(List<TSendEntity> batch) {
Set<String> bulkKeys = extractBulkKeys(batch);
if (bulkKeys.isEmpty()) {
return new BulkContext(Set.of(), Map.of());
}
List<TBulkSendEntity> bulkEntities =
bulkSendRepository.findByBulkSendKeyIn(new ArrayList<>(bulkKeys));
Map<String, TBulkSendEntity> bulkMap = bulkEntities.stream()
.collect(Collectors.toMap(
TBulkSendEntity::getBulkSendKey,
Function.identity(),
(a, b) -> a
));
return new BulkContext(bulkKeys, bulkMap);
}
private Set<String> extractBulkKeys(List<TSendEntity> batch) {
return batch.stream()
.map(TSendEntity::getBulkSendKey)
.filter(k -> k != null && !k.isBlank())
.collect(Collectors.toSet());
}
/**
* BizLog 반영 + send/bulk delta 수집
*/
private BatchResult applyResultsAndCollectDeltas(List<TSendEntity> batch, BulkContext bulkCtx) {
Map<String, Integer> successDelta = new HashMap<>();
Map<String, Integer> failDelta = new HashMap<>();
List<TSendEntity> 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<String, TBulkSendEntity> bulkMap,
Map<String, Integer> successDelta,
Map<String, Integer> 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<String, TBulkSendEntity> bulkMap,
Map<String, Integer> successDelta,
Map<String, Integer> failDelta,
LocalDateTime now
) {
Set<String> 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;
}
private short parseCode(String code) {
try {
return Short.parseShort(v.trim());
} catch (Exception e) {
return fallback;
return Short.parseShort(code.trim());
} catch (RuntimeException ex) {
return NotihubConst.SMS_NOT_RESULT;
}
}
private record BulkContext(Set<String> bulkKeys, Map<String, TBulkSendEntity> bulkMap) {
}
private record BatchResult(List<TSendEntity> updatedSends,
Map<String, Integer> successDelta,
Map<String, Integer> failDelta) {
}
}

View File

@@ -64,7 +64,7 @@ public class EmailBulkSendScheduler {
applySendResult(send, sendResult);
sendRepository.save(send);
if (sendResult.getStatus() == SendStatusType.FAIL) {
if (sendResult.status() == SendStatusType.FAIL) {
increaseBulkFailCount(send.getBulkSendKey(), now);
} else {
sendEmailService.afterPersistSendEntities(List.of(send));
@@ -136,9 +136,9 @@ public class EmailBulkSendScheduler {
}
private void applySendResult(TSendEntity send, SendInternalResultDto sendResult) {
send.setCmid(sendResult.getCmid());
send.setSendStatus(sendResult.getStatus().getCode());
send.setResultCode(sendResult.getResultCode());
send.setCmid(sendResult.cmid());
send.setSendStatus(sendResult.status().getCode());
send.setResultCode(sendResult.resultCode());
}
private void increaseBulkFailCount(String bulkSendKey, LocalDateTime now) {

View File

@@ -2,6 +2,7 @@ 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;
@@ -9,30 +10,29 @@ 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.ArrayList;
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;
import org.springframework.transaction.annotation.Transactional;
@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 * * * *}")
@Transactional(transactionManager = "transactionManager")
public void sendReservationEmail() {
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
while (true) {
List<TSendEntity> updatedSends = new ArrayList<>();
List<TSendEntity> reservationList = sendRepository.findReservedSendEmail(
SendType.EMAIL.getCode(),
NotihubConst.EMAIL_STANDBY,
@@ -45,30 +45,28 @@ public class SendReservationEmailScheduler {
}
for (TSendEntity s : reservationList) {
PringoSendRequestDto pringoReq = sendEmlService.buildPringoSendRequest(
s.getSendEml(),
s.getSendNm(),
s.getMsgTitle(),
s.getMsgBody(),
s.getTmplatIdx(),
s.getAtchFl(),
DestInfoDto.from(s)
);
SendInternalResultDto sendResult = sendEmlService.sendPringoEmail(pringoReq);
s.setCmid(sendResult.getCmid());
s.setSendStatus(sendResult.getStatus().getCode());
s.setResultCode(sendResult.getResultCode());
updatedSends.add(s);
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));
}
}
//TSendEntity update
sendRepository.saveAll(updatedSends);
sendRepository.flush();
//결과들을 모았다가 afterPersistSendEntities
sendEmlService.afterPersistSendEntities(updatedSends);
}
}
}

View File

@@ -120,7 +120,7 @@ public abstract class AbstractPringoSendService extends AbstractSendService {
SendStatusType sendStatus;
short resultCode;
if (pringoRes != null && pringoRes.isSuccess() && pringoRes.getReturnKey() != null) {
if (pringoRes != null && pringoRes.isSuccess() && pringoRes.returnKey() != null) {
//발송 요청에 성공한 것이지 발송이 성공이 아니므로 STANDBY 유지
sendStatus = SendStatusType.STANDBY;
resultCode = NotihubConst.EMAIL_PENDING;
@@ -155,15 +155,15 @@ public abstract class AbstractPringoSendService extends AbstractSendService {
DestInfoDto dest
) {
Map<String, Object> vars = new HashMap<>();
if (dest.getMsgParam() != null) {
vars.putAll(dest.getMsgParam());
if (dest.msgParam() != null) {
vars.putAll(dest.msgParam());
}
return PringoSendRequestDto.builder()
.sender(sendEml)
.senderName(Optional.ofNullable(sendNm).orElse(""))
.recipient(dest.getDestEml())
.recipientName(Optional.ofNullable(dest.getDestNm()).orElse(dest.getDestEml()))
.recipient(dest.destEml())
.recipientName(Optional.ofNullable(dest.destNm()).orElse(dest.destEml()))
.subject(Optional.ofNullable(msgTitle).orElse(""))
.body(Optional.ofNullable(msgBody).orElse(""))
.attachments(tmplatIdx == null
@@ -174,8 +174,8 @@ public abstract class AbstractPringoSendService extends AbstractSendService {
}
private String resolveEmailCmid(PringoSendResponseDto pringoRes) {
if (pringoRes != null && pringoRes.isSuccess() && pringoRes.getReturnKey() != null) {
return String.valueOf(pringoRes.getReturnKey());
if (pringoRes != null && pringoRes.isSuccess() && pringoRes.returnKey() != null) {
return String.valueOf(pringoRes.returnKey());
}
// return_key 미수신 케이스는 SendFau
return CommonUtil.uuid32();

View File

@@ -35,6 +35,8 @@ import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Isolation;
@RequiredArgsConstructor
public abstract class AbstractSendService {
@@ -144,7 +146,7 @@ public abstract class AbstractSendService {
}
DestInfoDto dest = req.getDestInfo();
String sendTo = isEmailChannel() ? dest.getDestEml() : dest.getDestTel();
String sendTo = isEmailChannel() ? dest.destEml() : dest.destTel();
if (sendTo == null || sendTo.isBlank()) {
if (isEmailChannel()) {
throw BusinessException.badRequest("DEST_EMAIL_REQUIRED", "destEml은 필수 입니다.");
@@ -153,12 +155,12 @@ public abstract class AbstractSendService {
}
}
String msgTitle = replacePlaceholder(tmplat.getTmplatTitle(), dest.getMsgParam());
String msgBody = renderMessageBody(tmplat.getTmplatBody(), dest.getMsgParam());
String msgTitle = replacePlaceholder(tmplat.getTmplatTitle(), dest.msgParam());
String msgBody = renderMessageBody(tmplat.getTmplatBody(), dest.msgParam());
PhoneVerificationIssue verificationIssue = null;
if (tmplat.getTmplatPurpose() == TemplatePurpose.PHONE_VERIFICATION) {
verificationIssue = phoneVerificationService.issue(dest.getDestTel(), now);
verificationIssue = phoneVerificationService.issue(dest.destTel(), now);
msgBody = msgBody + "\n" + verificationIssue.message();
}
@@ -182,7 +184,7 @@ public abstract class AbstractSendService {
req.setSendNm(sendNm);
if (verificationIssue != null) {
phoneVerificationService.persist(verificationIssue, sendResult.getCmid());
phoneVerificationService.persist(verificationIssue, sendResult.cmid());
}
List<TSendEntity> sendInfo = new ArrayList<>(List.of(
@@ -215,9 +217,11 @@ public abstract class AbstractSendService {
verificationIssue.expireDt().format(RESPONSE_DATE_TIME_FORMATTER)
);
return SendSingleResponseDto.of(sendResult.getCmid(), responseData);
return SendSingleResponseDto.of(
sendInfo.get(0).getSendIdx(), sendResult.cmid(), responseData);
}
@Transactional(isolation = Isolation.READ_COMMITTED)
public BulkSendResponseDto doSendBulk(SendRequestBulkDto req) {
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
@@ -229,12 +233,16 @@ public abstract class AbstractSendService {
throw BusinessException.badRequest("DEST_LIST_REQUIRED", "수신 정보가 없습니다.");
}
TBulkSendEntity bulk = bulkSendRepository.findById(bulkSendKey)
TBulkSendEntity bulk = bulkSendRepository.findForUpdate(bulkSendKey)
.orElseThrow(() ->
BusinessException.badRequest("BULK_SEND_KEY_NOT_FOUND", "bulkSendKey가 잘 못 됐습니다.")
.with("bulkSendKey", bulkSendKey)
);
if (bulk.getCancelDt() != null) {
throw BusinessException.badRequest("BULK_SEND_CANCELED", "취소 요청된 벌크에는 수신자를 추가할 수 없습니다.");
}
if (bulk.getTrgtCnt() <= bulk.getSendCnt()) {
BusinessException.badRequest("OVERFLOW_SEND_CNT", "해당 bulkSendKey로 발송할 수 있는 한도를 초과 했습니다.")
.with("bulkSendKey", bulkSendKey)
@@ -284,14 +292,14 @@ public abstract class AbstractSendService {
continue;
}
String sendTo = isEmailChannel() ? dest.getDestEml() : dest.getDestTel();
String sendTo = isEmailChannel() ? dest.destEml() : dest.destTel();
if (StringUtil.isNullOrBlank(sendTo)) {
failCnt++;
continue;
}
String msgTitle = replacePlaceholder(tmplat.getTmplatTitle(), dest.getMsgParam());
String msgBody = renderMessageBody(tmplat.getTmplatBody(), dest.getMsgParam());
String msgTitle = replacePlaceholder(tmplat.getTmplatTitle(), dest.msgParam());
String msgBody = renderMessageBody(tmplat.getTmplatBody(), dest.msgParam());
SendInternalResultDto sendResult = doSendInternal(
isResve,
@@ -306,12 +314,12 @@ public abstract class AbstractSendService {
dest
);
if (sendResult.getStatus() == SendStatusType.STANDBY) {
if (sendResult.status() == SendStatusType.STANDBY) {
acceptCnt++;
} else if (sendResult.getStatus() == SendStatusType.SUCCESS) {
} else if (sendResult.status() == SendStatusType.SUCCESS) {
acceptCnt++;
successCnt++;
} else if (sendResult.getStatus() == SendStatusType.FAIL) {
} else if (sendResult.status() == SendStatusType.FAIL) {
failCnt++;
}
@@ -346,6 +354,9 @@ public abstract class AbstractSendService {
bulk.setSendCnt(Optional.ofNullable(bulk.getSendCnt()).orElse(0) + requestCnt);
bulk.setSuccesCnt(Optional.ofNullable(bulk.getSuccesCnt()).orElse(0) + successCnt);
bulk.setFailCnt(Optional.ofNullable(bulk.getFailCnt()).orElse(0) + failCnt);
long canceledCnt = sendRepository.countByBulkSendKeyAndSendStatus(
bulkSendKey, SendStatusType.CANCELED.getCode());
bulk.completeIfSettled(canceledCnt, now);
bulkSendRepository.save(bulk);
return BulkSendResponseDto.of(bulkSendKey, requestCnt, acceptCnt, failCnt);

View File

@@ -87,7 +87,7 @@ public class EmailResultPoller {
);
})
.sorted(Comparator.comparingLong(i ->
i.getRemainingMs() != null ? i.getRemainingMs() : Long.MAX_VALUE
i.remainingMs() != null ? i.remainingMs() : Long.MAX_VALUE
))
.toList();

View File

@@ -8,7 +8,6 @@ import com.kri.notihub.server.common.external.pringo.PringoApiClient;
import com.kri.notihub.server.common.external.pringo.dto.PringoReturnItemDto;
import com.kri.notihub.server.common.external.pringo.dto.PringoReturnResponseDto;
import com.kri.notihub.server.persistence.entity.TSendEntity;
import com.kri.notihub.server.persistence.repository.BulkSendRepository;
import com.kri.notihub.server.persistence.repository.SendRepository;
import java.time.LocalDateTime;
import java.util.Optional;
@@ -23,7 +22,7 @@ class EmailResultUpdater {
private final PringoApiClient pringoApiClient;
private final SendRepository sendRepository;
private final BulkSendRepository bulkSendRepository;
private final SendResultService resultService;
/**
* Pringo 결과 조회 후 t_send 갱신
@@ -40,47 +39,27 @@ class EmailResultUpdater {
TSendEntity e = opt.get();
try {
PringoReturnResponseDto resp = pringoApiClient.jsonReturn(Long.valueOf(returnKey));
if (resp == null || !resp.isSuccess() || resp.getItemList() == null || resp.getItemList()
if (resp == null || !resp.isSuccess() || resp.itemList() == null || resp.itemList()
.isEmpty()) {
e.setResultCode(NotihubConst.EMAIL_NOT_RESULT);
e.setReportDt(now);
sendRepository.save(e);
resultService.record(e.getSendIdx(), null, SendStatusType.STANDBY,
NotihubConst.EMAIL_NOT_RESULT, now);
return true;
}
PringoReturnItemDto item = resp.getItemList().get(0);
if (item == null || item.getStatus() == null || item.getStatus().isBlank()) {
e.setResultCode(NotihubConst.EMAIL_NOT_RESULT);
e.setReportDt(now);
sendRepository.save(e);
PringoReturnItemDto item = resp.itemList().get(0);
if (item == null || item.status() == null || item.status().isBlank()) {
resultService.record(e.getSendIdx(), null, SendStatusType.STANDBY,
NotihubConst.EMAIL_NOT_RESULT, now);
return true;
}
short resultCode = NumericUtil.safeParseShort(item.getStatus(), NotihubConst.EMAIL_NOT_RESULT);
short resultCode = NumericUtil.safeParseShort(item.status(), NotihubConst.EMAIL_NOT_RESULT);
//resultCode를 대상으로 Success인지 아닌지 판별 필요
SendStatusType sendStatus =
resultCode == NotihubConst.EMAIL_SUCCESS ? SendStatusType.SUCCESS : SendStatusType.FAIL;
e.setSendStatus(sendStatus.getCode());
e.setResultCode(resultCode);
e.setReportDt(DateTimeUtil.parseLocalDateTime(item.getSendTime()));
sendRepository.save(e);
if (e.getBulkSendKey() != null && !e.getBulkSendKey().isBlank()) {
bulkSendRepository.findByBulkSendKey(e.getBulkSendKey()).ifPresent(bulk -> {
if (sendStatus == SendStatusType.SUCCESS) {
bulk.setSuccesCnt(bulk.getSuccesCnt() + 1);
} else {
bulk.setFailCnt(bulk.getFailCnt() + 1);
}
if (bulk.getSendCnt() <= bulk.getSuccesCnt() + bulk.getFailCnt()) {
bulk.setCompleteDt(now);
}
bulkSendRepository.save(bulk);
});
}
resultService.record(e.getSendIdx(), null, sendStatus, resultCode,
DateTimeUtil.parseLocalDateTime(item.sendTime()));
return true;
} catch (Exception ex) {

View File

@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kri.common.feature.web.BusinessException;
import com.kri.notihub.server.common.consts.NotihubConst;
import com.kri.notihub.server.common.external.kakao.KkoTemplateApiClient;
import com.kri.notihub.server.config.KkoTemplateProperties;
import com.kri.notihub.server.dto.template.KkoTemplateDetailDto;
@@ -46,7 +47,7 @@ public class KkoTemplateService {
throw KkoTemplateApiClient.invalidResponse();
}
KkoTemplateSummaryDto template = read(item, KkoTemplateSummaryDto.class);
templates.putIfAbsent(template.getTemplateCode(), template);
templates.putIfAbsent(template.templateCode(), template);
}
int count = nonNegativeInt(root, "totalCount");
if (count > Integer.MAX_VALUE - totalCount) {
@@ -83,35 +84,36 @@ public class KkoTemplateService {
KkoTemplateDetailDto detail = getDetail(template.getKkoTmplatCd());
validateAvailable(detail);
validateBasicTextFormat(detail);
if (detail.getTemplatePreviewMessage() != null
&& detail.getTemplatePreviewMessage().length() > 128) {
if (detail.templatePreviewMessage() != null
&& detail.templatePreviewMessage().length() > 128) {
throw KkoTemplateApiClient.invalidResponse();
}
template.setTmplatBody(detail.getTemplateContent());
template.setTmplatTitle(detail.getTemplatePreviewMessage());
template.setTmplatBody(detail.templateContent());
template.setTmplatTitle(detail.templatePreviewMessage());
template.setSenderKey(properties.getSenderKey());
}
private void validateAvailable(KkoTemplateDetailDto detail) {
if (!"APR".equals(detail.getInspectionStatus()) || !"A".equals(detail.getStatus())
|| !Boolean.FALSE.equals(detail.getBlock()) || !Boolean.FALSE.equals(detail.getDormant())) {
if (!"APR".equals(detail.inspectionStatus())
|| !NotihubConst.KKO_TEMPLATE_AVAILABLE_STATUSES.contains(detail.status())
|| !Boolean.FALSE.equals(detail.block()) || !Boolean.FALSE.equals(detail.dormant())) {
throw BusinessException.badRequest("KKO_TEMPLATE_UNAVAILABLE",
"승인된 정상 상태이며 차단·휴면 상태가 아닌 알림톡 템플릿만 저장할 수 있습니다.");
"승인된 정상·사용준비 상태이며 차단·휴면 상태가 아닌 알림톡 템플릿만 저장할 수 있습니다.");
}
}
private void validateBasicTextFormat(KkoTemplateDetailDto detail) {
// 현재 발송 경로는 기본 텍스트형만 지원한다. 버튼·이미지 등 발송 지원이 추가되면
// 이 저장 제한을 완화하거나 제거하고, 추가 요소의 저장·발송·변수 처리도 함께 검증해야 한다.
if (!"BA".equals(detail.getTemplateMessageType())
|| !"NONE".equals(detail.getTemplateEmphasizeType())
|| hasText(detail.getTemplateExtra()) || hasText(detail.getTemplateImageName())
|| hasText(detail.getTemplateImageUrl()) || hasText(detail.getTemplateTitle())
|| hasText(detail.getTemplateSubtitle()) || hasText(detail.getTemplateHeader())
|| hasValue(detail.getTemplateItemHighlight()) || hasValue(detail.getTemplateItem())
|| hasValue(detail.getTemplateRepresentLink())
|| (detail.getButtons() != null && !detail.getButtons().isEmpty())
|| (detail.getQuickReplies() != null && !detail.getQuickReplies().isEmpty())) {
if (!"BA".equals(detail.templateMessageType())
|| !"NONE".equals(detail.templateEmphasizeType())
|| hasText(detail.templateExtra()) || hasText(detail.templateImageName())
|| hasText(detail.templateImageUrl()) || hasText(detail.templateTitle())
|| hasText(detail.templateSubtitle()) || hasText(detail.templateHeader())
|| hasValue(detail.templateItemHighlight()) || hasValue(detail.templateItem())
|| hasValue(detail.templateRepresentLink())
|| (detail.buttons() != null && !detail.buttons().isEmpty())
|| (detail.quickReplies() != null && !detail.quickReplies().isEmpty())) {
throw BusinessException.badRequest("KKO_TEMPLATE_UNSUPPORTED_FORMAT",
"추가 요소가 없는 기본 텍스트형 알림톡 템플릿만 저장할 수 있습니다.");
}

View File

@@ -56,23 +56,23 @@ public class PhoneVerificationService {
@Transactional
public PhoneVerificationResponseDto verify(PhoneVerificationRequestDto request) {
String normalizedTel = normalizePhoneNumber(request.getSendTel());
String normalizedTel = normalizePhoneNumber(request.sendTel());
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
TPhoneVerificationEntity entity = phoneVerificationRepository
.findByVerificationIdForUpdate(request.getVerificationId())
.findByVerificationIdForUpdate(request.verificationId())
.orElse(null);
if (entity == null || !now.isBefore(entity.getExpireDt())) {
return failed(request.getVerificationId(), normalizedTel);
return failed(request.verificationId(), normalizedTel);
}
boolean matches = entity.getSendTel().equals(normalizedTel)
&& entity.getVerificationCode().equals(request.getVerificationCode());
&& entity.getVerificationCode().equals(request.verificationCode());
if (entity.getStatus().equals(PhoneVerificationStatus.VERIFIED.getCode())) {
return PhoneVerificationResponseDto.of(
request.getVerificationId(),
request.verificationId(),
normalizedTel,
matches,
matches ? entity.getVerifiedDt() : null
@@ -80,17 +80,17 @@ public class PhoneVerificationService {
}
if (entity.getAttemptCount() >= properties.getMaxAttempts()) {
return failed(request.getVerificationId(), normalizedTel);
return failed(request.verificationId(), normalizedTel);
}
if (!matches) {
entity.increaseAttemptCount();
return failed(request.getVerificationId(), normalizedTel);
return failed(request.verificationId(), normalizedTel);
}
entity.markVerified(now);
return PhoneVerificationResponseDto.of(
request.getVerificationId(),
request.verificationId(),
normalizedTel,
true,
now

View File

@@ -50,6 +50,7 @@ import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
@Service
@@ -85,6 +86,7 @@ public class ReportService {
.toList();
}
@Transactional(readOnly = true)
public List<BulkSendInfoDto> getBulkSendList(SendType sendTy, String reqstSvc, String prjctCd,
String regCmpn) {
List<Short> sendTyList = switch (sendTy) {
@@ -93,14 +95,24 @@ public class ReportService {
case KKO_AT -> NotihubConst.KKO_TYPE_CODE_LIST;
};
if (regCmpn == null) {
return bulkSendRepository.findBySendTyInAndReqstSvcAndPrjctCd(sendTyList, reqstSvc, prjctCd)
.stream().map(BulkSendInfoDto::from).toList();
} else {
return bulkSendRepository.findBySendTyInAndReqstSvcAndPrjctCdAndRegCmpn(sendTyList, reqstSvc,
prjctCd, regCmpn)
.stream().map(BulkSendInfoDto::from).toList();
List<TBulkSendEntity> bulks = regCmpn == null
? bulkSendRepository.findBySendTyInAndReqstSvcAndPrjctCd(sendTyList, reqstSvc, prjctCd)
: bulkSendRepository.findBySendTyInAndReqstSvcAndPrjctCdAndRegCmpn(
sendTyList, reqstSvc, prjctCd, regCmpn);
if (bulks.isEmpty()) {
return List.of();
}
Map<String, SendRepository.CancellationCount> counts = sendRepository.countCanceledByBulkSendKeys(
bulks.stream().map(TBulkSendEntity::getBulkSendKey).toList()).stream()
.collect(Collectors.toMap(SendRepository.CancellationCount::getBulkSendKey,
Function.identity()));
return bulks.stream().map(bulk -> {
BulkSendInfoDto dto = BulkSendInfoDto.from(bulk);
SendRepository.CancellationCount count = counts.get(bulk.getBulkSendKey());
dto.applyCanceledCount(count == null ? 0 : count.getCanceledCount(),
count == null ? 0 : count.getTargetCount());
return dto;
}).toList();
}
public PageResponseDto<SendResultInfoDto> getBulkSendDetail(String bulkSendKey,
@@ -177,15 +189,15 @@ public class ReportService {
public List<SendResultSummaryResponseDto> getSendResultSummary(
SendResultSummaryRequestDto req) {
SendResultSummaryRequestDto condition = req != null ? req : new SendResultSummaryRequestDto();
SendResultSummaryRequestDto condition = req != null ? req : SendResultSummaryRequestDto.builder().build();
List<SendResultSummaryDto> summaries = sendRepository.findSendResultSummary(
normalize(condition.getBulkSendKey()),
normalize(condition.getItrntPrjctCd()),
normalize(condition.getReqstSvc()),
normalize(condition.getPrjctCd()),
condition.getSendStartDt(),
condition.getSendEndDt()
normalize(condition.bulkSendKey()),
normalize(condition.itrntPrjctCd()),
normalize(condition.reqstSvc()),
normalize(condition.prjctCd()),
condition.sendStartDt(),
condition.sendEndDt()
);
Map<SendPriceKey, TUnitPriceEntity> unitPriceMap = unitPriceRepository.findByUseTrue()
@@ -216,9 +228,9 @@ public class ReportService {
public List<SendCostSummaryWithItrntPrjctDto> getSendCostSummaryWithItrntPrjct(
SendCostSummaryRequestDto req
) {
SendCostSummaryRequestDto condition = req != null ? req : new SendCostSummaryRequestDto();
LocalDateTime startDt = condition.getStartDt().atStartOfDay();
LocalDateTime endDt = condition.getEndDt().plusDays(1).atStartOfDay();
SendCostSummaryRequestDto condition = req != null ? req : SendCostSummaryRequestDto.builder().build();
LocalDateTime startDt = condition.startDt().atStartOfDay();
LocalDateTime endDt = condition.endDt().plusDays(1).atStartOfDay();
List<SendCostSummaryWithItrntPrjctDto> summaries =
sendRepository.findSendCostSummaryWithItrntPrjct(
@@ -234,9 +246,9 @@ public class ReportService {
Map<String, IntranetProjectBaseInfoDto> projectInfoMap =
intranetApiClient.getProjectWithPChildSn(itrntPrjctCds).stream()
.filter(project -> StringUtils.hasText(project.getChildSn()))
.filter(project -> StringUtils.hasText(project.childSn()))
.collect(Collectors.toMap(
IntranetProjectBaseInfoDto::getChildSn,
IntranetProjectBaseInfoDto::childSn,
Function.identity(),
(left, right) -> left
));
@@ -309,6 +321,7 @@ public class ReportService {
.successCount(successCount)
.failCount(failCount)
.standByCount(standByCount)
.canceledCount(summary != null ? summary.getCanceledCount() : 0L)
.totalCount(totalCount)
.price(price)
.cost(cost)
@@ -322,6 +335,7 @@ public class ReportService {
.successCount(nullToZero(left.getSuccessCount()) + nullToZero(right.getSuccessCount()))
.failCount(nullToZero(left.getFailCount()) + nullToZero(right.getFailCount()))
.standByCount(nullToZero(left.getStandByCount()) + nullToZero(right.getStandByCount()))
.canceledCount(nullToZero(left.getCanceledCount()) + nullToZero(right.getCanceledCount()))
.totalCount(nullToZero(left.getTotalCount()) + nullToZero(right.getTotalCount()))
.build();
}

View File

@@ -0,0 +1,148 @@
package com.kri.notihub.server.service;
import com.kri.common.feature.datetime.DateTimeUtil;
import com.kri.common.feature.web.BusinessException;
import com.kri.common.feature.web.RequestUserContext;
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.dto.send.SendCancelResponseDto;
import com.kri.notihub.server.persistence.entity.TBulkSendEntity;
import com.kri.notihub.server.persistence.entity.TSendEntity;
import com.kri.notihub.server.persistence.repository.BizMsgRepository;
import com.kri.notihub.server.persistence.repository.BulkSendRepository;
import com.kri.notihub.server.persistence.repository.SendRepository;
import jakarta.persistence.EntityManager;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Isolation;
@Service
@RequiredArgsConstructor
public class SendCancelService {
private final SendRepository sendRepository;
private final BulkSendRepository bulkSendRepository;
private final BizMsgRepository bizMsgRepository;
private final EntityManager entityManager;
@Transactional(isolation = Isolation.READ_COMMITTED)
public SendCancelResponseDto cancelSingle(Long sendIdx, RequestUserContext ctx) {
validateUser(ctx);
// 벌크 -> 상세 순서를 등록/결과 반영과 공유한다.
TSendEntity snapshot = sendRepository.findById(sendIdx).orElseThrow(this::notFound);
authorize(ctx, snapshot.getRegCmpn());
String bulkKey = snapshot.getBulkSendKey();
entityManager.detach(snapshot);
TBulkSendEntity bulk = bulkKey == null ? null
: bulkSendRepository.findForUpdate(bulkKey).orElseThrow(this::notFound);
TSendEntity send = sendRepository.findForUpdate(sendIdx).orElseThrow(this::notFound);
authorize(ctx, send.getRegCmpn());
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
int result = cancel(send, ctx.getUserId(), now);
sendRepository.flush();
if (bulk != null) {
completeBulkIfSettled(bulk, now);
}
return response(1, result == 1 ? 1 : 0, result == 2 ? 1 : 0);
}
@Transactional(isolation = Isolation.READ_COMMITTED)
public SendCancelResponseDto cancelBulk(String bulkSendKey, RequestUserContext ctx) {
validateUser(ctx);
TBulkSendEntity bulk = bulkSendRepository.findForUpdate(bulkSendKey)
.orElseThrow(this::notFound);
authorize(ctx, bulk.getRegCmpn());
if (!Boolean.TRUE.equals(bulk.getResve())) {
throw BusinessException.badRequest("SEND_CANCEL_NOT_RESERVED", "예약 발송만 취소할 수 있습니다.");
}
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
if (bulk.getCancelDt() == null) {
bulk.setCancelUser(ctx.getUserId());
bulk.setCancelDt(now);
}
long target = 0, canceled = 0, already = 0, afterIdx = 0;
while (true) {
List<Long> ids = sendRepository.findBulkSendIds(
bulkSendKey, afterIdx, PageRequest.of(0, 500));
if (ids.isEmpty()) {
break;
}
for (Long id : ids) {
TSendEntity send = sendRepository.findForUpdate(id).orElseThrow(this::notFound);
authorize(ctx, send.getRegCmpn());
int result = cancel(send, ctx.getUserId(), now);
target++;
canceled += result == 1 ? 1 : 0;
already += result == 2 ? 1 : 0;
sendRepository.flush();
entityManager.detach(send);
afterIdx = id;
}
}
completeBulkIfSettled(bulk, now);
return response(target, canceled, already);
}
private int cancel(TSendEntity send, String user, LocalDateTime now) {
if (Objects.equals(send.getSendStatus(), SendStatusType.CANCELED.getCode())) {
return 2;
}
if (!send.isResve() || !Objects.equals(send.getSendStatus(), SendStatusType.STANDBY.getCode())
|| send.getCancelDt() != null) {
return 0;
}
if (Objects.equals(send.getSendTy(), SendType.EMAIL.getCode())) {
if (!Objects.equals(send.getResultCode(), NotihubConst.EMAIL_STANDBY)) {
return 0;
}
} else if (NotihubConst.SMS_TYPE_CODE_LIST.contains(send.getSendTy())
|| NotihubConst.KKO_TYPE_CODE_LIST.contains(send.getSendTy())) {
if (bizMsgRepository.deleteWaiting(send.getCmid()) != 1) {
return 0;
}
} else {
return 0;
}
send.setSendStatus(SendStatusType.CANCELED.getCode());
send.setResultCode(Objects.equals(send.getSendTy(), SendType.EMAIL.getCode())
? NotihubConst.EMAIL_CANCELED : NotihubConst.BIZPPURIO_CANCELED);
send.setCancelUser(user);
send.setCancelDt(now);
return 1;
}
private void completeBulkIfSettled(TBulkSendEntity bulk, LocalDateTime now) {
long canceled = sendRepository.countByBulkSendKeyAndSendStatus(
bulk.getBulkSendKey(), SendStatusType.CANCELED.getCode());
bulk.completeIfSettled(canceled, now);
}
private SendCancelResponseDto response(long target, long canceled, long already) {
return new SendCancelResponseDto(target, canceled, already, target - canceled - already);
}
private void validateUser(RequestUserContext ctx) {
if (ctx == null || ctx.getUserId() == null || ctx.getUserId().isBlank()
|| ctx.getUserId().length() > 32 || ctx.getUserRole() == null) {
throw BusinessException.forbidden("SEND_CANCEL_FORBIDDEN", "취소 처리자 정보가 필요합니다.");
}
}
private void authorize(RequestUserContext ctx, String company) {
if (ctx.getUserRole() >= NotihubConst.OUTSOURCE_USER_ROLE
&& (ctx.getUserCmpn() == null || ctx.getUserCmpn().isBlank()
|| !Objects.equals(ctx.getUserCmpn(), company))) {
throw BusinessException.forbidden("SEND_CANCEL_FORBIDDEN", "취소 권한이 없습니다.");
}
}
private BusinessException notFound() {
return BusinessException.notFound("SEND_CANCEL_TARGET_NOT_FOUND", "취소 대상을 찾을 수 없습니다.");
}
}

View File

@@ -1,13 +1,20 @@
package com.kri.notihub.server.service;
import com.kri.common.feature.datetime.DateTimeUtil;
import com.kri.notihub.server.common.consts.NotihubConst;
import com.kri.notihub.server.common.enums.ChannelType;
import com.kri.notihub.server.common.enums.SendStatusType;
import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.common.external.pringo.PringoApiClient;
import com.kri.notihub.server.persistence.entity.TSendEntity;
import com.kri.notihub.server.persistence.jdbc.SendBulkJdbcWriter;
import com.kri.notihub.server.persistence.repository.BulkSendRepository;
import com.kri.notihub.server.persistence.repository.SendRepository;
import com.kri.notihub.server.persistence.repository.TemplateRepository;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Slf4j
@Service
@@ -34,4 +41,18 @@ public class SendEmailService extends AbstractPringoSendService {
protected ChannelType defaultChannelType() {
return ChannelType.EMAIL;
}
@Transactional
public TSendEntity claimReservedEmail(Long sendIdx) {
TSendEntity send = sendRepository.findForUpdate(sendIdx).orElse(null);
if (send == null || !send.isResve() || send.getCancelDt() != null
|| !Objects.equals(send.getSendTy(), SendType.EMAIL.getCode())
|| !Objects.equals(send.getSendStatus(), SendStatusType.STANDBY.getCode())
|| !Objects.equals(send.getResultCode(), NotihubConst.EMAIL_STANDBY)
|| send.getSendDt().isAfter(DateTimeUtil.nowKstLocalDateTime())) {
return null;
}
send.setResultCode(NotihubConst.EMAIL_SENDING);
return send;
}
}

View File

@@ -0,0 +1,71 @@
package com.kri.notihub.server.service;
import com.kri.common.feature.datetime.DateTimeUtil;
import com.kri.notihub.server.common.enums.SendStatusType;
import com.kri.notihub.server.persistence.entity.TBulkSendEntity;
import com.kri.notihub.server.persistence.entity.TSendEntity;
import com.kri.notihub.server.persistence.repository.BulkSendRepository;
import com.kri.notihub.server.persistence.repository.SendRepository;
import jakarta.persistence.EntityManager;
import java.time.LocalDateTime;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Isolation;
@Service
@RequiredArgsConstructor
public class SendResultService {
private final SendRepository sendRepository;
private final BulkSendRepository bulkSendRepository;
private final EntityManager entityManager;
// 벌크 잠금 대기 전에 읽은 스냅샷으로 취소 건수를 집계하지 않도록 한다.
@Transactional(isolation = Isolation.READ_COMMITTED)
public TSendEntity record(Long sendIdx, String cmid, SendStatusType status,
short resultCode, LocalDateTime reportDt) {
TSendEntity snapshot = sendRepository.findById(sendIdx).orElse(null);
if (snapshot == null) {
return null;
}
String bulkKey = snapshot.getBulkSendKey();
entityManager.detach(snapshot);
TBulkSendEntity bulk = bulkKey == null ? null
: bulkSendRepository.findForUpdate(bulkKey).orElseThrow();
TSendEntity send = sendRepository.findForUpdate(sendIdx).orElseThrow();
boolean canceled = Objects.equals(send.getSendStatus(), SendStatusType.CANCELED.getCode());
if (!canceled && !Objects.equals(send.getSendStatus(), SendStatusType.STANDBY.getCode())) {
return null;
}
// 취소 후에는 실제 최종 결과만 반영하고 취소 이력은 유지한다.
if (canceled && status == SendStatusType.STANDBY) {
return null;
}
send.setSendStatus(status.getCode());
send.setResultCode(resultCode);
if (cmid != null) {
send.setCmid(cmid);
}
if (reportDt != null) {
send.setReportDt(reportDt);
}
sendRepository.flush();
if (bulk != null && (status == SendStatusType.SUCCESS || status == SendStatusType.FAIL)) {
if (status == SendStatusType.SUCCESS) {
bulk.setSuccesCnt(value(bulk.getSuccesCnt()) + 1);
} else {
bulk.setFailCnt(value(bulk.getFailCnt()) + 1);
}
long canceledCount = sendRepository.countByBulkSendKeyAndSendStatus(
bulk.getBulkSendKey(), SendStatusType.CANCELED.getCode());
bulk.completeIfSettled(canceledCount, DateTimeUtil.nowKstLocalDateTime());
}
return send;
}
private int value(Integer count) {
return count == null ? 0 : count;
}
}