From e6d412c5eb74e2d4f64e34a0b12d0552197ce7ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A3=BC=EC=88=98=ED=98=84?= Date: Tue, 29 Jul 2025 12:20:41 +0900 Subject: [PATCH] =?UTF-8?q?=ED=8C=8C=EC=9D=BC=20=EC=82=AD=EC=A0=9C=20?= =?UTF-8?q?=EB=B0=8F=20=ED=8D=BC=EB=B8=94=20=EB=B0=98=EC=98=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../application/enums/FileStorageType.java | 3 +- .../application/enums/FileUploadType.java | 7 +- .../application/util/SftpFileDeleteUtil.java | 130 ----- .../application/util/SftpFileDownloader.java | 102 ---- .../adapters/DownloadFileController.java | 60 --- .../application/strategy/SftpConnector.java | 71 --- .../SftpStorageFileUploadStrategy.java | 129 ----- .../adapters/persistence/UpdateFileDao.java | 14 - .../url/strategy/SftpFileUrlStrategy.java | 24 - .../adapters/web/GetAttachmentController.java | 21 - .../resources/templates/record/calendar.html | 496 +++++++++++------- 11 files changed, 309 insertions(+), 748 deletions(-) delete mode 100644 core/src/main/java/app/module/core/config/application/util/SftpFileDeleteUtil.java delete mode 100644 core/src/main/java/app/module/core/config/application/util/SftpFileDownloader.java delete mode 100644 core/src/main/java/app/module/core/usecase/file/downloadFile/adapters/DownloadFileController.java delete mode 100644 core/src/main/java/app/module/core/usecase/file/saveToStorage/ports/application/strategy/SftpConnector.java delete mode 100644 core/src/main/java/app/module/core/usecase/file/saveToStorage/ports/application/strategy/SftpStorageFileUploadStrategy.java delete mode 100644 core/src/main/java/app/module/core/usecase/file/url/strategy/SftpFileUrlStrategy.java diff --git a/core/src/main/java/app/module/core/config/application/enums/FileStorageType.java b/core/src/main/java/app/module/core/config/application/enums/FileStorageType.java index 0a4cee07..2c5e5479 100644 --- a/core/src/main/java/app/module/core/config/application/enums/FileStorageType.java +++ b/core/src/main/java/app/module/core/config/application/enums/FileStorageType.java @@ -7,8 +7,7 @@ import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public enum FileStorageType { LOCAL("로컬 스토리지"), - S3("AWS S3 스토리지"), - SFTP("SFTP"); + S3("AWS S3 스토리지"); private final String desc; private String name; diff --git a/core/src/main/java/app/module/core/config/application/enums/FileUploadType.java b/core/src/main/java/app/module/core/config/application/enums/FileUploadType.java index 78d06094..0916389c 100644 --- a/core/src/main/java/app/module/core/config/application/enums/FileUploadType.java +++ b/core/src/main/java/app/module/core/config/application/enums/FileUploadType.java @@ -13,7 +13,7 @@ public enum FileUploadType { // URI og:image 용 이미지 파일 OG_IMAGE(Set.of(FileStorageType.LOCAL), "/ogImage", Set.of(AcceptableFileType.IMAGE)), // WEB Editor 이미지 파일 - EDITOR_IMAGE(Set.of(FileStorageType.SFTP,FileStorageType.LOCAL), "/editorImage", Set.of(AcceptableFileType.IMAGE)), + EDITOR_IMAGE(Set.of(FileStorageType.LOCAL), "/editorImage", Set.of(AcceptableFileType.IMAGE)), PUBLIC( Set.of(FileStorageType.LOCAL), @@ -43,7 +43,6 @@ public enum FileUploadType { AcceptableFileType.ZIP)), NOTICE( Set.of( - FileStorageType.SFTP, FileStorageType.LOCAL ), "/notice", @@ -58,14 +57,14 @@ public enum FileUploadType { AcceptableFileType.PDF, AcceptableFileType.ZIP)), INCOME( - Set.of(FileStorageType.SFTP,FileStorageType.LOCAL), + Set.of(FileStorageType.LOCAL), "/income", Set.of( AcceptableFileType.IMAGE ) ), EXPENSE( - Set.of(FileStorageType.SFTP,FileStorageType.LOCAL), + Set.of(FileStorageType.LOCAL), "/expense", Set.of( AcceptableFileType.IMAGE diff --git a/core/src/main/java/app/module/core/config/application/util/SftpFileDeleteUtil.java b/core/src/main/java/app/module/core/config/application/util/SftpFileDeleteUtil.java deleted file mode 100644 index 4fff9402..00000000 --- a/core/src/main/java/app/module/core/config/application/util/SftpFileDeleteUtil.java +++ /dev/null @@ -1,130 +0,0 @@ -package app.module.core.config.application.util; - -import app.module.core.usecase.file.getFile.adapters.persistence.GetFileMapper; -import app.module.core.usecase.file.getFile.ports.application.domain.GetFile; -import app.module.core.usecase.file.saveToStorage.ports.application.strategy.SftpConnector; -import app.module.core.usecase.file.updateFile.adapters.persistence.UpdateFileMapper; -import app.module.core.usecase.file.updateFile.ports.application.domain.UploadFileDto; -import com.jcraft.jsch.ChannelSftp; -import com.jcraft.jsch.JSchException; -import com.jcraft.jsch.SftpException; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import java.nio.file.Paths; - -@Slf4j -@Component -@RequiredArgsConstructor -public class SftpFileDeleteUtil { - - private final SftpConnector sftpConnector; - private final GetFileMapper getFileMapper; - private final UpdateFileMapper updateFileMapper; - - @Value("${path.upload.sftp.public}") - private String publicPath; - - /** - * SFTP 서버에서 파일을 삭제하는 공통 메서드 - * @param deleteFile 삭제할 파일 정보 - * @throws JSchException SFTP 연결 오류 - * @throws SftpException SFTP 작업 오류 - */ - public void deleteRealFile(UploadFileDto deleteFile) throws JSchException, SftpException { - if (deleteFile == null || deleteFile.getPath() == null || deleteFile.getName() == null) { - log.error("Invalid file information: {}", deleteFile); - throw new IllegalArgumentException("Invalid file information"); - } - - // 경로 검증 및 생성 - String filePath = constructSafeFilePath(deleteFile.getPath(), deleteFile.getName()); - log.info("Attempting to delete file from SFTP: {}", filePath); - - // SFTP 연결 확인 및 재연결 - if (!sftpConnector.isConnected()) { - log.warn("SFTP connection lost, attempting to reconnect"); - sftpConnector.connect(); - } - ChannelSftp channelSftp = sftpConnector.getChannelSftp(); - if (channelSftp == null) { - log.error("SFTP channel is not initialized"); - throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP channel is not initialized"); - } - - // 파일 삭제 - try { - channelSftp.stat(filePath); // 파일 존재 여부 확인 - channelSftp.rm(filePath); - log.info("File deleted successfully from SFTP: {}", filePath); - } catch (SftpException e) { - if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) { - log.warn("File does not exist on SFTP: {}", filePath); - } else { - log.error("Failed to delete file from SFTP: {}, error: {}", filePath, e.getMessage(), e); - throw e; - } - } - } - - public void deleteRealFile(Long deleteFileId) throws JSchException, SftpException { - GetFile deleteFile = getFileMapper.findById(deleteFileId).orElseThrow(); - updateFileMapper.deleteReceiptFile(deleteFileId,CommonUtil.getLoginUsername()); - - if (deleteFile == null || deleteFile.getPath() == null || deleteFile.getName() == null) { - log.error("Invalid file information: {}", deleteFile); - throw new IllegalArgumentException("Invalid file information"); - } - - // 경로 검증 및 생성 - String filePath = constructSafeFilePath(deleteFile.getPath(), deleteFile.getName()); - log.info("Attempting to delete file from SFTP: {}", filePath); - - // SFTP 연결 확인 및 재연결 - if (!sftpConnector.isConnected()) { - log.warn("SFTP connection lost, attempting to reconnect"); - sftpConnector.connect(); - } - ChannelSftp channelSftp = sftpConnector.getChannelSftp(); - if (channelSftp == null) { - log.error("SFTP channel is not initialized"); - throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP channel is not initialized"); - } - - // 파일 삭제 - try { - channelSftp.stat(filePath); // 파일 존재 여부 확인 - channelSftp.rm(filePath); - log.info("File deleted successfully from SFTP: {}", filePath); - } catch (SftpException e) { - if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) { - log.warn("File does not exist on SFTP: {}", filePath); - } else { - log.error("Failed to delete file from SFTP: {}, error: {}", filePath, e.getMessage(), e); - throw e; - } - } - } - - - - /** - * 경로 조작 방지를 위해 안전한 파일 경로 생성 - */ - private String constructSafeFilePath(String subPath, String fileName) { - // 경로 및 파일 이름 정규화 - String normalizedSubPath = Paths.get(subPath).normalize().toString().replace("\\", "/"); - String normalizedFileName = Paths.get(fileName).getFileName().toString(); - String safePath = CommonUtil.removeLastChar(publicPath, "/") + "/" + normalizedSubPath + "/" + normalizedFileName; - - // 경로가 publicPath로 시작하는지 검증 - if (!safePath.startsWith(publicPath)) { - log.error("Invalid file path detected: {}", safePath); - throw new IllegalArgumentException("Invalid file path: " + safePath); - } - - return safePath; - } -} \ No newline at end of file diff --git a/core/src/main/java/app/module/core/config/application/util/SftpFileDownloader.java b/core/src/main/java/app/module/core/config/application/util/SftpFileDownloader.java deleted file mode 100644 index df993fb8..00000000 --- a/core/src/main/java/app/module/core/config/application/util/SftpFileDownloader.java +++ /dev/null @@ -1,102 +0,0 @@ -package app.module.core.config.application.util; - -import app.module.core.usecase.file.getFile.ports.application.domain.GetFile; -import app.module.core.usecase.file.saveToStorage.ports.application.strategy.SftpConnector; -import com.jcraft.jsch.ChannelSftp; -import com.jcraft.jsch.JSchException; -import com.jcraft.jsch.SftpException; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; - -@Slf4j -@Component -@RequiredArgsConstructor -public class SftpFileDownloader { - private final SftpConnector sftpConnector; - private final AESEncryptUtil encryptUtil; - - @Value("${path.upload.sftp.public}") - private String publicPath; - - @Value("${file.download.base-path:/tmp/downloads}") - private String defaultDownloadBasePath; - - public void downloadFile(GetFile file) throws JSchException, SftpException, IOException { - // SFTP 연결 확인 및 재연결 - if (!sftpConnector.isConnected()) { - log.info("SFTP connection lost, attempting to reconnect"); - sftpConnector.connect(); - } - ChannelSftp channelSftp = sftpConnector.getChannelSftp(); - if (channelSftp == null) { - throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP channel is not initialized"); - } - - try { - // 원격 파일 경로 (암호화된 파일명 사용) - String remoteFilePath = CommonUtil.removeLastChar(publicPath, "/") + file.getPath() + "/" +"encrypted_"+ file.getName(); - log.info("Remote file path: {}", remoteFilePath); - - // 다운로드 경로 정규화 - String basePath = CommonUtil.normalizePath(defaultDownloadBasePath); - log.info("Base path: {}", basePath); - String localEncryptedFilePath = basePath + File.separator + "encrypted_" + file.getOriginName(); - String localDecryptedFilePath = basePath + File.separator + file.getOriginName(); - log.info("Local encrypted file path: {}", localEncryptedFilePath); - log.info("Local decrypted file path: {}", localDecryptedFilePath); - - // 로컬 디렉토리 생성 - File localDir = new File(localEncryptedFilePath).getParentFile(); - CommonUtil.createDirectories(localDir); - - // 원격 파일 존재 여부 확인 (디버깅 용) - try { - channelSftp.lstat(remoteFilePath); - log.info("Remote file exists: {}", remoteFilePath); - } catch (SftpException e) { - log.error("Remote file does not exist: {}", remoteFilePath, e); - throw new SftpException(ChannelSftp.SSH_FX_NO_SUCH_FILE, "Remote file does not exist: " + remoteFilePath); - } - - // 암호화된 파일 다운로드 - try (FileOutputStream fos = new FileOutputStream(localEncryptedFilePath)) { - channelSftp.get(remoteFilePath, fos); - log.info("File downloaded to: {}", localEncryptedFilePath); - } - - // 파일 복호화 - try { - byte[] encryptedContent = Files.readAllBytes(Paths.get(localEncryptedFilePath)); - byte[] decryptedContent = encryptUtil.decryptAesCbc(encryptedContent); - Files.write(Paths.get(localDecryptedFilePath), decryptedContent); - log.info("File decrypted and saved to: {}", localDecryptedFilePath); - file.setLocalPath(localDecryptedFilePath); - } catch (Exception e) { - log.error("Failed to decrypt file: {}", file.getOriginName(), e); - throw new IOException("Failed to decrypt file", e); - } finally { - // 암호화된 임시 파일 삭제 - Files.deleteIfExists(Paths.get(localEncryptedFilePath)); - log.info("Temporary encrypted file deleted: {}", localEncryptedFilePath); - } - - } catch (SftpException e) { - log.error("Failed to download file: {} (Error: {})", file.getOriginName(), e.getMessage()); - throw e; - } catch (IOException e) { - log.error("IO error during file download or decryption: {}", file.getOriginName(), e); - throw e; - } catch (Exception e) { - log.error("Unexpected error during file download: {}", file.getOriginName(), e); - throw new RuntimeException("Unexpected error during file download", e); - } - } -} \ No newline at end of file diff --git a/core/src/main/java/app/module/core/usecase/file/downloadFile/adapters/DownloadFileController.java b/core/src/main/java/app/module/core/usecase/file/downloadFile/adapters/DownloadFileController.java deleted file mode 100644 index d9a8f718..00000000 --- a/core/src/main/java/app/module/core/usecase/file/downloadFile/adapters/DownloadFileController.java +++ /dev/null @@ -1,60 +0,0 @@ -package app.module.core.usecase.file.downloadFile.adapters; - -import app.module.core.config.application.util.SftpFileDownloader; -import app.module.core.usecase.file.getFile.ports.GetFilePortIn; -import app.module.core.usecase.file.getFile.ports.application.domain.GetFile; -import app.module.core.usecase.file.getFile.ports.application.domain.GetFileCmd; -import com.jcraft.jsch.JSchException; -import com.jcraft.jsch.SftpException; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.core.io.FileSystemResource; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RestController; - -import java.io.File; -import java.io.IOException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; - -@Slf4j -@RestController -@RequiredArgsConstructor -class DownloadFileController { - private final GetFilePortIn getFilePortIn; - private final SftpFileDownloader sftpFileDownloader; - - @GetMapping(path = "/api/file/download/{fileId}") - ResponseEntity downloadFile(@PathVariable Long fileId) throws JSchException, SftpException, IOException { - GetFile file = getFilePortIn.operate(new GetFileCmd(fileId)).orElseThrow(() -> new IllegalArgumentException("File not found: " + fileId)); - - // SFTP에서 파일 다운로드 - sftpFileDownloader.downloadFile(file); - - // 로컬 파일 경로 - File downloadedFile = new File(file.getLocalPath()); - if (!downloadedFile.exists()) { - throw new IllegalStateException("파일 다운로드에 실패하였습니다."); - } - - - String encodedFileName = URLEncoder.encode(file.getOriginName(), StandardCharsets.UTF_8) - .replace("+", "%20"); - // HTTP 헤더 설정 - HttpHeaders headers = new HttpHeaders(); - headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName); - headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); - headers.add(HttpHeaders.PRAGMA, "no-cache"); - headers.add(HttpHeaders.EXPIRES, "0"); - - return ResponseEntity.ok() - .headers(headers) - .contentLength(downloadedFile.length()) - .contentType(MediaType.APPLICATION_OCTET_STREAM) - .body(new FileSystemResource(downloadedFile)); - } -} diff --git a/core/src/main/java/app/module/core/usecase/file/saveToStorage/ports/application/strategy/SftpConnector.java b/core/src/main/java/app/module/core/usecase/file/saveToStorage/ports/application/strategy/SftpConnector.java deleted file mode 100644 index df3a3e46..00000000 --- a/core/src/main/java/app/module/core/usecase/file/saveToStorage/ports/application/strategy/SftpConnector.java +++ /dev/null @@ -1,71 +0,0 @@ -package app.module.core.usecase.file.saveToStorage.ports.application.strategy; - -import com.jcraft.jsch.ChannelSftp; -import com.jcraft.jsch.JSch; -import com.jcraft.jsch.JSchException; -import com.jcraft.jsch.Session; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -@Component -@Slf4j -public class SftpConnector { - @Value("${file.upload.sftp.ip}") - private String host; - @Value("${file.upload.sftp.id}") - private String id; - @Value("${file.upload.sftp.password}") - private String password; - - @Value("${file.upload.sftp.port}") - private int port; - - private Session session; - private ChannelSftp channelSftp; - - public void connect() throws JSchException { - - if (host == null || id == null || password == null) { - throw new IllegalStateException("SFTP configuration is incomplete: host=" + host + ", id=" + id + ", password=" + (password != null ? "****" : null)); - } - - try { - JSch jsch = new JSch(); - // 세션 설정 - session = jsch.getSession(id, host, port); - session.setPassword(password); - // 호스트 키 검증 비활성화 (개발 환경에서만 사용, 프로덕션에서는 적절히 설정) - session.setConfig("StrictHostKeyChecking", "no"); - // 연결 - session.connect(); - - // SFTP 채널 열기 - channelSftp = (ChannelSftp) session.openChannel("sftp"); - channelSftp.connect(); - log.info("SFTP connection established successfully"); - }catch (JSchException e){ - log.error("Failed to connect to SFTP server", e); - } - } - - public void disconnect() { - if (channelSftp != null && channelSftp.isConnected()) { - channelSftp.disconnect(); - log.info("SFTP channel disconnected"); - } - if (session != null && session.isConnected()) { - session.disconnect(); - log.info("SFTP channel disconnected"); - } - } - public boolean isConnected() { - return channelSftp != null && channelSftp.isConnected() && session != null && session.isConnected(); - } - - // ChannelSftp 객체 반환 - public ChannelSftp getChannelSftp() { - return channelSftp; - } - -} diff --git a/core/src/main/java/app/module/core/usecase/file/saveToStorage/ports/application/strategy/SftpStorageFileUploadStrategy.java b/core/src/main/java/app/module/core/usecase/file/saveToStorage/ports/application/strategy/SftpStorageFileUploadStrategy.java deleted file mode 100644 index 606b6a83..00000000 --- a/core/src/main/java/app/module/core/usecase/file/saveToStorage/ports/application/strategy/SftpStorageFileUploadStrategy.java +++ /dev/null @@ -1,129 +0,0 @@ -package app.module.core.usecase.file.saveToStorage.ports.application.strategy; - -import app.module.core.config.application.enums.FileStorageType; -import app.module.core.config.application.util.AESEncryptUtil; -import app.module.core.config.application.util.CommonUtil; -import com.jcraft.jsch.ChannelSftp; -import com.jcraft.jsch.JSchException; -import com.jcraft.jsch.SftpException; -import jakarta.annotation.PostConstruct; -import jakarta.annotation.PreDestroy; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -@Service -@RequiredArgsConstructor -@Slf4j -public class SftpStorageFileUploadStrategy implements FileUploadStrategy { - @Value("${path.upload.sftp.public}") - private String publicPath; - - private final SftpConnector sftpConnector; - private final AESEncryptUtil aesEncryptUtil; - - @PostConstruct - public void initialize() throws Exception { - log.info("FileIoService - initialize : path.upload.public is {}", publicPath); - - try { - // SFTP 연결 초기화 - sftpConnector.connect(); - // 원격 디렉토리 생성 - createRemoteDirectories(publicPath); - } catch (JSchException | SftpException e) { - throw new IOException("Could not initialize SFTP connection or directories", e); - } - } - - private void createRemoteDirectories(String path) throws SftpException { - ChannelSftp channelSftp = sftpConnector.getChannelSftp(); - if (channelSftp != null) { - String[] folders = path.split("/"); - String currentPath = ""; - for (String folder : folders) { - if (!folder.isEmpty()) { - currentPath += "/" + folder; - try { - channelSftp.cd(currentPath); - } catch (SftpException e) { - channelSftp.mkdir(currentPath); - channelSftp.cd(currentPath); - } - } - } - } - } - - @Override - public FileStorageType getStorageType() { - return FileStorageType.SFTP; - } - - @Override - public void operate(MultipartFile multipartFile, String createSubPath, String createFilename) throws IOException { - if (multipartFile == null || multipartFile.isEmpty()) { - throw new IllegalArgumentException("파일이 비어 있거나 null입니다."); - } - - // 경로 조작 방지를 위해 subPath와 filename 유효성 검사 - if (createSubPath == null || createSubPath.contains("..") || createFilename == null || createFilename.contains("..")) { - throw new IllegalArgumentException("잘못된 파일 경로 또는 이름입니다."); - } - - // 메모리 내에서 파일 암호화 - byte[] encryptedContent; - try { - byte[] fileContent = multipartFile.getBytes(); // 파일을 메모리로 직접 읽음 - encryptedContent = aesEncryptUtil.encryptAesCbc(fileContent); // 암호화 - } catch (Exception e) { - log.error("파일 암호화 실패: {}", createFilename, e); - throw new IOException("파일 암호화에 실패했습니다.", e); - } - - // SFTP 경로 생성 - String remotePath = CommonUtil.removeLastChar(publicPath, "/") + createSubPath; - String remoteFilePath = remotePath + "/encrypted_" + createFilename; - - // SFTP 업로드 - try { - // 연결 상태 확인 및 재연결 (최대 3회 시도) - int retryCount = 0; - while (!sftpConnector.isConnected() && retryCount < 3) { - log.warn("SFTP 연결이 끊겼습니다. 재연결 시도 {}회", retryCount + 1); - sftpConnector.connect(); - retryCount++; - } - if (!sftpConnector.isConnected()) { - throw new IOException("SFTP 서버에 연결할 수 없습니다."); - } - - createRemoteDirectories(remotePath); - ChannelSftp channelSftp = sftpConnector.getChannelSftp(); - if (channelSftp == null) { - throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP 채널이 초기화되지 않았습니다."); - } - - // 암호화된 내용을 SFTP에 직접 업로드 - try (ByteArrayInputStream encryptedInputStream = new ByteArrayInputStream(encryptedContent)) { - channelSftp.put(encryptedInputStream, remoteFilePath); - channelSftp.chmod(0644, remoteFilePath); // 파일 권한 설정 - log.info("암호화된 파일이 SFTP에 업로드되었습니다: {}", remoteFilePath); - } - } catch (SftpException | JSchException e) { - log.error("SFTP 업로드 실패: {}", remoteFilePath, e); - throw new IOException("SFTP에 파일 업로드 실패", e); - } - - } - - @PreDestroy - public void cleanup() { - sftpConnector.disconnect(); - } -} diff --git a/core/src/main/java/app/module/core/usecase/file/updateFile/adapters/persistence/UpdateFileDao.java b/core/src/main/java/app/module/core/usecase/file/updateFile/adapters/persistence/UpdateFileDao.java index e25e5a0e..b1441115 100644 --- a/core/src/main/java/app/module/core/usecase/file/updateFile/adapters/persistence/UpdateFileDao.java +++ b/core/src/main/java/app/module/core/usecase/file/updateFile/adapters/persistence/UpdateFileDao.java @@ -2,7 +2,6 @@ package app.module.core.usecase.file.updateFile.adapters.persistence; import app.module.core.config.application.annotation.DeleteCommand; import app.module.core.config.application.util.AuditUtil; -import app.module.core.config.application.util.SftpFileDeleteUtil; import app.module.core.usecase.file.updateFile.ports.UpdateFilePortOut; import app.module.core.usecase.file.updateFile.ports.application.domain.UpdateFileCmd; import app.module.core.usecase.file.updateFile.ports.application.domain.UpdateUploadFileParam; @@ -18,7 +17,6 @@ import java.util.List; @RequiredArgsConstructor class UpdateFileDao implements UpdateFilePortOut { private final UpdateFileMapper mapper; - private final SftpFileDeleteUtil sftpFileDeleteUtil; @Override @DeleteCommand @@ -30,18 +28,6 @@ class UpdateFileDao implements UpdateFilePortOut { command.getType().getName() ))); -/* for (UploadFileDto file : deletedFileList) { - try { - sftpFileDeleteUtil.deleteRealFile(file); - } catch (JSchException | SftpException e) { - log.error("Failed to delete file from SFTP for mapping ID {}: {}", file.getId(), e.getMessage(), e); - throw new RuntimeException("Failed to delete file from SFTP", e); - } catch (Exception e) { - log.error("Unexpected error while deleting file for mapping ID {}: {}", file.getId(), e.getMessage(), e); - throw new RuntimeException("Unexpected error while deleting file", e); - } - }*/ - if (!deletedFileList.isEmpty()) { mapper.deleteFile( AuditUtil.delete(new UpdateUploadFileParam( diff --git a/core/src/main/java/app/module/core/usecase/file/url/strategy/SftpFileUrlStrategy.java b/core/src/main/java/app/module/core/usecase/file/url/strategy/SftpFileUrlStrategy.java deleted file mode 100644 index 34f25031..00000000 --- a/core/src/main/java/app/module/core/usecase/file/url/strategy/SftpFileUrlStrategy.java +++ /dev/null @@ -1,24 +0,0 @@ -package app.module.core.usecase.file.url.strategy; - -import app.module.core.config.application.enums.FileStorageType; -import org.springframework.stereotype.Service; - -@Service -public class SftpFileUrlStrategy implements FileUrlStrategy { - - @Override - public FileStorageType getStorageType() { - return FileStorageType.SFTP; - } - - @Override - public String getInlineURL(String subPath, String filename) { - return String.format("/content-disposition/inline%s/%s", subPath, filename); - } - - @Override - public String getAttachmentURL(Long fileId) { - return String.format("/content-disposition/attachment/%s", fileId); - } - -} diff --git a/core/src/main/java/app/module/core/usecase/getAttachment/adapters/web/GetAttachmentController.java b/core/src/main/java/app/module/core/usecase/getAttachment/adapters/web/GetAttachmentController.java index 11aa3da5..7eda247d 100644 --- a/core/src/main/java/app/module/core/usecase/getAttachment/adapters/web/GetAttachmentController.java +++ b/core/src/main/java/app/module/core/usecase/getAttachment/adapters/web/GetAttachmentController.java @@ -1,7 +1,6 @@ package app.module.core.usecase.getAttachment.adapters.web; import app.module.core.config.application.enums.FileStorageType; -import app.module.core.config.application.util.SftpFileDownloader; import app.module.core.usecase.file.getFile.ports.GetFilePortIn; import app.module.core.usecase.file.getFile.ports.application.domain.GetFile; import app.module.core.usecase.file.getFile.ports.application.domain.GetFileCmd; @@ -33,7 +32,6 @@ import java.nio.file.Paths; class GetAttachmentController { private final GetFilePortIn getFilePortIn; - private final SftpFileDownloader sftpFileDownloader; @Value("${path.upload.public}") private String publicPath; @@ -109,25 +107,6 @@ class GetAttachmentController { .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(s3Resource); - case SFTP: - try { - sftpFileDownloader.downloadFile(getFile); - } catch (JSchException | SftpException | IOException e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("SFTP 파일 다운로드에 실패했습니다 " + e.getMessage()); - } - File downloadedFile = new File(getFile.getLocalPath()); - if (!downloadedFile.exists()) { - return ResponseEntity.status(HttpStatus.NOT_FOUND) - .body("다운로드된 파일을 찾을 수 없습니다 " + getFile.getLocalPath()); - } - - return ResponseEntity.ok() - .headers(headers) - .contentLength(downloadedFile.length()) - .contentType(MediaType.APPLICATION_OCTET_STREAM) - .body(new FileSystemResource(downloadedFile)); - default: return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("지원되지 않는 저장소 타입입니다: " + uploadStorageType); diff --git a/front/src/main/resources/templates/record/calendar.html b/front/src/main/resources/templates/record/calendar.html index 6932b7a3..1c591ec2 100644 --- a/front/src/main/resources/templates/record/calendar.html +++ b/front/src/main/resources/templates/record/calendar.html @@ -254,7 +254,21 @@ const date = new Date(detail.viewDate) const monthKey = this._getMonthKey(date) - // this._setupMonth(date) + // 주 모드일 때 월이 변경되면 weekStart 업데이트 + if (this.state.mode === 'week') { + this._setFirstDateDay(date) + + // datepicker 옵션 업데이트 + this.instances.datepicker.setOptions({ + ...this.instances.datepickerComp.core.props, + weekStart: this.state.weekStart + }) + + // refresh를 통해 요일 헤더 업데이트 + if (this.instances.datepicker.refresh) { + this.instances.datepicker.refresh() + } + } if (!this.state.isLoading) { await this.loadMonthData(date) @@ -263,6 +277,32 @@ this.callbacks.changeMonth(monthKey, date) } + async _finalizeDateLoading(date) { + this._setupMonth(date) + + const today = new Date() + const targetDate = this._getTargetDate(date, today) + this.instances.datepicker.setDate(targetDate) + + // 주 모드일 때 요일 헤더 업데이트 + if (this.state.mode === 'week') { + this._setFirstDateDay(date) + this.instances.datepicker.setOptions({ + ...this.instances.datepickerComp.core.props, + weekStart: this.state.weekStart + }) + } + + this._scheduleClick() + + if (date >= this.data.minDate) { + this.instances.datepicker.refresh() + } + + this._loadingEnd() + this.elements.datepicker.classList.remove(DatepickerComponent.CONSTANTS.CLASSES.LOADING) + } + _handleWeekChange({ detail }) { @@ -325,15 +365,30 @@ ...this.instances.datepickerComp.core.props, weekStart: this.state.weekStart }) + // 옵션 변경 후 즉시 refresh 호출 + if (this.instances.datepicker.refresh) { + this.instances.datepicker.refresh() + } } _initializeWeekMode() { const selectedDate = this.instances.datepicker.getDate() const selectedDay = selectedDate.getDate() - // // 선택된 날짜가 포함된 주차 계산 + // 선택된 날짜가 포함된 주차 계산 this.state.weekPaging = Math.floor((selectedDay - 1) / DatepickerComponent.CONSTANTS.DAYS_PER_WEEK) + // weekStart 설정 및 옵션 업데이트 + this._setFirstDateDay(selectedDate) + this.instances.datepicker.setOptions({ + ...this.instances.datepickerComp.core.props, + weekStart: this.state.weekStart + }) + + // refresh를 통해 요일 헤더 업데이트 + if (this.instances.datepicker.refresh) { + this.instances.datepicker.refresh() + } this._weekPagination() this._updateWeekNavigationButtons() } @@ -367,15 +422,31 @@ if (this.state.mode !== 'week') return const currentDate = this.instances.datepicker.getDate() + const currentMonth = currentDate.getMonth() + const currentYear = currentDate.getFullYear() - // // 이전주 버튼 상태 확인 + // 이전주 버튼 상태 확인 const prevWeekDate = this._getPrevWeekDate(currentDate) const isPrevDisabled = prevWeekDate <= this.data.minDate this._toggleButtonDisabled(this.elements.prevWeek, isPrevDisabled) - // // 다음주 버튼 상태 확인 - const nextWeekDate = this._getNextWeekDate(currentDate) - const isNextDisabled = nextWeekDate >= this.data.maxDate + // 다음주 버튼 상태 확인 개선 + const nextWeekStart = this._getNextWeekDate(currentDate) + + // maxDate와 비교할 때 더 정확한 계산 + // 다음주가 시작되는 날짜가 maxDate를 초과하는지 확인 + let isNextDisabled = false + + // 다음주가 다음 달로 넘어가는 경우 체크 + if (nextWeekStart.getMonth() !== currentMonth) { + // 다음 달의 첫째 날이 maxDate를 초과하는지 확인 + const nextMonthFirstDay = new Date(currentYear, currentMonth + 1, 1) + isNextDisabled = nextMonthFirstDay > this.data.maxDate + } else { + // 같은 달 내에서 다음주 시작일이 maxDate를 초과하는지 확인 + isNextDisabled = nextWeekStart > this.data.maxDate + } + this._toggleButtonDisabled(this.elements.nextWeek, isNextDisabled) } @@ -385,8 +456,12 @@ } _getNextWeekDate(currentDate) { - const endWeekDate = (this.state.weekPaging + 2) * DatepickerComponent.CONSTANTS.DAYS_PER_WEEK - return new Date(currentDate.getFullYear(), currentDate.getMonth(), endWeekDate) + // 현재 주의 시작일 계산 + const currentWeekStart = (this.state.weekPaging * DatepickerComponent.CONSTANTS.DAYS_PER_WEEK) + 1 + // 다음주의 시작일 계산 + const nextWeekStart = currentWeekStart + DatepickerComponent.CONSTANTS.DAYS_PER_WEEK + + return new Date(currentDate.getFullYear(), currentDate.getMonth(), nextWeekStart) } _weekPagingPrev() { @@ -412,11 +487,7 @@ this.state.maxWeekPaging = Math.ceil(lastDayOfMonth / DatepickerComponent.CONSTANTS.DAYS_PER_WEEK) - const endWeekDate = (this.state.weekPaging + 2) * DatepickerComponent.CONSTANTS.DAYS_PER_WEEK - const date = new Date(currentDate.getFullYear(), currentDate.getMonth(), endWeekDate) - - this._disablePrevNextButtons('next', date) - + // 현재 주가 마지막 주인지 확인 if (this.state.weekPaging >= this.state.maxWeekPaging - 1) { this._moveToNextMonth() return @@ -425,6 +496,8 @@ this.state.weekPaging += 1 this._clickFirstVisibleCell() this._dispatchWeekChangeEvent('next', currentDate) + this._weekPagination('next') + this._updateWeekNavigationButtons() // 버튼 상태 업데이트 추가 } _clickFirstVisibleCell() { @@ -487,13 +560,31 @@ _moveToPreviousMonth() { const currentDate = this.instances.datepicker.getDate() + const prevMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1) const lastDayOfPrevMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 0).getDate() const lastWeekOfPrevMonth = Math.ceil(lastDayOfPrevMonth / DatepickerComponent.CONSTANTS.DAYS_PER_WEEK) - 1 const firstDayOfLastWeek = (lastWeekOfPrevMonth * DatepickerComponent.CONSTANTS.DAYS_PER_WEEK) + 1 const targetDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, firstDayOfLastWeek) + // 먼저 날짜 설정 this.instances.datepicker.setDate(targetDate) + + // 새로운 달의 첫째 날 기준으로 weekStart 업데이트 + this._setFirstDateDay(prevMonth) + + // datepicker 옵션 업데이트 + this.instances.datepicker.setOptions({ + ...this.instances.datepickerComp.core.props, + weekStart: this.state.weekStart + }) + this.state.weekPaging = lastWeekOfPrevMonth + + // refresh를 통해 요일 헤더 업데이트 + if (this.instances.datepicker.refresh) { + this.instances.datepicker.refresh() + } + this._weekPagination('prev') this._clickFirstVisibleCell() this._updateWeekNavigationButtons() @@ -503,18 +594,41 @@ const currentDate = this.instances.datepicker.getDate() const nextMonthFirstDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1) + // 먼저 날짜 설정 this.instances.datepicker.setDate(nextMonthFirstDay) + + // 새로운 달의 첫째 날 기준으로 weekStart 업데이트 + this._setFirstDateDay(nextMonthFirstDay) + + // datepicker 옵션 업데이트 + this.instances.datepicker.setOptions({ + ...this.instances.datepickerComp.core.props, + weekStart: this.state.weekStart + }) + this.state.weekPaging = 0 - // // 주 모드에서 월 이동 시 적절한 날짜가 선택되도록 loadMonthData 호출 - // // changeMonth 이벤트가 자동으로 발생하여 loadMonthData가 호출됨 + // refresh를 통해 요일 헤더 업데이트 + if (this.instances.datepicker.refresh) { + this.instances.datepicker.refresh() + } + this._weekPagination('next') + this._clickFirstVisibleCell() this._updateWeekNavigationButtons() } _setFirstDateDay(date) { const firstDate = new Date(date.getFullYear(), date.getMonth(), 1) this.state.weekStart = firstDate.getDay() + + // 주 모드일 때 datepicker 옵션도 즉시 업데이트 + if (this.state.mode === 'week' && this.instances.datepicker) { + this.instances.datepicker.setOptions({ + ...this.instances.datepickerComp.core.props, + weekStart: this.state.weekStart + }) + } } _weekPagination(direction) { @@ -768,198 +882,198 @@
- - - + + - + - + - - + {{/for}} + + + {{include tmpl="#etcRowTmpl" /}} + + +
\ No newline at end of file