파일 삭제 및 퍼블 반영
This commit is contained in:
@@ -7,8 +7,7 @@ import lombok.RequiredArgsConstructor;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public enum FileStorageType {
|
public enum FileStorageType {
|
||||||
LOCAL("로컬 스토리지"),
|
LOCAL("로컬 스토리지"),
|
||||||
S3("AWS S3 스토리지"),
|
S3("AWS S3 스토리지");
|
||||||
SFTP("SFTP");
|
|
||||||
private final String desc;
|
private final String desc;
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ public enum FileUploadType {
|
|||||||
// URI og:image 용 이미지 파일
|
// URI og:image 용 이미지 파일
|
||||||
OG_IMAGE(Set.of(FileStorageType.LOCAL), "/ogImage", Set.of(AcceptableFileType.IMAGE)),
|
OG_IMAGE(Set.of(FileStorageType.LOCAL), "/ogImage", Set.of(AcceptableFileType.IMAGE)),
|
||||||
// WEB Editor 이미지 파일
|
// 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(
|
PUBLIC(
|
||||||
Set.of(FileStorageType.LOCAL),
|
Set.of(FileStorageType.LOCAL),
|
||||||
@@ -43,7 +43,6 @@ public enum FileUploadType {
|
|||||||
AcceptableFileType.ZIP)),
|
AcceptableFileType.ZIP)),
|
||||||
NOTICE(
|
NOTICE(
|
||||||
Set.of(
|
Set.of(
|
||||||
FileStorageType.SFTP,
|
|
||||||
FileStorageType.LOCAL
|
FileStorageType.LOCAL
|
||||||
),
|
),
|
||||||
"/notice",
|
"/notice",
|
||||||
@@ -58,14 +57,14 @@ public enum FileUploadType {
|
|||||||
AcceptableFileType.PDF,
|
AcceptableFileType.PDF,
|
||||||
AcceptableFileType.ZIP)),
|
AcceptableFileType.ZIP)),
|
||||||
INCOME(
|
INCOME(
|
||||||
Set.of(FileStorageType.SFTP,FileStorageType.LOCAL),
|
Set.of(FileStorageType.LOCAL),
|
||||||
"/income",
|
"/income",
|
||||||
Set.of(
|
Set.of(
|
||||||
AcceptableFileType.IMAGE
|
AcceptableFileType.IMAGE
|
||||||
)
|
)
|
||||||
),
|
),
|
||||||
EXPENSE(
|
EXPENSE(
|
||||||
Set.of(FileStorageType.SFTP,FileStorageType.LOCAL),
|
Set.of(FileStorageType.LOCAL),
|
||||||
"/expense",
|
"/expense",
|
||||||
Set.of(
|
Set.of(
|
||||||
AcceptableFileType.IMAGE
|
AcceptableFileType.IMAGE
|
||||||
|
|||||||
@@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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.annotation.DeleteCommand;
|
||||||
import app.module.core.config.application.util.AuditUtil;
|
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.UpdateFilePortOut;
|
||||||
import app.module.core.usecase.file.updateFile.ports.application.domain.UpdateFileCmd;
|
import app.module.core.usecase.file.updateFile.ports.application.domain.UpdateFileCmd;
|
||||||
import app.module.core.usecase.file.updateFile.ports.application.domain.UpdateUploadFileParam;
|
import app.module.core.usecase.file.updateFile.ports.application.domain.UpdateUploadFileParam;
|
||||||
@@ -18,7 +17,6 @@ import java.util.List;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
class UpdateFileDao implements UpdateFilePortOut {
|
class UpdateFileDao implements UpdateFilePortOut {
|
||||||
private final UpdateFileMapper mapper;
|
private final UpdateFileMapper mapper;
|
||||||
private final SftpFileDeleteUtil sftpFileDeleteUtil;
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@DeleteCommand
|
@DeleteCommand
|
||||||
@@ -30,18 +28,6 @@ class UpdateFileDao implements UpdateFilePortOut {
|
|||||||
command.getType().getName()
|
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()) {
|
if (!deletedFileList.isEmpty()) {
|
||||||
mapper.deleteFile(
|
mapper.deleteFile(
|
||||||
AuditUtil.delete(new UpdateUploadFileParam(
|
AuditUtil.delete(new UpdateUploadFileParam(
|
||||||
|
|||||||
@@ -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);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
package app.module.core.usecase.getAttachment.adapters.web;
|
package app.module.core.usecase.getAttachment.adapters.web;
|
||||||
|
|
||||||
import app.module.core.config.application.enums.FileStorageType;
|
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.GetFilePortIn;
|
||||||
import app.module.core.usecase.file.getFile.ports.application.domain.GetFile;
|
import app.module.core.usecase.file.getFile.ports.application.domain.GetFile;
|
||||||
import app.module.core.usecase.file.getFile.ports.application.domain.GetFileCmd;
|
import app.module.core.usecase.file.getFile.ports.application.domain.GetFileCmd;
|
||||||
@@ -33,7 +32,6 @@ import java.nio.file.Paths;
|
|||||||
class GetAttachmentController {
|
class GetAttachmentController {
|
||||||
|
|
||||||
private final GetFilePortIn getFilePortIn;
|
private final GetFilePortIn getFilePortIn;
|
||||||
private final SftpFileDownloader sftpFileDownloader;
|
|
||||||
|
|
||||||
@Value("${path.upload.public}")
|
@Value("${path.upload.public}")
|
||||||
private String publicPath;
|
private String publicPath;
|
||||||
@@ -109,25 +107,6 @@ class GetAttachmentController {
|
|||||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||||
.body(s3Resource);
|
.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:
|
default:
|
||||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||||
.body("지원되지 않는 저장소 타입입니다: " + uploadStorageType);
|
.body("지원되지 않는 저장소 타입입니다: " + uploadStorageType);
|
||||||
|
|||||||
@@ -254,7 +254,21 @@
|
|||||||
const date = new Date(detail.viewDate)
|
const date = new Date(detail.viewDate)
|
||||||
const monthKey = this._getMonthKey(date)
|
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) {
|
if (!this.state.isLoading) {
|
||||||
await this.loadMonthData(date)
|
await this.loadMonthData(date)
|
||||||
@@ -263,6 +277,32 @@
|
|||||||
this.callbacks.changeMonth(monthKey, date)
|
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({
|
_handleWeekChange({
|
||||||
detail
|
detail
|
||||||
}) {
|
}) {
|
||||||
@@ -325,15 +365,30 @@
|
|||||||
...this.instances.datepickerComp.core.props,
|
...this.instances.datepickerComp.core.props,
|
||||||
weekStart: this.state.weekStart
|
weekStart: this.state.weekStart
|
||||||
})
|
})
|
||||||
|
// 옵션 변경 후 즉시 refresh 호출
|
||||||
|
if (this.instances.datepicker.refresh) {
|
||||||
|
this.instances.datepicker.refresh()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_initializeWeekMode() {
|
_initializeWeekMode() {
|
||||||
const selectedDate = this.instances.datepicker.getDate()
|
const selectedDate = this.instances.datepicker.getDate()
|
||||||
const selectedDay = selectedDate.getDate()
|
const selectedDay = selectedDate.getDate()
|
||||||
|
|
||||||
// // 선택된 날짜가 포함된 주차 계산
|
// 선택된 날짜가 포함된 주차 계산
|
||||||
this.state.weekPaging = Math.floor((selectedDay - 1) / DatepickerComponent.CONSTANTS.DAYS_PER_WEEK)
|
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._weekPagination()
|
||||||
this._updateWeekNavigationButtons()
|
this._updateWeekNavigationButtons()
|
||||||
}
|
}
|
||||||
@@ -367,15 +422,31 @@
|
|||||||
if (this.state.mode !== 'week') return
|
if (this.state.mode !== 'week') return
|
||||||
|
|
||||||
const currentDate = this.instances.datepicker.getDate()
|
const currentDate = this.instances.datepicker.getDate()
|
||||||
|
const currentMonth = currentDate.getMonth()
|
||||||
|
const currentYear = currentDate.getFullYear()
|
||||||
|
|
||||||
// // 이전주 버튼 상태 확인
|
// 이전주 버튼 상태 확인
|
||||||
const prevWeekDate = this._getPrevWeekDate(currentDate)
|
const prevWeekDate = this._getPrevWeekDate(currentDate)
|
||||||
const isPrevDisabled = prevWeekDate <= this.data.minDate
|
const isPrevDisabled = prevWeekDate <= this.data.minDate
|
||||||
this._toggleButtonDisabled(this.elements.prevWeek, isPrevDisabled)
|
this._toggleButtonDisabled(this.elements.prevWeek, isPrevDisabled)
|
||||||
|
|
||||||
// // 다음주 버튼 상태 확인
|
// 다음주 버튼 상태 확인 개선
|
||||||
const nextWeekDate = this._getNextWeekDate(currentDate)
|
const nextWeekStart = this._getNextWeekDate(currentDate)
|
||||||
const isNextDisabled = nextWeekDate >= this.data.maxDate
|
|
||||||
|
// 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)
|
this._toggleButtonDisabled(this.elements.nextWeek, isNextDisabled)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -385,8 +456,12 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
_getNextWeekDate(currentDate) {
|
_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() {
|
_weekPagingPrev() {
|
||||||
@@ -412,11 +487,7 @@
|
|||||||
|
|
||||||
this.state.maxWeekPaging = Math.ceil(lastDayOfMonth / DatepickerComponent.CONSTANTS.DAYS_PER_WEEK)
|
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) {
|
if (this.state.weekPaging >= this.state.maxWeekPaging - 1) {
|
||||||
this._moveToNextMonth()
|
this._moveToNextMonth()
|
||||||
return
|
return
|
||||||
@@ -425,6 +496,8 @@
|
|||||||
this.state.weekPaging += 1
|
this.state.weekPaging += 1
|
||||||
this._clickFirstVisibleCell()
|
this._clickFirstVisibleCell()
|
||||||
this._dispatchWeekChangeEvent('next', currentDate)
|
this._dispatchWeekChangeEvent('next', currentDate)
|
||||||
|
this._weekPagination('next')
|
||||||
|
this._updateWeekNavigationButtons() // 버튼 상태 업데이트 추가
|
||||||
}
|
}
|
||||||
|
|
||||||
_clickFirstVisibleCell() {
|
_clickFirstVisibleCell() {
|
||||||
@@ -487,13 +560,31 @@
|
|||||||
|
|
||||||
_moveToPreviousMonth() {
|
_moveToPreviousMonth() {
|
||||||
const currentDate = this.instances.datepicker.getDate()
|
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 lastDayOfPrevMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 0).getDate()
|
||||||
const lastWeekOfPrevMonth = Math.ceil(lastDayOfPrevMonth / DatepickerComponent.CONSTANTS.DAYS_PER_WEEK) - 1
|
const lastWeekOfPrevMonth = Math.ceil(lastDayOfPrevMonth / DatepickerComponent.CONSTANTS.DAYS_PER_WEEK) - 1
|
||||||
const firstDayOfLastWeek = (lastWeekOfPrevMonth * 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)
|
const targetDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, firstDayOfLastWeek)
|
||||||
|
|
||||||
|
// 먼저 날짜 설정
|
||||||
this.instances.datepicker.setDate(targetDate)
|
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
|
this.state.weekPaging = lastWeekOfPrevMonth
|
||||||
|
|
||||||
|
// refresh를 통해 요일 헤더 업데이트
|
||||||
|
if (this.instances.datepicker.refresh) {
|
||||||
|
this.instances.datepicker.refresh()
|
||||||
|
}
|
||||||
|
|
||||||
this._weekPagination('prev')
|
this._weekPagination('prev')
|
||||||
this._clickFirstVisibleCell()
|
this._clickFirstVisibleCell()
|
||||||
this._updateWeekNavigationButtons()
|
this._updateWeekNavigationButtons()
|
||||||
@@ -503,18 +594,41 @@
|
|||||||
const currentDate = this.instances.datepicker.getDate()
|
const currentDate = this.instances.datepicker.getDate()
|
||||||
const nextMonthFirstDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1)
|
const nextMonthFirstDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1)
|
||||||
|
|
||||||
|
// 먼저 날짜 설정
|
||||||
this.instances.datepicker.setDate(nextMonthFirstDay)
|
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
|
this.state.weekPaging = 0
|
||||||
|
|
||||||
// // 주 모드에서 월 이동 시 적절한 날짜가 선택되도록 loadMonthData 호출
|
// refresh를 통해 요일 헤더 업데이트
|
||||||
// // changeMonth 이벤트가 자동으로 발생하여 loadMonthData가 호출됨
|
if (this.instances.datepicker.refresh) {
|
||||||
|
this.instances.datepicker.refresh()
|
||||||
|
}
|
||||||
|
|
||||||
this._weekPagination('next')
|
this._weekPagination('next')
|
||||||
|
this._clickFirstVisibleCell()
|
||||||
this._updateWeekNavigationButtons()
|
this._updateWeekNavigationButtons()
|
||||||
}
|
}
|
||||||
|
|
||||||
_setFirstDateDay(date) {
|
_setFirstDateDay(date) {
|
||||||
const firstDate = new Date(date.getFullYear(), date.getMonth(), 1)
|
const firstDate = new Date(date.getFullYear(), date.getMonth(), 1)
|
||||||
this.state.weekStart = firstDate.getDay()
|
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) {
|
_weekPagination(direction) {
|
||||||
@@ -768,198 +882,198 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<section layout:fragment="script">
|
<section layout:fragment="script">
|
||||||
<script th:src="@{/static/library/jsRender/jsrender.min.js}"></script>
|
<script th:src="@{/static/library/jsRender/jsrender.min.js}"></script>
|
||||||
<script th:src="@{/static/ui/page/daily-record.js}"></script>
|
<script th:src="@{/static/ui/page/daily-record.js}"></script>
|
||||||
<script th:inline="javascript">
|
<script th:inline="javascript">
|
||||||
let ENV = {
|
let ENV = {
|
||||||
httpUrl: {
|
httpUrl: {
|
||||||
root: '',
|
root: '',
|
||||||
list: '/record/calendar/{searchMonth}/{groupNo}',
|
list: '/record/calendar/{searchMonth}/{groupNo}',
|
||||||
create: '/record/daily/{searchMonth}/{groupNo}',
|
create: '/record/daily/{searchMonth}/{groupNo}',
|
||||||
alert: '/api/record/daily/alert/{searchMonth}',
|
alert: '/api/record/daily/alert/{searchMonth}',
|
||||||
},
|
},
|
||||||
submitted: false,
|
submitted: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
let formControl = {
|
let formControl = {
|
||||||
setDetail(rowdata, currentDate, viewDate) {
|
setDetail(rowdata, currentDate, viewDate) {
|
||||||
const searchMonth = viewDate.getFullYear().toString() + (viewDate.getMonth() + 1).toString().padStart(2, '0');
|
const searchMonth = viewDate.getFullYear().toString() + (viewDate.getMonth() + 1).toString().padStart(2, '0');
|
||||||
let childList = rowdata.children;
|
let childList = rowdata.children;
|
||||||
let monthlyList = rowdata.monthly;
|
let monthlyList = rowdata.monthly;
|
||||||
if (rowdata == null) {
|
if (rowdata == null) {
|
||||||
kri.logger.error('달력 선택 데이터 없음.')
|
kri.logger.error('달력 선택 데이터 없음.')
|
||||||
}
|
}
|
||||||
|
|
||||||
let tmpl = $.templates('#dailyNoneTmpl');
|
let tmpl = $.templates('#dailyNoneTmpl');
|
||||||
let html = '';
|
let html = '';
|
||||||
if (childList === undefined || childList.length === 0) {
|
if (childList === undefined || childList.length === 0) {
|
||||||
html = tmpl.render({
|
html = tmpl.render({
|
||||||
month: searchMonth,
|
month: searchMonth,
|
||||||
no: rowdata.no,
|
no: rowdata.no,
|
||||||
date: currentDate,
|
date: currentDate,
|
||||||
monthlyList: monthlyList,
|
monthlyList: monthlyList,
|
||||||
registrable: rowdata.registrable,
|
registrable: rowdata.registrable,
|
||||||
modifiable: rowdata.modifiable,
|
modifiable: rowdata.modifiable,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
tmpl = $.templates('#dailyListTmpl');
|
tmpl = $.templates('#dailyListTmpl');
|
||||||
html = tmpl.render({
|
html = tmpl.render({
|
||||||
month: searchMonth,
|
month: searchMonth,
|
||||||
no: rowdata.no,
|
no: rowdata.no,
|
||||||
date: currentDate,
|
date: currentDate,
|
||||||
list: childList,
|
list: childList,
|
||||||
monthlyList: monthlyList,
|
monthlyList: monthlyList,
|
||||||
registrable: rowdata.registrable,
|
registrable: rowdata.registrable,
|
||||||
modifiable: rowdata.modifiable,
|
modifiable: rowdata.modifiable,
|
||||||
carryOver: rowdata.carryOver != null ? Number(rowdata.carryOver).toLocaleString() : null,
|
carryOver: rowdata.carryOver != null ? Number(rowdata.carryOver).toLocaleString() : null,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
$('#selectedDay').html(html);
|
$('#selectedDay').html(html);
|
||||||
|
|
||||||
// 오늘 날짜가 해당 달의 마지막 날인지 확인
|
// 오늘 날짜가 해당 달의 마지막 날인지 확인
|
||||||
const today = new Date();
|
const today = new Date();
|
||||||
const lastDayOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0); // 해당 달의 마지막 날
|
const lastDayOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0); // 해당 달의 마지막 날
|
||||||
// 마지막 alert 날짜 확인
|
// 마지막 alert 날짜 확인
|
||||||
const lastAlertDate = sessionStorage.getItem('lastAlertDate');
|
const lastAlertDate = sessionStorage.getItem('lastAlertDate');
|
||||||
const todayDateString = today.toDateString();
|
const todayDateString = today.toDateString();
|
||||||
|
|
||||||
if (lastAlertDate !== todayDateString &&
|
if (lastAlertDate !== todayDateString &&
|
||||||
today.getFullYear() === lastDayOfMonth.getFullYear() &&
|
today.getFullYear() === lastDayOfMonth.getFullYear() &&
|
||||||
today.getMonth() === lastDayOfMonth.getMonth() &&
|
today.getMonth() === lastDayOfMonth.getMonth() &&
|
||||||
today.getDate() === lastDayOfMonth.getDate()) {
|
today.getDate() === lastDayOfMonth.getDate()) {
|
||||||
ajaxUtil._ajaxSyncMethod(
|
ajaxUtil._ajaxSyncMethod(
|
||||||
ENV.httpUrl.alert.replace('{searchMonth}', searchMonth.replace('-', '')),
|
ENV.httpUrl.alert.replace('{searchMonth}', searchMonth.replace('-', '')),
|
||||||
{},
|
{},
|
||||||
function (response) {
|
function (response) {
|
||||||
let dailyNo = []
|
let dailyNo = []
|
||||||
let msgTxt = '';
|
let msgTxt = '';
|
||||||
let month = viewDate.getMonth() + 1;
|
let month = viewDate.getMonth() + 1;
|
||||||
let idxPlus = 0;
|
let idxPlus = 0;
|
||||||
msgTxt += "등록하지 않은 일계부 항목이 있습니다.\n 정확한 조사를 위해 꾸준히 입력해 주세요.\n";
|
msgTxt += "등록하지 않은 일계부 항목이 있습니다.\n 정확한 조사를 위해 꾸준히 입력해 주세요.\n";
|
||||||
if(response.dailyRecordAlertDtoList.length > 0){
|
if(response.dailyRecordAlertDtoList.length > 0){
|
||||||
response.dailyRecordAlertDtoList.forEach((dto) =>{
|
response.dailyRecordAlertDtoList.forEach((dto) =>{
|
||||||
let dateTxt;
|
let dateTxt;
|
||||||
if(dto.startDay === dto.endDay){
|
if(dto.startDay === dto.endDay){
|
||||||
dateTxt = month+"월 "+dto.startDay+"일";
|
dateTxt = month+"월 "+dto.startDay+"일";
|
||||||
}else{
|
}else{
|
||||||
dateTxt = month+"월 "+dto.startDay+"~"+dto.endDay+"일";
|
dateTxt = month+"월 "+dto.startDay+"~"+dto.endDay+"일";
|
||||||
}
|
}
|
||||||
dailyNo.push(dateTxt);
|
dailyNo.push(dateTxt);
|
||||||
});
|
});
|
||||||
msgTxt += "<p class=\"dialog-info-tit\">1. 일계부 미등록 </p>\n <p class=\"dialog-info\">"+dailyNo.join(',')+"</p>\n";
|
msgTxt += "<p class=\"dialog-info-tit\">1. 일계부 미등록 </p>\n <p class=\"dialog-info\">"+dailyNo.join(',')+"</p>\n";
|
||||||
idxPlus ++;
|
idxPlus ++;
|
||||||
}
|
}
|
||||||
if(response.monthRecordAlertDtoList.length > 0) {
|
if(response.monthRecordAlertDtoList.length > 0) {
|
||||||
response.monthRecordAlertDtoList.forEach((dto,idx) => {
|
response.monthRecordAlertDtoList.forEach((dto,idx) => {
|
||||||
msgTxt += "<p class=\"dialog-info-tit\">"+ (idx+idxPlus+1) +". "+dto+"</p>\n";
|
msgTxt += "<p class=\"dialog-info-tit\">"+ (idx+idxPlus+1) +". "+dto+"</p>\n";
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if(response.dailyRecordAlertDtoList.length > 0 || dto.monthRecordAlertDtoList.length > 0) {
|
if(response.dailyRecordAlertDtoList.length > 0 || dto.monthRecordAlertDtoList.length > 0) {
|
||||||
etUI.dialog.alert({
|
etUI.dialog.alert({
|
||||||
title: '',
|
title: '',
|
||||||
message: msgTxt,
|
message: msgTxt,
|
||||||
type:'alert',
|
type:'alert',
|
||||||
callback: function () {
|
callback: function () {
|
||||||
sessionStorage.setItem('lastAlertDate',lastDayOfMonth.toDateString());
|
sessionStorage.setItem('lastAlertDate',lastDayOfMonth.toDateString());
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
function (rstData, status) {
|
function (rstData, status) {
|
||||||
|
|
||||||
},
|
},
|
||||||
'get'
|
'get'
|
||||||
,'json'
|
,'json'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
recordCreate(searchMonth, groupNo) {
|
recordCreate(searchMonth, groupNo) {
|
||||||
location.href = ENV.httpUrl.create.replace('{searchMonth}', searchMonth.replace('-', '')).replace('{groupNo}', groupNo);
|
location.href = ENV.httpUrl.create.replace('{searchMonth}', searchMonth.replace('-', '')).replace('{groupNo}', groupNo);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
<script id="dailyNoneTmpl" type="text/x-jsrender">
|
<script id="dailyNoneTmpl" type="text/x-jsrender">
|
||||||
{{include tmpl="#titleTmpl" /}}
|
{{include tmpl="#titleTmpl" /}}
|
||||||
|
|
||||||
{{if registrable}}
|
{{if registrable}}
|
||||||
<div class="component-btns btn-add">
|
<div class="component-btns btn-add">
|
||||||
<button type="button" onclick="formControl.recordCreate('{{:month}}', {{:no}});">
|
<button type="button" onclick="formControl.recordCreate('{{:month}}', {{:no}});">
|
||||||
<p class="txt">일계부 등록하기</p>
|
<p class="txt">일계부 등록하기</p>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{{/if}}
|
|
||||||
|
|
||||||
{{include tmpl="#etcRowTmpl" /}}
|
|
||||||
</script>
|
|
||||||
<script id="dailyListTmpl" type="text/x-jsrender">
|
|
||||||
{{include tmpl="#titleTmpl" /}}
|
|
||||||
|
|
||||||
<ul class="btn-column-list">
|
|
||||||
{{if no == 1}}
|
|
||||||
<li>
|
|
||||||
<p class="label">월초이월금</p>
|
|
||||||
{{if carryOver == null}}
|
|
||||||
<p class="value">정산중입니다.</p>
|
|
||||||
{{else}}
|
|
||||||
<p class="value"><em><b>{{:carryOver}}</b> 원</em></p>
|
|
||||||
{{/if}}
|
|
||||||
</li>
|
|
||||||
{{/if}}
|
{{/if}}
|
||||||
{{for list ~edit=modifiable}}
|
|
||||||
{{if status == null}}
|
{{include tmpl="#etcRowTmpl" /}}
|
||||||
|
</script>
|
||||||
|
<script id="dailyListTmpl" type="text/x-jsrender">
|
||||||
|
{{include tmpl="#titleTmpl" /}}
|
||||||
|
|
||||||
|
<ul class="btn-column-list">
|
||||||
|
{{if no == 1}}
|
||||||
<li>
|
<li>
|
||||||
<p class="label">{{:codeLabel}}</p>
|
<p class="label">월초이월금</p>
|
||||||
<p class="value">미작성</p>
|
{{if carryOver == null}}
|
||||||
</li>
|
<p class="value">정산중입니다.</p>
|
||||||
{{else}}
|
{{else}}
|
||||||
<li class="{{if ~edit}}edit{{else}}view{{/if}}">
|
<p class="value"><em><b>{{:carryOver}}</b> 원</em></p>
|
||||||
{{if status == 'TARGET' && total != 0}}
|
|
||||||
<a href="{{:path}}?type=update">
|
|
||||||
<p class="label">{{:codeLabel}}</p>
|
|
||||||
<p class="value"><em>총 <b>{{:total}}</b>건</em></p>
|
|
||||||
</a>
|
|
||||||
{{else status == 'TARGET' && total == 0}}
|
|
||||||
<a href="{{:path}}?type=update">
|
|
||||||
<p class="label">{{:codeLabel}}</p>
|
|
||||||
<p class="value">미완료</p>
|
|
||||||
</a>
|
|
||||||
{{else status == 'TODAY_NONE'}}
|
|
||||||
<a href="{{:path}}?type=update">
|
|
||||||
<p class="label">{{:codeLabel}}</p>
|
|
||||||
<p class="value">없음</p>
|
|
||||||
</a>
|
|
||||||
{{/if}}
|
{{/if}}
|
||||||
</li>
|
</li>
|
||||||
{{/if}}
|
{{/if}}
|
||||||
{{/for}}
|
{{for list ~edit=modifiable}}
|
||||||
</ul>
|
{{if status == null}}
|
||||||
|
<li>
|
||||||
{{include tmpl="#etcRowTmpl" /}}
|
<p class="label">{{:codeLabel}}</p>
|
||||||
</script>
|
<p class="value">미작성</p>
|
||||||
<script id="titleTmpl" type="text/x-jsrender">
|
</li>
|
||||||
{{if date.start == date.end}}
|
|
||||||
<p class="date">{{:date.start}}</p>
|
|
||||||
{{else}}
|
|
||||||
<p class="date">{{:date.start}} ~ {{:date.end}}</p>
|
|
||||||
{{/if}}
|
|
||||||
</script>
|
|
||||||
<script id="etcRowTmpl" type="text/x-jsrender">
|
|
||||||
<div class="regist-btn-area">
|
|
||||||
{{for monthlyList}}
|
|
||||||
<a href="{{:path ? path : 'javascript:void(0);'}}" class="btn{{if total != null && total != 0}} complete{{/if}}">
|
|
||||||
<p>{{:codeLabel}}</p>
|
|
||||||
{{if total != null && total != 0}}
|
|
||||||
<span>등록완료</span>
|
|
||||||
{{else}}
|
{{else}}
|
||||||
<span>미등록</span>
|
<li class="{{if ~edit}}edit{{else}}view{{/if}}">
|
||||||
|
{{if status == 'TARGET' && total != 0}}
|
||||||
|
<a href="{{:path}}?type=update">
|
||||||
|
<p class="label">{{:codeLabel}}</p>
|
||||||
|
<p class="value"><em>총 <b>{{:total}}</b>건</em></p>
|
||||||
|
</a>
|
||||||
|
{{else status == 'TARGET' && total == 0}}
|
||||||
|
<a href="{{:path}}?type=update">
|
||||||
|
<p class="label">{{:codeLabel}}</p>
|
||||||
|
<p class="value">미완료</p>
|
||||||
|
</a>
|
||||||
|
{{else status == 'TODAY_NONE'}}
|
||||||
|
<a href="{{:path}}?type=update">
|
||||||
|
<p class="label">{{:codeLabel}}</p>
|
||||||
|
<p class="value">없음</p>
|
||||||
|
</a>
|
||||||
|
{{/if}}
|
||||||
|
</li>
|
||||||
{{/if}}
|
{{/if}}
|
||||||
</a>
|
{{/for}}
|
||||||
{{/for}}
|
</ul>
|
||||||
</div>
|
|
||||||
</script>
|
{{include tmpl="#etcRowTmpl" /}}
|
||||||
|
</script>
|
||||||
|
<script id="titleTmpl" type="text/x-jsrender">
|
||||||
|
{{if date.start == date.end}}
|
||||||
|
<p class="date">{{:date.start}}</p>
|
||||||
|
{{else}}
|
||||||
|
<p class="date">{{:date.start}} ~ {{:date.end}}</p>
|
||||||
|
{{/if}}
|
||||||
|
</script>
|
||||||
|
<script id="etcRowTmpl" type="text/x-jsrender">
|
||||||
|
<div class="regist-btn-area">
|
||||||
|
{{for monthlyList}}
|
||||||
|
<a href="{{:path ? path : 'javascript:void(0);'}}" class="btn{{if total != null && total != 0}} complete{{/if}}">
|
||||||
|
<p>{{:codeLabel}}</p>
|
||||||
|
{{if total != null && total != 0}}
|
||||||
|
<span>등록완료</span>
|
||||||
|
{{else}}
|
||||||
|
<span>미등록</span>
|
||||||
|
{{/if}}
|
||||||
|
</a>
|
||||||
|
{{/for}}
|
||||||
|
</div>
|
||||||
|
</script>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
</html>
|
</html>
|
||||||
Reference in New Issue
Block a user