first commit
This commit is contained in:
350
src/main/java/com/kri/notihub/server/service/SendService.java
Normal file
350
src/main/java/com/kri/notihub/server/service/SendService.java
Normal file
@@ -0,0 +1,350 @@
|
||||
package com.kri.notihub.server.service;
|
||||
|
||||
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.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.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.apache.commons.lang3.StringUtils.firstNonBlank;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public abstract class SendService {
|
||||
|
||||
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();
|
||||
|
||||
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보다 커야 합니다.");
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
protected void validateTemplateType(TemplateDto tmplat, SendType requiredType) {
|
||||
if (tmplat == null || requiredType == null) return;
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
public final void doSendSingle(SendRequestSingleDto req, String regCmpn, String regUser) {
|
||||
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
|
||||
|
||||
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 (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);
|
||||
}
|
||||
|
||||
protected String replacePlaceholder(String text, Map<String, String> msgParam){
|
||||
if (text == null || text.isEmpty() || msgParam == null || msgParam.isEmpty()) {
|
||||
return text;
|
||||
}
|
||||
|
||||
Pattern pattern = Pattern.compile("\\[\\$([^\\]]+)]");
|
||||
Matcher matcher = pattern.matcher(text);
|
||||
|
||||
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 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;
|
||||
|
||||
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();
|
||||
|
||||
afterPersistSendEntities(sub);
|
||||
}
|
||||
}
|
||||
|
||||
protected static void sleepSilently(long ms) {
|
||||
if (ms <= 0) return;
|
||||
try {
|
||||
Thread.sleep(ms);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract SendType getSendType();
|
||||
}
|
||||
Reference in New Issue
Block a user