260825_02_ENH: 파일 업로드 시 유일성 정보를 waveCd, fileName에서 waveCd, fileOrder로 변경
This commit is contained in:
@@ -20,7 +20,7 @@
|
||||
- Excel endpoints are `POST /api/v1/excel/import`, `GET /api/v1/excel/template`, `GET /api/v1/excel/waves/{waveCd}/export`, and `DELETE /api/v1/excel/waves/{waveCd}`. Downloads use the same eleven sheets, order, and headers; a missing Wave exports an empty workbook.
|
||||
- Imports atomically replace every included Wave: validate first, delete all eleven managed tables, then insert. Failures restore prior data. Standalone reset uses the same child-to-root deletion and retains `t_file` metadata and physical files, allowing temporary orphans until that `wave_cd` is reimported.
|
||||
- A reference-file upload writes both the physical file and its `t_file` metadata. Accept `fileTitle` and `fileOrder` as multipart request fields, derive `file_type` from the lowercase filename extension, and keep the original filename as `file_name`.
|
||||
- For reference-file uploads, accept `waveCd` as a path variable and store the file under `{kri.file.base-dir}/References/{waveCd}` using the original filename. Treat `(wave_cd, file_name)` as the upload logical key: uploading the same filename again preserves `file_idx`, replaces the physical file, and updates `file_title`, `file_order`, and `file_type`.
|
||||
- For reference-file uploads, accept `waveCd` as a path variable and store files under `{kri.file.base-dir}/References/{waveCd}` using their original names. Treat `(wave_cd, file_order)` as the upload logical key: repeat uploads preserve `file_idx`, replace metadata and the physical file, and remove the prior filename after commit. Reject a filename already used by another order in the same Wave.
|
||||
- Reject a reference-file upload when its `waveCd` does not exist. Coordinate the database transaction and filesystem replacement so a database rollback restores the previous file or removes a newly created file.
|
||||
|
||||
## Dashboard Data Model Contract
|
||||
|
||||
@@ -282,7 +282,7 @@ When implementation is complete, report in Korean:
|
||||
- Excel endpoints are `POST /api/v1/excel/import`, `GET /api/v1/excel/template`, `GET /api/v1/excel/waves/{waveCd}/export`, and `DELETE /api/v1/excel/waves/{waveCd}`. Downloads use the same eleven sheets, order, and headers; a missing Wave exports an empty workbook.
|
||||
- Imports atomically replace every included Wave: validate first, delete all eleven managed tables, then insert. Failures restore prior data. Standalone reset uses the same child-to-root deletion and retains `t_file` metadata and physical files, allowing temporary orphans until that `wave_cd` is reimported.
|
||||
- A reference-file upload writes both the physical file and its `t_file` metadata. Accept `fileTitle` and `fileOrder` as multipart request fields, derive `file_type` from the lowercase filename extension, and keep the original filename as `file_name`.
|
||||
- For reference-file uploads, accept `waveCd` as a path variable and store the file under `{kri.file.base-dir}/References/{waveCd}` using the original filename. Treat `(wave_cd, file_name)` as the upload logical key: uploading the same filename again preserves `file_idx`, replaces the physical file, and updates `file_title`, `file_order`, and `file_type`.
|
||||
- For reference-file uploads, accept `waveCd` as a path variable and store files under `{kri.file.base-dir}/References/{waveCd}` using their original names. Treat `(wave_cd, file_order)` as the upload logical key: repeat uploads preserve `file_idx`, replace metadata and the physical file, and remove the prior filename after commit. Reject a filename already used by another order in the same Wave.
|
||||
- Reject a reference-file upload when its `waveCd` does not exist. Coordinate the database transaction and filesystem replacement so a database rollback restores the previous file or removes a newly created file.
|
||||
|
||||
## Dashboard Data Model Contract
|
||||
|
||||
@@ -9,5 +9,7 @@ public interface FileRepository extends JpaRepository<TFileEntity, Integer> {
|
||||
|
||||
List<TFileEntity> findByWaveCdOrderByFileOrderAsc(Short waveCd);
|
||||
|
||||
Optional<TFileEntity> findFirstByWaveCdAndFileOrder(Short waveCd, Short fileOrder);
|
||||
|
||||
Optional<TFileEntity> findFirstByWaveCdAndFileName(Short waveCd, String fileName);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package com.kri.epolicy.dash.back.persistence.repository;
|
||||
|
||||
import com.kri.epolicy.dash.back.persistence.entity.TWaveEntity;
|
||||
import jakarta.persistence.LockModeType;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.Lock;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
@@ -11,6 +14,10 @@ public interface WaveRepository extends JpaRepository<TWaveEntity, Short> {
|
||||
|
||||
List<TWaveEntity> findAllByOrderByYearDescWaveDesc();
|
||||
|
||||
@Lock(LockModeType.PESSIMISTIC_WRITE)
|
||||
@Query("select e from TWaveEntity e where e.id = :waveCd")
|
||||
Optional<TWaveEntity> findForUpdateById(@Param("waveCd") Short waveCd);
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query("delete from TWaveEntity e where e.id = :waveCd")
|
||||
int deleteForResetByWaveCd(@Param("waveCd") Short waveCd);
|
||||
|
||||
@@ -43,7 +43,7 @@ public class ReferenceFileStorageService {
|
||||
MultipartFile file
|
||||
) {
|
||||
validateRequest(waveCd, fileTitle, fileOrder, file);
|
||||
if (!waveRepository.existsById(waveCd)) {
|
||||
if (waveRepository.findForUpdateById(waveCd).isEmpty()) {
|
||||
throw BusinessException.validationError(
|
||||
"WAVE_NOT_FOUND", "존재하지 않는 waveCd입니다.").with("waveCd", waveCd);
|
||||
}
|
||||
@@ -61,10 +61,15 @@ public class ReferenceFileStorageService {
|
||||
throw invalidFilename("허용되지 않는 파일 경로입니다.");
|
||||
}
|
||||
|
||||
TFileEntity entity = fileRepository.findFirstByWaveCdAndFileOrder(waveCd, fileOrder)
|
||||
.orElseGet(TFileEntity::new);
|
||||
validateFilenameConflict(waveCd, originalFilename, entity.getId());
|
||||
String previousFilename = entity.getFileName();
|
||||
Path previousTarget = previousFilename == null
|
||||
? null : resolveStoredTarget(targetDirectory, previousFilename);
|
||||
|
||||
Path stagedFile = stageFile(targetDirectory, file);
|
||||
try {
|
||||
TFileEntity entity = fileRepository.findFirstByWaveCdAndFileName(waveCd, originalFilename)
|
||||
.orElseGet(TFileEntity::new);
|
||||
entity.setWaveCd(waveCd);
|
||||
entity.setFileOrder(fileOrder);
|
||||
entity.setFileTitle(normalizedTitle);
|
||||
@@ -74,6 +79,9 @@ public class ReferenceFileStorageService {
|
||||
|
||||
replaceFileWithRollbackProtection(stagedFile, target);
|
||||
stagedFile = null;
|
||||
if (previousTarget != null && !previousTarget.equals(target)) {
|
||||
removeFileWithRollbackProtection(previousTarget);
|
||||
}
|
||||
|
||||
String relativePath = REFERENCES_DIRECTORY + "/" + waveCd + "/" + originalFilename;
|
||||
return new ReferenceFileUploadResponse(
|
||||
@@ -154,6 +162,30 @@ public class ReferenceFileStorageService {
|
||||
return fileType;
|
||||
}
|
||||
|
||||
private void validateFilenameConflict(
|
||||
Short waveCd,
|
||||
String originalFilename,
|
||||
Integer currentFileId
|
||||
) {
|
||||
fileRepository.findFirstByWaveCdAndFileName(waveCd, originalFilename)
|
||||
.filter(existing -> !existing.getId().equals(currentFileId))
|
||||
.ifPresent(existing -> {
|
||||
throw BusinessException.validationError(
|
||||
"REFERENCE_FILENAME_CONFLICT",
|
||||
"같은 Wave의 다른 파일 순서에서 이미 사용 중인 파일명입니다.")
|
||||
.with("waveCd", waveCd)
|
||||
.with("fileOrder", existing.getFileOrder());
|
||||
});
|
||||
}
|
||||
|
||||
private Path resolveStoredTarget(Path targetDirectory, String filename) {
|
||||
Path storedTarget = targetDirectory.resolve(filename).normalize();
|
||||
if (!storedTarget.startsWith(targetDirectory)) {
|
||||
throw storageError();
|
||||
}
|
||||
return storedTarget;
|
||||
}
|
||||
|
||||
private Path stageFile(Path targetDirectory, MultipartFile file) {
|
||||
Path stagedFile = null;
|
||||
try {
|
||||
@@ -215,6 +247,58 @@ public class ReferenceFileStorageService {
|
||||
});
|
||||
}
|
||||
|
||||
private void removeFileWithRollbackProtection(Path target) {
|
||||
if (!Files.exists(target)) {
|
||||
return;
|
||||
}
|
||||
Path backupFile = null;
|
||||
boolean targetMoved = false;
|
||||
try {
|
||||
backupFile = Files.createTempFile(target.getParent(), ".backup-", ".tmp");
|
||||
moveReplacing(target, backupFile);
|
||||
targetMoved = true;
|
||||
registerRemovedFileSynchronization(target, backupFile);
|
||||
} catch (IOException | RuntimeException exception) {
|
||||
if (targetMoved) {
|
||||
restoreRemovedFile(target, backupFile);
|
||||
} else {
|
||||
deleteQuietly(backupFile, "완성되지 않은 이전 파일 백업을 삭제하지 못했습니다.");
|
||||
}
|
||||
throw storageError();
|
||||
}
|
||||
}
|
||||
|
||||
private void registerRemovedFileSynchronization(Path target, Path backupFile) {
|
||||
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||
restoreRemovedFile(target, backupFile);
|
||||
throw BusinessException.internalError(
|
||||
"REFERENCE_FILE_TRANSACTION_REQUIRED", "파일 저장 트랜잭션을 시작할 수 없습니다.");
|
||||
}
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||||
@Override
|
||||
public void afterCompletion(int status) {
|
||||
if (status == STATUS_COMMITTED) {
|
||||
deleteQuietly(backupFile, "교체된 이전 파일의 백업을 삭제하지 못했습니다.");
|
||||
return;
|
||||
}
|
||||
restoreRemovedFile(target, backupFile);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void restoreRemovedFile(Path target, Path backupFile) {
|
||||
if (backupFile == null || !Files.exists(backupFile)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
moveReplacing(backupFile, target);
|
||||
} catch (IOException exception) {
|
||||
log.error("트랜잭션 롤백 중 교체 전 파일을 복구하지 못했습니다: {}", target, exception);
|
||||
} finally {
|
||||
deleteQuietly(backupFile, "교체 전 파일의 백업을 삭제하지 못했습니다.");
|
||||
}
|
||||
}
|
||||
|
||||
private void restoreFile(Path target, Path backupFile, boolean targetExisted) {
|
||||
try {
|
||||
if (targetExisted && backupFile != null && Files.exists(backupFile)) {
|
||||
|
||||
Reference in New Issue
Block a user