260212_01_DOC: 프로젝트 전체에 구글 java 스타일 적용

This commit is contained in:
2026-02-12 11:24:10 +09:00
parent 6bd9b0902b
commit 774188088b
70 changed files with 3735 additions and 3388 deletions

View File

@@ -11,23 +11,23 @@ import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class NotihubServerApplication {
public static void main(String[] args) {
SpringApplication.run(NotihubServerApplication.class, args);
}
public static void main(String[] args) {
SpringApplication.run(NotihubServerApplication.class, args);
}
@Bean
ApplicationRunner dsCheck(ApplicationContext ctx) {
return args -> {
String[] names = ctx.getBeanNamesForType(javax.sql.DataSource.class);
log.info("DataSource beans = {}", java.util.Arrays.toString(names));
for (String n : names) {
Object ds = ctx.getBean(n);
log.info(" - {} = {}", n, ds.getClass().getName());
if (ds instanceof com.zaxxer.hikari.HikariDataSource hk) {
log.info(" jdbcUrl=" + hk.getJdbcUrl());
log.info(" driver=" + hk.getDriverClassName());
}
}
};
}
@Bean
ApplicationRunner dsCheck(ApplicationContext ctx) {
return args -> {
String[] names = ctx.getBeanNamesForType(javax.sql.DataSource.class);
log.info("DataSource beans = {}", java.util.Arrays.toString(names));
for (String n : names) {
Object ds = ctx.getBean(n);
log.info(" - {} = {}", n, ds.getClass().getName());
if (ds instanceof com.zaxxer.hikari.HikariDataSource hk) {
log.info(" jdbcUrl=" + hk.getJdbcUrl());
log.info(" driver=" + hk.getDriverClassName());
}
}
};
}
}

View File

@@ -1,38 +1,32 @@
package com.kri.notihub.server.common.consts;
import com.kri.notihub.server.common.enums.SendType;
import java.util.List;
public final class NotihubConst {
private NotihubConst() {}
public static final int OUTSOURCE_USER_ROLE = 4000;
public static final int CHUNK_SIZE = 5_000;
public static final int INSERT_CHUNK_SIZE = 1_000;
public static final int ROW_WINDOW = 500;
public static final short EMAIL_RESULT_SEARCH_DELAY = 500;
public static final short EMAIL_DELAY = 500;
public static final short DELAY_MAX_MS = (short)5_000; // 필요시 조정
public static final List<SendType> MOBILE_TYPE_LIST = List.of(SendType.SMS, SendType.LMS_MMS);
public static final List<Short> MOBILE_TYPE_CODE_LIST = List.of(SendType.SMS.getCode(), SendType.LMS_MMS.getCode());
public static final List<Short> EMAIL_TYPE_CODE_LIST = List.of(SendType.EMAIL.getCode());
public static final String EMAIL_RESERVATION_PREFIX = "RESERVATION_";
public static final short EMAIL_STANDBY = 100;
public static final short EMAIL_PENDING = (short) 111; // 발송요청은 성공했으나 json_return 미조회
public static final short EMAIL_SEND_FAIL = (short) 109; // 발송요청 실패(또는 return_key 미수신)
public static final short EMAIL_NOT_RESULT = (short) 119; // json_return 조회 실패/결과없음(최종상태 확보 실패)
public static final short EMAIL_SUCCESS = 250;
public static final short SMS_STANDBY = 4000;
public static final short SMS_SUCCESS = 4100;
public static final short SMS_NOT_RESULT = 9999;
public static final short LMS_MMS_STANDBY = 6000;
public static final short LMS_MMS_SUCCESS = 6600;
public static final int OUTSOURCE_USER_ROLE = 4000;
public static final int CHUNK_SIZE = 5_000;
public static final int INSERT_CHUNK_SIZE = 1_000;
public static final int ROW_WINDOW = 500;
public static final short EMAIL_RESULT_SEARCH_DELAY = 500;
public static final short EMAIL_DELAY = 500;
public static final short DELAY_MAX_MS = (short) 5_000; // 필요시 조정
public static final List<SendType> MOBILE_TYPE_LIST = List.of(SendType.SMS, SendType.LMS_MMS);
public static final List<Short> MOBILE_TYPE_CODE_LIST = List.of(SendType.SMS.getCode(),
SendType.LMS_MMS.getCode());
public static final List<Short> EMAIL_TYPE_CODE_LIST = List.of(SendType.EMAIL.getCode());
public static final String EMAIL_RESERVATION_PREFIX = "RESERVATION_";
public static final short EMAIL_STANDBY = 100;
public static final short EMAIL_PENDING = (short) 111; // 발송요청은 성공했으나 json_return 미조회
public static final short EMAIL_SEND_FAIL = (short) 109; // 발송요청 실패(또는 return_key 미수신)
public static final short EMAIL_NOT_RESULT = (short) 119; // json_return 조회 실패/결과없음(최종상태 확보 실패)
public static final short EMAIL_SUCCESS = 250;
public static final short SMS_STANDBY = 4000;
public static final short SMS_SUCCESS = 4100;
public static final short SMS_NOT_RESULT = 9999;
public static final short LMS_MMS_STANDBY = 6000;
public static final short LMS_MMS_SUCCESS = 6600;
private NotihubConst() {
}
}

View File

