469 lines
17 KiB
Java
469 lines
17 KiB
Java
package com.kri.contact.server.service;
|
|
|
|
import static com.kri.contact.server.common.consts.ContactConstant.REQUEST_SERVICE;
|
|
|
|
import com.kri.common.feature.web.BusinessException;
|
|
import com.kri.common.feature.web.RequestUserContext;
|
|
import com.kri.contact.server.common.enums.ChannelType;
|
|
import com.kri.contact.server.common.enums.ListHeaderType;
|
|
import com.kri.contact.server.common.enums.ListIsUse;
|
|
import com.kri.contact.server.common.external.notihub.NotiHubApiClient;
|
|
import com.kri.contact.server.common.external.notihub.NotiHubBulkSendCreateRequestDto;
|
|
import com.kri.contact.server.common.external.notihub.NotiHubBulkSendResponseDto;
|
|
import com.kri.contact.server.common.external.notihub.NotiHubDestInfoDto;
|
|
import com.kri.contact.server.common.external.notihub.NotiHubSendRequestBulkDto;
|
|
import com.kri.contact.server.common.external.notihub.NotiHubSendRequestSingleDto;
|
|
import com.kri.contact.server.common.external.notihub.NotiHubSendSingleResponseDto;
|
|
import com.kri.contact.server.common.external.notihub.NotiHubTemplateDto;
|
|
import com.kri.contact.server.dto.list.ListHeaderDto;
|
|
import com.kri.contact.server.dto.list.ListSendResultDto;
|
|
import com.kri.contact.server.dto.message.MessageBulkSendResponseDto;
|
|
import com.kri.contact.server.dto.message.MessageFailedChunkDto;
|
|
import com.kri.contact.server.dto.message.MessageSendBulkRequestDto;
|
|
import com.kri.contact.server.dto.message.MessageSendSingleRequestDto;
|
|
import com.kri.contact.server.dto.message.MessageSendSingleResponseDto;
|
|
import com.kri.contact.server.dto.project.ProjectInfoDto;
|
|
import java.util.ArrayList;
|
|
import java.util.Collection;
|
|
import java.util.Collections;
|
|
import java.util.HashSet;
|
|
import java.util.LinkedHashMap;
|
|
import java.util.LinkedHashSet;
|
|
import java.util.List;
|
|
import java.util.Locale;
|
|
import java.util.Map;
|
|
import java.util.Objects;
|
|
import java.util.Set;
|
|
import java.util.regex.Matcher;
|
|
import java.util.regex.Pattern;
|
|
import java.util.stream.Collectors;
|
|
import lombok.RequiredArgsConstructor;
|
|
import org.apache.commons.collections4.SetUtils;
|
|
import org.springframework.stereotype.Service;
|
|
import org.springframework.transaction.annotation.Transactional;
|
|
|
|
@Service
|
|
@RequiredArgsConstructor
|
|
public class MessageService {
|
|
private static final int BULK_SEND_CHUNK_SIZE = 1_000;
|
|
private static final Pattern TEMPLATE_PARAM_PATTERN = Pattern.compile("(?:\\[\\$|#\\{)([^\\]}]+)(?:]|})");
|
|
|
|
private final ProjectService projectService;
|
|
private final ListHeaderService listHeaderService;
|
|
private final ListSearchService listSearchService;
|
|
private final NotiHubApiClient notiHubApiClient;
|
|
|
|
@Transactional(readOnly = true)
|
|
public MessageSendSingleResponseDto sendEmailSingle(
|
|
Long prjctIdx,
|
|
MessageSendSingleRequestDto request,
|
|
RequestUserContext ctx
|
|
) {
|
|
return sendSingle(prjctIdx, request, ctx, ChannelType.EMAIL);
|
|
}
|
|
|
|
@Transactional(readOnly = true)
|
|
public MessageSendSingleResponseDto sendSmsSingle(
|
|
Long prjctIdx,
|
|
MessageSendSingleRequestDto request,
|
|
RequestUserContext ctx
|
|
) {
|
|
return sendSingle(prjctIdx, request, ctx, ChannelType.SMS);
|
|
}
|
|
|
|
@Transactional(readOnly = true)
|
|
public MessageBulkSendResponseDto sendEmailBulk(Long prjctIdx, MessageSendBulkRequestDto request, RequestUserContext ctx) {
|
|
return sendBulk(prjctIdx, request, ctx, ChannelType.EMAIL);
|
|
}
|
|
|
|
@Transactional(readOnly = true)
|
|
public MessageBulkSendResponseDto sendSmsBulk(Long prjctIdx, MessageSendBulkRequestDto request, RequestUserContext ctx) {
|
|
return sendBulk(prjctIdx, request, ctx, ChannelType.SMS);
|
|
}
|
|
|
|
private MessageSendSingleResponseDto sendSingle(
|
|
Long prjctIdx,
|
|
MessageSendSingleRequestDto request,
|
|
RequestUserContext ctx,
|
|
ChannelType channelType
|
|
) {
|
|
validateDestinationHeaders(request.getDestHeaderIds());
|
|
|
|
MessageContext messageContext = createMessageContext(prjctIdx, request.getTmplatIdx(), request.getDestHeaderIds());
|
|
ListSearchService.DownloadListRow row = listSearchService
|
|
.findDownloadListRows(prjctIdx, ListFilterDtoFactory.onlySid(request.getSid()), null)
|
|
.stream()
|
|
.findFirst()
|
|
.orElseThrow(() -> BusinessException.notFound("LIST_NOT_FOUND", "발송 대상 리스트를 찾을 수 없습니다.")
|
|
.with("sid", request.getSid()));
|
|
|
|
List<NotiHubDestInfoDto> destInfos = createDestInfos(
|
|
List.of(row),
|
|
request.getDestHeaderIds(),
|
|
request.getDestNameHeaderId(),
|
|
messageContext,
|
|
channelType,
|
|
new LinkedHashSet<>(),
|
|
true
|
|
);
|
|
if (destInfos.isEmpty()) {
|
|
throw BusinessException.badRequest("NO_DESTINATION", "발송 대상 이메일 또는 전화번호가 없습니다.");
|
|
}
|
|
|
|
NotiHubSendSingleResponseDto response = null;
|
|
for (NotiHubDestInfoDto destInfo : destInfos) {
|
|
NotiHubSendRequestSingleDto notiRequest = NotiHubSendRequestSingleDto.builder()
|
|
.destInfo(destInfo)
|
|
.tmplatIdx(request.getTmplatIdx())
|
|
.reqstSvc(REQUEST_SERVICE)
|
|
.prjctCd(messageContext.project().getPrjctCd())
|
|
.resve(request.getResve())
|
|
.sendDt(request.getSendDt())
|
|
.build();
|
|
|
|
if (channelType == ChannelType.EMAIL) {
|
|
response = notiHubApiClient.sendEmailSingle(notiRequest, ctx);
|
|
} else {
|
|
response = notiHubApiClient.sendSmsSingle(notiRequest, ctx);
|
|
}
|
|
}
|
|
return MessageSendSingleResponseDto.from(response);
|
|
}
|
|
|
|
private MessageBulkSendResponseDto sendBulk(
|
|
Long prjctIdx,
|
|
MessageSendBulkRequestDto request,
|
|
RequestUserContext ctx,
|
|
ChannelType channelType
|
|
) {
|
|
validateDestinationHeaders(request.getDestHeaderIds());
|
|
|
|
MessageContext messageContext = createMessageContext(prjctIdx, request.getTmplatIdx(), request.getDestHeaderIds());
|
|
List<NotiHubDestInfoDto> destInfos = createAllDestInfos(
|
|
prjctIdx,
|
|
request,
|
|
messageContext,
|
|
channelType,
|
|
Boolean.TRUE.equals(request.getDedupe())
|
|
);
|
|
if (destInfos.isEmpty()) {
|
|
throw BusinessException.badRequest("NO_DESTINATION", "발송 대상 이메일 또는 전화번호가 없습니다.");
|
|
}
|
|
|
|
String bulkSendKey = createBulkSendKey(request, ctx, messageContext, destInfos.size(), channelType);
|
|
int requestCount = 0;
|
|
int acceptCount = 0;
|
|
int failCount = 0;
|
|
List<MessageFailedChunkDto> failedChunks = new ArrayList<>();
|
|
|
|
for (int start = 0, chunkIndex = 1; start < destInfos.size(); start += BULK_SEND_CHUNK_SIZE, chunkIndex++) {
|
|
int end = Math.min(start + BULK_SEND_CHUNK_SIZE, destInfos.size());
|
|
List<NotiHubDestInfoDto> chunk = destInfos.subList(start, end);
|
|
try {
|
|
NotiHubBulkSendResponseDto response = sendBulkChunk(bulkSendKey, chunk, channelType);
|
|
requestCount += defaultInt(response.getRequestCount());
|
|
acceptCount += defaultInt(response.getAcceptCount());
|
|
failCount += defaultInt(response.getFailCount());
|
|
} catch (RuntimeException e) {
|
|
requestCount += chunk.size();
|
|
failCount += chunk.size();
|
|
failedChunks.add(MessageFailedChunkDto.builder()
|
|
.chunkIndex(chunkIndex)
|
|
.from(start + 1)
|
|
.to(end)
|
|
.targetCount(chunk.size())
|
|
.errorMessage(e.getMessage())
|
|
.build());
|
|
}
|
|
}
|
|
|
|
return MessageBulkSendResponseDto.builder()
|
|
.bulkSendKey(bulkSendKey)
|
|
.targetCount(destInfos.size())
|
|
.requestCount(requestCount)
|
|
.acceptCount(acceptCount)
|
|
.failCount(failCount)
|
|
.failedChunks(failedChunks)
|
|
.build();
|
|
}
|
|
|
|
private List<NotiHubDestInfoDto> createAllDestInfos(
|
|
Long prjctIdx,
|
|
MessageSendBulkRequestDto request,
|
|
MessageContext messageContext,
|
|
ChannelType channelType,
|
|
boolean dedupe
|
|
) {
|
|
List<NotiHubDestInfoDto> destInfos = new ArrayList<>();
|
|
Set<String> dedupeKeys = new LinkedHashSet<>();
|
|
String lastSid = null;
|
|
|
|
while (true) {
|
|
List<ListSearchService.DownloadListRow> rows = listSearchService.findDownloadListRows(
|
|
prjctIdx,
|
|
request.getListFilter(),
|
|
lastSid
|
|
);
|
|
if (rows.isEmpty()) {
|
|
break;
|
|
}
|
|
|
|
destInfos.addAll(createDestInfos(
|
|
rows,
|
|
request.getDestHeaderIds(),
|
|
request.getDestNameHeaderId(),
|
|
messageContext,
|
|
channelType,
|
|
dedupeKeys,
|
|
dedupe
|
|
));
|
|
lastSid = rows.get(rows.size() - 1).sid();
|
|
}
|
|
return destInfos;
|
|
}
|
|
|
|
private List<NotiHubDestInfoDto> createDestInfos(
|
|
Collection<ListSearchService.DownloadListRow> rows,
|
|
List<Integer> destHeaderIds,
|
|
Integer destNameHeaderId,
|
|
MessageContext messageContext,
|
|
ChannelType channelType,
|
|
Set<String> dedupeKeys,
|
|
boolean dedupe
|
|
) {
|
|
List<NotiHubDestInfoDto> result = new ArrayList<>();
|
|
for (ListSearchService.DownloadListRow row : rows) {
|
|
Map<String, String> msgParam = createMessageParams(row, messageContext.paramHeaderByName());
|
|
String destNm = resolveHeaderValue(row, messageContext.headerById().get(destNameHeaderId));
|
|
|
|
for (Integer destHeaderId : destHeaderIds) {
|
|
String rawDestination = row.itemMap().get(destHeaderId);
|
|
String destination = normalizeDestination(rawDestination, channelType);
|
|
if (destination == null || isDuplicateDestination(destination, channelType, dedupeKeys, dedupe)) {
|
|
continue;
|
|
}
|
|
|
|
NotiHubDestInfoDto.NotiHubDestInfoDtoBuilder builder = NotiHubDestInfoDto.builder()
|
|
.sid(String.valueOf(row.sid()))
|
|
.destNm(destNm)
|
|
.msgParam(msgParam);
|
|
if (channelType == ChannelType.EMAIL) {
|
|
builder.destEml(destination);
|
|
} else {
|
|
builder.destTel(destination);
|
|
}
|
|
result.add(builder.build());
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
private MessageContext createMessageContext(Long prjctIdx, Long tmplatIdx, List<Integer> destHeaderIds) {
|
|
ProjectInfoDto project = projectService.getProject(prjctIdx);
|
|
if (project == null) {
|
|
throw BusinessException.notFound("PROJECT_NOT_FOUND", "프로젝트를 찾을 수 없습니다.")
|
|
.with("prjctIdx", prjctIdx);
|
|
}
|
|
|
|
NotiHubTemplateDto template = notiHubApiClient.getTemplate(tmplatIdx);
|
|
Set<String> titleParams = extractTemplateParams(template.getTmplatTitle());
|
|
Set<String> bodyParams = extractTemplateParams(template.getTmplatBody());
|
|
Set<String> templateParams = SetUtils.union(titleParams, bodyParams);
|
|
|
|
Map<Integer, ListHeaderDto> headerById = listHeaderService.getHeader(prjctIdx).stream()
|
|
.collect(Collectors.toMap(
|
|
ListHeaderDto::getListHderId,
|
|
header -> header,
|
|
(left, right) -> left,
|
|
LinkedHashMap::new
|
|
));
|
|
|
|
List<Integer> missingDestHeaderIds = destHeaderIds.stream()
|
|
.filter(headerId -> !headerById.containsKey(headerId))
|
|
.toList();
|
|
if (!missingDestHeaderIds.isEmpty()) {
|
|
throw BusinessException.badRequest("DEST_HEADER_NOT_FOUND", "수신처 헤더를 찾을 수 없습니다.")
|
|
.with("destHeaderIds", missingDestHeaderIds);
|
|
}
|
|
|
|
Map<String, ListHeaderDto> paramHeaderByName = headerById.values().stream()
|
|
.filter(header -> templateParams.contains(header.getListHderNm()))
|
|
.collect(Collectors.toMap(
|
|
ListHeaderDto::getListHderNm,
|
|
header -> header,
|
|
(left, right) -> left,
|
|
LinkedHashMap::new
|
|
));
|
|
|
|
return new MessageContext(project, template, headerById, paramHeaderByName);
|
|
}
|
|
|
|
private String createBulkSendKey(
|
|
MessageSendBulkRequestDto request,
|
|
RequestUserContext ctx,
|
|
MessageContext messageContext,
|
|
int targetCount,
|
|
ChannelType channelType
|
|
) {
|
|
NotiHubBulkSendCreateRequestDto notiRequest = NotiHubBulkSendCreateRequestDto.builder()
|
|
.reqstCmpn(ctx == null ? null : ctx.getUserCmpn())
|
|
.reqstUser(ctx == null ? null : ctx.getUserId())
|
|
.reqstSvc(REQUEST_SERVICE)
|
|
.prjctCd(messageContext.project().getPrjctCd())
|
|
.tmplatIdx(request.getTmplatIdx())
|
|
.resve(request.getResve())
|
|
.sendDt(request.getSendDt())
|
|
.trgtCnt(targetCount)
|
|
.build();
|
|
|
|
return channelType == ChannelType.EMAIL
|
|
? notiHubApiClient.createEmailBulk(notiRequest)
|
|
: notiHubApiClient.createSmsBulk(notiRequest);
|
|
}
|
|
|
|
private NotiHubBulkSendResponseDto sendBulkChunk(
|
|
String bulkSendKey,
|
|
List<NotiHubDestInfoDto> destInfos,
|
|
ChannelType channelType
|
|
) {
|
|
NotiHubSendRequestBulkDto request = NotiHubSendRequestBulkDto.builder()
|
|
.bulkSendKey(bulkSendKey)
|
|
.destInfoList(destInfos)
|
|
.build();
|
|
|
|
return channelType == ChannelType.EMAIL
|
|
? notiHubApiClient.sendEmailBulk(request)
|
|
: notiHubApiClient.sendSmsBulk(request);
|
|
}
|
|
|
|
private Map<String, String> createMessageParams(
|
|
ListSearchService.DownloadListRow row,
|
|
Map<String, ListHeaderDto> paramHeaderByName
|
|
) {
|
|
Map<String, String> msgParam = new LinkedHashMap<>();
|
|
for (Map.Entry<String, ListHeaderDto> entry : paramHeaderByName.entrySet()) {
|
|
String value = resolveHeaderValue(row, entry.getValue());
|
|
if (value != null) {
|
|
msgParam.put(entry.getKey(), value);
|
|
}
|
|
}
|
|
return msgParam;
|
|
}
|
|
|
|
private String resolveHeaderValue(ListSearchService.DownloadListRow row, ListHeaderDto header) {
|
|
if (header == null) {
|
|
return null;
|
|
}
|
|
if (Objects.equals(header.getListHderTy(), ListHeaderType.SID)) {
|
|
return String.valueOf(row.sid());
|
|
}
|
|
if (Objects.equals(header.getListHderTy(), ListHeaderType.IS_USE)) {
|
|
return toUseValue(row.isUse());
|
|
}
|
|
if (Objects.equals(header.getListHderTy(), ListHeaderType.MEMO)) {
|
|
return normalizeBlank(row.memo());
|
|
}
|
|
if (Objects.equals(header.getListHderTy(), ListHeaderType.OUTSOURCE)) {
|
|
return normalizeBlank(String.join(", ", row.assignValues().outsourceUserIds()));
|
|
}
|
|
if (Objects.equals(header.getListHderTy(), ListHeaderType.CONTACT_INTERVIEWER)) {
|
|
return normalizeBlank(String.join(", ", row.assignValues().contactInterviewerIds()));
|
|
}
|
|
if (Objects.equals(header.getListHderTy(), ListHeaderType.FIELD_INTERVIEWER)) {
|
|
return normalizeBlank(String.join(", ", row.assignValues().fieldInterviewerIds()));
|
|
}
|
|
return normalizeBlank(row.itemMap().get(header.getListHderId()));
|
|
}
|
|
|
|
private String toUseValue(Short isUse) {
|
|
if (Objects.equals(isUse, ListIsUse.USABLE.getCode())) {
|
|
return "O";
|
|
}
|
|
if (Objects.equals(isUse, ListIsUse.UNUSABLE.getCode())) {
|
|
return "X";
|
|
}
|
|
if (Objects.equals(isUse, ListIsUse.TEST.getCode())) {
|
|
return "TEST";
|
|
}
|
|
return isUse == null ? null : String.valueOf(isUse);
|
|
}
|
|
|
|
private Set<String> extractTemplateParams(String templateBody) {
|
|
if (templateBody == null || templateBody.isBlank()) {
|
|
return Set.of();
|
|
}
|
|
|
|
Set<String> params = new HashSet<>();
|
|
Matcher matcher = TEMPLATE_PARAM_PATTERN.matcher(templateBody);
|
|
while (matcher.find()) {
|
|
String param = normalizeBlank(matcher.group(1));
|
|
if (param != null) {
|
|
params.add(param);
|
|
}
|
|
}
|
|
return params;
|
|
}
|
|
|
|
private void validateDestinationHeaders(List<Integer> destHeaderIds) {
|
|
if (destHeaderIds == null || destHeaderIds.isEmpty()) {
|
|
throw BusinessException.badRequest("DEST_HEADER_REQUIRED", "수신처 헤더가 필요합니다.");
|
|
}
|
|
}
|
|
|
|
private String normalizeDestination(String value, ChannelType channelType) {
|
|
String normalized = normalizeBlank(value);
|
|
if (normalized == null) {
|
|
return null;
|
|
}
|
|
if (channelType == ChannelType.SMS) {
|
|
String digits = normalized.replaceAll("\\D", "");
|
|
return digits.isBlank() ? null : digits;
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
private boolean isDuplicateDestination(
|
|
String destination,
|
|
ChannelType channelType,
|
|
Set<String> dedupeKeys,
|
|
boolean dedupe
|
|
) {
|
|
if (!dedupe) {
|
|
return false;
|
|
}
|
|
return !dedupeKeys.add(createDedupeKey(destination, channelType));
|
|
}
|
|
|
|
private String createDedupeKey(String destination, ChannelType channelType) {
|
|
if (channelType == ChannelType.EMAIL) {
|
|
return destination.toLowerCase(Locale.ROOT);
|
|
}
|
|
return destination;
|
|
}
|
|
|
|
private String normalizeBlank(String value) {
|
|
if (value == null) {
|
|
return null;
|
|
}
|
|
String trimmed = value.trim();
|
|
return trimmed.isEmpty() ? null : trimmed;
|
|
}
|
|
|
|
private int defaultInt(Integer value) {
|
|
return value == null ? 0 : value;
|
|
}
|
|
|
|
private record MessageContext(
|
|
ProjectInfoDto project,
|
|
NotiHubTemplateDto template,
|
|
Map<Integer, ListHeaderDto> headerById,
|
|
Map<String, ListHeaderDto> paramHeaderByName
|
|
) {}
|
|
|
|
private static class ListFilterDtoFactory {
|
|
static com.kri.contact.server.dto.list.ListFilterDto onlySid(String sid) {
|
|
return com.kri.contact.server.dto.list.ListFilterDto.onlyOneSid(sid);
|
|
}
|
|
}
|
|
}
|