260806_01_ENH: 파일첨부 발송 추가

This commit is contained in:
2026-08-06 14:36:13 +09:00
parent c4c57654da
commit de67433539
17 changed files with 616 additions and 69 deletions

View File

@@ -13,6 +13,7 @@ import com.kri.notihub.server.common.external.pringo.dto.PringoReturnRequestDto;
import com.kri.notihub.server.common.external.pringo.dto.PringoReturnResponseDto;
import com.kri.notihub.server.common.external.pringo.dto.PringoSendRequestDto;
import com.kri.notihub.server.common.external.pringo.dto.PringoSendResponseDto;
import com.kri.notihub.server.dto.email.EmailAttachmentDto;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
@@ -83,6 +84,7 @@ public class PringoApiClient {
addFormField(parts, "subject", request.getSubject());
addFormField(parts, "body", request.getBody());
addFormField(parts, "user_info", objectMapper.writeValueAsString(buildUserInfo(request)));
addFileParts(parts, request.getAttachments());
ExternalApiResponse response = externalApiClient.postMultipart(url, headers, parts);
return objectMapper.readValue(response.getBody(), PringoSendResponseDto.class);
@@ -185,6 +187,31 @@ public class PringoApiClient {
parts.add(ExternalApiMultipartPart.formField(name, value));
}
private void addFileParts(
List<ExternalApiMultipartPart> parts,
List<EmailAttachmentDto> attachments
) {
if (attachments == null || attachments.isEmpty()) {
return;
}
if (attachments.size() > 5) {
throw new IllegalArgumentException("Pringo attachments must not exceed 5 files.");
}
for (EmailAttachmentDto attachment : attachments) {
if (attachment.content().length >= 1_000_000) {
throw new IllegalArgumentException(
"Pringo attachment must be smaller than 1 MB: " + attachment.fileName());
}
parts.add(ExternalApiMultipartPart.file(
"files",
attachment.fileName(),
attachment.contentType(),
attachment.content()
));
}
}
private Map<String, Object> buildUserInfo(PringoSendRequestDto request) {
Map<String, Object> recipientInfo = new LinkedHashMap<>();
recipientInfo.put("alternates", request.getVars() == null ? Map.of() : request.getVars());

View File

@@ -4,8 +4,10 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.kri.notihub.server.dto.email.EmailAttachmentDto;
import com.kri.notihub.server.dto.template.TemplateBasicDto;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
@@ -26,7 +28,7 @@ public class PringoSendRequestDto {
"api_key", "template_id",
"sender", "sender_name",
"recipient", "recipient_name",
"subject", "body"
"subject", "body", "files"
);
@JsonProperty("api_key")
@@ -61,6 +63,10 @@ public class PringoSendRequestDto {
*/
private String body;
@JsonIgnore
@Builder.Default
private List<EmailAttachmentDto> attachments = List.of();
/**
* Pringo 템플릿 치환용 동적 변수 예) body: "...[$jstest]..." vars: {"jstest":"테스트 지롱~"}
*/
@@ -142,6 +148,7 @@ public class PringoSendRequestDto {
.recipientName(this.recipientName)
.subject(this.subject)
.body(this.body)
.attachments(this.attachments == null ? List.of() : List.copyOf(this.attachments))
.vars(new java.util.LinkedHashMap<>(this.vars))
.build();
}
@@ -187,4 +194,4 @@ public class PringoSendRequestDto {
throw new IllegalArgumentException("body is required.");
}
}
}
}

View File