@@ -10,21 +10,25 @@ import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public enum ChannelType implements CodeEnum<Short> {
EMAIL((short) 1),
SMS((short) 2);
EMAIL((short) 1),
SMS((short) 2);
private final Short code;
private final Short code;
ChannelType(CodeEnum<Short> source) {
this.code = source.getCode();
ChannelType(CodeEnum<Short> source) {
this.code = source.getCode();
}
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static ChannelType fromCode(Short code) {
if (code == null) {
return null;
}
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static ChannelType fromCode(Short code) {
if (code == null) return null;
for (ChannelType s : values()) {
if (s.code == code) return s;
}
throw new IllegalArgumentException("Unknown ChannelType code: " + code);
for (ChannelType s : values()) {
if (s.code == code) {
return s;
}
}
throw new IllegalArgumentException("Unknown ChannelType code: " + code);
}
}

View File

@@ -9,17 +9,21 @@ import lombok.RequiredArgsConstructor;
@Getter(onMethod_ = @JsonValue)
@RequiredArgsConstructor
public enum SendCorpType implements CodeEnum<Short> {
PRINGO((short) 1001),
BIZ_PPURIO((short) 2001);
PRINGO((short) 1001),
BIZ_PPURIO((short) 2001);
private final Short code;
private final Short code;
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static SendCorpType fromCode(Short code) {
if (code == null) return null;
for (SendCorpType s : values()) {
if (s.code == code) return s;
}
throw new IllegalArgumentException("Unknown SendCorpType code: " + code);
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static SendCorpType fromCode(Short code) {
if (code == null) {
return null;
}
for (SendCorpType s : values()) {
if (s.code == code) {
return s;
}
}
throw new IllegalArgumentException("Unknown SendCorpType code: " + code);
}
}

View File

@@ -9,16 +9,20 @@ import lombok.RequiredArgsConstructor;
@Getter(onMethod_ = @JsonValue)
@RequiredArgsConstructor
public enum SendEmailType implements CodeEnum<Short> {
EMAIL((short) 11);
EMAIL((short) 11);
private final Short code;
private final Short code;
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static SendEmailType fromCode(Short code) {
if (code == null) return null;
for (SendEmailType s : values()) {
if (s.code == code) return s;
}
throw new IllegalArgumentException("Unknown SendEmailType code: " + code);
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static SendEmailType fromCode(Short code) {
if (code == null) {
return null;
}
for (SendEmailType s : values()) {
if (s.code == code) {
return s;
}
}
throw new IllegalArgumentException("Unknown SendEmailType code: " + code);
}
}

View File

@@ -8,18 +8,22 @@ import lombok.RequiredArgsConstructor;
@Getter(onMethod_ = @JsonValue)
@RequiredArgsConstructor
public enum SendSmsType implements CodeEnum<Short> {
SMS((short) 21),
LMS_MMS((short) 22);
public enum SendSmsType implements CodeEnum<Short> {
SMS((short) 21),
LMS_MMS((short) 22);
private final Short code;
private final Short code;
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static SendSmsType fromCode(Short code) {
if (code == null) return null;
for (SendSmsType s : values()) {
if (s.code == code) return s;
}
throw new IllegalArgumentException("Unknown SendSmsType code: " + code);
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static SendSmsType fromCode(Short code) {
if (code == null) {
return null;
}
for (SendSmsType s : values()) {
if (s.code == code) {
return s;
}
}
throw new IllegalArgumentException("Unknown SendSmsType code: " + code);
}
}

View File

@@ -10,22 +10,26 @@ import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public enum SendStatusType implements CodeEnum<Short> {
STANDBY((short) 0),
SUCCESS((short) 1),
FAIL((short) 9);
STANDBY((short) 0),
SUCCESS((short) 1),
FAIL((short) 9);
private final Short code;
private final Short code;
SendStatusType(CodeEnum<Short> source) {
this.code = source.getCode();
SendStatusType(CodeEnum<Short> source) {
this.code = source.getCode();
}
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static SendStatusType fromCode(Short code) {
if (code == null) {
return null;
}
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static SendStatusType fromCode(Short code) {
if (code == null) return null;
for (SendStatusType s : values()) {
if (s.code == code) return s;
}
throw new IllegalArgumentException("Unknown SendStatusType code: " + code);
for (SendStatusType s : values()) {
if (s.code == code) {
return s;
}
}
throw new IllegalArgumentException("Unknown SendStatusType code: " + code);
}
}

View File

@@ -9,22 +9,26 @@ import lombok.RequiredArgsConstructor;
@Getter(onMethod_ = @JsonValue)
@RequiredArgsConstructor
public enum SendType implements CodeEnum<Short> {
EMAIL(SendEmailType.EMAIL),
SMS(SendSmsType.SMS),
LMS_MMS(SendSmsType.LMS_MMS);
EMAIL(SendEmailType.EMAIL),
SMS(SendSmsType.SMS),
LMS_MMS(SendSmsType.LMS_MMS);
private final Short code;
private final Short code;
SendType(CodeEnum<Short> source) {
this.code = source.getCode();
SendType(CodeEnum<Short> source) {
this.code = source.getCode();
}
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static SendType fromCode(Short code) {
if (code == null) {
return null;
}
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static SendType fromCode(Short code) {
if (code == null) return null;
for (SendType s : values()) {
if (s.code == code) return s;
}
throw new IllegalArgumentException("Unknown SendType code: " + code);
for (SendType s : values()) {
if (s.code == code) {
return s;
}
}
throw new IllegalArgumentException("Unknown SendType code: " + code);
}
}

View File

@@ -8,9 +8,9 @@ import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public enum TemplateEventType implements CodeEnum<Short> {
CREATE_TEMPLATE((short) 0), // 프로젝트 생성
UPDATE_TEMPLATE((short) 1), // 프로젝트 수정
DELETE_TEMPLATE((short) 2); // 프로젝트 삭제
CREATE_TEMPLATE((short) 0), // 프로젝트 생성
UPDATE_TEMPLATE((short) 1), // 프로젝트 수정
DELETE_TEMPLATE((short) 2); // 프로젝트 삭제
private final Short code;
private final Short code;
}

View File

@@ -6,160 +6,167 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kri.common.http.ExternalApiClient;
import com.kri.common.http.ExternalApiResponse;
import com.kri.notihub.server.common.external.pringo.dto.*;
import com.kri.notihub.server.common.external.pringo.dto.PringoJsonReturnErrorDto;
import com.kri.notihub.server.common.external.pringo.dto.PringoJsonReturnItemDto;
import com.kri.notihub.server.common.external.pringo.dto.PringoJsonReturnRequestDto;
import com.kri.notihub.server.common.external.pringo.dto.PringoJsonReturnResponseDto;
import com.kri.notihub.server.common.external.pringo.dto.PringoJsonSendRequestDto;
import com.kri.notihub.server.common.external.pringo.dto.PringoJsonSendResponseDto;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
@RequiredArgsConstructor
public class PringoApiClient {
@Value("${kri.api.pringo.url}")
private String pringoBaseUrl;
@Value("${kri.api.pringo.apiKey}")
private String apiKey;
private final ExternalApiClient externalApiClient = new ExternalApiClient();
private final ObjectMapper objectMapper = new ObjectMapper();
@Value("${kri.api.pringo.url}")
private String pringoBaseUrl;
@Value("${kri.api.pringo.apiKey}")
private String apiKey;
@Value("${kri.api.pringo.template-id}")
private String templateId;
@Value("${kri.api.pringo.template-id}")
private String templateId;
/**
* Pringo 자동메일 Json 발송 POST {pringoBaseUrl}/json-send
*/
public PringoJsonSendResponseDto jsonSend(PringoJsonSendRequestDto request) {
String url = String.format("%s/json-send", pringoBaseUrl);
private final ExternalApiClient externalApiClient = new ExternalApiClient();
private final ObjectMapper objectMapper = new ObjectMapper();
// defaults 주입
request.applyDefaults(apiKey, templateId);
/**
* Pringo 자동메일 Json 발송
* POST {pringoBaseUrl}/json-send
*/
public PringoJsonSendResponseDto jsonSend(PringoJsonSendRequestDto request) {
String url = String.format("%s/json-send", pringoBaseUrl);
// 필수값 검증(Pringo 실패 케이스 사전 차단)
request.validateRequired();
// defaults 주입
request.applyDefaults(apiKey, templateId);
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Accept", "application/json");
// 필수값 검증(Pringo 실패 케이스 사전 차단)
request.validateRequired();
try {
String body = objectMapper.writeValueAsString(request);
ExternalApiResponse response = externalApiClient.post(url, headers, body);
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Accept", "application/json");
return objectMapper.readValue(response.getBody(), PringoJsonSendResponseDto.class);
} catch (JsonProcessingException e) {
// 프로젝트 스타일에 맞게 BusinessException으로 바꿔도 됨
throw new IllegalStateException("Failed to call Pringo json-send API.", e);
}
}
try {
String body = objectMapper.writeValueAsString(request);
ExternalApiResponse response = externalApiClient.post(url, headers, body);
/**
* 편의 메서드: vars 포함해서 바로 발송
*/
public PringoJsonSendResponseDto jsonSend(
String sender,
String senderName,
String recipient,
String recipientName,
String subject,
String htmlBody,
Map<String, Object> vars
) {
PringoJsonSendRequestDto req = PringoJsonSendRequestDto.builder()
.sender(sender)
.senderName(senderName)
.recipient(recipient)
.recipientName(recipientName)
.subject(subject)
.body(htmlBody)
.build();
return objectMapper.readValue(response.getBody(), PringoJsonSendResponseDto.class);
} catch (JsonProcessingException e) {
// 프로젝트 스타일에 맞게 BusinessException으로 바꿔도 됨
throw new IllegalStateException("Failed to call Pringo json-send API.", e);
}
if (vars != null) {
vars.forEach(req::putVar);
}
/**
* 편의 메서드: vars 포함해서 바로 발송
*/
public PringoJsonSendResponseDto jsonSend(
String sender,
String senderName,
String recipient,
String recipientName,
String subject,
String htmlBody,
Map<String, Object> vars
) {
PringoJsonSendRequestDto req = PringoJsonSendRequestDto.builder()
.sender(sender)
.senderName(senderName)
.recipient(recipient)
.recipientName(recipientName)
.subject(subject)
.body(htmlBody)
.build();
return jsonSend(req);
}
if (vars != null) {
vars.forEach(req::putVar);
}
/**
* Pringo 자동메일 Json 조회 POST {pringoBaseUrl}/json-return
*/
public PringoJsonReturnResponseDto jsonReturn(PringoJsonReturnRequestDto request) {
String url = String.format("%s/json-return", pringoBaseUrl);
return jsonSend(req);
request.applyDefaults(apiKey, templateId);
request.validateRequired();
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Accept", "application/json");
try {
String body = objectMapper.writeValueAsString(request);
ExternalApiResponse response = externalApiClient.post(url, headers, body);
// 응답은 항상 배열 형태
JsonNode root = objectMapper.readTree(response.getBody());
if (root == null || !root.isArray() || root.size() == 0) {
// 비정상/빈 응답 방어
return PringoJsonReturnResponseDto.builder()
.itemList(List.of())
.error(PringoJsonReturnErrorDtoBuilder.noResultFallback())
.build();
}
JsonNode first = root.get(0);
// 실패 형태 판별: result/msg가 있으면 오류 DTO로 본다
if (first.has("result") && first.has("msg")) {
PringoJsonReturnErrorDto err = objectMapper.convertValue(first,
PringoJsonReturnErrorDto.class);
return PringoJsonReturnResponseDto.builder()
.itemList(List.of())
.error(err)
.build();
}
// 성공 형태: row 리스트
List<PringoJsonReturnItemDto> items = objectMapper.convertValue(
root, new TypeReference<List<PringoJsonReturnItemDto>>() {
}
);
return PringoJsonReturnResponseDto.builder()
.itemList(items)
.error(null)
.build();
} catch (JsonProcessingException e) {
throw new IllegalStateException("Failed to call Pringo json-return API.", e);
}
}
/**
* Pringo 자동메일 Json 조회
* POST {pringoBaseUrl}/json-return
*/
public PringoJsonReturnResponseDto jsonReturn(PringoJsonReturnRequestDto request) {
String url = String.format("%s/json-return", pringoBaseUrl);
/**
* 편의 메서드: returnKey만으로 조회
*/
public PringoJsonReturnResponseDto jsonReturn(String returnKey) {
PringoJsonReturnRequestDto req = PringoJsonReturnRequestDto.builder()
.returnKey(returnKey)
.build();
return jsonReturn(req);
}
request.applyDefaults(apiKey, templateId);
request.validateRequired();
/**
* 편의 메서드: long도 지원
*/
public PringoJsonReturnResponseDto jsonReturn(long returnKey) {
return jsonReturn(Long.toString(returnKey));
}
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Accept", "application/json");
// 내부 fallback builder (원하시면 별도 클래스로 분리)
private static final class PringoJsonReturnErrorDtoBuilder {
try {
String body = objectMapper.writeValueAsString(request);
ExternalApiResponse response = externalApiClient.post(url, headers, body);
// 응답은 항상 배열 형태
JsonNode root = objectMapper.readTree(response.getBody());
if (root == null || !root.isArray() || root.size() == 0) {
// 비정상/빈 응답 방어
return PringoJsonReturnResponseDto.builder()
.itemList(List.of())
.error(PringoJsonReturnErrorDtoBuilder.noResultFallback())
.build();
}
JsonNode first = root.get(0);
// 실패 형태 판별: result/msg가 있으면 오류 DTO로 본다
if (first.has("result") && first.has("msg")) {
PringoJsonReturnErrorDto err = objectMapper.convertValue(first, PringoJsonReturnErrorDto.class);
return PringoJsonReturnResponseDto.builder()
.itemList(List.of())
.error(err)
.build();
}
// 성공 형태: row 리스트
List<PringoJsonReturnItemDto> items = objectMapper.convertValue(
root, new TypeReference<List<PringoJsonReturnItemDto>>() {}
);
return PringoJsonReturnResponseDto.builder()
.itemList(items)
.error(null)
.build();
} catch (JsonProcessingException e) {
throw new IllegalStateException("Failed to call Pringo json-return API.", e);
}
}
/** 편의 메서드: returnKey만으로 조회 */
public PringoJsonReturnResponseDto jsonReturn(String returnKey) {
PringoJsonReturnRequestDto req = PringoJsonReturnRequestDto.builder()
.returnKey(returnKey)
.build();
return jsonReturn(req);
}
/** 편의 메서드: long도 지원 */
public PringoJsonReturnResponseDto jsonReturn(long returnKey) {
return jsonReturn(Long.toString(returnKey));
}
// 내부 fallback builder (원하시면 별도 클래스로 분리)
private static final class PringoJsonReturnErrorDtoBuilder {
static PringoJsonReturnErrorDto noResultFallback() {
PringoJsonReturnErrorDto e = new PringoJsonReturnErrorDto();
e.setResult("0");
e.setMsg("응답이 비어 있습니다.");
return e;
}
static PringoJsonReturnErrorDto noResultFallback() {
PringoJsonReturnErrorDto e = new PringoJsonReturnErrorDto();
e.setResult("0");
e.setMsg("응답이 비어 있습니다.");
return e;
}
}
}

View File

@@ -8,17 +8,19 @@ import lombok.Setter;
@Setter
public class PringoJsonReturnErrorDto {
private String type;
private String type;
@JsonProperty("typeAlias")
private String typeAlias;
@JsonProperty("typeAlias")
private String typeAlias;
/** 예: "0" */
private String result;
/**
* 예: "0"
*/
private String result;
private String msg;
private String msg;
public boolean isNoResult() {
return "0".equals(result);
}
public boolean isNoResult() {
return "0".equals(result);
}
}

View File

@@ -9,28 +9,36 @@ import lombok.Setter;
@Setter
public class PringoJsonReturnItemDto {
@JsonProperty("No")
private Integer no;
@JsonProperty("No")
private Integer no;
@JsonProperty("return_key")
private Long returnKey;
@JsonProperty("return_key")
private Long returnKey;
@JsonProperty("email")
private String email;
@JsonProperty("email")
private String email;
/** "O" / "X" */
@JsonProperty("open")
private String open;
/**
* "O" / "X"
*/
@JsonProperty("open")
private String open;
/** "O" / "X" */
@JsonProperty("send_success")
private String sendSuccess;
/**
* "O" / "X"
*/
@JsonProperty("send_success")
private String sendSuccess;
/** "yyyy-MM-dd HH:mm:ss" (문자열로 보관 권장) */
@JsonProperty("send_time")
private 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")
private String status;
}

View File

@@ -1,7 +1,11 @@
package com.kri.notihub.server.common.external.pringo.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@@ -10,23 +14,33 @@ import lombok.*;
@AllArgsConstructor
public class PringoJsonReturnRequestDto {
@JsonProperty("api_key")
private String apiKey;
@JsonProperty("api_key")
private String apiKey;
@JsonProperty("template_id")
private String templateId;
@JsonProperty("template_id")
private String templateId;
@JsonProperty("return_key")
private String returnKey;
@JsonProperty("return_key")
private String returnKey;
public void applyDefaults(String defaultApiKey, String defaultTemplateId) {
if (this.apiKey == null || this.apiKey.isBlank()) this.apiKey = defaultApiKey;
if (this.templateId == null || this.templateId.isBlank()) this.templateId = defaultTemplateId;
public void applyDefaults(String defaultApiKey, String defaultTemplateId) {
if (this.apiKey == null || this.apiKey.isBlank()) {
this.apiKey = defaultApiKey;
}
public void validateRequired() {
if (apiKey == null || apiKey.isBlank()) throw new IllegalArgumentException("api_key is required.");
if (templateId == null || templateId.isBlank()) throw new IllegalArgumentException("template_id is required.");
if (returnKey == null || returnKey.isBlank()) throw new IllegalArgumentException("return_key is required.");
if (this.templateId == null || this.templateId.isBlank()) {
this.templateId = defaultTemplateId;
}
}
public void validateRequired() {
if (apiKey == null || apiKey.isBlank()) {
throw new IllegalArgumentException("api_key is required.");
}
if (templateId == null || templateId.isBlank()) {
throw new IllegalArgumentException("template_id is required.");
}
if (returnKey == null || returnKey.isBlank()) {
throw new IllegalArgumentException("return_key is required.");
}
}
}

View File

@@ -1,8 +1,11 @@
package com.kri.notihub.server.common.external.pringo.dto;
import lombok.*;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@@ -11,17 +14,21 @@ import java.util.List;
@AllArgsConstructor
public class PringoJsonReturnResponseDto {
/** 조회 결과 row들(성공 시) */
private List<PringoJsonReturnItemDto> itemList;
/**
* 조회 결과 row들(성공 시)
*/
private List<PringoJsonReturnItemDto> itemList;
/** 조회 실패/없음(실패 시) */
private PringoJsonReturnErrorDto error;
/**
* 조회 실패/없음(실패 시)
*/
private PringoJsonReturnErrorDto error;
public boolean isSuccess() {
return itemList != null && !itemList.isEmpty();
}
public boolean isSuccess() {
return itemList != null && !itemList.isEmpty();
}
public boolean isNoResult() {
return error != null && error.isNoResult();
}
public boolean isNoResult() {
return error != null && error.isNoResult();
}
}

View File

@@ -5,12 +5,15 @@ import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.kri.notihub.server.dto.template.TemplateBasicDto;
import lombok.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@@ -19,154 +22,169 @@ import java.util.Set;
@AllArgsConstructor
public class PringoJsonSendRequestDto {
private static final Set<String> RESERVED_KEYS = Set.of(
"api_key", "template_id",
"sender", "sender_name",
"recipient", "recipient_name",
"subject", "body"
);
private static final Set<String> RESERVED_KEYS = Set.of(
"api_key", "template_id",
"sender", "sender_name",
"recipient", "recipient_name",
"subject", "body"
);
@JsonProperty("api_key")
private String apiKey;
@JsonProperty("api_key")
private String apiKey;
@JsonProperty("template_id")
private String templateId;
@JsonProperty("template_id")
private String templateId;
/** sender email */
private String sender;
/**
* sender email
*/
private String sender;
@JsonProperty("sender_name")
private String senderName;
@JsonProperty("sender_name")
private String senderName;
@JsonProperty("recipient_name")
private String recipientName;
@JsonProperty("recipient_name")
private String recipientName;
/** recipient email */
private String recipient;
/**
* recipient email
*/
private String recipient;
/** subject */
private String subject;
/**
* subject
*/
private String subject;
/** html body */
private String body;
/**
* html body
*/
private String body;
/**
* Pringo 템플릿 치환용 동적 변수
* 예) body: "...[$jstest]..."
* vars: {"jstest":"테스트 지롱~"}
*/
@JsonIgnore
@Builder.Default
private Map<String, Object> vars = new LinkedHashMap<>();
/**
* Pringo 템플릿 치환용 동적 변수 예) body: "...[$jstest]..." vars: {"jstest":"테스트 지롱~"}
*/
@JsonIgnore
@Builder.Default
private Map<String, Object> vars = new LinkedHashMap<>();
@JsonAnyGetter
public Map<String, Object> any() {
return vars;
/**
* TemplateBasicDto -> Pringo 발송 DTO 기본 매핑 - recipient/recipientName 은 템플릿에 없으므로 여기서는 비워두고 이후 세팅
*/
public static PringoJsonSendRequestDto from(TemplateBasicDto template, String sendName,
String sendEmail) {
return from(template, sendName, sendEmail, null, null);
}
public static PringoJsonSendRequestDto from(TemplateBasicDto template, String sendName,
String sendEmail, String recipient, String recipientName) {
Objects.requireNonNull(template, "template is required");
String sender = sendEmail != null && !sendEmail.isBlank() ? sendEmail : template.getSendEml();
String senderName = sendName != null && !sendName.isBlank() ? sendName : template.getSendNm();
return PringoJsonSendRequestDto.builder()
.sender(sender)
.senderName(senderName)
.recipient(recipient)
.recipientName(recipientName)
.subject(template.getTmplatTitle())
.body(template.getTmplatBody())
.build();
}
public static PringoJsonSendRequestDto of(
String sender,
String senderName,
String recipient,
String recipientName,
String subject,
String htmlBody
) {
return PringoJsonSendRequestDto.builder()
.sender(sender)
.senderName(senderName)
.recipient(recipient)
.recipientName(recipientName)
.subject(subject)
.body(htmlBody)
.build();
}
@JsonAnyGetter
public Map<String, Object> any() {
return vars;
}
@JsonAnySetter
public void setAny(String key, Object value) {
if (key == null) {
return;
}
@JsonAnySetter
public void setAny(String key, Object value) {
if (key == null) return;
if (RESERVED_KEYS.contains(key)) {
// 동적 변수로 reserved key를 덮어쓰는 실수를 방지
throw new IllegalArgumentException("Reserved key cannot be used as variable: " + key);
}
vars.put(key, value);
if (RESERVED_KEYS.contains(key)) {
// 동적 변수로 reserved key를 덮어쓰는 실수를 방지
throw new IllegalArgumentException("Reserved key cannot be used as variable: " + key);
}
vars.put(key, value);
}
public void putVar(String key, Object value) {
setAny(key, value);
public void putVar(String key, Object value) {
setAny(key, value);
}
public PringoJsonSendRequestDto copy() {
return PringoJsonSendRequestDto.builder()
.apiKey(this.apiKey)
.templateId(this.templateId)
.sender(this.sender)
.senderName(this.senderName)
.recipient(this.recipient)
.recipientName(this.recipientName)
.subject(this.subject)
.body(this.body)
.vars(new java.util.LinkedHashMap<>(this.vars))
.build();
}
/**
* recipient를 나중에 세팅할 수 있게 체이닝용
*/
public PringoJsonSendRequestDto withRecipient(String recipient, String recipientName) {
this.recipient = recipient;
this.recipientName = recipientName;
return this;
}
public void applyDefaults(String defaultApiKey, String defaultTemplateId) {
if (this.apiKey == null || this.apiKey.isBlank()) {
this.apiKey = defaultApiKey;
}
public PringoJsonSendRequestDto copy() {
return PringoJsonSendRequestDto.builder()
.apiKey(this.apiKey)
.templateId(this.templateId)
.sender(this.sender)
.senderName(this.senderName)
.recipient(this.recipient)
.recipientName(this.recipientName)
.subject(this.subject)
.body(this.body)
.vars(new java.util.LinkedHashMap<>(this.vars))
.build();
if (this.templateId == null || this.templateId.isBlank()) {
this.templateId = defaultTemplateId;
}
}
/**
* TemplateBasicDto -> Pringo 발송 DTO 기본 매핑
* - recipient/recipientName 은 템플릿에 없으므로 여기서는 비워두고 이후 세팅
*/
public static PringoJsonSendRequestDto from(TemplateBasicDto template, String sendName, String sendEmail) {
return from(template, sendName, sendEmail, null, null);
public void validateRequired() {
if (apiKey == null || apiKey.isBlank()) {
throw new IllegalArgumentException("api_key is required.");
}
public static PringoJsonSendRequestDto from(TemplateBasicDto template, String sendName, String sendEmail, String recipient, String recipientName) {
Objects.requireNonNull(template, "template is required");
String sender = sendEmail != null && !sendEmail.isBlank() ? sendEmail : template.getSendEml();
String senderName = sendName != null && !sendName.isBlank() ? sendName : template.getSendNm();
return PringoJsonSendRequestDto.builder()
.sender(sender)
.senderName(senderName)
.recipient(recipient)
.recipientName(recipientName)
.subject(template.getTmplatTitle())
.body(template.getTmplatBody())
.build();
if (templateId == null || templateId.isBlank()) {
throw new IllegalArgumentException("template_id is required.");
}
public static PringoJsonSendRequestDto of(
String sender,
String senderName,
String recipient,
String recipientName,
String subject,
String htmlBody
) {
return PringoJsonSendRequestDto.builder()
.sender(sender)
.senderName(senderName)
.recipient(recipient)
.recipientName(recipientName)
.subject(subject)
.body(htmlBody)
.build();
if (sender == null || sender.isBlank()) {
throw new IllegalArgumentException("sender is required.");
}
/** recipient를 나중에 세팅할 수 있게 체이닝용 */
public PringoJsonSendRequestDto withRecipient(String recipient, String recipientName) {
this.recipient = recipient;
this.recipientName = recipientName;
return this;
if (senderName == null || senderName.isBlank()) {
throw new IllegalArgumentException("sender_name is required.");
}
public void applyDefaults(String defaultApiKey, String defaultTemplateId) {
if (this.apiKey == null || this.apiKey.isBlank()) this.apiKey = defaultApiKey;
if (this.templateId == null || this.templateId.isBlank()) this.templateId = defaultTemplateId;
if (recipient == null || recipient.isBlank()) {
throw new IllegalArgumentException("recipient is required.");
}
public void validateRequired() {
if (apiKey == null || apiKey.isBlank()) {
throw new IllegalArgumentException("api_key is required.");
}
if (templateId == null || templateId.isBlank()) {
throw new IllegalArgumentException("template_id is required.");
}
if (sender == null || sender.isBlank()) {
throw new IllegalArgumentException("sender is required.");
}
if (senderName == null || senderName.isBlank()) {
throw new IllegalArgumentException("sender_name is required.");
}
if (recipient == null || recipient.isBlank()) {
throw new IllegalArgumentException("recipient is required.");
}
if (subject == null || subject.isBlank()) {
throw new IllegalArgumentException("subject is required.");
}
if (body == null || body.isBlank()) {
throw new IllegalArgumentException("body is required.");
}
if (subject == null || subject.isBlank()) {
throw new IllegalArgumentException("subject is required.");
}
if (body == null || body.isBlank()) {
throw new IllegalArgumentException("body is required.");
}
}
}

View File

@@ -8,27 +8,27 @@ import lombok.Setter;
@Setter
public class PringoJsonSendResponseDto {
private String type;
private String type;
@JsonProperty("typeAlias")
private String typeAlias;
@JsonProperty("typeAlias")
private String typeAlias;
/**
* 성공: 1
* 실패: "-1"
* (API가 숫자/문자 둘 다 줄 수 있으니 String으로 받는 편이 안전)
*/
@JsonProperty("result")
private String result;
/**
* 성공: 1 실패: "-1" (API가 숫자/문자 둘 다 줄 수 있으니 String으로 받는 편이 안전)
*/
@JsonProperty("result")
private String result;
@JsonProperty("msg")
private String msg;
@JsonProperty("msg")
private String msg;
/** 응답 JSON 오타 그대로 "retrun_key" */
@JsonProperty("retrun_key")
private Long returnKey;
/**
* 응답 JSON 오타 그대로 "retrun_key"
*/
@JsonProperty("retrun_key")
private Long returnKey;
public boolean isSuccess() {
return "1".equals(result);
}
public boolean isSuccess() {
return "1".equals(result);
}
}

View File

@@ -2,149 +2,171 @@ package com.kri.notihub.server.common.util;
import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.dto.template.TemplateBasicDto;
import org.jsoup.Jsoup;
import org.jsoup.safety.Safelist;
import org.jsoup.nodes.Document;
import java.nio.charset.StandardCharsets;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Safelist;
public final class TemplateContentSanitizer {
// 필요 시 시스템 정책에 맞게 조정
// (KOR 환경에서 SMS는 바이트 기준으로 제한을 두는 경우가 흔함)
private static final int SMS_MAX_BYTES_UTF8 = 90;
// 필요 시 시스템 정책에 맞게 조정
// (KOR 환경에서 SMS는 바이트 기준으로 제한을 두는 경우가 흔함)
private static final int SMS_MAX_BYTES_UTF8 = 90;
private TemplateContentSanitizer() {}
private TemplateContentSanitizer() {
}
private static int utf8ByteLength(String s) {
if (s == null) return 0;
return s.getBytes(StandardCharsets.UTF_8).length;
private static int utf8ByteLength(String s) {
if (s == null) {
return 0;
}
return s.getBytes(StandardCharsets.UTF_8).length;
}
private static boolean isBlank(String s) {
return s == null || s.isBlank();
}
/**
* title은 최대 128자(코드포인트 기준)로 절단
*/
private static String truncateTo128CodePoints(String s) {
if (s == null) {
return null;
}
String trimmed = s.trim();
int cpCount = trimmed.codePointCount(0, trimmed.length());
if (cpCount <= 128) {
return trimmed;
}
private static boolean isBlank(String s) {
return s == null || s.isBlank();
int end = trimmed.offsetByCodePoints(0, 128);
return trimmed.substring(0, end);
}
/**
* 제어문자 제거(개행/탭은 옵션), 줄바꿈은 \n 으로 통일
*/
private static String normalizeControls(String s, boolean keepNewlines) {
if (s == null) {
return null;
}
String v = s.replace("\r\n", "\n").replace('\r', '\n');
if (keepNewlines) {
v = v.replaceAll("[\\p{Cntrl}&&[^\\n\\t]]", "");
} else {
v = v.replaceAll("\\p{Cntrl}", "");
}
return v;
}
/**
* EMAIL body: 안전한 HTML만 유지(스크립트/iframe 등 제거)
*/
private static String sanitizeEmailHtml(String html) {
if (html == null) {
return null;
}
/** title은 최대 128자(코드포인트 기준)로 절단 */
private static String truncateTo128CodePoints(String s) {
if (s == null) return null;
String trimmed = s.trim();
int cpCount = trimmed.codePointCount(0, trimmed.length());
if (cpCount <= 128) return trimmed;
Safelist safelist = Safelist.relaxed()
.addProtocols("a", "href", "http", "https", "mailto")
.addProtocols("img", "src", "http", "https");
int end = trimmed.offsetByCodePoints(0, 128);
return trimmed.substring(0, end);
Document.OutputSettings out = new Document.OutputSettings().prettyPrint(false);
String cleaned = Jsoup.clean(html, "", safelist, out);
cleaned = normalizeControls(cleaned, true);
return cleaned.trim();
}
/**
* SMS/LMS body: HTML -> 평문(개행 보존)
*/
private static String htmlToPlainTextPreserveNewlines(String html) {
if (html == null) {
return null;
}
/** 제어문자 제거(개행/탭은 옵션), 줄바꿈은 \n 으로 통일 */
private static String normalizeControls(String s, boolean keepNewlines) {
if (s == null) return null;
String v = s.replace("\r\n", "\n").replace('\r', '\n');
String v = html;
v = v.replaceAll("(?i)<\\s*br\\s*/?\\s*>", "\n");
v = v.replaceAll("(?i)<\\s*/\\s*p\\s*>", "\n");
v = v.replaceAll("(?i)<\\s*/\\s*div\\s*>", "\n");
v = v.replaceAll("(?i)<\\s*/\\s*li\\s*>", "\n");
v = v.replaceAll("(?i)<\\s*/\\s*tr\\s*>", "\n");
if (keepNewlines) {
v = v.replaceAll("[\\p{Cntrl}&&[^\\n\\t]]", "");
} else {
v = v.replaceAll("\\p{Cntrl}", "");
}
return v;
Document doc = Jsoup.parse(v);
doc.outputSettings(new Document.OutputSettings().prettyPrint(false));
String text = doc.body() != null ? doc.body().wholeText() : doc.wholeText();
text = normalizeControls(text, true);
text = text.replaceAll("[ \\t\\f\\v]+", " ");
text = text.replaceAll("\\n{3,}", "\n\n");
return text.trim();
}
/**
* 1) tmplatTy별 치환/정리 2) (SMS/LMS_MMS) 치환 후 길이 기반으로 타입 재결정 - SMS는 제목 저장 안 함 - LMS_MMS는 본문 짧아도 제목
* 있으면 그대로 유지
*/
public static SanitizedTemplate sanitizeAndNormalize(SendType originalType, String title,
String body) {
SendType type = originalType;
String outTitle = title;
String outBody = body;
// 1) 치환/정리
switch (originalType) {
case EMAIL -> {
// 제목: 헤더 인젝션 방지(개행 제거) + 128 제한
outTitle = normalizeControls(outTitle, false);
outTitle = outTitle.replace("\n", " ").trim();
outTitle = truncateTo128CodePoints(outTitle);
outBody = sanitizeEmailHtml(outBody);
}
case SMS, LMS_MMS -> {
// 평문화
outTitle = htmlToPlainTextPreserveNewlines(outTitle);
outTitle = truncateTo128CodePoints(outTitle);
outBody = htmlToPlainTextPreserveNewlines(outBody);
}
}
/** EMAIL body: 안전한 HTML만 유지(스크립트/iframe 등 제거) */
private static String sanitizeEmailHtml(String html) {
if (html == null) return null;
// 2) 타입 재결정(요청사항)
if (type == SendType.SMS) {
// SMS는 제목 저장 안 함
outTitle = null;
Safelist safelist = Safelist.relaxed()
.addProtocols("a", "href", "http", "https", "mailto")
.addProtocols("img", "src", "http", "https");
// 본문이 SMS 한도 초과면 LMS_MMS로 승격
if (utf8ByteLength(outBody) > SMS_MAX_BYTES_UTF8) {
type = SendType.LMS_MMS;
}
} else if (type == SendType.LMS_MMS) {
boolean hasTitle = !isBlank(outTitle);
Document.OutputSettings out = new Document.OutputSettings().prettyPrint(false);
String cleaned = Jsoup.clean(html, "", safelist, out);
cleaned = normalizeControls(cleaned, true);
return cleaned.trim();
// "LMS_MMS인데 본문이 짧으면 SMS로 강등"이 기본인데,
// 단, 제목이 있으면 본문이 짧아도 LMS_MMS 유지
if (!hasTitle && utf8ByteLength(outBody) <= SMS_MAX_BYTES_UTF8) {
type = SendType.SMS;
outTitle = null; // SMS는 제목 저장 안 함
}
}
/** SMS/LMS body: HTML -> 평문(개행 보존) */
private static String htmlToPlainTextPreserveNewlines(String html) {
if (html == null) return null;
return new SanitizedTemplate(type, outTitle, outBody);
}
String v = html;
v = v.replaceAll("(?i)<\\s*br\\s*/?\\s*>", "\n");
v = v.replaceAll("(?i)<\\s*/\\s*p\\s*>", "\n");
v = v.replaceAll("(?i)<\\s*/\\s*div\\s*>", "\n");
v = v.replaceAll("(?i)<\\s*/\\s*li\\s*>", "\n");
v = v.replaceAll("(?i)<\\s*/\\s*tr\\s*>", "\n");
public static void sanitizeAndNormalizeInPlace(TemplateBasicDto dto) {
SanitizedTemplate st = sanitizeAndNormalize(dto.getTmplatTy(), dto.getTmplatTitle(),
dto.getTmplatBody());
dto.setTmplatTy(st.type());
dto.setTmplatTitle(st.title());
dto.setTmplatBody(st.body());
}
Document doc = Jsoup.parse(v);
doc.outputSettings(new Document.OutputSettings().prettyPrint(false));
String text = doc.body() != null ? doc.body().wholeText() : doc.wholeText();
public record SanitizedTemplate(SendType type, String title, String body) {
text = normalizeControls(text, true);
text = text.replaceAll("[ \\t\\f\\v]+", " ");
text = text.replaceAll("\\n{3,}", "\n\n");
return text.trim();
}
/**
* 1) tmplatTy별 치환/정리
* 2) (SMS/LMS_MMS) 치환 후 길이 기반으로 타입 재결정
* - SMS는 제목 저장 안 함
* - LMS_MMS는 본문 짧아도 제목 있으면 그대로 유지
*/
public static SanitizedTemplate sanitizeAndNormalize(SendType originalType, String title, String body) {
SendType type = originalType;
String outTitle = title;
String outBody = body;
// 1) 치환/정리
switch (originalType) {
case EMAIL -> {
// 제목: 헤더 인젝션 방지(개행 제거) + 128 제한
outTitle = normalizeControls(outTitle, false);
outTitle = outTitle.replace("\n", " ").trim();
outTitle = truncateTo128CodePoints(outTitle);
outBody = sanitizeEmailHtml(outBody);
}
case SMS, LMS_MMS -> {
// 평문화
outTitle = htmlToPlainTextPreserveNewlines(outTitle);
outTitle = truncateTo128CodePoints(outTitle);
outBody = htmlToPlainTextPreserveNewlines(outBody);
}
}
// 2) 타입 재결정(요청사항)
if (type == SendType.SMS) {
// SMS는 제목 저장 안 함
outTitle = null;
// 본문이 SMS 한도 초과면 LMS_MMS로 승격
if (utf8ByteLength(outBody) > SMS_MAX_BYTES_UTF8) {
type = SendType.LMS_MMS;
}
} else if (type == SendType.LMS_MMS) {
boolean hasTitle = !isBlank(outTitle);
// "LMS_MMS인데 본문이 짧으면 SMS로 강등"이 기본인데,
// 단, 제목이 있으면 본문이 짧아도 LMS_MMS 유지
if (!hasTitle && utf8ByteLength(outBody) <= SMS_MAX_BYTES_UTF8) {
type = SendType.SMS;
outTitle = null; // SMS는 제목 저장 안 함
}
}
return new SanitizedTemplate(type, outTitle, outBody);
}
public static void sanitizeAndNormalizeInPlace(TemplateBasicDto dto) {
SanitizedTemplate st = sanitizeAndNormalize(dto.getTmplatTy(), dto.getTmplatTitle(), dto.getTmplatBody());
dto.setTmplatTy(st.type());
dto.setTmplatTitle(st.title());
dto.setTmplatBody(st.body());
}
public record SanitizedTemplate(SendType type, String title, String body) {}
}
}

View File

@@ -13,11 +13,11 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
public class DefaultTxConfig {
@Bean(name = "transactionManager")
@Primary
public PlatformTransactionManager transactionManager(
@Qualifier("entityManagerFactory") EntityManagerFactory emf
) {
return new JpaTransactionManager(emf);
}
@Bean(name = "transactionManager")
@Primary
public PlatformTransactionManager transactionManager(
@Qualifier("entityManagerFactory") EntityManagerFactory emf
) {
return new JpaTransactionManager(emf);
}
}

View File

@@ -8,13 +8,13 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebResourceConfig implements WebMvcConfigurer {
@Value("${kri.body-image.upload-base-dir}")
private String uploadBaseDir;
@Value("${kri.body-image.upload-base-dir}")
private String uploadBaseDir;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// /body-image/** → /data/upload-file/body-image/** 매핑
registry.addResourceHandler("/body-image/**")
.addResourceLocations("file:" + uploadBaseDir + "/");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// /body-image/** → /data/upload-file/body-image/** 매핑
registry.addResourceHandler("/body-image/**")
.addResourceLocations("file:" + uploadBaseDir + "/");
}
}

View File

@@ -12,10 +12,14 @@ import com.kri.notihub.server.service.ReportService;
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.*;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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/report")
@@ -23,32 +27,33 @@ import java.util.List;
@Tag(name = "Report", description = "발송 정보/결과 조회")
public class ReportController {
private final ReportService reportService;
private final ReportService reportService;
@Operation(summary = "대량발송 리스트 조회")
@GetMapping("/bulk-list/{sendTy}/{reqstSvc}/{prjctCd}")
public List<BulkSendInfoDto> getBulkSendList(
@PathVariable SendType sendTy,
@PathVariable String reqstSvc,
@PathVariable String prjctCd,
RequestUserContext ctx
){
String regCmpn = ctx.getUserRole() < NotihubConst.OUTSOURCE_USER_ROLE ? null : ctx.getUserCmpn();
return reportService.getBulkSendList(sendTy, reqstSvc, prjctCd, regCmpn);
}
@Operation(summary = "대량발송 리스트 조회")
@GetMapping("/bulk-list/{sendTy}/{reqstSvc}/{prjctCd}")
public List<BulkSendInfoDto> getBulkSendList(
@PathVariable SendType sendTy,
@PathVariable String reqstSvc,
@PathVariable String prjctCd,
RequestUserContext ctx
) {
String regCmpn =
ctx.getUserRole() < NotihubConst.OUTSOURCE_USER_ROLE ? null : ctx.getUserCmpn();
return reportService.getBulkSendList(sendTy, reqstSvc, prjctCd, regCmpn);
}
@Operation(summary = "대량발송 결과 조회")
@PostMapping("/bulk-detail/{bulkSendKey}")
public PageResponseDto<SendInfoDto> getBulkSendDetail(
@PathVariable String bulkSendKey,
@Valid @RequestBody PageRequestDto pageReq
){
return reportService.getBulkSendDetail(bulkSendKey, pageReq);
}
@Operation(summary = "대량발송 결과 조회")
@PostMapping("/bulk-detail/{bulkSendKey}")
public PageResponseDto<SendInfoDto> getBulkSendDetail(
@PathVariable String bulkSendKey,
@Valid @RequestBody PageRequestDto pageReq
) {
return reportService.getBulkSendDetail(bulkSendKey, pageReq);
}
@Operation(summary = "대량발송 결과 다운로드")
@PostMapping("/bulk-detail/excel/{bulkSendKey}")
public ReportExcelResponseDto getBulkSendDetailExcel(@PathVariable String bulkSendKey){
return reportService.getBulkSendDetailExcel(bulkSendKey);
}
@Operation(summary = "대량발송 결과 다운로드")
@PostMapping("/bulk-detail/excel/{bulkSendKey}")
public ReportExcelResponseDto getBulkSendDetailExcel(@PathVariable String bulkSendKey) {
return reportService.getBulkSendDetailExcel(bulkSendKey);
}
}

View File

@@ -1,50 +1,60 @@
package com.kri.notihub.server.controller;
import com.kri.common.webmvc.RequestUserContext;
import com.kri.notihub.server.dto.send.*;
import com.kri.notihub.server.dto.send.BulkSendCreateRequestDto;
import com.kri.notihub.server.dto.send.BulkSendResponseDto;
import com.kri.notihub.server.dto.send.EmailPollQueueResponseDto;
import com.kri.notihub.server.dto.send.SendRequestBulkDto;
import com.kri.notihub.server.dto.send.SendRequestSingleDto;
import com.kri.notihub.server.service.EmailResultPoller;
import com.kri.notihub.server.service.SendEmailService;
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.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
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-email")
@RequiredArgsConstructor
@Tag(name = "Send Email", description = "이메일 발송 API")
public class SendEmailController {
//발송 타입은 템플릿에 있음
private final SendEmailService sendEmailService;
private final EmailResultPoller emailResultPoller;
@Operation(summary = "Email 결과조회 Poller 큐(cmid=return_key) 목록 조회")
@GetMapping("/queue")
public EmailPollQueueResponseDto getQueue() {
return emailResultPoller.snapshotQueue();
}
//발송 타입은 템플릿에 있음
private final SendEmailService sendEmailService;
private final EmailResultPoller emailResultPoller;
@Operation(summary = "벌크 발송키 생성")
@PutMapping("/create/bulk")
public String createBulkSendKey(@Valid @RequestBody BulkSendCreateRequestDto req) {
return sendEmailService.issueBulkKey(req);
}
@Operation(summary = "Email 결과조회 Poller 큐(cmid=return_key) 목록 조회")
@GetMapping("/queue")
public EmailPollQueueResponseDto getQueue() {
return emailResultPoller.snapshotQueue();
}
@Operation(summary = "이메일 단건 발송")
@PostMapping("/single")
public void sendSingle(
@Valid @RequestBody SendRequestSingleDto req,
RequestUserContext ctx
) {
sendEmailService.doSendSingle(req, ctx.getUserCmpn(), ctx.getUserId());
}
@Operation(summary = "벌크 발송키 생성")
@PutMapping("/create/bulk")
public String createBulkSendKey(@Valid @RequestBody BulkSendCreateRequestDto req) {
return sendEmailService.issueBulkKey(req);
}
@Operation(summary = "bulkSendKey 기반 이메일 벌크 발송")
@PostMapping("/bulk")
public BulkSendResponseDto sendBulk(
@Valid @RequestBody SendRequestBulkDto req
) {
return sendEmailService.doSendBulk(req);
}
@Operation(summary = "이메일 단건 발송")
@PostMapping("/single")
public void sendSingle(
@Valid @RequestBody SendRequestSingleDto req,
RequestUserContext ctx
) {
sendEmailService.doSendSingle(req, ctx.getUserCmpn(), ctx.getUserId());
}
@Operation(summary = "bulkSendKey 기반 이메일 벌크 발송")
@PostMapping("/bulk")
public BulkSendResponseDto sendBulk(
@Valid @RequestBody SendRequestBulkDto req
) {
return sendEmailService.doSendBulk(req);
}
}

View File

@@ -1,14 +1,23 @@
package com.kri.notihub.server.controller;
import com.kri.common.webmvc.RequestUserContext;
import com.kri.notihub.server.dto.send.*;
import com.kri.notihub.server.dto.send.BulkSendCreateRequestDto;
import com.kri.notihub.server.dto.send.BulkSendResponseDto;
import com.kri.notihub.server.dto.send.SendRequestBulkDto;
import com.kri.notihub.server.dto.send.SendRequestSingleDto;
import com.kri.notihub.server.dto.send.SmsCursorResponseDto;
import com.kri.notihub.server.service.SendSmsService;
import com.kri.notihub.server.service.SmsSendCursorStore;
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.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
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-sms")
@@ -16,35 +25,35 @@ import org.springframework.web.bind.annotation.*;
@Tag(name = "Send SMS", description = "문자 발송 API")
public class SendSmsController {
private final SendSmsService sendSmsService;
private final SmsSendCursorStore cursorStore;
private final SendSmsService sendSmsService;
private final SmsSendCursorStore cursorStore;
@Operation(summary = "SMS 결과 반영 커서(send_idx) 조회")
@GetMapping("/cursor")
public SmsCursorResponseDto getCursor() {
return SmsCursorResponseDto.of(cursorStore.get());
}
@Operation(summary = "SMS 결과 반영 커서(send_idx) 조회")
@GetMapping("/cursor")
public SmsCursorResponseDto getCursor() {
return SmsCursorResponseDto.of(cursorStore.get());
}
@Operation(summary = "벌크 발송키 생성")
@PutMapping("/create/bulk")
public String createBulkSendKey(@Valid @RequestBody BulkSendCreateRequestDto req) {
return sendSmsService.issueBulkKey(req);
}
@Operation(summary = "벌크 발송키 생성")
@PutMapping("/create/bulk")
public String createBulkSendKey(@Valid @RequestBody BulkSendCreateRequestDto req) {
return sendSmsService.issueBulkKey(req);
}
@Operation(summary = "문자 단건 발송")
@PostMapping("/single")
public void sendSingle(
@Valid @RequestBody SendRequestSingleDto req,
RequestUserContext ctx
) {
sendSmsService.doSendSingle(req, ctx.getUserCmpn(), ctx.getUserId());
}
@Operation(summary = "문자 단건 발송")
@PostMapping("/single")
public void sendSingle(
@Valid @RequestBody SendRequestSingleDto req,
RequestUserContext ctx
) {
sendSmsService.doSendSingle(req, ctx.getUserCmpn(), ctx.getUserId());
}
@Operation(summary = "bulkSendKey 기반 문자 벌크 발송")
@PostMapping("/bulk")
public BulkSendResponseDto sendBulk(
@Valid @RequestBody SendRequestBulkDto req
) {
return sendSmsService.doSendBulk(req);
}
@Operation(summary = "bulkSendKey 기반 문자 벌크 발송")
@PostMapping("/bulk")
public BulkSendResponseDto sendBulk(
@Valid @RequestBody SendRequestBulkDto req
) {
return sendSmsService.doSendBulk(req);
}
}

View File

@@ -10,11 +10,18 @@ import com.kri.notihub.server.service.TemplateService;
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.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/api/v1/template")
@@ -22,69 +29,71 @@ import java.util.List;
@Tag(name = "Template", description = "템플릿 API")
public class TemplateController {
private final TemplateService templateService;
private final FileService fileService;
private final TemplateService templateService;
private final FileService fileService;
@Operation(summary = "템플릿 목록 조회")
@GetMapping("/list/{chnnlTy}/{itrntPrjctCd}")
public List<TemplateSummaryDto> getTemplateList(
@PathVariable ChannelType chnnlTy,
@PathVariable String itrntPrjctCd
) {
return templateService.getTemplateList(chnnlTy, itrntPrjctCd);
}
@Operation(summary = "템플릿 목록 조회")
@GetMapping("/list/{chnnlTy}/{itrntPrjctCd}")
public List<TemplateSummaryDto> getTemplateList(
@PathVariable ChannelType chnnlTy,
@PathVariable String itrntPrjctCd
) {
return templateService.getTemplateList(chnnlTy, itrntPrjctCd);
}
@Operation(summary = "템플릿 단건 조회")
@GetMapping("/{tmplatIdx}")
public TemplateDto getTemplate(@PathVariable long tmplatIdx) {
return templateService.getTemplate(tmplatIdx);
}
@Operation(summary = "템플릿 단건 조회")
@GetMapping("/{tmplatIdx}")
public TemplateDto getTemplate(@PathVariable long tmplatIdx) {
return templateService.getTemplate(tmplatIdx);
}
@Operation(summary = "템플릿 생성")
@PutMapping
public TemplateDto createTemplate(
@Valid @RequestBody TemplateBasicDto template,
RequestUserContext ctx
) {
TemplateDto newTmplat = templateService.createTemplate(template.getItrntPrjctCd(), template, ctx.getUserId());
@Operation(summary = "템플릿 생성")
@PutMapping
public TemplateDto createTemplate(
@Valid @RequestBody TemplateBasicDto template,
RequestUserContext ctx
) {
TemplateDto newTmplat = templateService.createTemplate(template.getItrntPrjctCd(), template,
ctx.getUserId());
String newHtml = fileService.syncOnSave(
newTmplat.getItrntPrjctCd(),
newTmplat.getTmplatIdx(),
newTmplat.getTmplatBody()
);
newTmplat.setTmplatBody(newHtml);
String newHtml = fileService.syncOnSave(
newTmplat.getItrntPrjctCd(),
newTmplat.getTmplatIdx(),
newTmplat.getTmplatBody()
);
newTmplat.setTmplatBody(newHtml);
templateService.updateTemplateBodyWithCreate(newTmplat);
templateService.updateTemplateBodyWithCreate(newTmplat);
return newTmplat;
}
return newTmplat;
}
@Operation(summary = "시나리오 이미지 업로드")
@PutMapping("/body-image/{itrntPrjctCd}")
public String uploadContactSenarioImage(@PathVariable String itrntPrjctCd, @RequestParam("file") MultipartFile file) {
return fileService.storeTempFile(itrntPrjctCd, file);
}
@Operation(summary = "시나리오 이미지 업로드")
@PutMapping("/body-image/{itrntPrjctCd}")
public String uploadContactSenarioImage(@PathVariable String itrntPrjctCd,
@RequestParam("file") MultipartFile file) {
return fileService.storeTempFile(itrntPrjctCd, file);
}
@Operation(summary = "템플릿 수정")
@PatchMapping
public TemplateDto updateTemplate(
@Valid @RequestBody TemplateDto template,
RequestUserContext ctx
) {
String newHtml = fileService.syncOnSave(
template.getItrntPrjctCd(),
template.getTmplatIdx(),
template.getTmplatBody()
);
template.setTmplatBody(newHtml);
@Operation(summary = "템플릿 수정")
@PatchMapping
public TemplateDto updateTemplate(
@Valid @RequestBody TemplateDto template,
RequestUserContext ctx
) {
String newHtml = fileService.syncOnSave(
template.getItrntPrjctCd(),
template.getTmplatIdx(),
template.getTmplatBody()
);
template.setTmplatBody(newHtml);
return templateService.updateTemplate(template, ctx.getUserId());
}
return templateService.updateTemplate(template, ctx.getUserId());
}
@Operation(summary = "템플릿 삭제(소프트 삭제)")
@DeleteMapping("/{tmplatIdx}")
public void deleteTemplate(@PathVariable long tmplatIdx, RequestUserContext ctx) {
templateService.deleteTemplate(tmplatIdx, ctx.getUserId());
}
@Operation(summary = "템플릿 삭제(소프트 삭제)")
@DeleteMapping("/{tmplatIdx}")
public void deleteTemplate(@PathVariable long tmplatIdx, RequestUserContext ctx) {
templateService.deleteTemplate(tmplatIdx, ctx.getUserId());
}
}

View File

@@ -6,9 +6,12 @@ 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.*;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@@ -18,82 +21,84 @@ import java.time.LocalDateTime;
@Schema(description = "대량발송 정보")
public class BulkSendInfoDto {
@Size(max = 32)
@NotBlank
@Schema(description = "대량발송 키", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String bulkSendKey;
@Size(max = 32)
@NotBlank
@Schema(description = "대량발송 키", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String bulkSendKey;
@Size(max = 16)
@NotBlank
@Schema(description = "요청 서비스")
private String reqstSvc;
@Size(max = 16)
@NotBlank
@Schema(description = "요청 서비스")
private String reqstSvc;
@Size(max = 32)
@NotBlank
@Schema(description = "프로젝트 코드")
private String prjctCd;
@Size(max = 32)
@NotBlank
@Schema(description = "프로젝트 코드")
private String prjctCd;
@Schema(description = "템플릿 인덱스")
private Long tmplatIdx;
@Schema(description = "템플릿 인덱스")
private Long tmplatIdx;
@NotNull
@Schema(description = "예약 여부")
private Boolean resve;
@NotNull
@Schema(description = "예약 여부")
private Boolean resve;
@NotNull
@Schema(description = "발송일시")
private LocalDateTime sendDt;
@NotNull
@Schema(description = "발송일시")
private LocalDateTime sendDt;
@NotNull
@Schema(description = "대상 건수")
private Integer trgtCnt;
@NotNull
@Schema(description = "대상 건수")
private Integer trgtCnt;
@NotNull
@Schema(description = "발송 건수", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Integer sendCnt;
@NotNull
@Schema(description = "발송 건수", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Integer sendCnt;
@NotNull
@Schema(description = "성공 건수", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Integer succesCnt;
@NotNull
@Schema(description = "성공 건수", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Integer succesCnt;
@NotNull
@Schema(description = "실패 건수", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Integer failCnt;
@NotNull
@Schema(description = "실패 건수", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Integer failCnt;
@Schema(description = "완료일시", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private LocalDateTime completeDt;
@Schema(description = "완료일시", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private LocalDateTime completeDt;
@Size(max = 32)
@Schema(description = "등록자", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String regUser;
@Size(max = 32)
@Schema(description = "등록자", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String regUser;
@Schema(description = "등록일시", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private LocalDateTime regDt;
@Schema(description = "등록일시", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private LocalDateTime regDt;
public static BulkSendInfoDto from(TBulkSendEntity entity) {
if (entity == null) return null;
return BulkSendInfoDto.builder()
.bulkSendKey(entity.getBulkSendKey())
.reqstSvc(entity.getReqstSvc())
.prjctCd(entity.getPrjctCd())
.tmplatIdx(entity.getTmplatIdx())
.resve(entity.getResve() != null ? entity.getResve() : Boolean.FALSE)
.sendDt(entity.getSendDt())
.trgtCnt(entity.getTrgtCnt())
.sendCnt(entity.getSendCnt())
.succesCnt(entity.getSuccesCnt())
.failCnt(entity.getFailCnt())
.completeDt(entity.getCompleteDt())
.regUser(entity.getRegUser())
.regDt(entity.getRegDt())
.build();
public static BulkSendInfoDto from(TBulkSendEntity entity) {
if (entity == null) {
return null;
}
return BulkSendInfoDto.builder()
.bulkSendKey(entity.getBulkSendKey())
.reqstSvc(entity.getReqstSvc())
.prjctCd(entity.getPrjctCd())
.tmplatIdx(entity.getTmplatIdx())
.resve(entity.getResve() != null ? entity.getResve() : Boolean.FALSE)
.sendDt(entity.getSendDt())
.trgtCnt(entity.getTrgtCnt())
.sendCnt(entity.getSendCnt())
.succesCnt(entity.getSuccesCnt())
.failCnt(entity.getFailCnt())
.completeDt(entity.getCompleteDt())
.regUser(entity.getRegUser())
.regDt(entity.getRegDt())
.build();
}
}

View File

@@ -10,9 +10,9 @@ import lombok.Setter;
@Builder
public class ReportExcelResponseDto {
@Schema(description = "프론트가 저장용으로 쓸 파일명")
private String errorFileName;
@Schema(description = "프론트가 저장용으로 쓸 파일명")
private String errorFileName;
@Schema(description = "에러 엑셀 파일 (xlsx)의 Base64 문자열 (hasErrorFile == true일 때만 세팅)")
private String errorFileBase64;
@Schema(description = "에러 엑셀 파일 (xlsx)의 Base64 문자열 (hasErrorFile == true일 때만 세팅)")
private String errorFileBase64;
}

View File

@@ -9,10 +9,13 @@ 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.*;
import java.time.LocalDateTime;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@@ -22,146 +25,148 @@ import java.util.List;
@Schema(description = "발송 정보")
public class SendInfoDto {
@Size(max = 32)
@NotBlank
@Schema(description = "CMID")
private String cmid;
@Size(max = 32)
@NotBlank
@Schema(description = "CMID")
private String cmid;
@Size(max = 32)
@Schema(description = "대량발송 키")
private String bulkSendKey;
@Size(max = 32)
@Schema(description = "대량발송 키")
private String bulkSendKey;
@NotNull
@Schema(description = "발송 타입 코드")
private Short sendTyCode;
@NotNull
@Schema(description = "발송 타입 코드")
private Short sendTyCode;
@NotNull
@Schema(description = "발송 타입 라벨")
private String sendTyLabel;
@NotNull
@Schema(description = "발송 타입 라벨")
private String sendTyLabel;
@NotNull
@Schema(description = "예약 여부")
private Boolean resve;
@NotNull
@Schema(description = "예약 여부")
private Boolean resve;
@NotNull
@Schema(description = "발송 상태")
private Short sendStatusCode;
@NotNull
@Schema(description = "발송 상태")
private Short sendStatusCode;
@NotNull
@ExcelColumn(header = "발송 상태", order = 0)
@Schema(description = "발송 상태 라벨")
private String sendStatusLabel;
@NotNull
@ExcelColumn(header = "발송 상태", order = 0)
@Schema(description = "발송 상태 라벨")
private String sendStatusLabel;
@NotNull
@Schema(description = "결과 코드")
private Short resultCode;
@NotNull
@Schema(description = "결과 코드")
private Short resultCode;
@NotNull
@ExcelColumn(header = "발송 결과", order = 1)
@Schema(description = "결과 라벨")
private String resultLabel;
@NotNull
@ExcelColumn(header = "발송 결과", order = 1)
@Schema(description = "결과 라벨")
private String resultLabel;
@Size(max = 16)
@NotBlank
@Schema(description = "요청 서비스")
private String reqstSvc;
@Size(max = 16)
@NotBlank
@Schema(description = "요청 서비스")
private String reqstSvc;
@Size(max = 32)
@NotBlank
@Schema(description = "프로젝트 코드")
private String prjctCd;
@Size(max = 32)
@NotBlank
@Schema(description = "프로젝트 코드")
private String prjctCd;
@Schema(description = "템플릿 인덱스")
private Long tmplatIdx;
@Schema(description = "템플릿 인덱스")
private Long tmplatIdx;
@Size(max = 64)
@ExcelColumn(header = "발신지", order = 2)
@Schema(description = "발신지(EMAIL이면 sendEml, 아니면 sendTel)")
private 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 = "발신자명")
private String sendNm;
@Size(max = 32)
@ExcelColumn(header = "발신자명", order = 3)
@Schema(description = "발신자명")
private String sendNm;
@NotNull
@ExcelColumn(header = "발송 일시", order = 4)
@Schema(description = "발송 일시")
private LocalDateTime sendDt;
@NotNull
@ExcelColumn(header = "발송 일시", order = 4)
@Schema(description = "발송 일시")
private LocalDateTime sendDt;
@Size(max = 128)
@NotBlank
@ExcelColumn(header = "SID", order = 5)
@Schema(description = "SID")
private 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)")
private 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 = "수신자명")
private String destNm;
@Size(max = 32)
@ExcelColumn(header = "수신자명", order = 7)
@Schema(description = "수신자명")
private String destNm;
@ExcelColumn(header = "발송 결과 확인 일시", order = 8)
@Schema(description = "리포트 일시")
private LocalDateTime reportDt;
@ExcelColumn(header = "발송 결과 확인 일시", order = 8)
@Schema(description = "리포트 일시")
private LocalDateTime reportDt;
@Size(max = 32)
@NotBlank
@Schema(description = "등록 회사")
private String regCmpn;
@Size(max = 32)
@NotBlank
@Schema(description = "등록 회사")
private String regCmpn;
@Size(max = 32)
@NotBlank
@ExcelColumn(header = "발송 요청자", order = 9)
@Schema(description = "등록자")
private String regUser;
@Size(max = 32)
@NotBlank
@ExcelColumn(header = "발송 요청자", order = 9)
@Schema(description = "등록자")
private String regUser;
@NotNull
@ExcelColumn(header = "발송 요청 일시", order = 10)
@Schema(description = "등록일시")
private LocalDateTime regDt;
@NotNull
@ExcelColumn(header = "발송 요청 일시", order = 10)
@Schema(description = "등록일시")
private LocalDateTime regDt;
public static SendInfoDto from(TSendEntity entity, List<TSendResultCodeEntity> resultCodeEntity) {
if (entity == null) return null;
boolean isEmail = entity.getSendTy() != null
&& entity.getSendTy().equals(SendType.EMAIL.getCode());
String sendFrom = isEmail ? entity.getSendEml() : entity.getSendTel();
String destTo = isEmail ? entity.getDestEml() : entity.getDestTel();
String resultViewLabel = resultCodeEntity.stream()
.filter(e -> e.getId() != null && e.getId().getResultCode().equals(entity.getResultCode()))
.map(TSendResultCodeEntity::getResultViewLabel)
.findFirst()
.orElse(null); // 없으면 null
return SendInfoDto.builder()
.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())
.resultCode(entity.getResultCode())
.resultLabel(resultViewLabel)
.reqstSvc(entity.getReqstSvc())
.prjctCd(entity.getPrjctCd())
.tmplatIdx(entity.getTmplatIdx())
.sendFrom(sendFrom)
.sendNm(entity.getSendNm())
.sendDt(entity.getSendDt())
.sid(entity.getSid())
.destTo(destTo)
.destNm(entity.getDestNm())
.reportDt(entity.getReportDt())
.regUser(entity.getRegUser())
.regDt(entity.getRegDt())
.build();
public static SendInfoDto from(TSendEntity entity, List<TSendResultCodeEntity> resultCodeEntity) {
if (entity == null) {
return null;
}
boolean isEmail = entity.getSendTy() != null
&& entity.getSendTy().equals(SendType.EMAIL.getCode());
String sendFrom = isEmail ? entity.getSendEml() : entity.getSendTel();
String destTo = isEmail ? entity.getDestEml() : entity.getDestTel();
String resultViewLabel = resultCodeEntity.stream()
.filter(e -> e.getId() != null && e.getId().getResultCode().equals(entity.getResultCode()))
.map(TSendResultCodeEntity::getResultViewLabel)
.findFirst()
.orElse(null); // 없으면 null
return SendInfoDto.builder()
.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())
.resultCode(entity.getResultCode())
.resultLabel(resultViewLabel)
.reqstSvc(entity.getReqstSvc())
.prjctCd(entity.getPrjctCd())
.tmplatIdx(entity.getTmplatIdx())
.sendFrom(sendFrom)
.sendNm(entity.getSendNm())
.sendDt(entity.getSendDt())
.sid(entity.getSid())
.destTo(destTo)
.destNm(entity.getDestNm())
.reportDt(entity.getReportDt())
.regUser(entity.getRegUser())
.regDt(entity.getRegDt())
.build();
}
}

View File

@@ -5,9 +5,12 @@ 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.*;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@@ -16,37 +19,30 @@ import java.time.LocalDateTime;
@AllArgsConstructor
public class BulkSendCreateRequestDto {
@NotBlank
@Schema(description = "발송 요청 서비스 (로그용)")
private String reqstSvc;
@Schema(description = "발송 요청 서비스의 프로젝트 코드 (로그용)")
private String prjctCd;
@NotNull
@Schema(description = "템플릿 idx")
private Long tmplatIdx;
@NotNull
@Builder.Default
@Schema(description = "예약 여부")
private Boolean resve = false;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Schema(description = "발송일시(미입력 시 현재 시간)")
private LocalDateTime sendDt;
@NotNull
@Schema(description = "대상자 수")
private Integer trgtCnt;
@Size(max = 32)
@NotBlank
@Schema(description = "발송 요청 회사")
String reqstCmpn;
@Size(max = 32)
@NotBlank
@Schema(description = "발송 요청자")
String reqstUser;
@Size(max = 32)
@NotBlank
@Schema(description = "발송 요청 회사")
String reqstCmpn;
@Size(max = 32)
@NotBlank
@Schema(description = "발송 요청자")
String reqstUser;
@NotBlank
@Schema(description = "발송 요청 서비스 (로그용)")
private String reqstSvc;
@Schema(description = "발송 요청 서비스의 프로젝트 코드 (로그용)")
private String prjctCd;
@NotNull
@Schema(description = "템플릿 idx")
private Long tmplatIdx;
@NotNull
@Builder.Default
@Schema(description = "예약 여부")
private Boolean resve = false;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Schema(description = "발송일시(미입력 시 현재 시간)")
private LocalDateTime sendDt;
@NotNull
@Schema(description = "대상자 수")
private Integer trgtCnt;
}

View File

@@ -12,24 +12,25 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor
public class BulkSendResponseDto {
@Schema(description = "bulkSendKey")
private String bulkSendKey;
@Schema(description = "bulkSendKey")
private String bulkSendKey;
@Schema(description = "요청 건수")
private Integer requestCount;
@Schema(description = "요청 건수")
private Integer requestCount;
@Schema(description = "Pringo send 요청 성공(return_key 수신) 건수")
private Integer acceptCount;
@Schema(description = "Pringo send 요청 성공(return_key 수신) 건수")
private Integer acceptCount;
@Schema(description = "Pringo send 요청 실패(return_key 미수신) 건수")
private Integer failCount;
@Schema(description = "Pringo send 요청 실패(return_key 미수신) 건수")
private Integer failCount;
public static BulkSendResponseDto of(String bulkSendKey, Integer requestCount, Integer acceptCount, Integer failCount) {
return BulkSendResponseDto.builder()
.bulkSendKey(bulkSendKey)
.requestCount(requestCount)
.acceptCount(acceptCount)
.failCount(failCount)
.build();
}
public static BulkSendResponseDto of(String bulkSendKey, Integer requestCount,
Integer acceptCount, Integer failCount) {
return BulkSendResponseDto.builder()
.bulkSendKey(bulkSendKey)
.requestCount(requestCount)
.acceptCount(acceptCount)
.failCount(failCount)
.build();
}
}

View File

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

View File

@@ -3,39 +3,39 @@ package com.kri.notihub.server.dto.send;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.kri.common.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;
import java.time.Instant;
import java.time.LocalDateTime;
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class EmailPollQueueItemDto {
@Schema(description = "Pringo return_key(cmid)")
private String cmid;
@Schema(description = "Pringo return_key(cmid)")
private String cmid;
@Schema(description = "폴링 시도 횟수(0부터 시작)")
private Integer attempt;
@Schema(description = "폴링 시도 횟수(0부터 시작)")
private Integer attempt;
@Schema(description = "구동까지 남은 시간(ms)")
private Long remainingMs;
@Schema(description = "구동까지 남은 시간(ms)")
private Long remainingMs;
@Schema(description = "구동 예상 시간(KST LocalDateTime)")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime triggerAt;
@Schema(description = "구동 예상 시간(KST LocalDateTime)")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime triggerAt;
public static EmailPollQueueItemDto of(String cmid, int attempt, long remainingMs, long triggerAtEpochMs) {
return EmailPollQueueItemDto.builder()
.cmid(cmid)
.attempt(attempt)
.remainingMs(remainingMs)
.triggerAt(DateTimeUtil.toKstLocalDateTime(Instant.ofEpochMilli(triggerAtEpochMs)))
.build();
}
public static EmailPollQueueItemDto of(String cmid, int attempt, long remainingMs,
long triggerAtEpochMs) {
return EmailPollQueueItemDto.builder()
.cmid(cmid)
.attempt(attempt)
.remainingMs(remainingMs)
.triggerAt(DateTimeUtil.toKstLocalDateTime(Instant.ofEpochMilli(triggerAtEpochMs)))
.build();
}
}

View File

@@ -1,28 +1,28 @@
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;
import java.util.List;
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class EmailPollQueueResponseDto {
@Schema(description = "Queue size (snapshot)")
private Integer size;
@Schema(description = "Queue에 있는 작업 내용 (snapshot)")
private List<EmailPollQueueItemDto> items;
@Schema(description = "Queue size (snapshot)")
private Integer size;
public static EmailPollQueueResponseDto of(List<EmailPollQueueItemDto> items) {
return EmailPollQueueResponseDto.builder()
.size(items != null ? items.size() : 0)
.items(items)
.build();
}
@Schema(description = "Queue에 있는 작업 내용 (snapshot)")
private List<EmailPollQueueItemDto> items;
public static EmailPollQueueResponseDto of(List<EmailPollQueueItemDto> items) {
return EmailPollQueueResponseDto.builder()
.size(items != null ? items.size() : 0)
.items(items)
.build();
}
}

View File

@@ -2,7 +2,11 @@ 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.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@@ -12,17 +16,17 @@ import lombok.*;
@Schema(description = "이메일/문자 발송 결과")
public class SendInternalResultDto {
private String cmid;
private String cmid;
private SendStatusType status;
private SendStatusType status;
private Short resultCode;
private Short resultCode;
public static SendInternalResultDto of(String cmid, SendStatusType status, short resultCode) {
return SendInternalResultDto.builder()
.cmid(cmid)
.status(status)
.resultCode(resultCode)
.build();
}
public static SendInternalResultDto of(String cmid, SendStatusType status, short resultCode) {
return SendInternalResultDto.builder()
.cmid(cmid)
.status(status)
.resultCode(resultCode)
.build();
}
}

View File

@@ -2,9 +2,12 @@ package com.kri.notihub.server.dto.send;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@@ -14,16 +17,16 @@ import lombok.*;
@Schema(description = "발송 기본 정보")
public class SendRequestBasicDto {
@Size(max = 64)
@Email
@Schema(description = "발신 이메일 (이메일 발송에만 사용)")
private String sendEml;
@Size(max = 64)
@Email
@Schema(description = "발신 이메일 (이메일 발송에만 사용)")
private String sendEml;
@Size(max = 16)
@Schema(description = "발신 전화번호 (문자 발송에만 사용)")
private String sendTel;
@Size(max = 16)
@Schema(description = "발신 전화번호 (문자 발송에만 사용)")
private String sendTel;
@Size(max = 32)
@Schema(description = "발신 이름")
private String sendNm;
@Size(max = 32)
@Schema(description = "발신 이름")
private String sendNm;
}

View File

@@ -4,20 +4,21 @@ 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.*;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Schema(description = "일괄 발송 요청 정보")
public class SendRequestBulkDto extends SendRequestBasicDto {
@Size(max = 32)
@NotBlank
@Schema(description = "일괄 발송 고유키")
String bulkSendKey;
@Size(max = 32)
@NotBlank
@Schema(description = "일괄 발송 고유키")
String bulkSendKey;
@NotNull
@Schema(description = "수신자 정보")
List<DestInfoDto> destInfoList;
@NotNull
@Schema(description = "수신자 정보")
List<DestInfoDto> destInfoList;
}

View File

@@ -5,36 +5,31 @@ import com.kri.common.datetime.LenientLocalDateTime;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.*;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Schema(description = "단건 발송 요청 정보")
public class SendRequestSingleDto extends SendRequestBasicDto {
@NotNull
@Schema(description = "발송 템플릿")
private long tmplatIdx;
@NotBlank
@Schema(description = "발송 요청 서비스 (로그용)")
private String reqstSvc;
@Schema(description = "발송 요청 서비스의 프로젝트 코드 (로그용)")
private String prjctCd;
@NotNull
@Schema(description = "예약 여부")
private Boolean resve = false;
@Schema(description = "발송 희망 시간 (비어있는 경우 즉시)")
@LenientLocalDateTime
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime sendDt;
@NotNull
@Schema(description = "수신자 정보")
DestInfoDto destInfo;
@NotNull
@Schema(description = "수신자 정보")
DestInfoDto destInfo;
@NotNull
@Schema(description = "발송 템플릿")
private long tmplatIdx;
@NotBlank
@Schema(description = "발송 요청 서비스 (로그용)")
private String reqstSvc;
@Schema(description = "발송 요청 서비스의 프로젝트 코드 (로그용)")
private String prjctCd;
@NotNull
@Schema(description = "예약 여부")
private Boolean resve = false;
@Schema(description = "발송 희망 시간 (비어있는 경우 즉시)")
@LenientLocalDateTime
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime sendDt;
}

View File

@@ -12,12 +12,12 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor
public class SmsCursorResponseDto {
@Schema(description = "SMS 결과 반영 스케줄러 커서(send_idx)")
private Long cursor;
@Schema(description = "SMS 결과 반영 스케줄러 커서(send_idx)")
private Long cursor;
public static SmsCursorResponseDto of(long cursor) {
return SmsCursorResponseDto.builder()
.cursor(cursor)
.build();
}
public static SmsCursorResponseDto of(long cursor) {
return SmsCursorResponseDto.builder()
.cursor(cursor)
.build();
}
}

View File

@@ -19,42 +19,42 @@ import lombok.experimental.SuperBuilder;
@AllArgsConstructor
public class TemplateBasicDto {
@Size(max = 32)
@NotBlank
@Schema(description = "인트라넷 프로젝트 코드")
public String itrntPrjctCd;
@Size(max = 32)
@NotBlank
@Schema(description = "인트라넷 프로젝트 코드")
public String itrntPrjctCd;
@NotNull
@Schema(description = "템플릿 타입")
public SendType tmplatTy;
@NotNull
@Schema(description = "템플릿 타입")
public SendType tmplatTy;
@Size(max = 32)
@NotBlank
@Schema(description = "템플릿 명")
public String tmplatNm;
@Size(max = 32)
@NotBlank
@Schema(description = "템플릿 명")
public String tmplatNm;
@Size(max = 128)
@Schema(description = "발송시 제목")
public String tmplatTitle;
@Size(max = 128)
@Schema(description = "발송시 제목")
public String tmplatTitle;
@NotBlank
@Schema(description = "발송 내용")
public String tmplatBody;
@NotBlank
@Schema(description = "발송 내용")
public String tmplatBody;
@Schema(description = "이메일 건당 발송 딜레이(단위 ms, 기본: 500ms)")
public Short delayTime ;
@Schema(description = "이메일 건당 발송 딜레이(단위 ms, 기본: 500ms)")
public Short delayTime;
@Size(max = 16)
@Schema(description = "발송 전화번호(문자 발송에서 사용)")
public String sendTel;
@Size(max = 16)
@Schema(description = "발송 전화번호(문자 발송에서 사용)")
public String sendTel;
@Size(max = 64)
@Email
@Schema(description = "발송 이메일(이메일 발송에서 사용)")
public String sendEml;
@Size(max = 64)
@Email
@Schema(description = "발송 이메일(이메일 발송에서 사용)")
public String sendEml;
@Size(max = 32)
@NotBlank
@Schema(description = "발송자 이름")
public String sendNm;
@Size(max = 32)
@NotBlank
@Schema(description = "발송자 이름")
public String sendNm;
}

View File

@@ -4,13 +4,14 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.persistence.entity.TTmplatEntity;
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.*;
import lombok.experimental.SuperBuilder;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
@Getter
@Setter
@@ -18,46 +19,46 @@ import java.time.LocalDateTime;
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "템플릿 정보")
public class TemplateDto extends TemplateBasicDto{
public class TemplateDto extends TemplateBasicDto {
@NotNull
@Schema(description = "템플릿 고유 키 (없으면 Create / 있으면 Update)")
public Long tmplatIdx;
@NotNull
@Schema(description = "템플릿 고유 키 (없으면 Create / 있으면 Update)")
public Long tmplatIdx;
@Size(max = 32)
@Schema(description = "등록자", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String regUser;
@Size(max = 32)
@Schema(description = "등록자", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String regUser;
@Schema(description = "등록일시", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private LocalDateTime regDt;
@Schema(description = "등록일시", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private LocalDateTime regDt;
@Size(max = 32)
@Schema(description = "수정자", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String modUser;
@Size(max = 32)
@Schema(description = "수정자", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String modUser;
@Schema(description = "수정일시", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private LocalDateTime modDt;
@Schema(description = "수정일시", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private LocalDateTime modDt;
public static TemplateDto from(TTmplatEntity entity) {
return TemplateDto.builder()
.tmplatIdx(entity.getTmplatIdx())
.itrntPrjctCd(entity.getItrntPrjctCd())
.tmplatTy(SendType.fromCode(entity.getTmplatTy()))
.tmplatNm(entity.getTmplatNm())
.tmplatTitle(entity.getTmplatTitle())
.tmplatBody(entity.getTmplatBody())
.delayTime(entity.getDelayTime())
.sendTel(entity.getSendTel())
.sendEml(entity.getSendEml())
.sendNm(entity.getSendNm())
.regUser(entity.getRegUser())
.regDt(entity.getRegDt())
.modUser(entity.getModUser())
.modDt(entity.getModDt())
.build();
}
public static TemplateDto from(TTmplatEntity entity) {
return TemplateDto.builder()
.tmplatIdx(entity.getTmplatIdx())
.itrntPrjctCd(entity.getItrntPrjctCd())
.tmplatTy(SendType.fromCode(entity.getTmplatTy()))
.tmplatNm(entity.getTmplatNm())
.tmplatTitle(entity.getTmplatTitle())
.tmplatBody(entity.getTmplatBody())
.delayTime(entity.getDelayTime())
.sendTel(entity.getSendTel())
.sendEml(entity.getSendEml())
.sendNm(entity.getSendNm())
.regUser(entity.getRegUser())
.regDt(entity.getRegDt())
.modUser(entity.getModUser())
.modDt(entity.getModDt())
.build();
}
}

View File

@@ -2,7 +2,11 @@ package com.kri.notihub.server.dto.template;
import com.kri.notihub.server.persistence.entity.TTmplatEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@@ -11,16 +15,17 @@ import lombok.*;
@AllArgsConstructor
@Schema(description = "템플릿 요약 정보")
public class TemplateSummaryDto {
@Schema(description = "템플릿 고유 키")
public Long tmplatIdx;
@Schema(description = "템플릿 명")
public String tmplatNm;
@Schema(description = "템플릿 고유 키")
public Long tmplatIdx;
public static TemplateSummaryDto from(TTmplatEntity entity) {
return TemplateSummaryDto.builder()
.tmplatIdx(entity.getTmplatIdx())
.tmplatNm(entity.getTmplatNm())
.build();
}
@Schema(description = "템플릿 명")
public String tmplatNm;
public static TemplateSummaryDto from(TTmplatEntity entity) {
return TemplateSummaryDto.builder()
.tmplatIdx(entity.getTmplatIdx())
.tmplatNm(entity.getTmplatNm())
.build();
}
}

View File

@@ -4,145 +4,143 @@ import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import java.time.LocalDateTime;
@Getter
@Setter
@Entity
@Table(name = "`BIZ_LOG`")
public class BizLogEntity {
@Id
@Size(max = 32)
@Column(name = "`CMID`", length = 32)
private String cmid;
@Size(max = 32)
@Column(name = "`UMID`", length = 32)
private String umid;
@Id
@Size(max = 32)
@Column(name = "`CMID`", length = 32)
private String cmid;
@Column(name = "`MSG_TYPE`")
private Integer msgType;
@Size(max = 32)
@Column(name = "`UMID`", length = 32)
private String umid;
@Column(name = "`STATUS`")
private Integer status;
@Column(name = "`MSG_TYPE`")
private Integer msgType;
@Size(max = 32)
@Column(name = "`CALL_STATUS`", length = 32)
private String callStatus;
@Column(name = "`STATUS`")
private Integer status;
@Column(name = "`REQUEST_TIME`")
private LocalDateTime requestTime;
@Size(max = 32)
@Column(name = "`CALL_STATUS`", length = 32)
private String callStatus;
@Column(name = "`SEND_TIME`")
private LocalDateTime sendTime;
@Column(name = "`REQUEST_TIME`")
private LocalDateTime requestTime;
@Column(name = "`REPORT_TIME`")
private LocalDateTime reportTime;
@Column(name = "`SEND_TIME`")
private LocalDateTime sendTime;
@Size(max = 16)
@Column(name = "`DEST_PHONE`", length = 16)
private String destPhone;
@Column(name = "`REPORT_TIME`")
private LocalDateTime reportTime;
@Size(max = 32)
@Column(name = "`DEST_NAME`", length = 32)
private String destName;
@Size(max = 16)
@Column(name = "`DEST_PHONE`", length = 16)
private String destPhone;
@Size(max = 16)
@Column(name = "`SEND_PHONE`", length = 16)
private String sendPhone;
@Size(max = 32)
@Column(name = "`DEST_NAME`", length = 32)
private String destName;
@Size(max = 32)
@Column(name = "`SEND_NAME`", length = 32)
private String sendName;
@Size(max = 16)
@Column(name = "`SEND_PHONE`", length = 16)
private String sendPhone;
@Size(max = 64)
@Column(name = "`SUBJECT`", length = 64)
private String subject;
@Size(max = 32)
@Column(name = "`SEND_NAME`", length = 32)
private String sendName;
@Size(max = 2000)
@Column(name = "`MSG_BODY`", length = 2000)
private String msgBody;
@Size(max = 64)
@Column(name = "`SUBJECT`", length = 64)
private String subject;
@Size(max = 5)
@Column(name = "`NATION_CODE`", length = 5)
private String nationCode;
@Size(max = 2000)
@Column(name = "`MSG_BODY`", length = 2000)
private String msgBody;
@Size(max = 40)
@Column(name = "`SENDER_KEY`", length = 40)
private String senderKey;
@Size(max = 5)
@Column(name = "`NATION_CODE`", length = 5)
private String nationCode;
@Size(max = 64)
@Column(name = "`TEMPLATE_CODE`", length = 64)
private String templateCode;
@Size(max = 40)
@Column(name = "`SENDER_KEY`", length = 40)
private String senderKey;
@Size(max = 8)
@Column(name = "`RESPONSE_METHOD`", length = 8)
private String responseMethod;
@Size(max = 64)
@Column(name = "`TEMPLATE_CODE`", length = 64)
private String templateCode;
@Size(max = 4)
@Column(name = "`TIMEOUT`", length = 4)
private String timeout;
@Size(max = 8)
@Column(name = "`RESPONSE_METHOD`", length = 8)
private String responseMethod;
@Size(max = 3)
@Column(name = "`RE_TYPE`", length = 3)
private String reType;
@Size(max = 4)
@Column(name = "`TIMEOUT`", length = 4)
private String timeout;
@Size(max = 2000)
@Column(name = "`RE_BODY`", length = 2000)
private String reBody;
@Size(max = 3)
@Column(name = "`RE_TYPE`", length = 3)
private String reType;
@Size(max = 1)
@Column(name = "`RE_PART`", length = 1)
private String rePart;
@Size(max = 2000)
@Column(name = "`RE_BODY`", length = 2000)
private String reBody;
@Column(name = "`COVER_FLAG`")
private Integer coverFlag;
@Size(max = 1)
@Column(name = "`RE_PART`", length = 1)
private String rePart;
@Column(name = "`SMS_FLAG`")
private Integer smsFlag;
@Column(name = "`COVER_FLAG`")
private Integer coverFlag;
@Column(name = "`REPLY_FLAG`")
private Integer replyFlag;
@Column(name = "`SMS_FLAG`")
private Integer smsFlag;
@Column(name = "`RETRY_CNT`")
private Integer retryCnt;
@Column(name = "`REPLY_FLAG`")
private Integer replyFlag;
@Size(max = 1000)
@Column(name = "`ATTACHED_FILE`", length = 1000)
private String attachedFile;
@Column(name = "`RETRY_CNT`")
private Integer retryCnt;
@Size(max = 64)
@Column(name = "`VXML_FILE`", length = 64)
private String vxmlFile;
@Size(max = 1000)
@Column(name = "`ATTACHED_FILE`", length = 1000)
private String attachedFile;
@Column(name = "`USE_PAGE`")
private Integer usePage;
@Size(max = 64)
@Column(name = "`VXML_FILE`", length = 64)
private String vxmlFile;
@Column(name = "`USE_TIME`")
private Integer useTime;
@Column(name = "`USE_PAGE`")
private Integer usePage;
@Column(name = "`SN_RESULT`")
private Integer snResult;
@Column(name = "`USE_TIME`")
private Integer useTime;
@Size(max = 10)
@Column(name = "`TEL_INFO`", length = 10)
private String telInfo;
@Column(name = "`SN_RESULT`")
private Integer snResult;
@Size(max = 32)
@Column(name = "`CINFO`", length = 32)
private String cinfo;
@Size(max = 10)
@Column(name = "`TEL_INFO`", length = 10)
private String telInfo;
@Size(max = 30)
@Column(name = "`USER_KEY`", length = 30)
private String userKey;
@Size(max = 32)
@Column(name = "`CINFO`", length = 32)
private String cinfo;
@Size(max = 1)
@Column(name = "`AD_FLAG`", length = 1)
private String adFalg;
@Size(max = 30)
@Column(name = "`USER_KEY`", length = 30)
private String userKey;
@Size(max = 1)
@Column(name = "`AD_FLAG`", length = 1)
private String adFalg;
}

View File

@@ -7,10 +7,13 @@ import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.*;
import org.hibernate.annotations.ColumnDefault;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
@Getter
@Setter
@@ -20,151 +23,152 @@ import java.time.LocalDateTime;
@AllArgsConstructor
@Table(name = "`BIZ_MSG`")
public class BizMsgEntity {
@Id
@Size(max = 32)
@Column(name = "`CMID`", nullable = false, length = 32)
private String cmid;
@Size(max = 32)
@Column(name = "`UMID`", length = 32)
private String umid;
@Id
@Size(max = 32)
@Column(name = "`CMID`", nullable = false, length = 32)
private String cmid;
@NotNull
@ColumnDefault("0")
@Column(name = "`MSG_TYPE`", nullable = false)
private Integer msgType;
@Size(max = 32)
@Column(name = "`UMID`", length = 32)
private String umid;
@NotNull
@ColumnDefault("0")
@Column(name = "`STATUS`", nullable = false)
private Integer status;
@NotNull
@ColumnDefault("0")
@Column(name = "`MSG_TYPE`", nullable = false)
private Integer msgType;
@Size(max = 32)
@Column(name = "`CALL_STATUS`", length = 32)
private String callStatus;
@NotNull
@ColumnDefault("0")
@Column(name = "`STATUS`", nullable = false)
private Integer status;
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "`REQUEST_TIME`", nullable = false)
private LocalDateTime requestTime;
@Size(max = 32)
@Column(name = "`CALL_STATUS`", length = 32)
private String callStatus;
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "`SEND_TIME`", nullable = false)
private LocalDateTime sendTime;
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "`REQUEST_TIME`", nullable = false)
private LocalDateTime requestTime;
@Column(name = "`REPORT_TIME`")
private LocalDateTime reportTime;
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "`SEND_TIME`", nullable = false)
private LocalDateTime sendTime;
@Size(max = 16)
@NotNull
@Column(name = "`DEST_PHONE`", nullable = false, length = 16)
private String destPhone;
@Column(name = "`REPORT_TIME`")
private LocalDateTime reportTime;
@Size(max = 32)
@Column(name = "`DEST_NAME`", length = 32)
private String destName;
@Size(max = 16)
@NotNull
@Column(name = "`DEST_PHONE`", nullable = false, length = 16)
private String destPhone;
@Size(max = 16)
@NotNull
@Column(name = "`SEND_PHONE`", nullable = false, length = 16)
private String sendPhone;
@Size(max = 32)
@Column(name = "`DEST_NAME`", length = 32)
private String destName;
@Size(max = 32)
@Column(name = "`SEND_NAME`", length = 32)
private String sendName;
@Size(max = 16)
@NotNull
@Column(name = "`SEND_PHONE`", nullable = false, length = 16)
private String sendPhone;
@Size(max = 64)
@Column(name = "`SUBJECT`", length = 64)
private String subject;
@Size(max = 32)
@Column(name = "`SEND_NAME`", length = 32)
private String sendName;
@Size(max = 2000)
@NotNull
@Column(name = "`MSG_BODY`", nullable = false, length = 2000)
private String msgBody;
@Size(max = 64)
@Column(name = "`SUBJECT`", length = 64)
private String subject;
@Size(max = 5)
@Column(name = "`NATION_CODE`", length = 5)
private String nationCode;
@Size(max = 2000)
@NotNull
@Column(name = "`MSG_BODY`", nullable = false, length = 2000)
private String msgBody;
@Size(max = 40)
@Column(name = "`SENDER_KEY`", length = 40)
private String senderKey;
@Size(max = 5)
@Column(name = "`NATION_CODE`", length = 5)
private String nationCode;
@Size(max = 64)
@Column(name = "`TEMPLATE_CODE`", length = 64)
private String templateCode;
@Size(max = 40)
@Column(name = "`SENDER_KEY`", length = 40)
private String senderKey;
@Size(max = 8)
@Column(name = "`RESPONSE_METHOD`", length = 8)
private String responseMethod;
@Size(max = 64)
@Column(name = "`TEMPLATE_CODE`", length = 64)
private String templateCode;
@Size(max = 4)
@Column(name = "`TIMEOUT`", length = 4)
private String timeout;
@Size(max = 8)
@Column(name = "`RESPONSE_METHOD`", length = 8)
private String responseMethod;
@Size(max = 3)
@Column(name = "`RE_TYPE`", length = 3)
private String reType;
@Size(max = 4)
@Column(name = "`TIMEOUT`", length = 4)
private String timeout;
@Size(max = 2000)
@Column(name = "`RE_BODY`", length = 2000)
private String reBody;
@Size(max = 3)
@Column(name = "`RE_TYPE`", length = 3)
private String reType;
@Size(max = 1)
@Column(name = "`RE_PART`", length = 1)
private String rePart;
@Size(max = 2000)
@Column(name = "`RE_BODY`", length = 2000)
private String reBody;
@ColumnDefault("0")
@Column(name = "`COVER_FLAG`")
private Integer coverFlag;
@Size(max = 1)
@Column(name = "`RE_PART`", length = 1)
private String rePart;
@ColumnDefault("0")
@Column(name = "`SMS_FLAG`")
private Integer smsFlag;
@ColumnDefault("0")
@Column(name = "`COVER_FLAG`")
private Integer coverFlag;
@ColumnDefault("0")
@Column(name = "`REPLY_FLAG`")
private Integer replyFlag;
@ColumnDefault("0")
@Column(name = "`SMS_FLAG`")
private Integer smsFlag;
@Column(name = "`RETRY_CNT`")
private Integer retryCnt;
@ColumnDefault("0")
@Column(name = "`REPLY_FLAG`")
private Integer replyFlag;
@Size(max = 1000)
@Column(name = "`ATTACHED_FILE`", length = 1000)
private String attachedFile;
@Column(name = "`RETRY_CNT`")
private Integer retryCnt;
@Size(max = 64)
@Column(name = "`VXML_FILE`", length = 64)
private String vxmlFile;
@Size(max = 1000)
@Column(name = "`ATTACHED_FILE`", length = 1000)
private String attachedFile;
@ColumnDefault("0")
@Column(name = "`USE_PAGE`")
private Integer usePage;
@Size(max = 64)
@Column(name = "`VXML_FILE`", length = 64)
private String vxmlFile;
@ColumnDefault("0")
@Column(name = "`USE_TIME`")
private Integer useTime;
@ColumnDefault("0")
@Column(name = "`USE_PAGE`")
private Integer usePage;
@ColumnDefault("0")
@Column(name = "`SN_RESULT`")
private Integer snResult;
@ColumnDefault("0")
@Column(name = "`USE_TIME`")
private Integer useTime;
@Size(max = 10)
@Column(name = "`TEL_INFO`", length = 10)
private String telInfo;
@ColumnDefault("0")
@Column(name = "`SN_RESULT`")
private Integer snResult;
@Size(max = 32)
@Column(name = "`CINFO`", length = 32)
private String cinfo;
@Size(max = 10)
@Column(name = "`TEL_INFO`", length = 10)
private String telInfo;
@Size(max = 30)
@Column(name = "`USER_KEY`", length = 30)
private String userKey;
@Size(max = 32)
@Column(name = "`CINFO`", length = 32)
private String cinfo;
@Size(max = 1)
@Column(name = "`AD_FLAG`", length = 1)
private String adFalg;
@Size(max = 30)
@Column(name = "`USER_KEY`", length = 30)
private String userKey;
@Size(max = 1)
@Column(name = "`AD_FLAG`", length = 1)
private String adFalg;
/*
@Size(max = 32)
@@ -172,24 +176,24 @@ public class BizMsgEntity {
private String rcsRefkey;
*/
public static BizMsgEntity fromSend(TSendEntity s){
int msgType = s.getSendTy().equals(SendType.SMS.getCode()) ? 0 : 5;
String subject = s.getSendTy().equals(SendType.SMS.getCode()) ? null : s.getMsgTitle();
public static BizMsgEntity fromSend(TSendEntity s) {
int msgType = s.getSendTy().equals(SendType.SMS.getCode()) ? 0 : 5;
String subject = s.getSendTy().equals(SendType.SMS.getCode()) ? null : s.getMsgTitle();
return BizMsgEntity.builder()
.cmid(s.getCmid())
.msgType(msgType)
.status(0)
.requestTime(s.getRegDt())
.sendTime(s.getSendDt())
.destPhone(s.getDestTel().replace("-", ""))
.destName(s.getDestNm())
.sendPhone(s.getSendTel().replace("-", ""))
.sendName(s.getSendNm())
.subject(subject)
.msgBody(s.getMsgBody())
.cinfo(s.getReqstSvc())
.build();
}
return BizMsgEntity.builder()
.cmid(s.getCmid())
.msgType(msgType)
.status(0)
.requestTime(s.getRegDt())
.sendTime(s.getSendDt())
.destPhone(s.getDestTel().replace("-", ""))
.destName(s.getDestNm())
.sendPhone(s.getSendTel().replace("-", ""))
.sendName(s.getSendNm())
.subject(subject)
.msgBody(s.getMsgBody())
.cinfo(s.getReqstSvc())
.build();
}
}

View File

@@ -2,13 +2,19 @@ package com.kri.notihub.server.persistence.entity;
import com.kri.common.jpa.BaseUuidEntity;
import com.kri.notihub.server.dto.send.BulkSendCreateRequestDto;
import jakarta.persistence.*;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.*;
import org.hibernate.annotations.ColumnDefault;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
@Getter
@Setter
@@ -18,97 +24,98 @@ import java.time.LocalDateTime;
@AllArgsConstructor
@Table(name = "t_bulk_send")
public class TBulkSendEntity extends BaseUuidEntity {
@Id
@Size(max = 32)
@Column(name = "bulk_send_key", nullable = false, length = 32)
private String bulkSendKey;
@Size(max = 16)
@NotNull
@Column(name = "reqst_svc", nullable = false, length = 16)
private String reqstSvc;
@Id
@Size(max = 32)
@Column(name = "bulk_send_key", nullable = false, length = 32)
private String bulkSendKey;
@Size(max = 32)
@NotNull
@Column(name = "prjct_cd", nullable = false, length = 32)
private String prjctCd;
@Size(max = 16)
@NotNull
@Column(name = "reqst_svc", nullable = false, length = 16)
private String reqstSvc;
@Column(name = "tmplat_idx", columnDefinition = "int UNSIGNED")
private Long tmplatIdx;
@Size(max = 32)
@NotNull
@Column(name = "prjct_cd", nullable = false, length = 32)
private String prjctCd;
@NotNull
@Column(name = "is_resve", nullable = false)
private Boolean resve = false;
@Column(name = "tmplat_idx", columnDefinition = "int UNSIGNED")
private Long tmplatIdx;
@NotNull
@Column(name = "send_dt", nullable = false)
private LocalDateTime sendDt;
@NotNull
@Column(name = "is_resve", nullable = false)
private Boolean resve = false;
@NotNull
@Column(name = "trgt_cnt", nullable = false)
private Integer trgtCnt;
@NotNull
@Column(name = "send_dt", nullable = false)
private LocalDateTime sendDt;
@NotNull
@Column(name = "send_cnt", nullable = false)
private Integer sendCnt;
@NotNull
@Column(name = "trgt_cnt", nullable = false)
private Integer trgtCnt;
@NotNull
@Column(name = "succes_cnt", nullable = false)
private Integer succesCnt;
@NotNull
@Column(name = "send_cnt", nullable = false)
private Integer sendCnt;
@NotNull
@Column(name = "fail_cnt", nullable = false)
private Integer failCnt;
@NotNull
@Column(name = "succes_cnt", nullable = false)
private Integer succesCnt;
@Column(name = "complete_dt")
private LocalDateTime completeDt;
@NotNull
@Column(name = "fail_cnt", nullable = false)
private Integer failCnt;
@Size(max = 32)
@NotNull
@Column(name = "reg_cmpn", nullable = false, length = 32)
private String regCmpn;
@Column(name = "complete_dt")
private LocalDateTime completeDt;
@Size(max = 32)
@NotNull
@Column(name = "reg_user", nullable = false, length = 32)
private String regUser;
@Size(max = 32)
@NotNull
@Column(name = "reg_cmpn", nullable = false, length = 32)
private String regCmpn;
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private LocalDateTime regDt;
@Size(max = 32)
@NotNull
@Column(name = "reg_user", nullable = false, length = 32)
private String regUser;
public static TBulkSendEntity from(BulkSendCreateRequestDto req, LocalDateTime now) {
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private LocalDateTime regDt;
return TBulkSendEntity.builder()
.reqstSvc(req.getReqstSvc())
.prjctCd(req.getPrjctCd())
.tmplatIdx(req.getTmplatIdx())
.resve(req.getResve())
.sendDt(req.getSendDt() != null ? req.getSendDt() : now)
.trgtCnt(req.getTrgtCnt())
.sendCnt(0)
.succesCnt(0)
.failCnt(0)
.completeDt(null)
.regCmpn(req.getReqstCmpn())
.regUser(req.getReqstUser())
.regDt(now)
.build();
}
public static TBulkSendEntity from(BulkSendCreateRequestDto req, LocalDateTime now) {
@Override
protected String getId() {
return this.bulkSendKey;
}
return TBulkSendEntity.builder()
.reqstSvc(req.getReqstSvc())
.prjctCd(req.getPrjctCd())
.tmplatIdx(req.getTmplatIdx())
.resve(req.getResve())
.sendDt(req.getSendDt() != null ? req.getSendDt() : now)
.trgtCnt(req.getTrgtCnt())
.sendCnt(0)
.succesCnt(0)
.failCnt(0)
.completeDt(null)
.regCmpn(req.getReqstCmpn())
.regUser(req.getReqstUser())
.regDt(now)
.build();
}
@Override
protected void setId(String id) {
this.bulkSendKey = id;
}
@Override
protected String getId() {
return this.bulkSendKey;
}
@Override
protected int idLength() {
return 32; // cmid가 32면 생략해도 되지만 명시해두면 안전
}
@Override
protected void setId(String id) {
this.bulkSendKey = id;
}
@Override
protected int idLength() {
return 32; // cmid가 32면 생략해도 되지만 명시해두면 안전
}
}

View File

@@ -1,14 +1,22 @@
package com.kri.notihub.server.persistence.entity;
import io.hypersistence.utils.hibernate.type.json.JsonType;
import jakarta.persistence.*;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import lombok.*;
import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.Type;
import java.time.LocalDateTime;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.Type;
@Getter
@Setter
@@ -19,58 +27,58 @@ import java.util.Map;
@Table(name = "t_resve_send")
public class TResveSendEntity {
@Id
@NotNull
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "resve_idx", nullable = false)
private Long resveIdx;
@Id
@NotNull
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "resve_idx", nullable = false)
private Long resveIdx;
@Column(name = "bulk_send_key", length = 32)
private String bulkSendKey;
@Column(name = "bulk_send_key", length = 32)
private String bulkSendKey;
@NotNull
@Column(name = "send_ty", nullable = false)
private Short sendTy;
@NotNull
@Column(name = "send_ty", nullable = false)
private Short sendTy;
@NotNull
@Column(name = "reqst_svc", nullable = false, length = 16)
private String reqstSvc;
@NotNull
@Column(name = "reqst_svc", nullable = false, length = 16)
private String reqstSvc;
@NotNull
@Column(name = "prjct_cd", nullable = false, length = 32)
private String prjctCd;
@NotNull
@Column(name = "prjct_cd", nullable = false, length = 32)
private String prjctCd;
@Column(name = "tmplat_idx")
private Long tmplatIdx;
@Column(name = "tmplat_idx")
private Long tmplatIdx;
@NotNull
@Column(name = "resve_dt", nullable = false)
private LocalDateTime resveDt;
@NotNull
@Column(name = "resve_dt", nullable = false)
private LocalDateTime resveDt;
@NotNull
@Column(name = "sid", nullable = false)
private Integer sid;
@NotNull
@Column(name = "sid", nullable = false)
private Integer sid;
@NotNull
@Type(JsonType.class)
@Column(name = "msg_param", nullable = false, columnDefinition = "json")
private Map<String, Object> msgParam;
@NotNull
@Type(JsonType.class)
@Column(name = "msg_param", nullable = false, columnDefinition = "json")
private Map<String, Object> msgParam;
@Column(name = "dest_eml", length = 64)
private String destEml;
@Column(name = "dest_eml", length = 64)
private String destEml;
@Column(name = "dest_tel", length = 16)
private String destTel;
@Column(name = "dest_tel", length = 16)
private String destTel;
@Column(name = "dest_nm", length = 32)
private String destNm;
@Column(name = "dest_nm", length = 32)
private String destNm;
@NotNull
@Column(name = "reg_user", nullable = false, length = 32)
private String regUser;
@NotNull
@Column(name = "reg_user", nullable = false, length = 32)
private String regUser;
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private LocalDateTime regDt;
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private LocalDateTime regDt;
}

View File

@@ -7,15 +7,24 @@ import com.kri.notihub.server.dto.send.SendInternalResultDto;
import com.kri.notihub.server.dto.send.SendRequestBasicDto;
import com.kri.notihub.server.dto.send.SendRequestSingleDto;
import io.hypersistence.utils.hibernate.type.json.JsonType;
import jakarta.persistence.*;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Lob;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.*;
import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.Type;
import java.time.LocalDateTime;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.Type;
@Builder
@Getter
@@ -26,207 +35,214 @@ import java.util.Map;
@Table(name = "t_send")
public class TSendEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "send_idx", nullable = false)
private Long sendIdx;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "send_idx", nullable = false)
private Long sendIdx;
@NotNull
@Size(max = 32)
@Column(name = "cmid", nullable = false, length = 32)
private String cmid;
@NotNull
@Size(max = 32)
@Column(name = "cmid", nullable = false, length = 32)
private String cmid;
@Size(max = 32)
@Column(name = "bulk_send_key", length = 32)
private String bulkSendKey;
@Size(max = 32)
@Column(name = "bulk_send_key", length = 32)
private String bulkSendKey;
@NotNull
@Column(name = "send_ty", nullable = false)
private Short sendTy;
@NotNull
@Column(name = "send_ty", nullable = false)
private Short sendTy;
@NotNull
@Column(name = "is_resve", nullable = false)
private boolean resve = false;
@NotNull
@Column(name = "is_resve", nullable = false)
private boolean resve = false;
@NotNull
@Column(name = "send_corp", nullable = false)
private Short sendCorp;
@NotNull
@Column(name = "send_corp", nullable = false)
private Short sendCorp;
@NotNull
@Column(name = "send_status", nullable = false)
private Short sendStatus;
@NotNull
@Column(name = "send_status", nullable = false)
private Short sendStatus;
@NotNull
@Column(name = "result_code", nullable = false)
private Short resultCode;
@NotNull
@Column(name = "result_code", nullable = false)
private Short resultCode;
@Size(max = 32)
@NotNull
@Column(name = "itrnt_prjct_cd", nullable = false, length = 32)
private String itrntPrjctCd;
@Size(max = 32)
@NotNull
@Column(name = "itrnt_prjct_cd", nullable = false, length = 32)
private String itrntPrjctCd;
@Size(max = 16)
@NotNull
@Column(name = "reqst_svc", nullable = false, length = 16)
private String reqstSvc;
@Size(max = 16)
@NotNull
@Column(name = "reqst_svc", nullable = false, length = 16)
private String reqstSvc;
@Size(max = 32)
@NotNull
@Column(name = "prjct_cd", nullable = false, length = 32)
private String prjctCd;
@Size(max = 32)
@NotNull
@Column(name = "prjct_cd", nullable = false, length = 32)
private String prjctCd;
@Column(name = "tmplat_idx", columnDefinition = "int UNSIGNED")
private Long tmplatIdx;
@Column(name = "tmplat_idx", columnDefinition = "int UNSIGNED")
private Long tmplatIdx;
@Size(max = 64)
@Column(name = "send_eml", length = 64)
private String sendEml;
@Size(max = 64)
@Column(name = "send_eml", length = 64)
private String sendEml;
@Size(max = 16)
@Column(name = "send_tel", length = 16)
private String sendTel;
@Size(max = 16)
@Column(name = "send_tel", length = 16)
private String sendTel;
@Size(max = 32)
@Column(name = "send_nm", length = 32)
private String sendNm;
@Size(max = 32)
@Column(name = "send_nm", length = 32)
private String sendNm;
@NotNull
@Column(name = "send_dt", nullable = false)
private LocalDateTime sendDt;
@NotNull
@Column(name = "send_dt", nullable = false)
private LocalDateTime sendDt;
@NotNull
@Size(max = 128)
@Column(name = "sid", nullable = false, length = 128)
private String sid;
@NotNull
@Size(max = 128)
@Column(name = "sid", nullable = false, length = 128)
private String sid;
@Size(max = 128)
@Column(name = "msg_title", length = 128)
private String msgTitle;
@Size(max = 128)
@Column(name = "msg_title", length = 128)
private String msgTitle;
@NotNull
@Lob
@Column(name = "msg_body", nullable = false)
private String msgBody;
@NotNull
@Lob
@Column(name = "msg_body", nullable = false)
private String msgBody;
@NotNull
@Type(JsonType.class)
@Column(name = "msg_param", nullable = false)
private Map<String, String> msgParam;
@NotNull
@Type(JsonType.class)
@Column(name = "msg_param", nullable = false)
private Map<String, String> msgParam;
@Size(max = 64)
@Column(name = "dest_eml", length = 64)
private String destEml;
@Size(max = 64)
@Column(name = "dest_eml", length = 64)
private String destEml;
@Size(max = 16)
@Column(name = "dest_tel", length = 16)
private String destTel;
@Size(max = 16)
@Column(name = "dest_tel", length = 16)
private String destTel;
@Size(max = 32)
@Column(name = "dest_nm", length = 32)
private String destNm;
@Size(max = 32)
@Column(name = "dest_nm", length = 32)
private String destNm;
@Column(name = "report_dt")
private LocalDateTime reportDt;
@Column(name = "report_dt")
private LocalDateTime reportDt;
@Size(max = 32)
@NotNull
@Column(name = "reg_cmpn", nullable = false, length = 32)
private String regCmpn;
@Size(max = 32)
@NotNull
@Column(name = "reg_cmpn", nullable = false, length = 32)
private String regCmpn;
@Size(max = 32)
@NotNull
@Column(name = "reg_user", nullable = false, length = 32)
private String regUser;
@Size(max = 32)
@NotNull
@Column(name = "reg_user", nullable = false, length = 32)
private String regUser;
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private LocalDateTime regDt;
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private LocalDateTime regDt;
public static TSendEntity from(
SendRequestSingleDto req,
SendType sendTy,
SendInternalResultDto sendResult,
String itrntPrjctCd,
String msgTitle,
String msgBody,
String regCmpn,
String regUser,
Boolean resve,
LocalDateTime sendDt,
LocalDateTime regDt
){
if (req == null) return null;
return from(
req,
req.getDestInfo(),
sendTy,
sendResult,
itrntPrjctCd,
req.getReqstSvc(),
req.getPrjctCd(),
req.getTmplatIdx(),
msgTitle,
msgBody,
regCmpn,
regUser,
resve,
sendDt,
null,
regDt
);
public static TSendEntity from(
SendRequestSingleDto req,
SendType sendTy,
SendInternalResultDto sendResult,
String itrntPrjctCd,
String msgTitle,
String msgBody,
String regCmpn,
String regUser,
Boolean resve,
LocalDateTime sendDt,
LocalDateTime regDt
) {
if (req == null) {
return null;
}
return from(
req,
req.getDestInfo(),
sendTy,
sendResult,
itrntPrjctCd,
req.getReqstSvc(),
req.getPrjctCd(),
req.getTmplatIdx(),
msgTitle,
msgBody,
regCmpn,
regUser,
resve,
sendDt,
null,
regDt
);
}
public static TSendEntity from(
SendRequestBasicDto basic,
DestInfoDto dest,
SendType sendTy,
SendInternalResultDto sendResult,
String itrntPrjctCd,
String reqstSvc,
String prjctCd,
Long tmplatIdx,
String msgTitle,
String msgBody,
String regCmpn,
String regUser,
Boolean resve,
LocalDateTime sendDt,
String bulkSendKey,
LocalDateTime regDt
) {
if (basic == null) {
return null;
}
public static TSendEntity from(
SendRequestBasicDto basic,
DestInfoDto dest,
SendType sendTy,
SendInternalResultDto sendResult,
String itrntPrjctCd,
String reqstSvc,
String prjctCd,
Long tmplatIdx,
String msgTitle,
String msgBody,
String regCmpn,
String regUser,
Boolean resve,
LocalDateTime sendDt,
String bulkSendKey,
LocalDateTime regDt
){
if (basic == null) return null;
if (dest == null) return null;
Short sendCorp = sendTy == SendType.EMAIL ? SendCorpType.PRINGO.getCode() : SendCorpType.BIZ_PPURIO.getCode();
return TSendEntity.builder()
.cmid(sendResult.getCmid())
.bulkSendKey(bulkSendKey)
.sendTy(sendTy.getCode())
.resve(resve)
.sendCorp(sendCorp)
.sendStatus(sendResult.getStatus().getCode())
.resultCode(sendResult.getResultCode())
.itrntPrjctCd(itrntPrjctCd)
.reqstSvc(reqstSvc)
.prjctCd(prjctCd)
.tmplatIdx(tmplatIdx)
.sendEml(basic.getSendEml())
.sendTel(basic.getSendTel())
.sendNm(basic.getSendNm())
.sendDt(sendDt)
.sid(dest.getSid())
.msgTitle(msgTitle)
.msgBody(msgBody)
.msgParam(dest.getMsgParam() != null? dest.getMsgParam() : Map.of())
.destEml(dest.getDestEml())
.destTel(dest.getDestTel())
.destNm(dest.getDestNm())
.regCmpn(regCmpn)
.regUser(regUser)
.regDt(regDt)
.build();
if (dest == null) {
return null;
}
Short sendCorp = sendTy == SendType.EMAIL ? SendCorpType.PRINGO.getCode()
: SendCorpType.BIZ_PPURIO.getCode();
return TSendEntity.builder()
.cmid(sendResult.getCmid())
.bulkSendKey(bulkSendKey)
.sendTy(sendTy.getCode())
.resve(resve)
.sendCorp(sendCorp)
.sendStatus(sendResult.getStatus().getCode())
.resultCode(sendResult.getResultCode())
.itrntPrjctCd(itrntPrjctCd)
.reqstSvc(reqstSvc)
.prjctCd(prjctCd)
.tmplatIdx(tmplatIdx)
.sendEml(basic.getSendEml())
.sendTel(basic.getSendTel())
.sendNm(basic.getSendNm())
.sendDt(sendDt)
.sid(dest.getSid())
.msgTitle(msgTitle)
.msgBody(msgBody)
.msgParam(dest.getMsgParam() != null ? dest.getMsgParam() : Map.of())
.destEml(dest.getDestEml())
.destTel(dest.getDestTel())
.destNm(dest.getDestNm())
.regCmpn(regCmpn)
.regUser(regUser)
.regDt(regDt)
.build();
}
}

View File

@@ -14,28 +14,33 @@ import lombok.Setter;
@Entity
@Table(name = "t_send_result_code")
public class TSendResultCodeEntity {
@EmbeddedId
private TSendResultCodeEntityId id;
@NotNull
@Column(name = "result_ty", nullable = false)
private Short resultTy;
@EmbeddedId
private TSendResultCodeEntityId id;
@Size(max = 128)
@NotNull
@Column(name = "result_label", nullable = false, length = 128)
private String resultLabel;
@NotNull
@Column(name = "result_ty", nullable = false)
private Short resultTy;
@Size(max = 128)
@NotNull
@Column(name = "result_view_label", nullable = false, length = 128)
private String resultViewLabel;
@Size(max = 128)
@NotNull
@Column(name = "result_label", nullable = false, length = 128)
private String resultLabel;
@Size(max = 128)
@Column(name = "memo", length = 128)
private String memo;
@Size(max = 128)
@NotNull
@Column(name = "result_view_label", nullable = false, length = 128)
private String resultViewLabel;
public short getSendCorp() { return id.getSendCorp(); }
@Size(max = 128)
@Column(name = "memo", length = 128)
private String memo;
public short getResultCode() { return id.getResultCode(); }
public short getSendCorp() {
return id.getSendCorp();
}
public short getResultCode() {
return id.getResultCode();
}
}

View File

@@ -3,38 +3,42 @@ package com.kri.notihub.server.persistence.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import jakarta.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Objects;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.Hibernate;
import java.io.Serializable;
import java.util.Objects;
@Getter
@Setter
@Embeddable
public class TSendResultCodeEntityId implements Serializable {
private static final long serialVersionUID = -53054354660031517L;
@NotNull
@Column(name = "send_corp", nullable = false)
private Short sendCorp;
@NotNull
@Column(name = "result_code", nullable = false)
private Short resultCode;
private static final long serialVersionUID = -53054354660031517L;
@NotNull
@Column(name = "send_corp", nullable = false)
private Short sendCorp;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
TSendResultCodeEntityId entity = (TSendResultCodeEntityId) o;
return Objects.equals(this.sendCorp, entity.sendCorp) &&
Objects.equals(this.resultCode, entity.resultCode);
@NotNull
@Column(name = "result_code", nullable = false)
private Short resultCode;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
@Override
public int hashCode() {
return Objects.hash(sendCorp, resultCode);
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) {
return false;
}
TSendResultCodeEntityId entity = (TSendResultCodeEntityId) o;
return Objects.equals(this.sendCorp, entity.sendCorp) &&
Objects.equals(this.resultCode, entity.resultCode);
}
@Override
public int hashCode() {
return Objects.hash(sendCorp, resultCode);
}
}

View File

@@ -1,13 +1,22 @@
package com.kri.notihub.server.persistence.entity;
import com.kri.notihub.server.dto.template.TemplateBasicDto;
import jakarta.persistence.*;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Lob;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.*;
import org.hibernate.annotations.ColumnDefault;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
@Builder
@Getter
@@ -17,108 +26,110 @@ import java.time.LocalDateTime;
@NoArgsConstructor
@AllArgsConstructor
public class TTmplatEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "tmplat_idx", columnDefinition = "int UNSIGNED not null")
private Long tmplatIdx;
@Size(max = 32)
@NotNull
@Column(name = "itrnt_prjct_cd", nullable = false, length = 32)
private String itrntPrjctCd;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "tmplat_idx", columnDefinition = "int UNSIGNED not null")
private Long tmplatIdx;
@NotNull
@Column(name = "tmplat_ty", nullable = false)
private Short tmplatTy;
@Size(max = 32)
@NotNull
@Column(name = "itrnt_prjct_cd", nullable = false, length = 32)
private String itrntPrjctCd;
@Size(max = 32)
@NotNull
@Column(name = "tmplat_nm", nullable = false, length = 32)
private String tmplatNm;
@NotNull
@Column(name = "tmplat_ty", nullable = false)
private Short tmplatTy;
@Size(max = 128)
@Column(name = "tmplat_title", length = 128)
private String tmplatTitle;
@Size(max = 32)
@NotNull
@Column(name = "tmplat_nm", nullable = false, length = 32)
private String tmplatNm;
@NotNull
@Lob
@Column(name = "tmplat_body", nullable = false)
private String tmplatBody;
@Size(max = 128)
@Column(name = "tmplat_title", length = 128)
private String tmplatTitle;
@Column(name = "delay_time")
private Short delayTime;
@NotNull
@Lob
@Column(name = "tmplat_body", nullable = false)
private String tmplatBody;
@Size(max = 16)
@Column(name = "send_tel", length = 16)
private String sendTel;
@Column(name = "delay_time")
private Short delayTime;
@Size(max = 64)
@Column(name = "send_eml", length = 64)
private String sendEml;
@Size(max = 16)
@Column(name = "send_tel", length = 16)
private String sendTel;
@Size(max = 32)
@Column(name = "send_nm", length = 32)
private String sendNm;
@Size(max = 64)
@Column(name = "send_eml", length = 64)
private String sendEml;
@Size(max = 32)
@NotNull
@Column(name = "reg_user", nullable = false, length = 32, updatable = false)
private String regUser;
@Size(max = 32)
@Column(name = "send_nm", length = 32)
private String sendNm;
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false, updatable = false)
private LocalDateTime regDt;
@Size(max = 32)
@NotNull
@Column(name = "reg_user", nullable = false, length = 32, updatable = false)
private String regUser;
@Size(max = 32)
@Column(name = "mod_user", length = 32, insertable = false)
private String modUser;
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false, updatable = false)
private LocalDateTime regDt;
@Column(name = "mod_dt", insertable = false)
private LocalDateTime modDt;
@Size(max = 32)
@Column(name = "mod_user", length = 32, insertable = false)
private String modUser;
@NotNull
@ColumnDefault("0")
@Column(name = "is_del", nullable = false)
private Boolean del = false;
@Column(name = "mod_dt", insertable = false)
private LocalDateTime modDt;
@Size(max = 32)
@Column(name = "del_user", length = 32)
private String delUser;
@NotNull
@ColumnDefault("0")
@Column(name = "is_del", nullable = false)
private Boolean del = false;
@Column(name = "del_dt")
private LocalDateTime delDt;
@Size(max = 32)
@Column(name = "del_user", length = 32)
private String delUser;
public static TTmplatEntity create(String itrntPrjctCd, TemplateBasicDto template, String regUser, LocalDateTime regDt) {
return TTmplatEntity.builder()
.itrntPrjctCd(itrntPrjctCd)
.tmplatTy(template.tmplatTy.getCode())
.tmplatNm(template.tmplatNm)
.tmplatTitle(template.tmplatTitle)
.tmplatBody(template.tmplatBody)
.delayTime(template.delayTime)
.sendTel(template.sendTel)
.sendEml(template.sendEml)
.sendNm(template.sendNm)
.regUser(regUser)
.regDt(regDt)
.del(false)
.build();
}
@Column(name = "del_dt")
private LocalDateTime delDt;
public void updateFrom(TemplateBasicDto template, String modUser, LocalDateTime modDt) {
// 기본 정보 갱신
this.tmplatTy = template.tmplatTy.getCode();
this.tmplatNm = template.tmplatNm;
this.tmplatTitle = template.tmplatTitle;
this.tmplatBody = template.tmplatBody;
this.delayTime = template.delayTime;
this.sendTel = template.sendTel;
this.sendEml = template.sendEml;
this.sendNm = template.sendNm;
public static TTmplatEntity create(String itrntPrjctCd, TemplateBasicDto template, String regUser,
LocalDateTime regDt) {
return TTmplatEntity.builder()
.itrntPrjctCd(itrntPrjctCd)
.tmplatTy(template.tmplatTy.getCode())
.tmplatNm(template.tmplatNm)
.tmplatTitle(template.tmplatTitle)
.tmplatBody(template.tmplatBody)
.delayTime(template.delayTime)
.sendTel(template.sendTel)
.sendEml(template.sendEml)
.sendNm(template.sendNm)
.regUser(regUser)
.regDt(regDt)
.del(false)
.build();
}
// 수정 메타 갱신
this.modUser = modUser;
this.modDt = modDt;
}
public void updateFrom(TemplateBasicDto template, String modUser, LocalDateTime modDt) {
// 기본 정보 갱신
this.tmplatTy = template.tmplatTy.getCode();
this.tmplatNm = template.tmplatNm;
this.tmplatTitle = template.tmplatTitle;
this.tmplatBody = template.tmplatBody;
this.delayTime = template.delayTime;
this.sendTel = template.sendTel;
this.sendEml = template.sendEml;
this.sendNm = template.sendNm;
// 수정 메타 갱신
this.modUser = modUser;
this.modDt = modDt;
}
}

View File

@@ -3,15 +3,23 @@ package com.kri.notihub.server.persistence.entity;
import com.kri.notihub.server.common.enums.TemplateEventType;
import com.kri.notihub.server.dto.template.TemplateBasicDto;
import io.hypersistence.utils.hibernate.type.json.JsonType;
import jakarta.persistence.*;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.*;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.Type;
import java.time.LocalDateTime;
@Builder
@Getter
@Setter
@@ -20,52 +28,53 @@ import java.time.LocalDateTime;
@NoArgsConstructor
@AllArgsConstructor
public class TTmplatEventLogEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "tmplat_event_idx", columnDefinition = "int UNSIGNED not null")
private Long tmplatEventIdx;
@Column(name = "tmplat_idx", columnDefinition = "int UNSIGNED not null")
private Long tmplatIdx;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "tmplat_event_idx", columnDefinition = "int UNSIGNED not null")
private Long tmplatEventIdx;
@NotNull
@Column(name = "event_ty", nullable = false)
private Short eventTy;
@Column(name = "tmplat_idx", columnDefinition = "int UNSIGNED not null")
private Long tmplatIdx;
@Type(JsonType.class)
@Column(name = "before_tmplat")
private TemplateBasicDto beforeTmplat;
@NotNull
@Column(name = "event_ty", nullable = false)
private Short eventTy;
@NotNull
@Type(JsonType.class)
@Column(name = "after_tmplat", nullable = false)
private TemplateBasicDto afterTmplat;
@Type(JsonType.class)
@Column(name = "before_tmplat")
private TemplateBasicDto beforeTmplat;
@Size(max = 32)
@NotNull
@Column(name = "reg_user", nullable = false, length = 32)
private String regUser;
@NotNull
@Type(JsonType.class)
@Column(name = "after_tmplat", nullable = false)
private TemplateBasicDto afterTmplat;
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private LocalDateTime regDt;
@Size(max = 32)
@NotNull
@Column(name = "reg_user", nullable = false, length = 32)
private String regUser;
public static TTmplatEventLogEntity of(
Long tmplatIdx,
TemplateEventType eventTy,
TemplateBasicDto beforeTmplat,
TemplateBasicDto afterTmplat,
String regUser,
LocalDateTime regDt
) {
return TTmplatEventLogEntity.builder()
.tmplatIdx(tmplatIdx)
.eventTy(eventTy.getCode())
.beforeTmplat(beforeTmplat)
.afterTmplat(afterTmplat)
.regUser(regUser)
.regDt(regDt)
.build();
}
@NotNull
@ColumnDefault("CURRENT_TIMESTAMP")
@Column(name = "reg_dt", nullable = false)
private LocalDateTime regDt;
public static TTmplatEventLogEntity of(
Long tmplatIdx,
TemplateEventType eventTy,
TemplateBasicDto beforeTmplat,
TemplateBasicDto afterTmplat,
String regUser,
LocalDateTime regDt
) {
return TTmplatEventLogEntity.builder()
.tmplatIdx(tmplatIdx)
.eventTy(eventTy.getCode())
.beforeTmplat(beforeTmplat)
.afterTmplat(afterTmplat)
.regUser(regUser)
.regDt(regDt)
.build();
}
}

View File

@@ -1,16 +1,15 @@
package com.kri.notihub.server.persistence.repository;
import com.kri.notihub.server.persistence.entity.BizLogEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BizLogRepository extends JpaRepository<BizLogEntity, String> {
Optional<BizLogEntity> findTopByCmidOrderByReportTimeDesc(String cmid);
Optional<BizLogEntity> findTopByCmidOrderByReportTimeDesc(String cmid);
// 또는 대량처리용(필요시)
List<BizLogEntity> findByCmidIn(Collection<String> cmids);
// 또는 대량처리용(필요시)
List<BizLogEntity> findByCmidIn(Collection<String> cmids);
}

View File

@@ -4,4 +4,5 @@ import com.kri.notihub.server.persistence.entity.BizMsgEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BizMsgRepository extends JpaRepository<BizMsgEntity, String> {
}

View File

@@ -1,47 +1,46 @@
package com.kri.notihub.server.persistence.repository;
import com.kri.notihub.server.persistence.entity.TBulkSendEntity;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
import java.util.Optional;
public interface BulkSendRepository extends JpaRepository<TBulkSendEntity, String> {
List<TBulkSendEntity> findByBulkSendKeyIn(List<String> bulkSendKeyList);
List<TBulkSendEntity> findByBulkSendKeyIn(List<String> bulkSendKeyList);
@Query("""
select b
from TBulkSendEntity b
join TTmplatEntity t on t.tmplatIdx = b.tmplatIdx
where t.tmplatTy in :sendTyList
and b.reqstSvc = :reqstSvc
and b.prjctCd = :prjctCd
order by b.regDt desc
""")
List<TBulkSendEntity> findBySendTyInAndReqstSvcAndPrjctCd(
List<Short> sendTyList,
String reqstSvc,
String prjctCd
);
@Query("""
select b
from TBulkSendEntity b
join TTmplatEntity t on t.tmplatIdx = b.tmplatIdx
where t.tmplatTy in :sendTyList
and b.reqstSvc = :reqstSvc
and b.prjctCd = :prjctCd
order by b.regDt desc
""")
List<TBulkSendEntity> findBySendTyInAndReqstSvcAndPrjctCd(
List<Short> sendTyList,
String reqstSvc,
String prjctCd
);
@Query("""
select b
from TBulkSendEntity b
join TTmplatEntity t on t.tmplatIdx = b.tmplatIdx
where t.tmplatTy in :sendTyList
and b.reqstSvc = :reqstSvc
and b.prjctCd = :prjctCd
and b.regCmpn = :regCmpn
order by b.regDt desc
""")
List<TBulkSendEntity> findBySendTyInAndReqstSvcAndPrjctCdAndRegCmpn(
List<Short> sendTyList,
String reqstSvc,
String prjctCd,
String regCmpn
);
@Query("""
select b
from TBulkSendEntity b
join TTmplatEntity t on t.tmplatIdx = b.tmplatIdx
where t.tmplatTy in :sendTyList
and b.reqstSvc = :reqstSvc
and b.prjctCd = :prjctCd
and b.regCmpn = :regCmpn
order by b.regDt desc
""")
List<TBulkSendEntity> findBySendTyInAndReqstSvcAndPrjctCdAndRegCmpn(
List<Short> sendTyList,
String reqstSvc,
String prjctCd,
String regCmpn
);
Optional<TBulkSendEntity> findByBulkSendKey(String bulkSendKey);
Optional<TBulkSendEntity> findByBulkSendKey(String bulkSendKey);
}

View File

@@ -1,68 +1,67 @@
package com.kri.notihub.server.persistence.repository;
import com.kri.notihub.server.persistence.entity.TSendEntity;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
public interface SendRepository extends JpaRepository<TSendEntity, Long> {
Optional<TSendEntity> findByCmid(String cmid);
Optional<TSendEntity> findByCmid(String cmid);
@Query("""
select coalesce(min(s.sendIdx), 0)
from TSendEntity s
where s.sendTy = :sendTy and s.sendStatus = 0
""")
long findMinSendIdxBySendTy(short sendTy);
@Query("""
select coalesce(min(s.sendIdx), 0)
from TSendEntity s
where s.sendTy = :sendTy and s.sendStatus = 0
""")
long findMinSendIdxBySendTy(short sendTy);
@Query("""
select s
from TSendEntity s
where s.sendStatus = :sendStatus
and s.sendTy in :sendTyList
and s.sendDt between :fromDt and :toDt
order by s.sendIdx asc
""")
List<TSendEntity> findSendListToRefreshWithinHours(
List<Short> sendTyList,
short sendStatus,
LocalDateTime fromDt,
LocalDateTime toDt,
Pageable pageable
);
@Query("""
select s
from TSendEntity s
where s.sendStatus = :sendStatus
and s.sendTy in :sendTyList
and s.sendDt between :fromDt and :toDt
order by s.sendIdx asc
""")
List<TSendEntity> findSendListToRefreshWithinHours(
List<Short> sendTyList,
short sendStatus,
LocalDateTime fromDt,
LocalDateTime toDt,
Pageable pageable
);
@Query("""
select s
from TSendEntity s
where s.sendTy = :sendTy
and s.resultCode = :resultCode
and s.resve = true
and s.sendDt <= :now
order by s.sendIdx asc
""")
List<TSendEntity> findReservedSendEmail(
short sendTy,
short resultCode,
LocalDateTime now,
Pageable pageable
);
@Query("""
select s
from TSendEntity s
where s.sendTy = :sendTy
and s.resultCode = :resultCode
and s.resve = true
and s.sendDt <= :now
order by s.sendIdx asc
""")
List<TSendEntity> findReservedSendEmail(
short sendTy,
short resultCode,
LocalDateTime now,
Pageable pageable
);
/**
* Poller 복구용: STANDBY_EMAIL 상태로 남아있는 최근 발송건을 다시 enqueue 하기 위해 사용
*/
Page<TSendEntity> findBySendTyAndResultCodeAndSendDtAfterOrderBySendDtAsc(
short sendTy,
short resultCode,
LocalDateTime sendDtAfter,
Pageable pageable
);
/**
* Poller 복구용: STANDBY_EMAIL 상태로 남아있는 최근 발송건을 다시 enqueue 하기 위해 사용
*/
Page<TSendEntity> findBySendTyAndResultCodeAndSendDtAfterOrderBySendDtAsc(
short sendTy,
short resultCode,
LocalDateTime sendDtAfter,
Pageable pageable
);
Page<TSendEntity> findByBulkSendKey(String bulkSendKey, Pageable pageable);
Page<TSendEntity> findByBulkSendKey(String bulkSendKey, Pageable pageable);
}

View File

@@ -4,6 +4,8 @@ import com.kri.notihub.server.persistence.entity.TSendResultCodeEntity;
import com.kri.notihub.server.persistence.entity.TSendResultCodeEntityId;
import org.springframework.data.jpa.repository.JpaRepository;
public interface SendResultCodeRepository extends JpaRepository<TSendResultCodeEntity, TSendResultCodeEntityId> {
public interface SendResultCodeRepository extends
JpaRepository<TSendResultCodeEntity, TSendResultCodeEntityId> {
}

View File

@@ -4,6 +4,7 @@ import com.kri.notihub.server.persistence.entity.TTmplatEventLogEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface TemplateEventLogRepository extends JpaRepository<TTmplatEventLogEntity, Long>, JpaSpecificationExecutor<TTmplatEventLogEntity> {
public interface TemplateEventLogRepository extends JpaRepository<TTmplatEventLogEntity, Long>,
JpaSpecificationExecutor<TTmplatEventLogEntity> {
}

View File

@@ -1,29 +1,30 @@
package com.kri.notihub.server.persistence.repository;
import com.kri.notihub.server.persistence.entity.TTmplatEntity;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
public interface TemplateRepository extends JpaRepository<TTmplatEntity, Long>,
JpaSpecificationExecutor<TTmplatEntity> {
public interface TemplateRepository extends JpaRepository<TTmplatEntity, Long>, JpaSpecificationExecutor<TTmplatEntity> {
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("""
update TTmplatEntity t
set t.del = true,
t.delUser = :delUser,
t.delDt = :delDt
where t.tmplatIdx = :idx
and t.del = false
""")
int softDeleteByTmplatIdx(long idx, String delUser, LocalDateTime delDt);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("""
update TTmplatEntity t
set t.del = true,
t.delUser = :delUser,
t.delDt = :delDt
where t.tmplatIdx = :idx
and t.del = false
""")
int softDeleteByTmplatIdx(long idx, String delUser, LocalDateTime delDt);
List<TTmplatEntity> findAllByTmplatTyInAndItrntPrjctCdAndDelFalse(List<Short> tmplatTyList,
String itrntPrjctCd);
List<TTmplatEntity> findAllByTmplatTyInAndItrntPrjctCdAndDelFalse(List<Short> tmplatTyList, String itrntPrjctCd);
Optional<TTmplatEntity> findByTmplatIdxAndDelFalse(long tmplatIdx);
Optional<TTmplatEntity> findByTmplatIdxAndDelFalse(long tmplatIdx);
}

View File

@@ -11,226 +11,273 @@ 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.SmsSendCursorStore;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class BizLogResultScheduler {
private final SmsSendCursorStore cursorStore;
private final SendRepository sendRepository;
private final BizLogRepository bizLogRepository;
private final BulkSendRepository bulkSendRepository;
@Scheduled(fixedDelay = 60 * 1_000) // 나중에 증가시킬 것
@Transactional(transactionManager = "transactionManager")
public void syncSmsResults() {
private final SmsSendCursorStore cursorStore;
private final SendRepository sendRepository;
private final BizLogRepository bizLogRepository;
private final BulkSendRepository bulkSendRepository;
TimeWindow window = buildWindow(1L); // hours는 추후 파라미터화
@Scheduled(fixedDelay = 60 * 1_000) // 나중에 증가시킬 것
@Transactional(transactionManager = "transactionManager")
public void syncSmsResults() {
List<Short> sendTyList = List.of(SendType.SMS.getCode(), SendType.LMS_MMS.getCode());
TimeWindow window = buildWindow(1L); // hours는 추후 파라미터화
while (true) {
List<TSendEntity> batch = fetchRefreshTargets(sendTyList, window, 1000);
if (batch.isEmpty()) return;
List<Short> sendTyList = List.of(SendType.SMS.getCode(), SendType.LMS_MMS.getCode());
BulkContext bulkCtx = loadBulkContext(batch);
while (true) {
List<TSendEntity> batch = fetchRefreshTargets(sendTyList, window, 1000);
if (batch.isEmpty()) {
return;
}
BatchResult result = applyResultsAndCollectDeltas(batch, bulkCtx);
BulkContext bulkCtx = loadBulkContext(batch);
persistChanges(result, bulkCtx);
}
BatchResult result = applyResultsAndCollectDeltas(batch, bulkCtx);
persistChanges(result, bulkCtx);
}
}
private TimeWindow buildWindow(long hours) {
LocalDateTime toDt = LocalDateTime.now();
return new TimeWindow(toDt.minusHours(hours), toDt);
}
private List<TSendEntity> fetchRefreshTargets(List<Short> sendTyList, TimeWindow window,
int size) {
return sendRepository.findSendListToRefreshWithinHours(
sendTyList,
SendStatusType.STANDBY.getCode(),
window.from(),
window.to(),
PageRequest.of(0, size)
);
}
/**
* batch에서 bulkKey 수집 + bulk 엔티티 로딩 + Map 인덱싱
*/
private BulkContext loadBulkContext(List<TSendEntity> batch) {
Set<String> bulkKeys = extractBulkKeys(batch);
if (bulkKeys.isEmpty()) {
return new BulkContext(Set.of(), Map.of());
}
private TimeWindow buildWindow(long hours) {
LocalDateTime toDt = LocalDateTime.now();
return new TimeWindow(toDt.minusHours(hours), toDt);
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);
});
}
private List<TSendEntity> fetchRefreshTargets(List<Short> sendTyList, TimeWindow window, int size) {
return sendRepository.findSendListToRefreshWithinHours(
sendTyList,
SendStatusType.STANDBY.getCode(),
window.from(),
window.to(),
PageRequest.of(0, size)
);
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);
}
/**
* 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 (key == null || key.isBlank()) {
return;
}
if (!bulkMap.containsKey(key)) {
return;
}
/** 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);
if (!Objects.equals(beforeStatus, SendStatusType.STANDBY.getCode())) {
return;
}
private Set<String> extractBulkKeys(List<TSendEntity> batch) {
return batch.stream()
.map(TSendEntity::getBulkSendKey)
.filter(k -> k != null && !k.isBlank())
.collect(Collectors.toSet());
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());
}
/** 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);
if (bulkCtx.bulkMap().isEmpty()) {
return;
}
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);
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);
}
}
}
/** 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 (key == null || key.isBlank()) return;
if (!bulkMap.containsKey(key)) return;
private void applySmsResultFromBizLog(TSendEntity s, BizLogEntity log) {
// ReportDt(LocalDateTime) 반영
// BizLogEntity.reportTime 타입이 Date면 LocalDateTime 변환 로직으로 바꾸세요.
s.setReportDt(log.getReportTime());
if (!Objects.equals(beforeStatus, SendStatusType.STANDBY.getCode())) return;
short callStatus = safeParseShort(log.getCallStatus(), NotihubConst.SMS_NOT_RESULT);
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);
}
if (callStatus == NotihubConst.SMS_SUCCESS || callStatus == NotihubConst.LMS_MMS_SUCCESS) {
s.setSendStatus(SendStatusType.SUCCESS.getCode());
s.setResultCode(callStatus);
} else {
s.setSendStatus(SendStatusType.FAIL.getCode());
s.setResultCode(callStatus); // “그 외 실패”이지만, 실제 코드 보존이 운영/분석에 유리
}
}
/** 저장 + 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 short safeParseShort(String v, short fallback) {
if (v == null || v.isBlank()) {
return fallback;
}
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);
}
}
try {
return Short.parseShort(v.trim());
} catch (Exception e) {
return fallback;
}
}
private void applySmsResultFromBizLog(TSendEntity s, BizLogEntity log) {
// ReportDt(LocalDateTime) 반영
// BizLogEntity.reportTime 타입이 Date면 LocalDateTime 변환 로직으로 바꾸세요.
s.setReportDt(log.getReportTime());
private record TimeWindow(LocalDateTime from, LocalDateTime to) {
short callStatus = safeParseShort(log.getCallStatus(), NotihubConst.SMS_NOT_RESULT);
}
if (callStatus == NotihubConst.SMS_SUCCESS || callStatus == NotihubConst.LMS_MMS_SUCCESS) {
s.setSendStatus(SendStatusType.SUCCESS.getCode());
s.setResultCode(callStatus);
} else {
s.setSendStatus(SendStatusType.FAIL.getCode());
s.setResultCode(callStatus); // “그 외 실패”이지만, 실제 코드 보존이 운영/분석에 유리
}
}
private record BulkContext(Set<String> bulkKeys, Map<String, TBulkSendEntity> bulkMap) {
private short safeParseShort(String v, short fallback) {
if (v == null || v.isBlank()) return fallback;
try { return Short.parseShort(v.trim()); } catch (Exception e) { return fallback; }
}
}
private record TimeWindow(LocalDateTime from, LocalDateTime to) {}
private record BulkContext(Set<String> bulkKeys, Map<String, TBulkSendEntity> bulkMap) {}
private record BatchResult(List<TSendEntity> updatedSends,
Map<String, Integer> successDelta,
Map<String, Integer> failDelta) {}
private record BatchResult(List<TSendEntity> updatedSends,
Map<String, Integer> successDelta,
Map<String, Integer> failDelta) {
}
}

View File

@@ -10,64 +10,65 @@ 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 java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Service
@RequiredArgsConstructor
public class SendReservationEmailScheduler {
private final PringoApiClient pringoApiClient;
private final SendEmailService sendEmlService;
private final SendRepository sendRepository;
private final PringoApiClient pringoApiClient;
private final SendEmailService sendEmlService;
private final SendRepository sendRepository;
@Scheduled(cron = "0 */5 * * * *")
@Transactional(transactionManager = "transactionManager")
public void sendReservationEmail() {
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
@Scheduled(cron = "0 */5 * * * *")
@Transactional(transactionManager = "transactionManager")
public void sendReservationEmail() {
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
while (true) {
List<TSendEntity> updatedSends = new ArrayList<>();
while (true) {
List<TSendEntity> updatedSends = new ArrayList<>();
List<TSendEntity> reservationList = sendRepository.findReservedSendEmail(
SendType.EMAIL.getCode(),
NotihubConst.EMAIL_STANDBY,
now,
PageRequest.of(0, 1000)
);
List<TSendEntity> reservationList = sendRepository.findReservedSendEmail(
SendType.EMAIL.getCode(),
NotihubConst.EMAIL_STANDBY,
now,
PageRequest.of(0, 1000)
);
if(reservationList.isEmpty()) return;
if (reservationList.isEmpty()) {
return;
}
for (TSendEntity s : reservationList) {
PringoJsonSendRequestDto pringoReq = sendEmlService.buildPringoSendRequest(
s.getSendEml(),
s.getSendNm(),
s.getMsgTitle(),
s.getMsgBody(),
DestInfoDto.from(s)
);
for (TSendEntity s : reservationList) {
PringoJsonSendRequestDto pringoReq = sendEmlService.buildPringoSendRequest(
s.getSendEml(),
s.getSendNm(),
s.getMsgTitle(),
s.getMsgBody(),
DestInfoDto.from(s)
);
SendInternalResultDto sendResult = sendEmlService.sendPringoEmail(pringoReq);
SendInternalResultDto sendResult = sendEmlService.sendPringoEmail(pringoReq);
s.setCmid(sendResult.getCmid());
s.setSendStatus(sendResult.getStatus().getCode());
s.setResultCode(sendResult.getResultCode());
updatedSends.add(s);
}
s.setCmid(sendResult.getCmid());
s.setSendStatus(sendResult.getStatus().getCode());
s.setResultCode(sendResult.getResultCode());
updatedSends.add(s);
}
//TSendEntity update
sendRepository.saveAll(updatedSends);
sendRepository.flush();
//TSendEntity update
sendRepository.saveAll(updatedSends);
sendRepository.flush();
//결과들을 모았다가 afterPersistSendEntities
sendEmlService.afterPersistSendEntities(updatedSends);
}
//결과들을 모았다가 afterPersistSendEntities
sendEmlService.afterPersistSendEntities(updatedSends);
}
}
}

View File

@@ -1,91 +1,92 @@
package com.kri.notihub.server.scheduler;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Duration;
import java.time.Instant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Duration;
import java.time.Instant;
@Slf4j
@Component
public class TempFileCleanupScheduler {
private final Path uploadBaseDir;
private final Duration expireDuration;
private final Path uploadBaseDir;
private final Duration expireDuration;
public TempFileCleanupScheduler(
@Value("${kri.body-image.upload-base-dir}") String uploadBaseDirStr,
@Value("${kri.body-image.temp-expire-hours:24}") long expireHours
) {
this.uploadBaseDir = Paths.get(uploadBaseDirStr);
this.expireDuration = Duration.ofHours(expireHours);
public TempFileCleanupScheduler(
@Value("${kri.body-image.upload-base-dir}") String uploadBaseDirStr,
@Value("${kri.body-image.temp-expire-hours:24}") long expireHours
) {
this.uploadBaseDir = Paths.get(uploadBaseDirStr);
this.expireDuration = Duration.ofHours(expireHours);
}
/**
* 매일 자정(00:00)에 실행. 필요하면 application.yml 에서 kri.body-image.temp-cleanup-cron 으로 변경 가능.
*/
@Scheduled(cron = "${kri.body-image.temp-cleanup-cron:0 0 0 * * *}")
public void cleanupOldTempFiles() {
if (!Files.isDirectory(uploadBaseDir)) {
log.warn("[TempCleanup] uploadBaseDir({}) 가 디렉토리가 아닙니다.", uploadBaseDir);
return;
}
/**
* 매일 자정(00:00)에 실행.
* 필요하면 application.yml 에서 kri.body-image.temp-cleanup-cron 으로 변경 가능.
*/
@Scheduled(cron = "${kri.body-image.temp-cleanup-cron:0 0 0 * * *}")
public void cleanupOldTempFiles() {
if (!Files.isDirectory(uploadBaseDir)) {
log.warn("[TempCleanup] uploadBaseDir({}) 가 디렉토리가 아닙니다.", uploadBaseDir);
return;
Instant now = Instant.now();
Instant threshold = now.minus(expireDuration);
log.info("[TempCleanup] 시작 - baseDir={}, threshold={}", uploadBaseDir, threshold);
try (DirectoryStream<Path> projectDirs = Files.newDirectoryStream(uploadBaseDir)) {
for (Path projectDir : projectDirs) {
if (!Files.isDirectory(projectDir)) {
continue;
}
Instant now = Instant.now();
Instant threshold = now.minus(expireDuration);
log.info("[TempCleanup] 시작 - baseDir={}, threshold={}", uploadBaseDir, threshold);
try (DirectoryStream<Path> projectDirs = Files.newDirectoryStream(uploadBaseDir)) {
for (Path projectDir : projectDirs) {
if (!Files.isDirectory(projectDir)) {
continue;
}
Path tempDir = projectDir.resolve("Temp"); // {prjctCd}/Temp
if (!Files.isDirectory(tempDir)) {
continue;
}
cleanupTempDir(tempDir, threshold);
}
} catch (IOException e) {
log.error("[TempCleanup] baseDir 스캔 중 오류 - baseDir={}", uploadBaseDir, e);
Path tempDir = projectDir.resolve("Temp"); // {prjctCd}/Temp
if (!Files.isDirectory(tempDir)) {
continue;
}
log.info("[TempCleanup] 종료");
cleanupTempDir(tempDir, threshold);
}
} catch (IOException e) {
log.error("[TempCleanup] baseDir 스캔 중 오류 - baseDir={}", uploadBaseDir, e);
}
private void cleanupTempDir(Path tempDir, Instant threshold) {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(tempDir)) {
for (Path file : stream) {
if (!Files.isRegularFile(file)) {
continue;
}
log.info("[TempCleanup] 종료");
}
try {
BasicFileAttributes attrs =
Files.readAttributes(file, BasicFileAttributes.class);
// 생성 시간(지원 안 하면 마지막 수정 시간)을 기준으로 비교
Instant created = attrs.creationTime() != null
? attrs.creationTime().toInstant()
: attrs.lastModifiedTime().toInstant();
if (created.isBefore(threshold)) {
Files.deleteIfExists(file);
log.debug("[TempCleanup] 삭제: {} (created={})", file, created);
}
} catch (IOException ex) {
log.warn("[TempCleanup] 파일 삭제 실패: {}", file, ex);
}
}
} catch (IOException e) {
log.warn("[TempCleanup] temp 디렉토리 스캔 실패: {}", tempDir, e);
private void cleanupTempDir(Path tempDir, Instant threshold) {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(tempDir)) {
for (Path file : stream) {
if (!Files.isRegularFile(file)) {
continue;
}
try {
BasicFileAttributes attrs =
Files.readAttributes(file, BasicFileAttributes.class);
// 생성 시간(지원 안 하면 마지막 수정 시간)을 기준으로 비교
Instant created = attrs.creationTime() != null
? attrs.creationTime().toInstant()
: attrs.lastModifiedTime().toInstant();
if (created.isBefore(threshold)) {
Files.deleteIfExists(file);
log.debug("[TempCleanup] 삭제: {} (created={})", file, created);
}
} catch (IOException ex) {
log.warn("[TempCleanup] 파일 삭제 실패: {}", file, ex);
}
}
} catch (IOException e) {
log.warn("[TempCleanup] temp 디렉토리 스캔 실패: {}", tempDir, e);
}
}
}

View File

@@ -6,16 +6,6 @@ import com.kri.notihub.server.dto.send.EmailPollQueueItemDto;
import com.kri.notihub.server.dto.send.EmailPollQueueResponseDto;
import com.kri.notihub.server.persistence.entity.TSendEntity;
import com.kri.notihub.server.persistence.repository.SendRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import java.time.LocalDateTime;
@@ -27,14 +17,23 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
/**
* Pringo는 발송요청/결과조회가 "1건씩"만 가능하므로, 동기(요청 스레드)에서 json_return을
* 반복 호출하지 않고 Poller에서 비동기로 1회만 조회해 DB를 갱신한다.
*
* - 단건/벌크 공통: 발송요청 성공(return_key 수신) -> Poller enqueue -> (지연 후) json_return 1회 조회
* - 서비스 재기동 시: STANDBY_EMAIL + RESULT_CODE_PENDING 인 레코드를 DB에서 스캔하여 재등록
*
* Pringo는 발송요청/결과조회가 "1건씩"만 가능하므로, 동기(요청 스레드)에서 json_return을 반복 호출하지 않고 Poller에서 비동기로 1회만 조회해 DB를
* 갱신한다.
* <p>
* - 단건/벌크 공통: 발송요청 성공(return_key 수신) -> Poller enqueue -> (지연 후) json_return 1회 조회 - 서비스 재기동 시:
* STANDBY_EMAIL + RESULT_CODE_PENDING 인 레코드를 DB에서 스캔하여 재등록
* <p>
* 운영 정책(딜레이/재시도 횟수)은 설정으로 조정 가능(기본: 재시도 0회).
*/
@Slf4j
@@ -42,210 +41,232 @@ import java.util.concurrent.TimeUnit;
@RequiredArgsConstructor
public class EmailResultPoller {
private final DelayQueue<PollTask> queue = new DelayQueue<>();
private final EmailResultUpdater emailResultUpdater;
private final SendRepository sendRepository;
private final DelayQueue<PollTask> queue = new DelayQueue<>();
private final EmailResultUpdater emailResultUpdater;
private final SendRepository sendRepository;
/** 런타임 중 중복 enqueue 방지(같은 returnKey를 여러 번 등록하지 않기 위함) */
private final Set<String> scheduledKeys = ConcurrentHashMap.newKeySet();
/**
* 런타임 중 중복 enqueue 방지(같은 returnKey를 여러 번 등록하지 않기 위함)
*/
private final Set<String> scheduledKeys = ConcurrentHashMap.newKeySet();
private volatile boolean running = true;
private Thread worker;
private volatile boolean running = true;
private Thread worker;
/**
* 운영 권장값은 '최종 상태가 나올 가능성이 높은 지연'이다.
* 즉시성보다 '1회 조회로 최종 상태 반영'을 우선하면 60~180초 수준이 실무적으로 안정적이다.
*/
@Value("${kri.email.result-poll.initial-delay-ms:60000}")
private long initialDelayMs;
/**
* 운영 권장값은 '최종 상태가 나올 가능성이 높은 지연'이다. 즉시성보다 '1회 조회로 최종 상태 반영'을 우선하면 60~180초 수준이 실무적으로 안정적이다.
*/
@Value("${kri.email.result-poll.initial-delay-ms:60000}")
private long initialDelayMs;
/**
* 사용자는 json_return을 여러 번 호출하지 않을 예정이라고 했으므로 기본은 0(재시도 없음).
* 필요 시 설정으로 1~2 정도만 허용하는 것을 권장.
*/
@Value("${kri.email.result-poll.max-attempts:0}")
private int maxAttempts;
/**
* 사용자는 json_return을 여러 번 호출하지 않을 예정이라고 했으므로 기본은 0(재시도 없음). 필요 시 설정으로 1~2 정도만 허용하는 것을 권장.
*/
@Value("${kri.email.result-poll.max-attempts:0}")
private int maxAttempts;
@Value("${kri.email.result-poll.max-delay-ms:1800000}")
private long maxDelayMs;
@Value("${kri.email.result-poll.max-delay-ms:1800000}")
private long maxDelayMs;
@Value("${kri.email.result-poll.recover-days:3}")
private int recoverDays;
@Value("${kri.email.result-poll.recover-days:3}")
private int recoverDays;
@Value("${kri.email.result-poll.recover-page-size:1000}")
private int recoverPageSize;
@Value("${kri.email.result-poll.recover-page-size:1000}")
private int recoverPageSize;
public void enqueue(String returnKey) {
if (returnKey == null || returnKey.isBlank()) return;
enqueueInternal(returnKey.trim(), initialDelayMs, 0);
public void enqueue(String returnKey) {
if (returnKey == null || returnKey.isBlank()) {
return;
}
enqueueInternal(returnKey.trim(), initialDelayMs, 0);
}
public EmailPollQueueResponseDto snapshotQueue() {
final long nowNanos = System.nanoTime(); // queue 내부 기준(상대시간)
final long nowEpochMs = System.currentTimeMillis(); // 출력용 기준(절대시간)
public EmailPollQueueResponseDto snapshotQueue() {
final long nowNanos = System.nanoTime(); // queue 내부 기준(상대시간)
final long nowEpochMs = System.currentTimeMillis(); // 출력용 기준(절대시간)
List<EmailPollQueueItemDto> items = queue.stream()
.filter(Objects::nonNull)
.map(t -> {
long remainingNanos = t.triggerAtNanos - nowNanos;
long remainingMs = Math.max(0L, TimeUnit.NANOSECONDS.toMillis(remainingNanos));
List<EmailPollQueueItemDto> items = queue.stream()
.filter(Objects::nonNull)
.map(t -> {
long remainingNanos = t.triggerAtNanos - nowNanos;
long remainingMs = Math.max(0L, TimeUnit.NANOSECONDS.toMillis(remainingNanos));
// nanoTime은 epoch로 직접 변환 불가 → "현재 epoch + remainingMs"로 예상 시각 구성
long triggerAtEpochMs = nowEpochMs + remainingMs;
// nanoTime은 epoch로 직접 변환 불가 → "현재 epoch + remainingMs"로 예상 시각 구성
long triggerAtEpochMs = nowEpochMs + remainingMs;
return EmailPollQueueItemDto.of(
t.returnKey,
t.attempt,
remainingMs,
triggerAtEpochMs
);
})
.sorted(Comparator.comparingLong(i ->
i.getRemainingMs() != null ? i.getRemainingMs() : Long.MAX_VALUE
))
.toList();
return EmailPollQueueItemDto.of(
t.returnKey,
t.attempt,
remainingMs,
triggerAtEpochMs
);
})
.sorted(Comparator.comparingLong(i ->
i.getRemainingMs() != null ? i.getRemainingMs() : Long.MAX_VALUE
))
.toList();
return EmailPollQueueResponseDto.of(items);
return EmailPollQueueResponseDto.of(items);
}
/**
* 서비스 재기동 시 유실된 PollTask를 복구한다. - DB(t_send)에 STANDBY_EMAIL로 남아 있는 Pringo 이메일 중, cmid가
* return_key(숫자)인 레코드를 재등록 - in-memory 큐를 신뢰하지 않고, DB를 단일 소스 오브 트루스로 본다
*/
@EventListener(ApplicationReadyEvent.class)
public void recoverFromDbOnStartup() {
try {
LocalDateTime from = LocalDateTime.now().minusDays(Math.max(1, recoverDays));
int page = 0;
Pageable pageable = PageRequest.of(page, Math.max(100, recoverPageSize));
while (true) {
Page<TSendEntity> p = sendRepository.findBySendTyAndResultCodeAndSendDtAfterOrderBySendDtAsc(
SendType.EMAIL.getCode(),
NotihubConst.EMAIL_PENDING, // ★ STANDBY_EMAIL(100) 같은 값이 아니라 PENDING(111)을 복구 대상으로
from,
pageable
);
if (!p.hasContent()) {
break;
}
for (TSendEntity e : p.getContent()) {
if (isNumeric(e.getCmid())) {
// 재기동 복구는 '가능한 빨리' 한 번 조회하도록 짧은 딜레이로 등록
enqueueInternal(e.getCmid(), 1000L, 0);
}
}
if (!p.hasNext()) {
break;
}
pageable = p.nextPageable();
}
} catch (Exception ex) {
// 복구 실패가 서비스 기동을 막지 않도록
log.warn("EmailResultPoller recovery skipped due to error", ex);
}
}
/**
* 서비스 재기동 시 유실된 PollTask를 복구한다.
* - DB(t_send)에 STANDBY_EMAIL로 남아 있는 Pringo 이메일 중, cmid가 return_key(숫자)인 레코드를 재등록
* - in-memory 큐를 신뢰하지 않고, DB를 단일 소스 오브 트루스로 본다
*/
@EventListener(ApplicationReadyEvent.class)
public void recoverFromDbOnStartup() {
@PostConstruct
public void start() {
worker = new Thread(() -> {
while (running) {
try {
LocalDateTime from = LocalDateTime.now().minusDays(Math.max(1, recoverDays));
int page = 0;
Pageable pageable = PageRequest.of(page, Math.max(100, recoverPageSize));
while (true) {
Page<TSendEntity> p = sendRepository.findBySendTyAndResultCodeAndSendDtAfterOrderBySendDtAsc(
SendType.EMAIL.getCode(),
NotihubConst.EMAIL_PENDING, // ★ STANDBY_EMAIL(100) 같은 값이 아니라 PENDING(111)을 복구 대상으로
from,
pageable
);
if (!p.hasContent()) break;
if (queue.isEmpty()) {
Thread.sleep(5000);
continue;
}
for (TSendEntity e : p.getContent()) {
if (isNumeric(e.getCmid())) {
// 재기동 복구는 '가능한 빨리' 한 번 조회하도록 짧은 딜레이로 등록
enqueueInternal(e.getCmid(), 1000L, 0);
}
}
PollTask task = queue.take();
scheduledKeys.remove(task.returnKey);
if (!p.hasNext()) break;
pageable = p.nextPageable();
}
} catch (Exception ex) {
// 복구 실패가 서비스 기동을 막지 않도록
log.warn("EmailResultPoller recovery skipped due to error", ex);
boolean done = emailResultUpdater.tryUpdateEmailResult(task.returnKey);
if (!done && task.attempt < maxAttempts) {
long nextDelay = Math.min((long) (initialDelayMs * Math.pow(2, task.attempt + 1)),
maxDelayMs);
enqueueInternal(task.returnKey, nextDelay, task.attempt + 1);
} else if (!done) {
// 더 이상 재시도하지 않는 경우: 재기동 복구/중복 조회를 막기 위해 '조회 실패'로 마킹
markQueryFailIfPending(task.returnKey);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
// Poller 자체는 죽지 않도록 방어
log.debug("EmailResultPoller worker error", e);
}
}
}, "email-result-poller");
worker.setDaemon(true);
worker.start();
}
@PreDestroy
public void stop() {
running = false;
if (worker != null) {
worker.interrupt();
}
}
@PostConstruct
public void start() {
worker = new Thread(() -> {
while (running) {
try {
if(queue.isEmpty()){
Thread.sleep(5000);
continue;
}
PollTask task = queue.take();
scheduledKeys.remove(task.returnKey);
boolean done = emailResultUpdater.tryUpdateEmailResult(task.returnKey);
if (!done && task.attempt < maxAttempts) {
long nextDelay = Math.min((long) (initialDelayMs * Math.pow(2, task.attempt + 1)), maxDelayMs);
enqueueInternal(task.returnKey, nextDelay, task.attempt + 1);
} else if (!done) {
// 더 이상 재시도하지 않는 경우: 재기동 복구/중복 조회를 막기 위해 '조회 실패'로 마킹
markQueryFailIfPending(task.returnKey);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
// Poller 자체는 죽지 않도록 방어
log.debug("EmailResultPoller worker error", e);
}
}
}, "email-result-poller");
worker.setDaemon(true);
worker.start();
private void enqueueInternal(String returnKey, long delayMs, int attempt) {
if (!scheduledKeys.add(returnKey)) {
return;
}
queue.offer(new PollTask(returnKey, attempt, delayMs));
}
@PreDestroy
public void stop() {
running = false;
if (worker != null) worker.interrupt();
private boolean isNumeric(String s) {
if (s == null || s.isBlank()) {
return false;
}
private void enqueueInternal(String returnKey, long delayMs, int attempt) {
if (!scheduledKeys.add(returnKey)) return;
queue.offer(new PollTask(returnKey, attempt, delayMs));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
private boolean isNumeric(String s) {
if (s == null || s.isBlank()) return false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') return false;
private void markQueryFailIfPending(String returnKey) {
try {
sendRepository.findByCmid(returnKey).ifPresent(e -> {
if (e.getResultCode() != null && e.getResultCode() == NotihubConst.EMAIL_PENDING) {
e.setResultCode(NotihubConst.EMAIL_NOT_RESULT);
sendRepository.save(e);
}
});
} catch (Exception ex) {
log.debug("markQueryFailIfPending ignored. returnKey={}...", returnKey, ex);
}
}
static final class PollTask implements Delayed {
final String returnKey;
final int attempt;
final long triggerAtNanos;
PollTask(String returnKey, int attempt, long delayMs) {
this.returnKey = returnKey;
this.attempt = attempt;
long delayNanos = TimeUnit.MILLISECONDS.toNanos(Math.max(0, delayMs));
this.triggerAtNanos = System.nanoTime() + delayNanos;
}
@Override
public long getDelay(TimeUnit unit) {
long diffNanos = triggerAtNanos - System.nanoTime();
return unit.convert(diffNanos, TimeUnit.NANOSECONDS);
}
@Override
public int compareTo(Delayed o) {
if (o == this) {
return 0;
}
PollTask other = (PollTask) o;
return Long.compare(this.triggerAtNanos, other.triggerAtNanos);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof PollTask)) {
return false;
}
PollTask pollTask = (PollTask) o;
return attempt == pollTask.attempt && Objects.equals(returnKey, pollTask.returnKey)
&& triggerAtNanos == pollTask.triggerAtNanos;
}
private void markQueryFailIfPending(String returnKey) {
try {
sendRepository.findByCmid(returnKey).ifPresent(e -> {
if (e.getResultCode() != null && e.getResultCode() == NotihubConst.EMAIL_PENDING) {
e.setResultCode(NotihubConst.EMAIL_NOT_RESULT);
sendRepository.save(e);
}
});
} catch (Exception ex) {
log.debug("markQueryFailIfPending ignored. returnKey={}...", returnKey, ex);
}
}
static final class PollTask implements Delayed {
final String returnKey;
final int attempt;
final long triggerAtNanos;
PollTask(String returnKey, int attempt, long delayMs) {
this.returnKey = returnKey;
this.attempt = attempt;
long delayNanos = TimeUnit.MILLISECONDS.toNanos(Math.max(0, delayMs));
this.triggerAtNanos = System.nanoTime() + delayNanos;
}
@Override
public long getDelay(TimeUnit unit) {
long diffNanos = triggerAtNanos - System.nanoTime();
return unit.convert(diffNanos, TimeUnit.NANOSECONDS);
}
@Override
public int compareTo(Delayed o) {
if (o == this) return 0;
PollTask other = (PollTask) o;
return Long.compare(this.triggerAtNanos, other.triggerAtNanos);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PollTask)) return false;
PollTask pollTask = (PollTask) o;
return attempt == pollTask.attempt && Objects.equals(returnKey, pollTask.returnKey) && triggerAtNanos == pollTask.triggerAtNanos;
}
@Override
public int hashCode() {
return Objects.hash(returnKey, attempt, triggerAtNanos);
}
@Override
public int hashCode() {
return Objects.hash(returnKey, attempt, triggerAtNanos);
}
}
}

View File

@@ -10,80 +10,82 @@ import com.kri.notihub.server.common.external.pringo.dto.PringoJsonReturnRespons
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;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Optional;
@Slf4j
@Component
@RequiredArgsConstructor
class EmailResultUpdater {
private final PringoApiClient pringoApiClient;
private final SendRepository sendRepository;
private final BulkSendRepository bulkSendRepository;
private final PringoApiClient pringoApiClient;
private final SendRepository sendRepository;
private final BulkSendRepository bulkSendRepository;
/**
* Pringo 결과 조회 후 t_send 갱신
* @return true: 결과 조회 성공 및 갱신 완료, false: 아직 결과 없음/조회 실패
*/
public boolean tryUpdateEmailResult(String returnKey) {
Optional<TSendEntity> opt = sendRepository.findByCmid(returnKey);
if (opt.isEmpty()) return false;
LocalDateTime now = LocalDateTime.now();
TSendEntity e = opt.get();
try {
PringoJsonReturnResponseDto resp = pringoApiClient.jsonReturn(Long.valueOf(returnKey));
if (resp == null || !resp.isSuccess() || resp.getItemList() == null || resp.getItemList().isEmpty()) {
e.setResultCode(NotihubConst.EMAIL_NOT_RESULT);
e.setReportDt(now);
sendRepository.save(e);
return true;
}
PringoJsonReturnItemDto 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);
return true;
}
short resultCode = CommonUtil.safeParseShort(item.getStatus(), 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);
});
}
return true;
} catch (Exception ex) {
log.warn("Pringo return polling failed. returnKey={}", returnKey, ex);
return false;
}
/**
* Pringo 결과 조회 후 t_send 갱신
*
* @return true: 결과 조회 성공 및 갱신 완료, false: 아직 결과 없음/조회 실패
*/
public boolean tryUpdateEmailResult(String returnKey) {
Optional<TSendEntity> opt = sendRepository.findByCmid(returnKey);
if (opt.isEmpty()) {
return false;
}
LocalDateTime now = LocalDateTime.now();
TSendEntity e = opt.get();
try {
PringoJsonReturnResponseDto resp = pringoApiClient.jsonReturn(Long.valueOf(returnKey));
if (resp == null || !resp.isSuccess() || resp.getItemList() == null || resp.getItemList()
.isEmpty()) {
e.setResultCode(NotihubConst.EMAIL_NOT_RESULT);
e.setReportDt(now);
sendRepository.save(e);
return true;
}
PringoJsonReturnItemDto 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);
return true;
}
short resultCode = CommonUtil.safeParseShort(item.getStatus(), 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);
});
}
return true;
} catch (Exception ex) {
log.warn("Pringo return polling failed. returnKey={}", returnKey, ex);
return false;
}
}
}

View File

@@ -2,6 +2,16 @@ package com.kri.notihub.server.service;
import com.kri.common.file.FileUtil;
import com.kri.common.util.CommonUtil;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
@@ -12,186 +22,195 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.*;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
@Service
public class FileService {
private static final Logger log = LoggerFactory.getLogger(FileService.class);
private final Path uploadBaseDir; // ex) /data/upload-file/body-image
private final String publicBaseUrlPrefix; // ex) /upload-file/body-image
public FileService(
@Value("${kri.body-image.upload-base-dir}") String uploadBaseDir,
@Value("${kri.body-image.public-base-url}") String publicBaseUrlPrefix
) {
this.uploadBaseDir = Paths.get(uploadBaseDir).toAbsolutePath().normalize();
this.publicBaseUrlPrefix = publicBaseUrlPrefix.endsWith("/")
? publicBaseUrlPrefix.substring(0, publicBaseUrlPrefix.length() - 1)
: publicBaseUrlPrefix;
private static final Logger log = LoggerFactory.getLogger(FileService.class);
private final Path uploadBaseDir; // ex) /data/upload-file/body-image
private final String publicBaseUrlPrefix; // ex) /upload-file/body-image
public FileService(
@Value("${kri.body-image.upload-base-dir}") String uploadBaseDir,
@Value("${kri.body-image.public-base-url}") String publicBaseUrlPrefix
) {
this.uploadBaseDir = Paths.get(uploadBaseDir).toAbsolutePath().normalize();
this.publicBaseUrlPrefix = publicBaseUrlPrefix.endsWith("/")
? publicBaseUrlPrefix.substring(0, publicBaseUrlPrefix.length() - 1)
: publicBaseUrlPrefix;
}
/**
* Temp에 파일 저장 후, public URL 반환
*/
public String storeTempFile(String itrntPrjctCd, MultipartFile file) {
try {
String original = Optional.ofNullable(file.getOriginalFilename()).orElse("file");
String ext = "";
int dot = original.lastIndexOf('.');
if (dot > 0 && dot < original.length() - 1) {
ext = original.substring(dot);
}
String newName = CommonUtil.uuid32() + ext;
Path tempDir = getTempDir(itrntPrjctCd);
Files.createDirectories(tempDir);
Path target = tempDir.resolve(newName);
file.transferTo(target.toFile());
// 브라우저에서 사용할 URL
return publicBaseUrlPrefix + "/" + itrntPrjctCd + "/Temp/" + newName;
} catch (IOException e) {
throw new RuntimeException("파일 저장 실패", e);
}
}
/**
* 컨택 시나리오 저장 시: 1) HTML 내 Temp 이미지 -> Asset으로 이동 & src 수정 2) Asset 디렉토리에서 더 이상 사용되지 않는 파일 삭제 3)
* 정리된 HTML 반환
*/
public String syncOnSave(String prjctCd, Long tmplatIdx, String rawHtml) {
if (rawHtml == null) {
rawHtml = "";
}
/**
* Temp에 파일 저장 후, public URL 반환
*/
public String storeTempFile(String itrntPrjctCd, MultipartFile file) {
try {
String original = Optional.ofNullable(file.getOriginalFilename()).orElse("file");
String ext = "";
String returnHtml = rawHtml;
try {
// body fragment로 파싱 (KriEditor가 body 없이 <p>...</p> 형태 저장하므로)
Document doc = Jsoup.parseBodyFragment(rawHtml);
Elements imgs = doc.select("img[src]");
int dot = original.lastIndexOf('.');
if (dot > 0 && dot < original.length() - 1) {
ext = original.substring(dot);
}
Set<String> assetFileNamesToKeep = new HashSet<>();
String newName = CommonUtil.uuid32() + ext;
Path tempDir = getTempDir(itrntPrjctCd);
Files.createDirectories(tempDir);
Path target = tempDir.resolve(newName);
file.transferTo(target.toFile());
// 브라우저에서 사용할 URL
return publicBaseUrlPrefix + "/" + itrntPrjctCd + "/Temp/" + newName;
} catch (IOException e) {
throw new RuntimeException("파일 저장 실패", e);
for (Element img : imgs) {
String src = img.attr("src");
if (src == null || src.isBlank()) {
continue;
}
}
/**
* 컨택 시나리오 저장 시:
* 1) HTML 내 Temp 이미지 -> Asset으로 이동 & src 수정
* 2) Asset 디렉토리에서 더 이상 사용되지 않는 파일 삭제
* 3) 정리된 HTML 반환
*/
public String syncOnSave(String prjctCd, Long tmplatIdx, String rawHtml) {
if (rawHtml == null) rawHtml = "";
String returnHtml = rawHtml;
try{
// body fragment로 파싱 (KriEditor가 body 없이 <p>...</p> 형태 저장하므로)
Document doc = Jsoup.parseBodyFragment(rawHtml);
Elements imgs = doc.select("img[src]");
Set<String> assetFileNamesToKeep = new HashSet<>();
for (Element img : imgs) {
String src = img.attr("src");
if (src == null || src.isBlank()) continue;
if (!src.contains("/" + prjctCd + "/")) continue;
String fileName = FileUtil.extractFileNameFromPath(src);
if (src.contains("/" + prjctCd + "/Temp/")) {
// Temp → Asset 이동
moveTempToAsset(prjctCd, tmplatIdx, fileName);
String assetSrc = src.replace("/Temp/", "/Asset/" + tmplatIdx + "/");
img.attr("src", assetSrc);
assetFileNamesToKeep.add(fileName);
} else if (src.contains("/" + prjctCd + "/Asset/")) {
if (!src.contains("/" + prjctCd + "/Asset/" + tmplatIdx + "/")){
String[] srcArr = src.split("/" + prjctCd + "/Asset/");
String fromTmplatIdx = srcArr[1].split("/")[0].replace(fileName, "");
copyAssetToAsset(prjctCd, fromTmplatIdx, tmplatIdx, fileName);
String assetSrc = src.replace("/Asset/" + fromTmplatIdx + "/", "/Asset/" + tmplatIdx + "/");
img.attr("src", assetSrc);
}
assetFileNamesToKeep.add(fileName);
}
}
// Asset 디렉토리 정리 (본문에 없는 파일 삭제)
cleanupAssetDir(prjctCd, tmplatIdx, assetFileNamesToKeep);
// body 안의 HTML만 반환 (불필요한 <html><body> wrapper 제거)
returnHtml = doc.body().html();
}
catch (IOException e) {
log.warn("temp 파일 이동 실패: {}", rawHtml, e);
if (!src.contains("/" + prjctCd + "/")) {
continue;
}
return returnHtml;
}
String fileName = FileUtil.extractFileNameFromPath(src);
/***************************private************************************/
private String normalizeBaseUrl(String url) {
if (url.endsWith("/")) {
return url.substring(0, url.length() - 1);
if (src.contains("/" + prjctCd + "/Temp/")) {
// Temp → Asset 이동
moveTempToAsset(prjctCd, tmplatIdx, fileName);
String assetSrc = src.replace("/Temp/", "/Asset/" + tmplatIdx + "/");
img.attr("src", assetSrc);
assetFileNamesToKeep.add(fileName);
} else if (src.contains("/" + prjctCd + "/Asset/")) {
if (!src.contains("/" + prjctCd + "/Asset/" + tmplatIdx + "/")) {
String[] srcArr = src.split("/" + prjctCd + "/Asset/");
String fromTmplatIdx = srcArr[1].split("/")[0].replace(fileName, "");
copyAssetToAsset(prjctCd, fromTmplatIdx, tmplatIdx, fileName);
String assetSrc = src.replace("/Asset/" + fromTmplatIdx + "/",
"/Asset/" + tmplatIdx + "/");
img.attr("src", assetSrc);
}
assetFileNamesToKeep.add(fileName);
}
return url;
}
// Asset 디렉토리 정리 (본문에 없는 파일 삭제)
cleanupAssetDir(prjctCd, tmplatIdx, assetFileNamesToKeep);
// body 안의 HTML만 반환 (불필요한 <html><body> wrapper 제거)
returnHtml = doc.body().html();
} catch (IOException e) {
log.warn("temp 파일 이동 실패: {}", rawHtml, e);
}
private Path getTempDir(String prjctCd) {
return uploadBaseDir.resolve(prjctCd).resolve("Temp");
return returnHtml;
}
/***************************private************************************/
private String normalizeBaseUrl(String url) {
if (url.endsWith("/")) {
return url.substring(0, url.length() - 1);
}
return url;
}
private Path getTempDir(String prjctCd) {
return uploadBaseDir.resolve(prjctCd).resolve("Temp");
}
private Path getAssetDir(String prjctCd, String tmplatIdx) {
return uploadBaseDir.resolve(prjctCd).resolve("Asset").resolve(tmplatIdx);
}
private Path getAssetDir(String prjctCd, Long tmplatIdx) {
return uploadBaseDir.resolve(prjctCd).resolve("Asset").resolve(tmplatIdx.toString());
}
private void copyAssetToAsset(String prjctCd, String fromTmplatIdx, Long toTmplatIdx,
String fileName) throws IOException {
if (fileName == null || fileName.isBlank()) {
return;
}
Path fromDir = getAssetDir(prjctCd, fromTmplatIdx);
Path toDir = getAssetDir(prjctCd, toTmplatIdx);
Path src = fromDir.resolve(fileName).normalize();
Path dst = toDir.resolve(fileName).normalize();
Files.createDirectories(toDir);
if (!Files.exists(src)) {
throw new NoSuchFileException("Source asset not found: " + src);
}
private Path getAssetDir(String prjctCd, String tmplatIdx) {
return uploadBaseDir.resolve(prjctCd).resolve("Asset").resolve(tmplatIdx);
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
}
private void moveTempToAsset(String prjctCd, Long tmplatIdx, String fileName) throws IOException {
if (fileName == null || fileName.isBlank()) {
return;
}
private Path getAssetDir(String prjctCd, Long tmplatIdx) {
return uploadBaseDir.resolve(prjctCd).resolve("Asset").resolve(tmplatIdx.toString());
Path tempDir = getTempDir(prjctCd);
Path assetDir = getAssetDir(prjctCd, tmplatIdx);
Files.createDirectories(assetDir);
Path source = tempDir.resolve(fileName).normalize();
Path target = assetDir.resolve(fileName).normalize();
if (!source.startsWith(tempDir) || !target.startsWith(assetDir)) {
// 안전 체크
return;
}
if (!Files.exists(source)) {
return;
}
private void copyAssetToAsset(String prjctCd, String fromTmplatIdx, Long toTmplatIdx, String fileName) throws IOException {
if (fileName == null || fileName.isBlank()) return;
Path fromDir = getAssetDir(prjctCd, fromTmplatIdx);
Path toDir = getAssetDir(prjctCd, toTmplatIdx);
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
}
Path src = fromDir.resolve(fileName).normalize();
Path dst = toDir.resolve(fileName).normalize();
private void cleanupAssetDir(String prjctCd, Long tmplatIdx, Set<String> keepFileNames)
throws IOException {
Path assetDir = getAssetDir(prjctCd, tmplatIdx);
if (!Files.exists(assetDir)) {
return;
}
Files.createDirectories(toDir);
if (!Files.exists(src)) {
throw new NoSuchFileException("Source asset not found: " + src);
try (DirectoryStream<Path> stream = Files.newDirectoryStream(assetDir)) {
for (Path path : stream) {
if (!Files.isRegularFile(path)) {
continue;
}
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
}
private void moveTempToAsset(String prjctCd, Long tmplatIdx, String fileName) throws IOException {
if (fileName == null || fileName.isBlank()) return;
Path tempDir = getTempDir(prjctCd);
Path assetDir = getAssetDir(prjctCd, tmplatIdx);
Files.createDirectories(assetDir);
Path source = tempDir.resolve(fileName).normalize();
Path target = assetDir.resolve(fileName).normalize();
if (!source.startsWith(tempDir) || !target.startsWith(assetDir)) {
// 안전 체크
return;
}
if (!Files.exists(source)) {
return;
}
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
}
private void cleanupAssetDir(String prjctCd, Long tmplatIdx, Set<String> keepFileNames) throws IOException {
Path assetDir = getAssetDir(prjctCd, tmplatIdx);
if (!Files.exists(assetDir)) return;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(assetDir)) {
for (Path path : stream) {
if (!Files.isRegularFile(path)) continue;
String fileName = path.getFileName().toString();
if (!keepFileNames.contains(fileName)) {
Files.deleteIfExists(path);
}
}
String fileName = path.getFileName().toString();
if (!keepFileNames.contains(fileName)) {
Files.deleteIfExists(path);
}
}
}
}
}

View File

@@ -16,13 +16,6 @@ import com.kri.notihub.server.persistence.entity.TSendResultCodeEntity;
import com.kri.notihub.server.persistence.repository.BulkSendRepository;
import com.kri.notihub.server.persistence.repository.SendRepository;
import com.kri.notihub.server.persistence.repository.SendResultCodeRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
@@ -30,90 +23,105 @@ import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class ReportService {
private final SendResultCodeRepository sendResultCodeRepository;
private final BulkSendRepository bulkSendRepository;
private final SendRepository sendRepository;
private final SendResultCodeRepository sendResultCodeRepository;
private final BulkSendRepository bulkSendRepository;
private final SendRepository sendRepository;
public List<BulkSendInfoDto> getBulkSendList(SendType sendTy, String reqstSvc, String prjctCd, String regCmpn){
List<Short> sendTyList = sendTy == SendType.EMAIL ? List.of(SendType.EMAIL.getCode()) : List.of(SendType.SMS.getCode(), SendType.LMS_MMS.getCode());
public List<BulkSendInfoDto> getBulkSendList(SendType sendTy, String reqstSvc, String prjctCd,
String regCmpn) {
List<Short> sendTyList = sendTy == SendType.EMAIL ? List.of(SendType.EMAIL.getCode())
: List.of(SendType.SMS.getCode(), SendType.LMS_MMS.getCode());
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();
}
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();
}
}
public PageResponseDto<SendInfoDto> getBulkSendDetail(String bulkSendKey,
PageRequestDto pageReq) {
List<TSendResultCodeEntity> resultCodeList = sendResultCodeRepository.findAll();
Pageable pageable = Pageables.of(pageReq, TSendEntity.class);
Page<SendInfoDto> page = sendRepository.findByBulkSendKey(bulkSendKey, pageable)
.map(entity -> SendInfoDto.from(entity, resultCodeList));
return PageResponseDto.from(page);
}
public ReportExcelResponseDto getBulkSendDetailExcel(String bulkSendKey) {
List<TSendResultCodeEntity> resultCodeList = sendResultCodeRepository.findAll();
Sort sort = Sort.by(Sort.Direction.ASC, "sendIdx");
TBulkSendEntity bulkSend = bulkSendRepository.findByBulkSendKey(bulkSendKey).orElse(null);
if (bulkSend == null) {
throw BusinessException.badRequest("NOT FOUND BULK SEND", "해당 대량발송은 없습니다.")
.with("bulkSendKey", bulkSendKey);
}
public PageResponseDto<SendInfoDto> getBulkSendDetail(String bulkSendKey, PageRequestDto pageReq){
List<TSendResultCodeEntity> resultCodeList = sendResultCodeRepository.findAll();
String ts = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
String fileName = "대량 발송 내역_%s_%s_%s.xlsx".formatted(bulkSend.getReqstSvc(),
bulkSend.getPrjctCd(), ts);
Pageable pageable = Pageables.of(pageReq, TSendEntity.class);
Page<SendInfoDto> page = sendRepository.findByBulkSendKey(bulkSendKey, pageable)
.map(entity -> SendInfoDto.from(entity, resultCodeList));
ByteArrayOutputStream bos = new ByteArrayOutputStream(64 * 1024);
return PageResponseDto.from(page);
}
// Base64 스트림으로 바로 쓰기 (엑셀 bytes -> base64 bytes)
try (OutputStream b64Out = Base64.getEncoder().wrap(bos);
ExcelMapper.StreamingWriter<SendInfoDto> writer =
ExcelMapper.openStreamingWriter(SendInfoDto.class, NotihubConst.ROW_WINDOW)) {
public ReportExcelResponseDto getBulkSendDetailExcel(String bulkSendKey){
List<TSendResultCodeEntity> resultCodeList = sendResultCodeRepository.findAll();
int page = 0;
while (true) {
Page<TSendEntity> chunkPage = sendRepository.findByBulkSendKey(
bulkSendKey,
PageRequest.of(page++, NotihubConst.CHUNK_SIZE, sort)
);
Sort sort = Sort.by(Sort.Direction.ASC, "sendIdx");
TBulkSendEntity bulkSend = bulkSendRepository.findByBulkSendKey(bulkSendKey).orElse(null);
if(bulkSend == null){
throw BusinessException.badRequest("NOT FOUND BULK SEND","해당 대량발송은 없습니다.")
.with("bulkSendKey", bulkSendKey);
if (chunkPage.isEmpty()) {
break;
}
String ts = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
String fileName = "대량 발송 내역_%s_%s_%s.xlsx".formatted(bulkSend.getReqstSvc(), bulkSend.getPrjctCd(), ts);
List<SendInfoDto> chunk = chunkPage.getContent()
.stream()
.map(entity -> SendInfoDto.from(entity, resultCodeList))
.toList();
ByteArrayOutputStream bos = new ByteArrayOutputStream(64 * 1024);
writer.appendAll(chunk);
// Base64 스트림으로 바로 쓰기 (엑셀 bytes -> base64 bytes)
try (OutputStream b64Out = Base64.getEncoder().wrap(bos);
ExcelMapper.StreamingWriter<SendInfoDto> writer =
ExcelMapper.openStreamingWriter(SendInfoDto.class, NotihubConst.ROW_WINDOW)) {
int page = 0;
while (true) {
Page<TSendEntity> chunkPage = sendRepository.findByBulkSendKey(
bulkSendKey,
PageRequest.of(page++, NotihubConst.CHUNK_SIZE, sort)
);
if (chunkPage.isEmpty()) break;
List<SendInfoDto> chunk = chunkPage.getContent()
.stream()
.map(entity -> SendInfoDto.from(entity, resultCodeList))
.toList();
writer.appendAll(chunk);
if (!chunkPage.hasNext()) break;
}
//최종 1회 write (XLSX 마무리)
writer.writeTo(b64Out);
} catch (Exception e) {
throw BusinessException.internalError("FAIL MAKE EXCEL","엑셀(Base64) 생성 실패. " + e.getMessage())
.with("bulkSendKey", bulkSendKey);
if (!chunkPage.hasNext()) {
break;
}
}
String base64 = new String(bos.toByteArray(), StandardCharsets.UTF_8);
return ReportExcelResponseDto.builder()
.errorFileName(fileName)
.errorFileBase64(base64)
.build();
//최종 1회 write (XLSX 마무리)
writer.writeTo(b64Out);
} catch (Exception e) {
throw BusinessException.internalError("FAIL MAKE EXCEL",
"엑셀(Base64) 생성 실패. " + e.getMessage())
.with("bulkSendKey", bulkSendKey);
}
String base64 = new String(bos.toByteArray(), StandardCharsets.UTF_8);
return ReportExcelResponseDto.builder()
.errorFileName(fileName)
.errorFileBase64(base64)
.build();
}
}

View File

@@ -14,144 +14,155 @@ 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 com.kri.notihub.server.persistence.repository.TemplateRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class SendEmailService extends SendService {
private final PringoApiClient pringoApiClient;
private final EmailResultPoller emailResultPoller;
private final EmailResultUpdater emailResultUpdater;
private final PringoApiClient pringoApiClient;
private final EmailResultPoller emailResultPoller;
private final EmailResultUpdater emailResultUpdater;
public SendEmailService(
TemplateRepository templateRepository,
BulkSendRepository bulkSendRepository,
SendRepository sendRepository,
TemplateService templateService,
PringoApiClient pringoApiClient,
EmailResultPoller emailResultPoller,
EmailResultUpdater emailResultUpdater
) {
super(templateRepository, bulkSendRepository, sendRepository, templateService);
this.pringoApiClient = pringoApiClient;
this.emailResultPoller = emailResultPoller;
this.emailResultUpdater = emailResultUpdater;
public SendEmailService(
TemplateRepository templateRepository,
BulkSendRepository bulkSendRepository,
SendRepository sendRepository,
TemplateService templateService,
PringoApiClient pringoApiClient,
EmailResultPoller emailResultPoller,
EmailResultUpdater emailResultUpdater
) {
super(templateRepository, bulkSendRepository, sendRepository, templateService);
this.pringoApiClient = pringoApiClient;
this.emailResultPoller = emailResultPoller;
this.emailResultUpdater = emailResultUpdater;
}
@Override
protected SendType getSendType() {
return SendType.EMAIL;
}
@Override
protected SendInternalResultDto doSendInternal(
Boolean isResve,
String bulkSendKey,
SendType sendType, //Sms에서 사용 Email에서는 의미 없음
String sendEml,
String sendNm,
String msgTitle,
String msgBody,
DestInfoDto dest
) {
if (Boolean.TRUE.equals(isResve)) {
//예약 용 cmid 생성 추후 실제 발송 후 갱신
String ts = DateTimeUtil.nowKstLocalDateTime()
.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
int r = ThreadLocalRandom.current().nextInt(36 * 36 * 36);
String suffix = String.format("%3s", Integer.toString(r, 36)).replace(' ', '0');
String cmid = NotihubConst.EMAIL_RESERVATION_PREFIX + ts + suffix;
return SendInternalResultDto.of(cmid, SendStatusType.STANDBY, NotihubConst.EMAIL_STANDBY);
} else {
PringoJsonSendRequestDto pringoReq = buildPringoSendRequest(sendEml, sendNm, msgTitle,
msgBody, dest);
return sendPringoEmail(pringoReq);
}
}
public SendInternalResultDto sendPringoEmail(PringoJsonSendRequestDto pringoReq) {
PringoJsonSendResponseDto pringoRes = null;
try {
pringoRes = pringoApiClient.jsonSend(pringoReq);
} catch (Exception e) {
log.warn("Pringo json-send failed (pringoReq={})", pringoReq, e);
}
@Override
protected SendType getSendType() {
return SendType.EMAIL;
String cmid = resolveEmailCmid(pringoRes);
SendStatusType sendStatus;
short resultCode;
if (pringoRes != null && pringoRes.isSuccess() && pringoRes.getReturnKey() != null) {
//발송 요청에 성공한 것이지 발송이 성공이 아니므로 STANDBY 유지
//sendStatus = SendStatusType.SUCCESS;
sendStatus = SendStatusType.STANDBY;
resultCode = NotihubConst.EMAIL_PENDING;
} else {
sendStatus = SendStatusType.FAIL;
resultCode = NotihubConst.EMAIL_SEND_FAIL;
}
@Override
protected SendInternalResultDto doSendInternal(
Boolean isResve,
String bulkSendKey,
SendType sendType, //Sms에서 사용 Email에서는 의미 없음
String sendEml,
String sendNm,
String msgTitle,
String msgBody,
DestInfoDto dest
){
if(Boolean.TRUE.equals(isResve)){
//예약 용 cmid 생성 추후 실제 발송 후 갱신
String ts = DateTimeUtil.nowKstLocalDateTime()
.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
return SendInternalResultDto.of(cmid, sendStatus, resultCode);
}
int r = ThreadLocalRandom.current().nextInt(36 * 36 * 36);
String suffix = String.format("%3s", Integer.toString(r, 36)).replace(' ', '0');
String cmid = NotihubConst.EMAIL_RESERVATION_PREFIX + ts + suffix;
return SendInternalResultDto.of(cmid, SendStatusType.STANDBY, NotihubConst.EMAIL_STANDBY);
}
else {
PringoJsonSendRequestDto pringoReq = buildPringoSendRequest(sendEml, sendNm, msgTitle, msgBody, dest);
return sendPringoEmail(pringoReq);
}
@Override
public void afterPersistSendEntities(List<TSendEntity> persisted) {
if (persisted == null || persisted.isEmpty()) {
return;
}
public SendInternalResultDto sendPringoEmail(PringoJsonSendRequestDto pringoReq){
PringoJsonSendResponseDto pringoRes = null;
try {
pringoRes = pringoApiClient.jsonSend(pringoReq);
} catch (Exception e) {
log.warn("Pringo json-send failed (pringoReq={})", pringoReq, e);
}
for (TSendEntity e : persisted) {
if (e == null) {
continue;
}
String cmid = resolveEmailCmid(pringoRes);
SendStatusType sendStatus;
short resultCode;
// Pringo return polling이 필요한 상태만
if (e.getResultCode() == null || e.getResultCode() != NotihubConst.EMAIL_PENDING) {
continue;
}
if (pringoRes != null && pringoRes.isSuccess() && pringoRes.getReturnKey() != null) {
//발송 요청에 성공한 것이지 발송이 성공이 아니므로 STANDBY 유지
//sendStatus = SendStatusType.SUCCESS;
sendStatus = SendStatusType.STANDBY;
resultCode = NotihubConst.EMAIL_PENDING;
} else {
sendStatus = SendStatusType.FAIL;
resultCode = NotihubConst.EMAIL_SEND_FAIL;
}
//예약은 갱신용 큐에 넣지 않음
if (e.getCmid().startsWith(NotihubConst.EMAIL_RESERVATION_PREFIX)) {
continue;
}
return SendInternalResultDto.of(cmid, sendStatus, resultCode);
// return_key(숫자)인 경우만
if (!CommonUtil.isNumeric(e.getCmid())) {
continue;
}
emailResultPoller.enqueue(e.getCmid());
}
}
public PringoJsonSendRequestDto buildPringoSendRequest(
String sendEml,
String sendNm,
String msgTitle,
String msgBody,
DestInfoDto dest
) {
Map<String, Object> vars = new HashMap<>();
if (dest.getMsgParam() != null) {
vars.putAll(dest.getMsgParam());
}
@Override
public void afterPersistSendEntities(List<TSendEntity> persisted) {
if (persisted == null || persisted.isEmpty()) return;
return PringoJsonSendRequestDto.builder()
.sender(sendEml)
.senderName(Optional.ofNullable(sendNm).orElse(""))
.recipient(dest.getDestEml())
.recipientName(Optional.ofNullable(dest.getDestNm()).orElse(""))
.subject(Optional.ofNullable(msgTitle).orElse(""))
.body(Optional.ofNullable(msgBody).orElse(""))
.vars(vars)
.build();
}
for (TSendEntity e : persisted) {
if (e == null) continue;
// Pringo return polling이 필요한 상태만
if (e.getResultCode() == null || e.getResultCode() != NotihubConst.EMAIL_PENDING) continue;
//예약은 갱신용 큐에 넣지 않음
if(e.getCmid().startsWith(NotihubConst.EMAIL_RESERVATION_PREFIX)) continue;
// return_key(숫자)인 경우만
if (!CommonUtil.isNumeric(e.getCmid())) continue;
emailResultPoller.enqueue(e.getCmid());
}
}
public PringoJsonSendRequestDto buildPringoSendRequest(
String sendEml,
String sendNm,
String msgTitle,
String msgBody,
DestInfoDto dest
) {
Map<String, Object> vars = new HashMap<>();
if (dest.getMsgParam() != null) vars.putAll(dest.getMsgParam());
return PringoJsonSendRequestDto.builder()
.sender(sendEml)
.senderName(Optional.ofNullable(sendNm).orElse(""))
.recipient(dest.getDestEml())
.recipientName(Optional.ofNullable(dest.getDestNm()).orElse(""))
.subject(Optional.ofNullable(msgTitle).orElse(""))
.body(Optional.ofNullable(msgBody).orElse(""))
.vars(vars)
.build();
}
private String resolveEmailCmid(PringoJsonSendResponseDto pringoRes) {
if (pringoRes != null && pringoRes.isSuccess() && pringoRes.getReturnKey() != null) {
return String.valueOf(pringoRes.getReturnKey());
}
// return_key 미수신 케이스는 SendFau
return CommonUtil.uuid32();
private String resolveEmailCmid(PringoJsonSendResponseDto pringoRes) {
if (pringoRes != null && pringoRes.isSuccess() && pringoRes.getReturnKey() != null) {
return String.valueOf(pringoRes.getReturnKey());
}
// return_key 미수신 케이스는 SendFau
return CommonUtil.uuid32();
}
}

View File

@@ -1,350 +1,368 @@
package com.kri.notihub.server.service;
import static org.apache.commons.lang3.StringUtils.firstNonBlank;
import com.kri.common.datetime.DateTimeUtil;
import com.kri.common.web.BusinessException;
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.*;
import com.kri.notihub.server.dto.send.BulkSendCreateRequestDto;
import com.kri.notihub.server.dto.send.BulkSendResponseDto;
import com.kri.notihub.server.dto.send.DestInfoDto;
import com.kri.notihub.server.dto.send.SendInternalResultDto;
import com.kri.notihub.server.dto.send.SendRequestBulkDto;
import com.kri.notihub.server.dto.send.SendRequestSingleDto;
import com.kri.notihub.server.dto.template.TemplateDto;
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 com.kri.notihub.server.persistence.repository.TemplateRepository;
import lombok.RequiredArgsConstructor;
import java.time.LocalDateTime;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.commons.lang3.StringUtils.firstNonBlank;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public abstract class SendService {
protected final TemplateRepository templateRepository;
protected final BulkSendRepository bulkSendRepository;
protected final SendRepository sendRepository;
protected final TemplateService templateService;
protected final TemplateRepository templateRepository;
protected final BulkSendRepository bulkSendRepository;
protected final SendRepository sendRepository;
protected final TemplateService templateService;
public String issueBulkKey(BulkSendCreateRequestDto req) {
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
protected static void sleepSilently(long ms) {
if (ms <= 0) {
return;
}
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
if (req == null || req.getTmplatIdx() == null) {
throw BusinessException.badRequest("BULK_CREATE_INVALID", "tmplatIdx은 필수 입니다.");
}
if (req.getTrgtCnt() == null || req.getTrgtCnt() <= 0) {
throw BusinessException.badRequest("BULK_CREATE_INVALID", "trgtCnt는 0보다 커야 합니다.");
}
public String issueBulkKey(BulkSendCreateRequestDto req) {
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
if (req.getResve()) {
if (req.getSendDt() == null) {
throw BusinessException.badRequest("BULK_CREATE_INVALID", "예약 발송의 경우 희망 발송일시가 필수 입니다.");
}
if (!req.getSendDt().isAfter(now)) { // now보다 커야 함(같으면 불가)
throw BusinessException.badRequest("BULK_CREATE_INVALID", "예약 발송의 경우 희망 발송일시는 현재시간 이후여야 합니다.");
}
}
TemplateDto tmplat = templateService.getTemplate(req.getTmplatIdx());
validateTemplateType(tmplat, getSendType());
TBulkSendEntity bulk = TBulkSendEntity.from(req, now);
TBulkSendEntity saved = bulkSendRepository.save(bulk);
return saved.getBulkSendKey();
if (req == null || req.getTmplatIdx() == null) {
throw BusinessException.badRequest("BULK_CREATE_INVALID", "tmplatIdx은 필수 입니다.");
}
if (req.getTrgtCnt() == null || req.getTrgtCnt() <= 0) {
throw BusinessException.badRequest("BULK_CREATE_INVALID", "trgtCnt는 0보다 커야 합니다.");
}
protected void validateTemplateType(TemplateDto tmplat, SendType requiredType) {
if (tmplat == null || requiredType == null) return;
if (req.getResve()) {
if (req.getSendDt() == null) {
throw BusinessException.badRequest("BULK_CREATE_INVALID", "예약 발송의 경우 희망 발송일시가 필수 입니다.");
}
int tmplatTy = tmplat.getTmplatTy().getCode()/10;
int required = requiredType.getCode()/10;
if (tmplat.getTmplatTy() == null || tmplatTy != required) {
throw BusinessException.badRequest("WRONG_TEMPLATE_TYPE","템플릿 타입이 잘 못 됐습니다.")
.with("tmplatIdx", tmplat.getTmplatIdx())
.with("required", requiredType)
.with("tmplatTy", tmplat.getTmplatTy());
}
if (!req.getSendDt().isAfter(now)) { // now보다 커야 함(같으면 불가)
throw BusinessException.badRequest("BULK_CREATE_INVALID",
"예약 발송의 경우 희망 발송일시는 현재시간 이후여야 합니다.");
}
}
public final void doSendSingle(SendRequestSingleDto req, String regCmpn, String regUser) {
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
TemplateDto tmplat = templateService.getTemplate(req.getTmplatIdx());
validateTemplateType(tmplat, getSendType());
if (req == null || req.getDestInfo() == null) {
throw BusinessException.badRequest("DEST_INFO_REQUIRED", "destInfo 는 필수입니다.");
}
TBulkSendEntity bulk = TBulkSendEntity.from(req, now);
TBulkSendEntity saved = bulkSendRepository.save(bulk);
if (req.getResve()) {
if (req.getSendDt() == null) {
throw BusinessException.badRequest("SEND_SINGLE_INVALID", "예약 발송의 경우 희망 발송일시가 필수 입니다.");
}
return saved.getBulkSendKey();
}
if (!req.getSendDt().isAfter(now)) { // now보다 커야 함(같으면 불가)
throw BusinessException.badRequest("SEND_SINGLE_INVALID", "예약 발송의 경우 희망 발송일시는 현재시간 이후여야 합니다.");
}
}
protected void validateTemplateType(TemplateDto tmplat, SendType requiredType) {
if (tmplat == null || requiredType == null) {
return;
}
TemplateDto tmplat = templateService.getTemplate(req.getTmplatIdx());
validateTemplateType(tmplat, getSendType());
int tmplatTy = tmplat.getTmplatTy().getCode() / 10;
int required = requiredType.getCode() / 10;
LocalDateTime sendDt = req.getSendDt() != null ? req.getSendDt() : now;
String sendTel = firstNonBlank(req.getSendTel(), tmplat.getSendTel());
String sendEml = firstNonBlank(req.getSendEml(), tmplat.getSendEml());
String sendFrom = getSendType() == SendType.EMAIL ? sendEml : sendTel;
String sendNm = firstNonBlank(req.getSendNm(), tmplat.getSendNm());
if (tmplat.getTmplatTy() == null || tmplatTy != required) {
throw BusinessException.badRequest("WRONG_TEMPLATE_TYPE", "템플릿 타입이 잘 못 됐습니다.")
.with("tmplatIdx", tmplat.getTmplatIdx())
.with("required", requiredType)
.with("tmplatTy", tmplat.getTmplatTy());
}
}
if (sendFrom == null || sendFrom.isBlank()) {
if (getSendType() == SendType.EMAIL) {
throw BusinessException.badRequest("SEND_EMAIL_REQUIRED", "sendEml은 필수 입니다.");
} else {
throw BusinessException.badRequest("SEND_TEL_REQUIRED", "sendTel은 필수 입니다.");
}
}
public final void doSendSingle(SendRequestSingleDto req, String regCmpn, String regUser) {
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
DestInfoDto dest = req.getDestInfo();
if (req == null || req.getDestInfo() == null) {
throw BusinessException.badRequest("DEST_INFO_REQUIRED", "destInfo 는 필수입니다.");
}
if (req.getResve()) {
if (req.getSendDt() == null) {
throw BusinessException.badRequest("SEND_SINGLE_INVALID", "예약 발송의 경우 희망 발송일시가 필수 입니다.");
}
if (!req.getSendDt().isAfter(now)) { // now보다 커야 함(같으면 불가)
throw BusinessException.badRequest("SEND_SINGLE_INVALID",
"예약 발송의 경우 희망 발송일시는 현재시간 이후여야 합니다.");
}
}
TemplateDto tmplat = templateService.getTemplate(req.getTmplatIdx());
validateTemplateType(tmplat, getSendType());
LocalDateTime sendDt = req.getSendDt() != null ? req.getSendDt() : now;
String sendTel = firstNonBlank(req.getSendTel(), tmplat.getSendTel());
String sendEml = firstNonBlank(req.getSendEml(), tmplat.getSendEml());
String sendFrom = getSendType() == SendType.EMAIL ? sendEml : sendTel;
String sendNm = firstNonBlank(req.getSendNm(), tmplat.getSendNm());
if (sendFrom == null || sendFrom.isBlank()) {
if (getSendType() == SendType.EMAIL) {
throw BusinessException.badRequest("SEND_EMAIL_REQUIRED", "sendEml은 필수 입니다.");
} else {
throw BusinessException.badRequest("SEND_TEL_REQUIRED", "sendTel은 필수 입니다.");
}
}
DestInfoDto dest = req.getDestInfo();
String sendTo = getSendType() == SendType.EMAIL ? dest.getDestEml() : dest.getDestTel();
if (sendTo == null || sendTo.isBlank()) {
if (getSendType() == SendType.EMAIL) {
throw BusinessException.badRequest("DEST_EMAIL_REQUIRED", "destEml은 필수 입니다.");
} else {
throw BusinessException.badRequest("DEST_TEL_REQUIRED", "destTel은 필수 입니다.");
}
}
String msgTitle = replacePlaceholder(tmplat.getTmplatTitle(), dest.getMsgParam());
String msgBody = replacePlaceholder(tmplat.getTmplatBody(), dest.getMsgParam());
SendInternalResultDto sendResult = doSendInternal(
req.getResve(),
null,
tmplat.getTmplatTy(),
sendFrom,
sendNm,
msgTitle,
msgBody,
dest
);
req.setSendEml(sendEml);
req.setSendTel(sendTel);
req.setSendNm(sendNm);
List<TSendEntity> sendInfo = new ArrayList<>(List.of(
TSendEntity.from(
req,
tmplat.getTmplatTy(),
sendResult,
tmplat.getItrntPrjctCd(),
msgTitle,
msgBody,
regCmpn,
regUser,
req.getResve(),
sendDt,
now
)
));
sendRepository.saveAll(sendInfo);
sendRepository.flush();
afterPersistSendEntities(sendInfo);
}
public final BulkSendResponseDto doSendBulk(SendRequestBulkDto req) {
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
String bulkSendKey = req.getBulkSendKey();
if (bulkSendKey.isBlank()) {
throw BusinessException.badRequest("BULK_SEND_KEY_REQUIRED", "bulkSendKey는 필수입니다.");
}
if (req == null || req.getDestInfoList() == null || req.getDestInfoList().isEmpty()) {
throw BusinessException.badRequest("DEST_LIST_REQUIRED", "수신 정보가 없습니다.");
}
TBulkSendEntity bulk = bulkSendRepository.findById(bulkSendKey)
.orElseThrow(() ->
BusinessException.badRequest("BULK_SEND_KEY_NOT_FOUND", "bulkSendKey가 잘 못 됐습니다.")
.with("bulkSendKey", bulkSendKey)
);
if (bulk.getTrgtCnt() <= bulk.getSendCnt()) {
BusinessException.badRequest("OVERFLOW_SEND_CNT", "해당 bulkSendKey로 발송할 수 있는 한도를 초과 했습니다.")
.with("bulkSendKey", bulkSendKey)
.with("trgtCnt", bulk.getTrgtCnt())
.with("sendCnt", bulk.getSendCnt());
}
TemplateDto tmplat = templateService.getTemplate(bulk.getTmplatIdx());
validateTemplateType(tmplat, getSendType());
Boolean isResve = bulk.getResve();
LocalDateTime sendDt = bulk.getSendDt() != null ? bulk.getSendDt() : now;
String sendTel = firstNonBlank(req.getSendTel(), tmplat.getSendTel());
String sendEml = firstNonBlank(req.getSendEml(), tmplat.getSendEml());
String sendFrom = getSendType() == SendType.EMAIL ? sendEml : sendTel;
String sendNm = firstNonBlank(req.getSendNm(), tmplat.getSendNm());
if (sendFrom == null || sendFrom.isBlank()) {
if (getSendType() == SendType.EMAIL) {
throw BusinessException.badRequest("SENDER_EMAIL_REQUIRED", "sendEml은 필수 입니다.");
} else {
throw BusinessException.badRequest("SENDER_TEL_REQUIRED", "sendTel은 필수 입니다.");
}
}
req.setSendEml(sendEml);
req.setSendTel(sendTel);
req.setSendNm(sendNm);
int requestCnt = req.getDestInfoList().size();
int acceptCnt = 0;
int failCnt = 0;
List<TSendEntity> buffer = new ArrayList<>(
Math.min(requestCnt, NotihubConst.INSERT_CHUNK_SIZE));
for (int offset = 0; offset < requestCnt; offset += NotihubConst.CHUNK_SIZE) {
int end = Math.min(offset + NotihubConst.CHUNK_SIZE, requestCnt);
List<DestInfoDto> chunk = req.getDestInfoList().subList(offset, end);
for (DestInfoDto dest : chunk) {
String sendTo = getSendType() == SendType.EMAIL ? dest.getDestEml() : dest.getDestTel();
if (sendTo == null || sendTo.isBlank()) {
if (getSendType() == SendType.EMAIL) {
throw BusinessException.badRequest("DEST_EMAIL_REQUIRED", "destEml은 필수 입니다.");
} else {
throw BusinessException.badRequest("DEST_TEL_REQUIRED", "destTel은 필수 입니다.");
}
if (dest == null || sendTo.isBlank()) {
failCnt++;
continue;
}
String msgTitle = replacePlaceholder(tmplat.getTmplatTitle(), dest.getMsgParam());
String msgBody = replacePlaceholder(tmplat.getTmplatBody(), dest.getMsgParam());
SendInternalResultDto sendResult = doSendInternal(
req.getResve(),
null,
tmplat.getTmplatTy(),
sendFrom,
sendNm,
msgTitle,
msgBody,
dest
isResve,
bulkSendKey,
tmplat.getTmplatTy(),
sendFrom,
sendNm,
msgTitle,
msgBody,
dest
);
req.setSendEml(sendEml);
req.setSendTel(sendTel);
req.setSendNm(sendNm);
if (sendResult.getStatus() == SendStatusType.SUCCESS) {
acceptCnt++;
} else if (sendResult.getStatus() == SendStatusType.FAIL) {
failCnt++;
}
List<TSendEntity> sendInfo = new ArrayList<>(List.of(
TSendEntity.from(
req,
tmplat.getTmplatTy(),
sendResult,
tmplat.getItrntPrjctCd(),
msgTitle,
msgBody,
regCmpn,
regUser,
req.getResve(),
sendDt,
now
)
));
buffer.add(
TSendEntity.from(
req,
dest,
tmplat.getTmplatTy(),
sendResult,
tmplat.getItrntPrjctCd(),
bulk.getReqstSvc(),
bulk.getPrjctCd(),
bulk.getTmplatIdx(),
msgTitle,
msgBody,
bulk.getRegCmpn(),
bulk.getRegUser(),
isResve,
sendDt,
bulkSendKey,
now
)
);
sendRepository.saveAll(sendInfo);
sendRepository.flush();
afterPersistSendEntities(sendInfo);
if (getSendType() == SendType.EMAIL) {
// 발송 간 딜레이(Pringo rate-limit 대응)
long delay = Math.max(tmplat.getDelayTime(), NotihubConst.EMAIL_DELAY);
sleepSilently(delay);
}
}
}
public final BulkSendResponseDto doSendBulk(SendRequestBulkDto req) {
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
String bulkSendKey = req.getBulkSendKey();
if (bulkSendKey.isBlank()) throw BusinessException.badRequest("BULK_SEND_KEY_REQUIRED", "bulkSendKey는 필수입니다.");
if (req == null || req.getDestInfoList() == null || req.getDestInfoList().isEmpty()) {
throw BusinessException.badRequest("DEST_LIST_REQUIRED", "수신 정보가 없습니다.");
}
TBulkSendEntity bulk = bulkSendRepository.findById(bulkSendKey)
.orElseThrow(() ->
BusinessException.badRequest("BULK_SEND_KEY_NOT_FOUND", "bulkSendKey가 잘 못 됐습니다.")
.with("bulkSendKey", bulkSendKey)
);
if(bulk.getTrgtCnt() <= bulk.getSendCnt()){
BusinessException.badRequest("OVERFLOW_SEND_CNT", "해당 bulkSendKey로 발송할 수 있는 한도를 초과 했습니다.")
.with("bulkSendKey", bulkSendKey)
.with("trgtCnt", bulk.getTrgtCnt())
.with("sendCnt", bulk.getSendCnt());
}
TemplateDto tmplat = templateService.getTemplate(bulk.getTmplatIdx());
validateTemplateType(tmplat, getSendType());
Boolean isResve = bulk.getResve();
LocalDateTime sendDt = bulk.getSendDt() != null ? bulk.getSendDt() : now;
String sendTel = firstNonBlank(req.getSendTel(), tmplat.getSendTel());
String sendEml = firstNonBlank(req.getSendEml(), tmplat.getSendEml());
String sendFrom = getSendType() == SendType.EMAIL ? sendEml : sendTel;
String sendNm = firstNonBlank(req.getSendNm(), tmplat.getSendNm());
if (sendFrom == null || sendFrom.isBlank()) {
if (getSendType() == SendType.EMAIL) {
throw BusinessException.badRequest("SENDER_EMAIL_REQUIRED", "sendEml은 필수 입니다.");
} else {
throw BusinessException.badRequest("SENDER_TEL_REQUIRED", "sendTel은 필수 입니다.");
}
}
req.setSendEml(sendEml);
req.setSendTel(sendTel);
req.setSendNm(sendNm);
int requestCnt = req.getDestInfoList().size();
int acceptCnt = 0;
int failCnt = 0;
List<TSendEntity> buffer = new ArrayList<>(Math.min(requestCnt, NotihubConst.INSERT_CHUNK_SIZE));
for (int offset = 0; offset < requestCnt; offset += NotihubConst.CHUNK_SIZE) {
int end = Math.min(offset + NotihubConst.CHUNK_SIZE, requestCnt);
List<DestInfoDto> chunk = req.getDestInfoList().subList(offset, end);
for (DestInfoDto dest : chunk) {
String sendTo = getSendType() == SendType.EMAIL ? dest.getDestEml() : dest.getDestTel();
if (dest == null || sendTo.isBlank()) {
failCnt++;
continue;
}
String msgTitle = replacePlaceholder(tmplat.getTmplatTitle(), dest.getMsgParam());
String msgBody = replacePlaceholder(tmplat.getTmplatBody(), dest.getMsgParam());
SendInternalResultDto sendResult = doSendInternal(
isResve,
bulkSendKey,
tmplat.getTmplatTy(),
sendFrom,
sendNm,
msgTitle,
msgBody,
dest
);
if (sendResult.getStatus() == SendStatusType.SUCCESS) {
acceptCnt++;
} else if(sendResult.getStatus() == SendStatusType.FAIL) {
failCnt++;
}
buffer.add(
TSendEntity.from(
req,
dest,
tmplat.getTmplatTy(),
sendResult,
tmplat.getItrntPrjctCd(),
bulk.getReqstSvc(),
bulk.getPrjctCd(),
bulk.getTmplatIdx(),
msgTitle,
msgBody,
bulk.getRegCmpn(),
bulk.getRegUser(),
isResve,
sendDt,
bulkSendKey,
now
)
);
if(getSendType() == SendType.EMAIL) {
// 발송 간 딜레이(Pringo rate-limit 대응)
long delay = Math.max(tmplat.getDelayTime(), NotihubConst.EMAIL_DELAY);
sleepSilently(delay);
}
}
}
if (!buffer.isEmpty()) {
saveSendEntitiesChunked(buffer);
buffer.clear();
}
// bulk 집계 업데이트(요청/성공/실패 카운트)
bulk.setSendCnt(Optional.ofNullable(bulk.getSendCnt()).orElse(0) + requestCnt);
bulk.setSuccesCnt(Optional.ofNullable(bulk.getSuccesCnt()).orElse(0) + acceptCnt);
bulk.setFailCnt(Optional.ofNullable(bulk.getFailCnt()).orElse(0) + failCnt);
bulkSendRepository.save(bulk);
return BulkSendResponseDto.of(bulkSendKey, requestCnt, acceptCnt, failCnt);
if (!buffer.isEmpty()) {
saveSendEntitiesChunked(buffer);
buffer.clear();
}
protected String replacePlaceholder(String text, Map<String, String> msgParam){
if (text == null || text.isEmpty() || msgParam == null || msgParam.isEmpty()) {
return text;
}
// bulk 집계 업데이트(요청/성공/실패 카운트)
bulk.setSendCnt(Optional.ofNullable(bulk.getSendCnt()).orElse(0) + requestCnt);
bulk.setSuccesCnt(Optional.ofNullable(bulk.getSuccesCnt()).orElse(0) + acceptCnt);
bulk.setFailCnt(Optional.ofNullable(bulk.getFailCnt()).orElse(0) + failCnt);
bulkSendRepository.save(bulk);
Pattern pattern = Pattern.compile("\\[\\$([^\\]]+)]");
Matcher matcher = pattern.matcher(text);
return BulkSendResponseDto.of(bulkSendKey, requestCnt, acceptCnt, failCnt);
}
StringBuilder sb = new StringBuilder();
while (matcher.find()) {
String varName = matcher.group(1);
String value = msgParam.get(varName);
if (value == null) {
// 값이 없으면 원문 유지
matcher.appendReplacement(sb, Matcher.quoteReplacement(matcher.group(0)));
} else {
// 값 치환 (정규식 replacement 안전 처리)
matcher.appendReplacement(sb, Matcher.quoteReplacement(value));
}
}
matcher.appendTail(sb);
return sb.toString();
protected String replacePlaceholder(String text, Map<String, String> msgParam) {
if (text == null || text.isEmpty() || msgParam == null || msgParam.isEmpty()) {
return text;
}
/** 자식 클래스가 구현: 실제 발송 수행 */
protected abstract SendInternalResultDto doSendInternal(
Boolean isResve,
String bulkSendKey,
SendType sendType,
String sendFrom,
String sendNm,
String msgTitle,
String msgBody,
DestInfoDto dest
);
Pattern pattern = Pattern.compile("\\[\\$([^\\]]+)]");
Matcher matcher = pattern.matcher(text);
public abstract void afterPersistSendEntities(List<TSendEntity> persisted);
StringBuilder sb = new StringBuilder();
while (matcher.find()) {
String varName = matcher.group(1);
String value = msgParam.get(varName);
protected void saveSendEntitiesChunked(List<TSendEntity> entityList) {
if (entityList == null || entityList.isEmpty()) return;
if (value == null) {
// 값이 없으면 원문 유지
matcher.appendReplacement(sb, Matcher.quoteReplacement(matcher.group(0)));
} else {
// 값 치환 (정규식 replacement 안전 처리)
matcher.appendReplacement(sb, Matcher.quoteReplacement(value));
}
}
matcher.appendTail(sb);
int size = entityList.size();
for (int i = 0; i < size; i += NotihubConst.INSERT_CHUNK_SIZE) {
int end = Math.min(size, i + NotihubConst.INSERT_CHUNK_SIZE);
List<TSendEntity> sub = entityList.subList(i, end);
sendRepository.saveAll(sub);
sendRepository.flush();
return sb.toString();
}
afterPersistSendEntities(sub);
}
/**
* 자식 클래스가 구현: 실제 발송 수행
*/
protected abstract SendInternalResultDto doSendInternal(
Boolean isResve,
String bulkSendKey,
SendType sendType,
String sendFrom,
String sendNm,
String msgTitle,
String msgBody,
DestInfoDto dest
);
public abstract void afterPersistSendEntities(List<TSendEntity> persisted);
protected void saveSendEntitiesChunked(List<TSendEntity> entityList) {
if (entityList == null || entityList.isEmpty()) {
return;
}
protected static void sleepSilently(long ms) {
if (ms <= 0) return;
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
int size = entityList.size();
for (int i = 0; i < size; i += NotihubConst.INSERT_CHUNK_SIZE) {
int end = Math.min(size, i + NotihubConst.INSERT_CHUNK_SIZE);
List<TSendEntity> sub = entityList.subList(i, end);
sendRepository.saveAll(sub);
sendRepository.flush();
protected abstract SendType getSendType();
afterPersistSendEntities(sub);
}
}
protected abstract SendType getSendType();
}

View File

@@ -12,75 +12,81 @@ 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 com.kri.notihub.server.persistence.repository.TemplateRepository;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
@Service
public class SendSmsService extends SendService {
private final BizMsgRepository bizMsgRepository;
private final BizMsgRepository bizMsgRepository;
public SendSmsService(
BizMsgRepository bizMsgRepository,
TemplateRepository templateRepository,
BulkSendRepository bulkSendRepository,
SendRepository sendRepository,
TemplateService templateService
){
super(templateRepository, bulkSendRepository, sendRepository, templateService);
this.bizMsgRepository = bizMsgRepository;
public SendSmsService(
BizMsgRepository bizMsgRepository,
TemplateRepository templateRepository,
BulkSendRepository bulkSendRepository,
SendRepository sendRepository,
TemplateService templateService
) {
super(templateRepository, bulkSendRepository, sendRepository, templateService);
this.bizMsgRepository = bizMsgRepository;
}
@Override
protected SendType getSendType() {
//일단 SMS로 내보내고 발송시에 Template의 SendType 또는 MessageBody, 제목여부로 강화 필요
return SendType.SMS; // 프로젝트 enum 기준
}
@Override
protected SendInternalResultDto doSendInternal(
Boolean isResve,
String bulkSendKey,
SendType sendType,
String sendTel,
String sendNm,
String msgTitle,
String msgBody,
DestInfoDto dest
) {
//문자는 비즈 뿌리오가 발송을 해주기 때문에 예약도 따로 처리할 필요 없음
String cmid = CommonUtil.uuid32();
SendStatusType sendStatus = SendStatusType.STANDBY;
short resultCode =
sendType == SendType.LMS_MMS ? NotihubConst.LMS_MMS_STANDBY : NotihubConst.SMS_STANDBY;
return SendInternalResultDto.of(
cmid,
sendStatus,
resultCode
);
}
@Override
public void afterPersistSendEntities(List<TSendEntity> persisted) {
if (persisted == null || persisted.isEmpty()) {
return;
}
@Override
protected SendType getSendType() {
//일단 SMS로 내보내고 발송시에 Template의 SendType 또는 MessageBody, 제목여부로 강화 필요
return SendType.SMS; // 프로젝트 enum 기준
List<BizMsgEntity> msgList = new ArrayList<>(persisted.size());
for (TSendEntity s : persisted) {
if (s == null) {
continue;
}
if (NotihubConst.MOBILE_TYPE_LIST.contains(s.getSendTy())) {
continue;
}
BizMsgEntity m = BizMsgEntity.fromSend(s);
msgList.add(m);
}
@Override
protected SendInternalResultDto doSendInternal(
Boolean isResve,
String bulkSendKey,
SendType sendType,
String sendTel,
String sendNm,
String msgTitle,
String msgBody,
DestInfoDto dest
) {
//문자는 비즈 뿌리오가 발송을 해주기 때문에 예약도 따로 처리할 필요 없음
String cmid = CommonUtil.uuid32();
SendStatusType sendStatus = SendStatusType.STANDBY;
short resultCode = sendType == SendType.LMS_MMS ? NotihubConst.LMS_MMS_STANDBY : NotihubConst.SMS_STANDBY;
return SendInternalResultDto.of(
cmid,
sendStatus,
resultCode
);
}
@Override
public void afterPersistSendEntities(List<TSendEntity> persisted) {
if (persisted == null || persisted.isEmpty()) return;
List<BizMsgEntity> msgList = new ArrayList<>(persisted.size());
for (TSendEntity s : persisted) {
if (s == null) continue;
if (NotihubConst.MOBILE_TYPE_LIST.contains(s.getSendTy())) continue;
BizMsgEntity m = BizMsgEntity.fromSend(s);
msgList.add(m);
}
if (!msgList.isEmpty()) {
bizMsgRepository.saveAll(msgList);
bizMsgRepository.flush();
}
if (!msgList.isEmpty()) {
bizMsgRepository.saveAll(msgList);
bizMsgRepository.flush();
}
}
}

View File

@@ -10,23 +10,23 @@ import org.springframework.stereotype.Component;
@RequiredArgsConstructor
public class SmsSendCursorStore {
private final SendRepository sendRepository;
// 프로세스 전역 커서(스레드 세이프)
private static final java.util.concurrent.atomic.AtomicLong CURSOR = new java.util.concurrent.atomic.AtomicLong(
0L);
private final SendRepository sendRepository;
// 프로세스 전역 커서(스레드 세이프)
private static final java.util.concurrent.atomic.AtomicLong CURSOR = new java.util.concurrent.atomic.AtomicLong(0L);
// 서비스 기동 시: t_send에서 sendTy=SMS의 max(send_idx)로 초기화
@PostConstruct
public void init() {
long maxSendIdx = sendRepository.findMinSendIdxBySendTy(SendType.SMS.getCode());
CURSOR.set(maxSendIdx);
}
// 서비스 기동 시: t_send에서 sendTy=SMS의 max(send_idx)로 초기화
@PostConstruct
public void init() {
long maxSendIdx = sendRepository.findMinSendIdxBySendTy(SendType.SMS.getCode());
CURSOR.set(maxSendIdx);
}
public long get() {
return CURSOR.get();
}
public long get() {
return CURSOR.get();
}
public void set(long sendIdx) {
CURSOR.set(sendIdx);
}
public void set(long sendIdx) {
CURSOR.set(sendIdx);
}
}

View File

@@ -14,174 +14,175 @@ import com.kri.notihub.server.persistence.entity.TTmplatEntity;
import com.kri.notihub.server.persistence.entity.TTmplatEventLogEntity;
import com.kri.notihub.server.persistence.repository.TemplateEventLogRepository;
import com.kri.notihub.server.persistence.repository.TemplateRepository;
import java.time.LocalDateTime;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
@Service
@RequiredArgsConstructor
public class TemplateService {
private final TemplateRepository templateRepository;
private final TemplateEventLogRepository templateEventLogRepository;
private final TemplateRepository templateRepository;
private final TemplateEventLogRepository templateEventLogRepository;
@Transactional
public TemplateDto createTemplate(String itrntPrjctCd, TemplateBasicDto template, String regUser) {
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
@Transactional
public TemplateDto createTemplate(String itrntPrjctCd, TemplateBasicDto template,
String regUser) {
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
validateBySendType(template);
validateBySendType(template);
//제목, 본문 정규화
TemplateContentSanitizer.sanitizeAndNormalizeInPlace(template);
//제목, 본문 정규화
TemplateContentSanitizer.sanitizeAndNormalizeInPlace(template);
// 엔티티 생성은 엔티티 팩토리(내부 builder)로 위임
TTmplatEntity entity = TTmplatEntity.create(itrntPrjctCd, template, regUser, now);
TTmplatEntity saved = templateRepository.save(entity);
// 엔티티 생성은 엔티티 팩토리(내부 builder)로 위임
TTmplatEntity entity = TTmplatEntity.create(itrntPrjctCd, template, regUser, now);
TTmplatEntity saved = templateRepository.save(entity);
saveLog(saved.getTmplatIdx(), TemplateEventType.CREATE_TEMPLATE, null, template, regUser, now);
saveLog(saved.getTmplatIdx(), TemplateEventType.CREATE_TEMPLATE, null, template, regUser, now);
return TemplateDto.from(saved);
}
return TemplateDto.from(saved);
}
public List<TemplateSummaryDto> getTemplateList(ChannelType chnnlTy, String itrntPrjctCd) {
List<Short> tmplatTyList = chnnlTy == ChannelType.SMS
? NotihubConst.MOBILE_TYPE_CODE_LIST
: NotihubConst.EMAIL_TYPE_CODE_LIST;
public List<TemplateSummaryDto> getTemplateList(ChannelType chnnlTy, String itrntPrjctCd) {
List<Short> tmplatTyList = chnnlTy == ChannelType.SMS
? NotihubConst.MOBILE_TYPE_CODE_LIST
: NotihubConst.EMAIL_TYPE_CODE_LIST;
return templateRepository.findAllByTmplatTyInAndItrntPrjctCdAndDelFalse(tmplatTyList, itrntPrjctCd).stream()
.map(TemplateSummaryDto::from)
.toList();
}
return templateRepository.findAllByTmplatTyInAndItrntPrjctCdAndDelFalse(tmplatTyList,
itrntPrjctCd).stream()
.map(TemplateSummaryDto::from)
.toList();
}
public TemplateDto getTemplate(long tmplatIdx) {
return templateRepository.findByTmplatIdxAndDelFalse(tmplatIdx)
.map(TemplateDto::from)
.orElseThrow(() ->
BusinessException.notFound("TEMPLATE_NOT_FOUND", "템플릿을 찾을 수 없습니다.")
.with("tmplatIdx", tmplatIdx)
);
}
public TemplateDto getTemplate(long tmplatIdx) {
return templateRepository.findByTmplatIdxAndDelFalse(tmplatIdx)
.map(TemplateDto::from)
.orElseThrow(() ->
BusinessException.notFound("TEMPLATE_NOT_FOUND", "템플릿을 찾을 수 없습니다.")
.with("tmplatIdx", tmplatIdx)
);
}
@Transactional
public void updateTemplateBodyWithCreate(TemplateDto template) {
TTmplatEntity entity = templateRepository.findByTmplatIdxAndDelFalse(template.getTmplatIdx()).orElseThrow(() ->
BusinessException.notFound("TEMPLATE_NOT_FOUND", "템플릿을 찾을 수 없습니다.")
.with("tmplatIdx", template.getTmplatIdx())
@Transactional
public void updateTemplateBodyWithCreate(TemplateDto template) {
TTmplatEntity entity = templateRepository.findByTmplatIdxAndDelFalse(template.getTmplatIdx())
.orElseThrow(() ->
BusinessException.notFound("TEMPLATE_NOT_FOUND", "템플릿을 찾을 수 없습니다.")
.with("tmplatIdx", template.getTmplatIdx())
);
entity.setTmplatBody(template.getTmplatBody());
templateRepository.save(entity);
}
entity.setTmplatBody(template.getTmplatBody());
templateRepository.save(entity);
}
@Transactional
public TemplateDto updateTemplate(TemplateDto template, String modUser) {
long tmplatIdx = template.getTmplatIdx();
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
@Transactional
public TemplateDto updateTemplate(TemplateDto template, String modUser) {
long tmplatIdx = template.getTmplatIdx();
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
TTmplatEntity entity = templateRepository.findByTmplatIdxAndDelFalse(tmplatIdx).orElseThrow(() ->
BusinessException.notFound("TEMPLATE_NOT_FOUND", "템플릿을 찾을 수 없습니다.")
.with("tmplatIdx", tmplatIdx)
TTmplatEntity entity = templateRepository.findByTmplatIdxAndDelFalse(tmplatIdx)
.orElseThrow(() ->
BusinessException.notFound("TEMPLATE_NOT_FOUND", "템플릿을 찾을 수 없습니다.")
.with("tmplatIdx", tmplatIdx)
);
validateBySendType(template);
validateBySendType(template);
//제목, 본문 정규화
TemplateContentSanitizer.sanitizeAndNormalizeInPlace(template);
//제목, 본문 정규화
TemplateContentSanitizer.sanitizeAndNormalizeInPlace(template);
TemplateBasicDto before = TemplateDto.from(entity);
TemplateBasicDto before = TemplateDto.from(entity);
entity.updateFrom(template, modUser, now);
entity.updateFrom(template, modUser, now);
templateRepository.save(entity);
templateRepository.save(entity);
saveLog(tmplatIdx, TemplateEventType.UPDATE_TEMPLATE, before, template, modUser, now);
saveLog(tmplatIdx, TemplateEventType.UPDATE_TEMPLATE, before, template, modUser, now);
return template;
return template;
}
@Transactional
public void deleteTemplate(long tmplatIdx, String delUser) {
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
templateRepository.softDeleteByTmplatIdx(tmplatIdx, delUser, now);
saveLog(tmplatIdx, TemplateEventType.DELETE_TEMPLATE, null, null, delUser, now);
}
private void saveLog(
long tmplatIdx,
TemplateEventType eventType,
TemplateBasicDto beforeTmplat,
TemplateBasicDto afterTmplat,
String regUser,
LocalDateTime regDt
) {
TTmplatEventLogEntity log = TTmplatEventLogEntity.of(
tmplatIdx,
eventType,
beforeTmplat,
afterTmplat,
regUser,
regDt
);
templateEventLogRepository.save(log);
}
private void validateBySendType(TemplateBasicDto template) {
//공통 검증
if (template.getTmplatTy() == null) {
throw BusinessException.badRequest("NULL TYPE", "템플릿 타입은 필수입니다.");
}
@Transactional
public void deleteTemplate(long tmplatIdx, String delUser) {
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
templateRepository.softDeleteByTmplatIdx(tmplatIdx, delUser, now);
saveLog(tmplatIdx, TemplateEventType.DELETE_TEMPLATE, null, null, delUser, now);
if (template.getTmplatNm() == null || template.getTmplatNm().isBlank()) {
throw BusinessException.badRequest("EMPTY_NAME", "템플릿 명은 필수입니다.");
}
private void saveLog(
long tmplatIdx,
TemplateEventType eventType,
TemplateBasicDto beforeTmplat,
TemplateBasicDto afterTmplat,
String regUser,
LocalDateTime regDt
) {
TTmplatEventLogEntity log = TTmplatEventLogEntity.of(
tmplatIdx,
eventType,
beforeTmplat,
afterTmplat,
regUser,
regDt
);
templateEventLogRepository.save(log);
if (template.getTmplatBody() == null || template.getTmplatBody().isBlank()) {
throw BusinessException.badRequest("EMPTY_BODY", "내용은 필수입니다.");
}
private void validateBySendType(TemplateBasicDto template) {
//공통 검증
if (template.getTmplatTy() == null) {
throw BusinessException.badRequest("NULL TYPE", "템플릿 타입은 필수입니다.");
}
if (template.getTmplatNm() == null || template.getTmplatNm().isBlank()) {
throw BusinessException.badRequest("EMPTY_NAME", "템플릿 명은 필수입니다.");
}
if (template.getTmplatBody() == null || template.getTmplatBody().isBlank()) {
throw BusinessException.badRequest("EMPTY_BODY", "내용은 필수입니다.");
}
if(template.getSendNm() == null || template.getSendNm().isBlank()) {
throw BusinessException.badRequest("EMPTY_SEND_NAME", "발신자 명은 필수입니다.");
}
if (template.getDelayTime() != null) {
if (template.getDelayTime() < 0) {
template.setDelayTime((short) 0);
}
if (template.getDelayTime() > NotihubConst.DELAY_MAX_MS) {
template.setDelayTime(NotihubConst.DELAY_MAX_MS);
}
}
SendType ty = template.getTmplatTy();
if (ty == SendType.EMAIL) {
if (template.getSendEml() == null || template.getSendEml().isBlank()) {
throw BusinessException.badRequest("EMPTY_EMAIL", "이메일은 필수입니다.");
}
if (template.getTmplatTitle() == null || template.getTmplatTitle().isBlank()) {
throw BusinessException.badRequest("EMPTY_TITLE", "제목은 필수입니다.");
}
template.setSendTel(null);
}
else if (NotihubConst.MOBILE_TYPE_LIST.contains(ty)) {
if (template.getSendTel() == null || template.getSendTel().isBlank()) {
throw BusinessException.badRequest("EMPTY_TEL", "발송번호는 필수입니다.");
}
if (ty == SendType.SMS) {
template.setTmplatTitle(null);
}
template.setSendEml(null);
}
else {
// 혹시 enum 확장 대비
throw BusinessException.badRequest("INVALID_TYPE", "지원하지 않는 템플릿 타입입니다.")
.with("tmplatTy", ty);
}
if (template.getSendNm() == null || template.getSendNm().isBlank()) {
throw BusinessException.badRequest("EMPTY_SEND_NAME", "발신자 명은 필수입니다.");
}
if (template.getDelayTime() != null) {
if (template.getDelayTime() < 0) {
template.setDelayTime((short) 0);
}
if (template.getDelayTime() > NotihubConst.DELAY_MAX_MS) {
template.setDelayTime(NotihubConst.DELAY_MAX_MS);
}
}
SendType ty = template.getTmplatTy();
if (ty == SendType.EMAIL) {
if (template.getSendEml() == null || template.getSendEml().isBlank()) {
throw BusinessException.badRequest("EMPTY_EMAIL", "이메일은 필수입니다.");
}
if (template.getTmplatTitle() == null || template.getTmplatTitle().isBlank()) {
throw BusinessException.badRequest("EMPTY_TITLE", "제목은 필수입니다.");
}
template.setSendTel(null);
} else if (NotihubConst.MOBILE_TYPE_LIST.contains(ty)) {
if (template.getSendTel() == null || template.getSendTel().isBlank()) {
throw BusinessException.badRequest("EMPTY_TEL", "발송번호는 필수입니다.");
}
if (ty == SendType.SMS) {
template.setTmplatTitle(null);
}
template.setSendEml(null);
} else {
// 혹시 enum 확장 대비
throw BusinessException.badRequest("INVALID_TYPE", "지원하지 않는 템플릿 타입입니다.")
.with("tmplatTy", ty);
}
}
}