@@ -2,7 +2,7 @@ package com.kri.notihub.server.controller;
import com.kri.common.feature.web.RequestUserContext;
import com.kri.notihub.server.common.enums.ChannelType;
import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.dto.email.EmailAttachmentDto;
import com.kri.notihub.server.dto.template.TemplateBasicDto;
import com.kri.notihub.server.dto.template.TemplateDto;
import com.kri.notihub.server.dto.template.TemplateSummaryDto;
@@ -11,16 +11,21 @@ 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 java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@@ -48,27 +53,38 @@ public class TemplateController {
return templateService.getTemplate(tmplatIdx);
}
@Operation(summary = "템플릿 생성")
@PutMapping
@Operation(summary = "템플릿 첨부파일 개별 다운로드")
@GetMapping("/{tmplatIdx}/attachment")
public ResponseEntity<byte[]> downloadAttachment(
@PathVariable long tmplatIdx,
@RequestParam String fileName
) {
EmailAttachmentDto attachment = templateService.downloadAttachment(tmplatIdx, fileName);
String encodedFileName = URLEncoder.encode(attachment.fileName(), StandardCharsets.UTF_8)
.replace("+", "%20");
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename*=UTF-8''" + encodedFileName)
.header(HttpHeaders.CACHE_CONTROL, "no-store")
.contentType(MediaType.parseMediaType(attachment.contentType()))
.contentLength(attachment.content().length)
.body(attachment.content());
}
@Operation(summary = "첨부파일을 포함한 템플릿 생성")
@PutMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public TemplateDto createTemplate(
@Valid @RequestBody TemplateBasicDto template,
@Valid @RequestPart("template") TemplateBasicDto template,
@RequestPart(value = "files", required = false) List<MultipartFile> files,
RequestUserContext ctx
) {
TemplateDto newTmplat = templateService.createTemplate(template.getItrntPrjctCd(), template,
ctx.getUserId());
if (template.getTmplatTy() == SendType.EMAIL) {
String newHtml = fileService.syncOnSave(
newTmplat.getItrntPrjctCd(),
newTmplat.getTmplatIdx(),
newTmplat.getTmplatBody()
);
newTmplat.setTmplatBody(newHtml);
templateService.updateTemplateBodyWithCreate(newTmplat);
}
return newTmplat;
return templateService.createTemplate(
template.getItrntPrjctCd(),
template,
files,
ctx.getUserId()
);
}
@Operation(summary = "바디에 사용하는 이미지 업로드")
@@ -78,22 +94,20 @@ public class TemplateController {
return fileService.storeTempFile(itrntPrjctCd, file);
}
@Operation(summary = "템플릿 수정")
@PatchMapping
@Operation(summary = "첨부파일 변경을 포함한 템플릿 수정")
@PatchMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public TemplateDto updateTemplate(
@Valid @RequestBody TemplateDto template,
@Valid @RequestPart("template") TemplateDto template,
@RequestPart(value = "files", required = false) List<MultipartFile> files,
@RequestParam(value = "deleteFileNames", required = false) List<String> deleteFileNames,
RequestUserContext ctx
) {
if (template.getTmplatTy() == SendType.EMAIL) {
String newHtml = fileService.syncOnSave(
template.getItrntPrjctCd(),
template.getTmplatIdx(),
template.getTmplatBody()
);
template.setTmplatBody(newHtml);
}
return templateService.updateTemplate(template, ctx.getUserId());
return templateService.updateTemplate(
template,
files,
deleteFileNames,
ctx.getUserId()
);
}
@Operation(summary = "템플릿 삭제(소프트 삭제)")

View File

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

View File

@@ -1,5 +1,6 @@
package com.kri.notihub.server.dto.template;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.kri.notihub.server.common.enums.SendType;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.Column;
@@ -52,6 +53,7 @@ public class TemplateBasicDto {
private String nationCd;
@Schema(description = "첨부 파일 (여러 개일 경우, ‘I’문자로 구분)")
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String atchFl;
@Schema(description = "이메일 건당 발송 딜레이(단위 ms, 기본: 500ms)")

View File

@@ -147,7 +147,6 @@ public class TTmplatEntity {
this.senderKey = template.getSenderKey();
this.kkoTmplatCd = template.getKkoTmplatCd();
this.nationCd = template.getNationCd();
this.atchFl = template.getAtchFl();
this.delayTime = template.getDelayTime();
this.sendTel = template.getSendTel();
this.sendEml = template.getSendEml();

View File

@@ -128,6 +128,8 @@ public class EmailBulkSendScheduler {
send.getSendNm(),
send.getMsgTitle(),
send.getMsgBody(),
send.getTmplatIdx(),
send.getAtchFl(),
DestInfoDto.from(send)
);
return sendEmailService.sendPringoEmail(pringoReq);

View File

@@ -50,6 +50,8 @@ public class SendReservationEmailScheduler {
s.getSendNm(),
s.getMsgTitle(),
s.getMsgBody(),
s.getTmplatIdx(),
s.getAtchFl(),
DestInfoDto.from(s)
);

View File

@@ -52,6 +52,8 @@ public abstract class AbstractBizppurioSendService extends AbstractSendService {
Boolean isResve,
String bulkSendKey,
SendType sendType,
Long tmplatIdx,
String atchFl,
String sendTel,
String sendNm,
String msgTitle,

View File

@@ -32,6 +32,7 @@ public abstract class AbstractPringoSendService extends AbstractSendService {
private final PringoApiClient pringoApiClient;
private final EmailResultPoller emailResultPoller;
private final EmailBodyRenderer emailBodyRenderer;
private final EmailAttachmentService emailAttachmentService;
protected AbstractPringoSendService(
SendBulkJdbcWriter sendBulkJdbcWriter,
@@ -41,12 +42,14 @@ public abstract class AbstractPringoSendService extends AbstractSendService {
TemplateService templateService,
PringoApiClient pringoApiClient,
EmailResultPoller emailResultPoller,
EmailBodyRenderer emailBodyRenderer
EmailBodyRenderer emailBodyRenderer,
EmailAttachmentService emailAttachmentService
) {
super(sendBulkJdbcWriter, templateRepository, bulkSendRepository, sendRepository, templateService);
this.pringoApiClient = pringoApiClient;
this.emailResultPoller = emailResultPoller;
this.emailBodyRenderer = emailBodyRenderer;
this.emailAttachmentService = emailAttachmentService;
}
protected abstract ChannelType defaultChannelType();
@@ -66,6 +69,8 @@ public abstract class AbstractPringoSendService extends AbstractSendService {
Boolean isResve,
String bulkSendKey,
SendType sendType, //Sms에서 사용 Email에서는 의미 없음
Long tmplatIdx,
String atchFl,
String sendEml,
String sendNm,
String msgTitle,
@@ -89,6 +94,8 @@ public abstract class AbstractPringoSendService extends AbstractSendService {
sendNm,
msgTitle,
msgBody,
tmplatIdx,
atchFl,
dest
);
return sendPringoEmail(pringoReq);
@@ -141,6 +148,8 @@ public abstract class AbstractPringoSendService extends AbstractSendService {
String sendNm,
String msgTitle,
String msgBody,
Long tmplatIdx,
String atchFl,
DestInfoDto dest
) {
Map<String, Object> vars = new HashMap<>();
@@ -155,6 +164,9 @@ public abstract class AbstractPringoSendService extends AbstractSendService {
.recipientName(Optional.ofNullable(dest.getDestNm()).orElse(dest.getDestEml()))
.subject(Optional.ofNullable(msgTitle).orElse(""))
.body(Optional.ofNullable(msgBody).orElse(""))
.attachments(tmplatIdx == null
? List.of()
: emailAttachmentService.load(tmplatIdx, atchFl))
.vars(vars)
.build();
}

View File

@@ -139,6 +139,8 @@ public abstract class AbstractSendService {
req.getResve(),
null,
tmplat.getTmplatTy(),
tmplat.getTmplatIdx(),
tmplat.getAtchFl(),
sendFrom,
sendNm,
msgTitle,
@@ -243,6 +245,8 @@ public abstract class AbstractSendService {
isResve,
bulkSendKey,
tmplat.getTmplatTy(),
tmplat.getTmplatIdx(),
tmplat.getAtchFl(),
sendFrom,
sendNm,
msgTitle,
@@ -329,6 +333,8 @@ public abstract class AbstractSendService {
Boolean isResve,
String bulkSendKey,
SendType sendType,
Long tmplatIdx,
String atchFl,
String sendFrom,
String sendNm,
String msgTitle,

View File

@@ -0,0 +1,406 @@
package com.kri.notihub.server.service;
import com.kri.common.feature.web.BusinessException;
import com.kri.notihub.server.dto.email.EmailAttachmentDto;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service
public class EmailAttachmentService {
private static final String DELIMITER = "|";
private static final Pattern DELIMITER_PATTERN = Pattern.compile("\\|");
private static final Pattern INVALID_FILE_NAME = Pattern.compile("[<>:\"/\\\\|?*\\p{Cntrl}]");
private static final int ATCH_FL_MAX_LENGTH = 1000;
private final Path uploadBaseDir;
private final int maxFileCount;
private final long maxFileSize;
public EmailAttachmentService(
@Value("${kri.email-attachment.upload-base-dir}") String uploadBaseDir,
@Value("${kri.email-attachment.max-file-count:5}") int maxFileCount,
@Value("${kri.email-attachment.max-file-size:1000000}") long maxFileSize
) {
this.uploadBaseDir = Paths.get(uploadBaseDir).toAbsolutePath().normalize();
this.maxFileCount = maxFileCount;
this.maxFileSize = maxFileSize;
}
public String create(long tmplatIdx, List<MultipartFile> files) {
return patch(tmplatIdx, null, files, null);
}
public String patch(
long tmplatIdx,
String currentAtchFl,
List<MultipartFile> files,
List<String> deleteFileNames
) {
List<String> currentFileNames = parse(currentAtchFl);
List<ValidatedFile> uploadFiles = validateFiles(files);
Set<String> deleteKeys = validateDeleteFileNames(currentFileNames, deleteFileNames);
if (uploadFiles.isEmpty() && deleteKeys.isEmpty()) {
return currentFileNames.isEmpty() ? null : join(currentFileNames);
}
Map<String, String> currentByKey = indexByNormalizedName(currentFileNames);
for (ValidatedFile upload : uploadFiles) {
String key = normalizeKey(upload.fileName());
if (currentByKey.containsKey(key) && !deleteKeys.contains(key)) {
throw BusinessException.badRequest("EMAIL_ATTACHMENT_ALREADY_EXISTS",
"기존 첨부파일과 같은 이름을 추가하려면 삭제 목록에도 포함해야 합니다.")
.with("fileName", upload.fileName());
}
}
List<String> finalFileNames = new ArrayList<>();
for (String currentFileName : currentFileNames) {
if (!deleteKeys.contains(normalizeKey(currentFileName))) {
finalFileNames.add(currentFileName);
}
}
uploadFiles.stream().map(ValidatedFile::fileName).forEach(finalFileNames::add);
validateFinalFileNames(finalFileNames);
applyFileChanges(tmplatIdx, currentFileNames, finalFileNames, uploadFiles);
return finalFileNames.isEmpty() ? null : join(finalFileNames);
}
public List<EmailAttachmentDto> load(long tmplatIdx, String atchFl) {
List<String> fileNames = parse(atchFl);
if (fileNames.isEmpty()) {
return List.of();
}
List<EmailAttachmentDto> attachments = new ArrayList<>(fileNames.size());
for (String fileName : fileNames) {
attachments.add(readAttachment(tmplatIdx, fileName));
}
return attachments;
}
public EmailAttachmentDto download(long tmplatIdx, String atchFl, String requestedFileName) {
String validatedFileName = validateStoredFileName(
requestedFileName == null ? null : requestedFileName.trim()
);
String requestedKey = normalizeKey(validatedFileName);
String storedFileName = parse(atchFl).stream()
.filter(fileName -> normalizeKey(fileName).equals(requestedKey))
.findFirst()
.orElseThrow(() ->
BusinessException.notFound("EMAIL_ATTACHMENT_NOT_FOUND", "첨부파일을 찾을 수 없습니다.")
.with("tmplatIdx", tmplatIdx)
.with("fileName", validatedFileName)
);
return readAttachment(tmplatIdx, storedFileName);
}
public List<String> parse(String atchFl) {
if (atchFl == null || atchFl.isBlank()) {
return List.of();
}
return DELIMITER_PATTERN.splitAsStream(atchFl)
.map(String::trim)
.filter(value -> !value.isEmpty())
.map(this::validateStoredFileName)
.toList();
}
private List<ValidatedFile> validateFiles(List<MultipartFile> files) {
if (files == null || files.isEmpty()) {
return List.of();
}
if (files.size() > maxFileCount) {
throw BusinessException.badRequest("EMAIL_ATTACHMENT_COUNT_EXCEEDED",
"첨부파일은 최대 " + maxFileCount + "개까지 등록할 수 있습니다.")
.with("maxFileCount", maxFileCount);
}
List<ValidatedFile> result = new ArrayList<>(files.size());
Set<String> duplicateCheck = new LinkedHashSet<>();
for (MultipartFile file : files) {
if (file == null || file.isEmpty()) {
throw BusinessException.badRequest("EMPTY_EMAIL_ATTACHMENT", "빈 첨부파일은 등록할 수 없습니다.");
}
String fileName = validateUploadFileName(file.getOriginalFilename());
validateFileSize(fileName, file.getSize());
if (!duplicateCheck.add(normalizeKey(fileName))) {
throw BusinessException.badRequest("DUPLICATE_EMAIL_ATTACHMENT",
"동일한 이름의 첨부파일을 중복 등록할 수 없습니다.")
.with("fileName", fileName);
}
result.add(new ValidatedFile(fileName, file));
}
return result;
}
private Set<String> validateDeleteFileNames(
List<String> currentFileNames,
List<String> deleteFileNames
) {
if (deleteFileNames == null || deleteFileNames.isEmpty()) {
return Set.of();
}
Map<String, String> currentByKey = indexByNormalizedName(currentFileNames);
Set<String> deleteKeys = new LinkedHashSet<>();
for (String value : deleteFileNames) {
String fileName = validateStoredFileName(value == null ? null : value.trim());
String key = normalizeKey(fileName);
if (!deleteKeys.add(key)) {
throw BusinessException.badRequest("DUPLICATE_EMAIL_ATTACHMENT_DELETE",
"동일한 첨부파일을 삭제 목록에 중복 지정할 수 없습니다.")
.with("fileName", fileName);
}
if (!currentByKey.containsKey(key)) {
throw BusinessException.badRequest("EMAIL_ATTACHMENT_NOT_FOUND",
"삭제할 첨부파일이 현재 템플릿에 존재하지 않습니다.")
.with("fileName", fileName);
}
}
return deleteKeys;
}
private void validateFinalFileNames(List<String> fileNames) {
if (fileNames.size() > maxFileCount) {
throw BusinessException.badRequest("EMAIL_ATTACHMENT_COUNT_EXCEEDED",
"첨부파일은 최대 " + maxFileCount + "개까지 등록할 수 있습니다.")
.with("maxFileCount", maxFileCount)
.with("fileCount", fileNames.size());
}
String joined = join(fileNames);
if (joined.length() > ATCH_FL_MAX_LENGTH) {
throw BusinessException.badRequest("EMAIL_ATTACHMENT_NAMES_TOO_LONG",
"첨부파일명 전체 길이는 " + ATCH_FL_MAX_LENGTH + "자를 초과할 수 없습니다.")
.with("maxLength", ATCH_FL_MAX_LENGTH);
}
}
private void applyFileChanges(
long tmplatIdx,
List<String> currentFileNames,
List<String> finalFileNames,
List<ValidatedFile> uploadFiles
) {
Path templateDir = getTemplateDir(tmplatIdx);
Path stagingDir = null;
Path backupDir = null;
boolean installed = false;
try {
Files.createDirectories(uploadBaseDir);
stagingDir = Files.createTempDirectory(uploadBaseDir, "." + tmplatIdx + "-staging-");
Set<String> uploadKeys = uploadFiles.stream()
.map(ValidatedFile::fileName)
.map(this::normalizeKey)
.collect(java.util.stream.Collectors.toSet());
Map<String, String> currentByKey = indexByNormalizedName(currentFileNames);
for (String finalFileName : finalFileNames) {
if (uploadKeys.contains(normalizeKey(finalFileName))) {
continue;
}
String storedName = currentByKey.get(normalizeKey(finalFileName));
Path source = resolveFile(templateDir, storedName);
if (!Files.isRegularFile(source)) {
throw new IllegalStateException("기존 이메일 첨부파일을 찾을 수 없습니다: " + storedName);
}
Files.copy(source, resolveFile(stagingDir, storedName));
}
for (ValidatedFile upload : uploadFiles) {
Path target = resolveFile(stagingDir, upload.fileName());
try (InputStream input = upload.file().getInputStream()) {
Files.copy(input, target, StandardCopyOption.REPLACE_EXISTING);
}
}
if (Files.exists(templateDir)) {
backupDir = Files.createTempDirectory(uploadBaseDir, "." + tmplatIdx + "-backup-");
Files.delete(backupDir);
moveDirectory(templateDir, backupDir);
}
if (finalFileNames.isEmpty()) {
deleteFlatDirectory(stagingDir);
stagingDir = null;
} else {
moveDirectory(stagingDir, templateDir);
stagingDir = null;
installed = true;
}
if (backupDir != null) {
deleteFlatDirectory(backupDir);
backupDir = null;
}
} catch (IOException | RuntimeException e) {
try {
if (installed && Files.exists(templateDir)) {
deleteFlatDirectory(templateDir);
}
if (backupDir != null && Files.exists(backupDir)) {
moveDirectory(backupDir, templateDir);
backupDir = null;
}
if (stagingDir != null && Files.exists(stagingDir)) {
deleteFlatDirectory(stagingDir);
}
} catch (IOException rollbackError) {
e.addSuppressed(rollbackError);
}
throw new IllegalStateException("이메일 첨부파일 변경에 실패했습니다.", e);
}
}
private Map<String, String> indexByNormalizedName(List<String> fileNames) {
Map<String, String> result = new LinkedHashMap<>();
for (String fileName : fileNames) {
String validated = validateStoredFileName(fileName);
String previous = result.put(normalizeKey(validated), validated);
if (previous != null) {
throw new IllegalStateException("중복된 이메일 첨부파일명이 저장되어 있습니다: " + fileName);
}
}
return result;
}
private String validateUploadFileName(String originalFileName) {
if (originalFileName == null || originalFileName.isBlank()) {
throw BusinessException.badRequest("INVALID_EMAIL_ATTACHMENT_NAME", "첨부파일명이 필요합니다.");
}
String normalized = originalFileName.replace('\\', '/');
String fileName = normalized.substring(normalized.lastIndexOf('/') + 1).trim();
return validateStoredFileName(fileName);
}
private String validateStoredFileName(String fileName) {
if (fileName == null || fileName.isBlank()
|| ".".equals(fileName) || "..".equals(fileName)
|| fileName.endsWith(".") || fileName.endsWith(" ")
|| INVALID_FILE_NAME.matcher(fileName).find()) {
throw BusinessException.badRequest("INVALID_EMAIL_ATTACHMENT_NAME", "유효하지 않은 첨부파일명입니다.")
.with("fileName", fileName);
}
return fileName;
}
private void validateFileSize(String fileName, long fileSize) {
if (fileSize <= 0) {
throw BusinessException.badRequest("EMPTY_EMAIL_ATTACHMENT", "빈 첨부파일은 등록할 수 없습니다.")
.with("fileName", fileName);
}
if (fileSize >= maxFileSize) {
throw BusinessException.badRequest("EMAIL_ATTACHMENT_SIZE_EXCEEDED",
"첨부파일 크기는 " + maxFileSize + "바이트 미만이어야 합니다.")
.with("fileName", fileName)
.with("fileSize", fileSize)
.with("maxFileSize", maxFileSize);
}
}
private EmailAttachmentDto readAttachment(long tmplatIdx, String fileName) {
Path path = resolveFile(getTemplateDir(tmplatIdx), validateStoredFileName(fileName));
try {
if (!Files.isRegularFile(path)) {
throw new IllegalStateException("이메일 첨부파일을 찾을 수 없습니다: " + fileName);
}
long fileSize = Files.size(path);
validateFileSize(fileName, fileSize);
String contentType = MediaTypeFactory.getMediaType(fileName)
.map(MediaType::toString)
.orElse(MediaType.APPLICATION_OCTET_STREAM_VALUE);
return new EmailAttachmentDto(fileName, contentType, Files.readAllBytes(path));
} catch (IOException e) {
throw new IllegalStateException("이메일 첨부파일을 읽는 데 실패했습니다: " + fileName, e);
}
}
private Path getTemplateDir(long tmplatIdx) {
if (tmplatIdx <= 0) {
throw new IllegalArgumentException("tmplatIdx must be positive.");
}
Path templateDir = uploadBaseDir.resolve(Long.toString(tmplatIdx)).normalize();
if (!templateDir.startsWith(uploadBaseDir)) {
throw new IllegalArgumentException("Invalid template attachment directory.");
}
return templateDir;
}
private Path resolveFile(Path directory, String fileName) {
Path path = directory.resolve(fileName).normalize();
if (!path.startsWith(directory)) {
throw new IllegalArgumentException("Invalid email attachment path.");
}
return path;
}
private void moveDirectory(Path source, Path target) throws IOException {
try {
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException e) {
Files.move(source, target);
}
}
private void deleteFlatDirectory(Path directory) throws IOException {
if (!Files.exists(directory)) {
return;
}
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
for (Path path : stream) {
if (!Files.isRegularFile(path)) {
throw new IOException("Unexpected directory entry: " + path);
}
Files.deleteIfExists(path);
}
}
Files.deleteIfExists(directory);
}
private String normalizeKey(String fileName) {
return fileName.toLowerCase(Locale.ROOT);
}
private String join(List<String> fileNames) {
return String.join(DELIMITER, fileNames);
}
private record ValidatedFile(String fileName, MultipartFile file) {
}
}

View File

@@ -21,10 +21,11 @@ public class SendEmailService extends AbstractPringoSendService {
TemplateService templateService,
PringoApiClient pringoApiClient,
EmailResultPoller emailResultPoller,
EmailBodyRenderer emailBodyRenderer
EmailBodyRenderer emailBodyRenderer,
EmailAttachmentService emailAttachmentService
) {
super(sendBulkJdbcWriter, templateRepository, bulkSendRepository, sendRepository, templateService,
pringoApiClient, emailResultPoller, emailBodyRenderer);
pringoApiClient, emailResultPoller, emailBodyRenderer, emailAttachmentService);
}
@Override

View File

@@ -8,6 +8,7 @@ import com.kri.notihub.server.common.enums.ChannelType;
import com.kri.notihub.server.common.enums.SendType;
import com.kri.notihub.server.common.enums.TemplateEventType;
import com.kri.notihub.server.common.util.TemplateContentSanitizer;
import com.kri.notihub.server.dto.email.EmailAttachmentDto;
import com.kri.notihub.server.dto.template.TemplateBasicDto;
import com.kri.notihub.server.dto.template.TemplateDto;
import com.kri.notihub.server.dto.template.TemplateSummaryDto;
@@ -22,6 +23,7 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
@Log4j2
@Service
@@ -30,27 +32,44 @@ public class TemplateService {
private final TemplateRepository templateRepository;
private final TemplateEventLogRepository templateEventLogRepository;
private final FileService fileService;
private final EmailAttachmentService emailAttachmentService;
@Transactional
public TemplateDto createTemplate(
String itrntPrjctCd,
TemplateBasicDto template,
List<MultipartFile> files,
String regUser
) {
if (hasAttachments(files) && template.getTmplatTy() != SendType.EMAIL) {
throw BusinessException.badRequest("EMAIL_ATTACHMENT_ONLY",
"첨부파일은 이메일 템플릿에만 등록할 수 있습니다.");
}
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
validateBySendType(template);
//제목, 본문 정규화
TemplateContentSanitizer.sanitizeAndNormalizeInPlace(template);
// 엔티티 생성은 엔티티 팩토리(내부 builder)로 위임
TTmplatEntity entity = TTmplatEntity.create(itrntPrjctCd, template, regUser, now);
TTmplatEntity saved = templateRepository.save(entity);
entity.setAtchFl(null);
templateRepository.save(entity);
saveLog(saved.getTmplatIdx(), TemplateEventType.CREATE_TEMPLATE, null, template, regUser, now);
if (template.getTmplatTy() == SendType.EMAIL) {
entity.setTmplatBody(fileService.syncOnSave(
entity.getItrntPrjctCd(),
entity.getTmplatIdx(),
entity.getTmplatBody()
));
}
if (hasAttachments(files)) {
entity.setAtchFl(emailAttachmentService.create(entity.getTmplatIdx(), files));
}
templateRepository.save(entity);
return TemplateDto.from(saved);
TemplateDto created = TemplateDto.from(entity);
saveLog(entity.getTmplatIdx(), TemplateEventType.CREATE_TEMPLATE, null, created, regUser, now);
return created;
}
public List<TemplateSummaryDto> getTemplateList(ChannelType chnnlTy, String itrntPrjctCd) {
@@ -74,20 +93,29 @@ public class TemplateService {
);
}
@Transactional
public void updateTemplateBodyWithCreate(TemplateDto template) {
TTmplatEntity entity = templateRepository.findByTmplatIdxAndDelFalse(template.getTmplatIdx())
@Transactional(readOnly = true)
public EmailAttachmentDto downloadAttachment(long tmplatIdx, String fileName) {
TTmplatEntity entity = templateRepository.findByTmplatIdxAndDelFalse(tmplatIdx)
.orElseThrow(() ->
BusinessException.notFound("TEMPLATE_NOT_FOUND", "템플릿을 찾을 수 없습니다.")
.with("tmplatIdx", template.getTmplatIdx())
.with("tmplatIdx", tmplatIdx)
);
entity.setTmplatBody(template.getTmplatBody());
templateRepository.save(entity);
if (!Objects.equals(entity.getTmplatTy(), SendType.EMAIL.getCode())) {
throw BusinessException.badRequest("EMAIL_ATTACHMENT_ONLY",
"이메일 템플릿의 첨부파일만 다운로드할 수 있습니다.");
}
return emailAttachmentService.download(tmplatIdx, entity.getAtchFl(), fileName);
}
@Transactional
public TemplateDto updateTemplate(TemplateDto template, String modUser) {
public TemplateDto updateTemplate(
TemplateDto template,
List<MultipartFile> files,
List<String> deleteFileNames,
String modUser
) {
long tmplatIdx = template.getTmplatIdx();
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
@@ -99,18 +127,41 @@ public class TemplateService {
validateBySendType(template);
boolean attachmentChanged = hasAttachments(files) || hasDeleteFileNames(deleteFileNames);
if (attachmentChanged && template.getTmplatTy() != SendType.EMAIL) {
throw BusinessException.badRequest("EMAIL_ATTACHMENT_ONLY",
"첨부파일은 이메일 템플릿에만 등록할 수 있습니다.");
}
if (template.getTmplatTy() == SendType.EMAIL) {
template.setTmplatBody(fileService.syncOnSave(
template.getItrntPrjctCd(),
template.getTmplatIdx(),
template.getTmplatBody()
));
}
//제목, 본문 정규화
TemplateContentSanitizer.sanitizeAndNormalizeInPlace(template);
TemplateBasicDto before = TemplateDto.from(entity);
entity.updateFrom(template, modUser, now);
if (attachmentChanged) {
entity.setAtchFl(emailAttachmentService.patch(
tmplatIdx,
entity.getAtchFl(),
files,
deleteFileNames
));
}
templateRepository.save(entity);
saveLog(tmplatIdx, TemplateEventType.UPDATE_TEMPLATE, before, template, modUser, now);
TemplateDto after = TemplateDto.from(entity);
saveLog(tmplatIdx, TemplateEventType.UPDATE_TEMPLATE, before, after, modUser, now);
return template;
return after;
}
@Transactional
@@ -150,6 +201,14 @@ public class TemplateService {
};
}
private boolean hasAttachments(List<MultipartFile> files) {
return files != null && !files.isEmpty();
}
private boolean hasDeleteFileNames(List<String> deleteFileNames) {
return deleteFileNames != null && !deleteFileNames.isEmpty();
}
private void validateBySendType(TemplateBasicDto template) {
//공통 검증
if (template.getTmplatTy() == null) {