Merge branch 'dev' into deploy-dev-front

This commit is contained in:
주수현
2025-06-24 08:40:17 +09:00
21 changed files with 796 additions and 124 deletions

View File

@@ -112,6 +112,14 @@ recycle 의 demo 가 궁금하다면 아래 URL 에서 확인 해주세요.
-Dspring.datasource.url=jdbc:postgresql://15.165.180.203:5432/korea_research
-Dspring.datasource.username=ko_research
-Dspring.datasource.password=koresearch1@#4
-Daes.secret-key=092HW829O0A0AVR0
-Dpath.upload.storage=SFTP
-Dpath.upload.sftp.public=/home/etribe/data/upload
-Dpath.upload.sftp.tmpdir=${user.home}/upload/tmpdir
-Dfile.upload.sftp.ip=115.68.193.117
-Dfile.upload.sftp.id=etribe
-Dfile.upload.sftp.password=Etribe@3415
-Dfile.upload.sftp.port=22
```
## JDBC 및 데이터 핸들링 구성 옵션

View File

@@ -4,8 +4,8 @@
<div class="layer-wrap" th:fragment="modalFragment">
<form autocomplete="off" method="get" name="reqVisitForm">
<input name="page" value="0" type="hidden"/>
<input name="size" value="10" type="hidden">
<input type="hidden" name="visitInfoId">
<input type="hidden" name="householdSeq">
<div class="component-modal mypage-wrap modal01 modal-visit-info" data-props-dimm-click="true" data-state="close">
<div class="modal-dimm"></div>
@@ -90,7 +90,7 @@
<div class="component-btns bottom-btn-group">
<div class="btns-row align-right">
<button type="button" class="btn btn-primary" onclick="">
<button type="button" class="btn btn-primary" onclick="goVisitInfoSave();">
<span class="btn-txt">등록</span>
</button>
</div>
@@ -106,27 +106,33 @@
</form>
<script th:inline="javascript">
// form 초기화
const resetForm = () => {
const form = document.forms['reqVisitForm'];
const form = document.reqVisitForm;
if (!form) return;
const today = new Date().toISOString().slice(0, 10);
form.visitDate.value = today;
form.visitInfoId.value = '';
form.managementType.value = '';
form.content.value = '';
document.getElementById('isGiftSent_N').checked = true;
if (datepickerInstance) {
datepickerInstance.setDate(new Date(), { render: true });
}
}
</script>
<script th:inline="javascript">
// 임가방문정보 모달창 띄우기
const showVisitInfoModal = (id) => {
document.querySelector(".modal-visit-info").ui.open();
const f = document.reqVisitForm;
resetForm();
if(id != null) {
f.visitInfoId.value = id;
ajaxUtil._ajaxMethod(
'/api/visitInfo/' + id,
`/api/visitInfo/${id}`,
{},
(response) => {
console.log("임가방문정보 상세 응답값 : ", response);
@@ -139,21 +145,81 @@
'json'
);
}
document.querySelector(".modal-visit-info").ui.open();
}
// 임가방문정보 상세 값 set
const setFormData = (data) => {
const form = document.forms['reqVisitForm'];
const form = document.reqVisitForm;
if (!form) return;
// 폼에 값 세팅
form.visitDate.value = data.visitDate || '';
form.managementType.value = data.managementType || '';
form.content.value = data.content || '';
// 라디오 버튼 처리
document.getElementById('isGiftSent_Y').checked = data.isGiftSent === true;
document.getElementById('isGiftSent_N').checked = data.isGiftSent === false;
// 날짜 세팅
if (datepickerInstance && data.visitDate) {
datepickerInstance.setDate(new Date(data.visitDate), { render: true });
}
}
</script>
<script>
// 임가방문정보 등록
const goVisitInfoSave = () => {
const f = document.reqVisitForm;
let dataOj = $(f).serializeObject();
console.log("dataOj", dataOj);
// ajaxUtil._ajaxMethod(
// '/api/visitInfo/create',
// JSON.stringify(dataOj),
// (response) => { // 성공
// alert("등록이 완료되었습니다.");
// location.href = '/households';
// },
// function (code, rstData) {
// if(code == 422) alert(rstData.responseText);
// if(code == 400) alert(rstData.responseJSON.message); //임가번호 중복체크
// },
// 'post',
// 'json',
// { handle422Type: 'alert' }
// );
}
</script>
<script>
let datepickerInstance = null;
document.addEventListener('DOMContentLoaded', function () {
const $el = document.querySelector('.component-datepicker');
const datepicker = etUI.components.DatepickerComp();
datepicker.core.init($el, {
dateSelectCallback: function (selectedDate) {
console.log('선택된 날짜:', selectedDate);
}
});
datepickerInstance = datepicker.getDatepickerInstance();
// 초기 상태 오늘 날짜로
if (datepickerInstance) {
datepickerInstance.setDate(new Date(), { render: true });
}
});
$(document).ready(() => {
const reqForm = document.reqForm;
document.reqVisitForm.householdSeq.value = reqForm.householdSeq.value;
});
</script>
</div>
</html>

View File

@@ -618,7 +618,6 @@
<!-- 임가방문정보 모달 -->
<div th:replace="households/modal/modal-visit-info :: modalFragment"></div>
</section>
<section layout:fragment="script">

View File

@@ -7,6 +7,7 @@ import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public enum FileStorageType {
LOCAL("로컬 스토리지"),
S3("AWS S3 스토리지");
S3("AWS S3 스토리지"),
SFTP("SFTP");
private final String desc;
}

View File

@@ -41,7 +41,7 @@ public enum FileUploadType {
AcceptableFileType.PDF,
AcceptableFileType.ZIP)),
NOTICE(
FileStorageType.LOCAL,
FileStorageType.SFTP,
"/notice",
Set.of(
AcceptableFileType.IMAGE,
@@ -55,7 +55,7 @@ public enum FileUploadType {
AcceptableFileType.ZIP)),
RECEIPT(
FileStorageType.LOCAL,
FileStorageType.SFTP,
"/receipt",
Set.of(
AcceptableFileType.IMAGE

View File

@@ -11,18 +11,24 @@ import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class AESEncryptUtil {
@Value("${encrypt.aes.key}")
@Value("${aes.secret-key}")
private String key;
@Value("${encrypt.aes.iv}")
private String iv;
private static final String AES_ALGORITHM = "AES/CBC/PKCS5PADDING";
public static final String ENCRYPT_IV = "0123456789ABCDEF";
public String encrypt(String text)
throws NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException,
IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException {
@@ -48,6 +54,42 @@ public class AESEncryptUtil {
return new String(decrypted, StandardCharsets.UTF_8);
}
public byte[] encryptAesCbc(byte[] plainData) {
if (plainData == null || plainData.length == 0) {
throw new IllegalArgumentException("데이터는 null이거나 비어 있을 수 없습니다.");
}
try {
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(ENCRYPT_IV.getBytes(StandardCharsets.UTF_8));
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
return org.apache.commons.codec.binary.Base64.encodeBase64(cipher.doFinal(plainData));
} catch (Exception e) {
log.error("바이너리 데이터 암호화 실패", e);
throw new RuntimeException("바이너리 데이터 암호화 실패", e);
}
}
public byte[] decryptAesCbc(byte[] cipherData) {
if (cipherData == null || cipherData.length == 0) {
throw new IllegalArgumentException("암호문은 null이거나 비어 있을 수 없습니다.");
}
try {
byte[] encrypted = org.apache.commons.codec.binary.Base64.decodeBase64(cipherData);
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(ENCRYPT_IV.getBytes(StandardCharsets.UTF_8));
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
return cipher.doFinal(encrypted);
} catch (Exception e) {
log.error("바이너리 데이터 복호화 실패", e);
throw new RuntimeException("바이너리 데이터 복호화 실패", e);
}
}
private String getTransformation() {
return "AES/CBC/PKCS5Padding";
}

View File

@@ -3,9 +3,16 @@ package app.module.core.config.application.util;
import app.module.core.config.adapters.web.security.domain.SocialUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
@@ -14,6 +21,7 @@ import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@Slf4j
public class CommonUtil {
/**
@@ -106,4 +114,41 @@ public class CommonUtil {
flashMessages.add(msg);
session.setAttribute("flashAlertMessages", flashMessages);
}
public static String normalizePath(String path) {
if (path == null || path.trim().isEmpty()) {
log.warn("normalizePath: Input path is null or empty, returning default path");
String defaultPath = System.getProperty("user.home") + File.separator + "Downloads";
return Paths.get(defaultPath).toAbsolutePath().normalize().toString();
}
try {
// Paths.get을 사용하여 경로 정규화
Path normalizedPath = Paths.get(path).toAbsolutePath().normalize();
String result = normalizedPath.toString();
log.debug("Normalized path: {}", result);
return result;
} catch (Exception e) {
log.error("Error normalizing path: {}", path, e);
throw new IllegalArgumentException("Failed to normalize path: " + path, e);
}
}
public static void createDirectories(File directory) {
if (directory == null) {
throw new IllegalArgumentException("Directory cannot be null");
}
try {
if (!directory.exists()) {
boolean created = directory.mkdirs();
log.info("Directory created: {} (Success: {})", directory.getAbsolutePath(), created);
}
if (!directory.canWrite()) {
throw new IOException("No write permission for directory: " + directory.getAbsolutePath());
}
} catch (Exception e) {
log.error("Failed to create directory: {}", directory.getAbsolutePath(), e);
throw new RuntimeException("Failed to create directory", e);
}
}
}

View File

@@ -0,0 +1,102 @@
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);
}
}
}

View File

@@ -0,0 +1,60 @@
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("Downloaded file not found: " + file.getLocalPath());
}
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));
}
}

View File

@@ -9,8 +9,6 @@ import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@EqualsAndHashCode
public class GetFile {
private Long id;
private FileUploadType type;
@@ -18,8 +16,10 @@ public class GetFile {
private String name;
private String originName;
private Long fileLength;
private String localPath;
private LocalDateTime createdAt;
private String createdBy;
private LocalDateTime updatedAt;
private String updatedBy;
}

View File

@@ -0,0 +1,71 @@
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;
}
}

View File

@@ -0,0 +1,140 @@
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.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
@Service
@RequiredArgsConstructor
@Slf4j
public class SftpStorageFileUploadStrategy implements FileUploadStrategy {
@Value("${path.upload.sftp.public}")
private String publicPath;
@Value("${path.upload.sftp.tmpdir}")
private String tmpPath;
private final SftpConnector sftpConnector;
private final AESEncryptUtil encryptUtil; // EncryptUtil 주입
@PostConstruct
public void initialize() throws Exception {
log.info("FileIoService - initialize : path.upload.public is {}", publicPath);
log.info("FileIoService - initialize : path.upload.tmpdir is {}", tmpPath);
try {
Files.createDirectories(Paths.get(tmpPath));
// 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 RuntimeException("Failed to store empty file.");
}
// 로컬 임시 파일 저장
Path tmpFile = Paths.get(tmpPath, createFilename);
Files.createDirectories(tmpFile.getParent());
try (InputStream inputStream = multipartFile.getInputStream()) {
Files.copy(inputStream, tmpFile, StandardCopyOption.REPLACE_EXISTING);
}
// 파일 내용 암호화
Path encryptedFile = Paths.get(tmpPath, "encrypted_" + createFilename);
try {
// 파일 읽기
byte[] fileContent = Files.readAllBytes(tmpFile);
// 암호화
byte[] encryptedContent = encryptUtil.encryptAesCbc(fileContent);
// 암호화된 내용을 임시 파일로 저장
Files.write(encryptedFile, encryptedContent);
} catch (Exception e) {
log.error("Failed to encrypt file: {}", createFilename, e);
throw new IOException("Failed to encrypt file", e);
}
String remotePath = CommonUtil.removeLastChar(publicPath, "/") + createSubPath;
String remoteFilePath = remotePath + "/" + "encrypted_" + createFilename;
try {
// 연결 상태 확인 및 재연결
if (!sftpConnector.isConnected()) {
log.warn("SFTP connection lost, attempting to reconnect");
sftpConnector.connect();
}
createRemoteDirectories(remotePath);
ChannelSftp channelSftp = sftpConnector.getChannelSftp();
if (channelSftp == null) {
throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP channel is not initialized");
}
// 암호화된 파일 업로드
try (InputStream encryptedInputStream = Files.newInputStream(encryptedFile)) {
channelSftp.put(encryptedInputStream, remoteFilePath);
channelSftp.chmod(0644, remoteFilePath); // 권한 변경 (0777 -> 0644로 보안 강화)
log.info("Encrypted file uploaded to SFTP: {}", remoteFilePath);
}
} catch (SftpException | JSchException e) {
throw new RuntimeException("Failed to upload encrypted file to SFTP", e);
} finally {
// 임시 파일 삭제
Files.deleteIfExists(tmpFile);
Files.deleteIfExists(encryptedFile);
}
}
@PreDestroy
public void cleanup() {
sftpConnector.disconnect();
}
}

View File

@@ -0,0 +1,24 @@
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("/api/file/download/%s", fileId);
}
}

View File

@@ -7,7 +7,7 @@
<div class="inner">
<hgroup class="tit-group">
<h3>
<strong>은행 자동이체(수입) 내역 <span>[[${bankList.totalElements}]]</span>건 등록</strong> 되었습니다.
<strong>은행 자동이체(수입) 내역 <span id="totalItems">[[${bankList.totalElements}]]</span>건 등록</strong> 되었습니다.
</h3>
<p>수입 내역을 등록해 주세요.</p>
</hgroup>
@@ -246,7 +246,7 @@
clearAllItems.style.display = "none";
}
},
openAddForm() {
openAddForm(callback) {
ajaxUtil._ajaxAsyncMethod(
"/api/front/info/bank/create/input/from",
{},
@@ -298,6 +298,9 @@
ENV.module.modalPopup.open();
document.querySelector('.modal-content').scrollTop = 0;
// 모두 로드된 후 콜백 실행
if (typeof callback === 'function') callback();
},
function(code, rstData) {
kri.logger.error('Do nothing. code: '+ code, rstData);
@@ -423,11 +426,9 @@
const product = ENV.data.bankList.find(p => p.id == id);
if (!product) return;
this.openAddForm();
setTimeout(function(){
this.openAddForm(() => {
const form = document.getElementById('popupForm');
if (!form) return;
Object.entries(product).forEach(([key, val]) => {
const field = form.elements.namedItem(key);
@@ -446,20 +447,39 @@
ENV.elementRefs.select.transferCategoryCodeSelect.setValue(product.transferCategoryCode);
ENV.elementRefs.select.unitCodeSelect.setValue(product.unitCode);
document.getElementById("unit").value = product.unit;
},100)
});
},
// 선택 아이템 삭제
deleteItemById(id) {
ENV.data.bankList = ENV.data.bankList.filter(p => p.id != id);
const target = document.querySelector(`#listBody div[data-id='${id}']`);
if (target) target.remove();
this.updateLayout();
etUI.dialog.alert({
title: '삭제 안내',
message: '등록하신 내용을 삭제하시겠어요?<br>삭제된 내용은 복구할 수 없습니다.',
type: 'confirm',
dialogType: 'confirm',
callback: function () {
ENV.data.bankList = ENV.data.bankList.filter(p => p.id != id);
const target = document.querySelector(`#listBody div[data-id='${id}']`);
if (target) target.remove();
formControl.updateLayout();
},
});
},
// 전체 초기화
clearAllItems() {
location.reload();
etUI.dialog.alert({
title: '초기화 안내',
message: '등록하신 모든 내용을 삭제하시겠어요?<br>삭제된 내용은 복구할 수 없습니다.',
type: 'confirm',
dialogType: 'confirm',
callback: function () {
ENV.data.bankList = [];
document.getElementById('listBody').innerHTML = '';
formControl.updateLayout();
// TODO(ks): 선택 삭제 시 전체 count 미반영 중. 일단 전체 초기화에서만 count 갱신.
document.getElementById('totalItems').textContent = ENV.data.bankList.length;
},
});
},
goSave() {

View File

@@ -7,7 +7,7 @@
<div class="inner">
<hgroup class="tit-group">
<h3>
<strong>은행 자동이체(지출) 내역 <span>[[${bankList.totalElements}]]</span>건 등록</strong> 되었습니다.
<strong>은행 자동이체(지출) 내역 <span id="totalItems">[[${bankList.totalElements}]]</span>건 등록</strong> 되었습니다.
</h3>
<p>지출 내역을 등록해 주세요.</p>
</hgroup>
@@ -245,7 +245,7 @@
clearAllItems.style.display = "none";
}
},
openAddForm() {
openAddForm(callback) {
ajaxUtil._ajaxAsyncMethod(
"/api/front/info/bank/create/output/from",
{},
@@ -289,6 +289,9 @@
ENV.module.modalPopup.open();
document.querySelector('.modal-content').scrollTop = 0;
// 모두 로드된 후 콜백 실행
if (typeof callback === 'function') callback();
},
function(code, rstData) {
kri.logger.error('Do nothing. code: '+ code, rstData);
@@ -417,20 +420,18 @@
const product = ENV.data.bankList.find(p => p.id == id);
if (!product) return;
this.openAddForm();
setTimeout(function(){
this.openAddForm(() => {
const form = document.getElementById('popupForm');
if (!form) return;
Object.entries(product).forEach(([key, val]) => {
const field = form.elements.namedItem(key);
if (field) {
field.value = val;
if(key == 'transferCategoryCode' && val == "code.bank.input.self"){
document.getElementById(val+"_value").value = product["transferCategory"];
if (key === 'transferCategoryCode' && val === "code.bank.input.self") {
document.getElementById(val + "_value").value = product["transferCategory"];
}
if(key == 'unitCode' && val == "code.record.unit.self"){
if (key === 'unitCode' && val === "code.record.unit.self") {
document.getElementById("unitDiv").style.display = "";
}
}
@@ -439,20 +440,40 @@
ENV.elementRefs.select.transferCategoryCodeSelect.setValue(product.transferCategoryCode);
ENV.elementRefs.select.unitCodeSelect.setValue(product.unitCode);
document.getElementById("unit").value = product.unit;
},100)
});
},
// 선택 아이템 삭제
deleteItemById(id) {
ENV.data.bankList = ENV.data.bankList.filter(p => p.id != id);
const target = document.querySelector(`#listBody div[data-id='${id}']`);
if (target) target.remove();
this.updateLayout();
etUI.dialog.alert({
title: '삭제 안내',
message: '등록하신 내용을 삭제하시겠어요?<br>삭제된 내용은 복구할 수 없습니다.',
type: 'confirm',
dialogType: 'confirm',
callback: function () {
ENV.data.bankList = ENV.data.bankList.filter(p => p.id != id);
const target = document.querySelector(`#listBody div[data-id='${id}']`);
if (target) target.remove();
formControl.updateLayout();
},
});
},
// 전체 초기화
clearAllItems() {
location.reload();
etUI.dialog.alert({
title: '초기화 안내',
message: '등록하신 모든 내용을 삭제하시겠어요?<br>삭제된 내용은 복구할 수 없습니다.',
type: 'confirm',
dialogType: 'confirm',
callback: function () {
ENV.data.bankList = [];
document.getElementById('listBody').innerHTML = '';
formControl.updateLayout();
// TODO(ks): 선택 삭제 시 전체 count 미반영 중. 일단 전체 초기화에서만 count 갱신.
document.getElementById('totalItems').textContent = ENV.data.bankList.length;
},
});
},
goSave() {

View File

@@ -8,7 +8,7 @@
<hgroup class="tit-group">
<h3>
[[${currentMonthlyInfo.koreanMonth}]]의 <br>
<strong>임산물 현황 <span>[[${currentList.totalElements}]]</span>건 등록</strong> 되었습니다.
<strong>임산물 현황 <span id="totalItems">[[${currentList.totalElements}]]</span>건 등록</strong> 되었습니다.
</h3>
<p>임산물 현황을 등록해 주세요.</p>
</hgroup>
@@ -298,7 +298,7 @@
},
// 등록폼 추가
openAddForm() {
openAddForm(callback) {
ajaxUtil._ajaxAsyncMethod(
"/api/front/info/monthly/create/from",
@@ -341,6 +341,9 @@
ENV.module.modalPopup.open();
document.querySelector('.modal-content').scrollTop = 0;
// 모두 로드된 후 콜백 실행
if (typeof callback === 'function') callback();
},
function(code, rstData) {
kri.logger.error('Do nothing. code: '+ code, rstData);
@@ -461,11 +464,10 @@
const product = ENV.data.productList.find(p => p.id == id);
if (!product) return;
this.openAddForm();
setTimeout(function() {
this.openAddForm(() => {
const form = document.getElementById('forestForm');
if (!form) return;
Object.entries(product).forEach(([key, val]) => {
const field = form.elements.namedItem(key);
if (field) {
@@ -485,7 +487,6 @@
}
});
ENV.elementRefs.select.mainYieldUnitCodeSelect.setValue(product.mainYieldUnitCode);
ENV.elementRefs.select.mainSaleUnitCodeSelect.setValue(product.mainSaleUnitCode);
ENV.elementRefs.select.subYieldUnitCodeSelect.setValue(product.subYieldUnitCode);
@@ -494,23 +495,39 @@
document.getElementById("mainSaleUnit").value = product.mainSaleUnit;
document.getElementById("subYieldUnit").value = product.subYieldUnit;
document.getElementById("subSaleUnit").value = product.subSaleUnit;
},100);
});
},
// 선택 아이템 삭제
deleteItemById(id) {
ENV.data.productList = ENV.data.productList.filter(p => p.id != id);
const target = document.querySelector(`#listBody div[data-id='${id}']`);
if (target) target.remove();
this.updateLayout();
etUI.dialog.alert({
title: '삭제 안내',
message: '등록하신 내용을 삭제하시겠어요?<br>삭제된 내용은 복구할 수 없습니다.',
type: 'confirm',
dialogType: 'confirm',
callback: function () {
ENV.data.productList = ENV.data.productList.filter(p => p.id != id);
const target = document.querySelector(`#listBody div[data-id='${id}']`);
if (target) target.remove();
formControl.updateLayout();
},
});
},
// 전체 초기화
clearAllItems() {
location.reload();
// ENV.data.productList = [];
// document.getElementById('listBody').innerHTML = '';
// this.updateListHeader();
etUI.dialog.alert({
title: '초기화 안내',
message: '등록하신 모든 내용을 삭제하시겠어요?<br>삭제된 내용은 복구할 수 없습니다.',
type: 'confirm',
dialogType: 'confirm',
callback: function () {
ENV.data.productList = [];
document.getElementById('listBody').innerHTML = '';
formControl.updateLayout();
// TODO(ks): 선택 삭제 시 전체 count 미반영 중. 일단 전체 초기화에서만 count 갱신.
document.getElementById('totalItems').textContent = ENV.data.productList.length;
},
});
},
// 아이템 겟수 처리 아이템에 따른 레이아웃 정리

View File

@@ -20,7 +20,7 @@
</label>
</div>
<div class="input-field">
<input type="text" id="temp_input_0001" placeholder="이름을 입력해 주세요" th:field="*{ownerName}"
<input type="text" id="temp_input_0001" placeholder="이름을 입력해 주세요" name="ownerName" th:field="*{ownerName}"
maxlength="10">
</div>
</div>
@@ -61,23 +61,23 @@
</div>
<div class="select-scroll">
<ul class="">
<li class="option" data-value="02">02</li>
<li class="option" data-value="31">31</li>
<li class="option" data-value="033">033</li>
<li class="option" data-value="042">042</li>
<li class="option" data-value="043">043</li>
<li class="option" data-value="051">051</li>
<li class="option" data-value="052">052</li>
<li class="option" data-value="053">053</li>
<li class="option" data-value="054">054</li>
<li class="option" data-value="055">055</li>
<li class="option" data-value="061">061</li>
<li class="option" data-value="062">062</li>
<li class="option" data-value="063">063</li>
<li class="option" data-value="064">064</li>
<li class="option" data-value="010">010</li>
<li class="option" data-value="011">011</li>
<li class="option" data-value="111">111</li>
<li class="option" data-value="02" th:classappend="${userInfo.tel1 == '02'?' current':'' }">02</li>
<li class="option" data-value="031" th:classappend="${userInfo.tel1 == '031'?' current':'' }">31</li>
<li class="option" data-value="033" th:classappend="${userInfo.tel1 == '033'?' current':'' }">033</li>
<li class="option" data-value="042" th:classappend="${userInfo.tel1 == '042'?' current':'' }">042</li>
<li class="option" data-value="043" th:classappend="${userInfo.tel1 == '043'?' current':'' }">043</li>
<li class="option" data-value="051" th:classappend="${userInfo.tel1 == '051'?' current':'' }">051</li>
<li class="option" data-value="052" th:classappend="${userInfo.tel1 == '052'?' current':'' }">052</li>
<li class="option" data-value="053" th:classappend="${userInfo.tel1 == '053'?' current':'' }">053</li>
<li class="option" data-value="054" th:classappend="${userInfo.tel1 == '054'?' current':'' }">054</li>
<li class="option" data-value="055" th:classappend="${userInfo.tel1 == '055'?' current':'' }">055</li>
<li class="option" data-value="061" th:classappend="${userInfo.tel1 == '061'?' current':'' }">061</li>
<li class="option" data-value="062" th:classappend="${userInfo.tel1 == '062'?' current':'' }">062</li>
<li class="option" data-value="063" th:classappend="${userInfo.tel1 == '063'?' current':'' }">063</li>
<li class="option" data-value="064" th:classappend="${userInfo.tel1 == '064'?' current':'' }">064</li>
<li class="option" data-value="010" th:classappend="${userInfo.tel1 == '010'?' current':'' }">010</li>
<li class="option" data-value="011" th:classappend="${userInfo.tel1 == '011'?' current':'' }">011</li>
<li class="option" data-value="111" th:classappend="${userInfo.tel1 == '111'?' current':'' }">111</li>
</ul>
</div>
</div>
@@ -100,7 +100,7 @@
<!-- 휴대폰 번호 -->
<div class="input-flex-group type-num">
<div class="input-label">
<label for="phoneId" class="label-txt">
<label for="phone1Id" class="label-txt">
휴대폰 번호 <i class="ico-required-mark" role="img" aria-label="필수">*</i>
</label>
</div>
@@ -108,7 +108,7 @@
<div class="select-group">
<div id="phoneId" class="component-select bottom-sheet"
<div id="phone1Id" class="component-select bottom-sheet"
th:data-props-default="${userInfo.phone1}" data-props-type="bottomSheet">
<input type="hidden" th:field="*{phone1}" data-type="select">
<button type="button" class="select-box">
@@ -123,7 +123,8 @@
</div>
<div class="select-scroll">
<ul class="">
<li class="option" data-value="010" th:field="*{phone2}">010</li>
<li class="option" data-value="010" th:classappend="${userInfo.phone1 == '010'?' current':'' }">010</li>
<li class="option" data-value="011" th:classappend="${userInfo.phone1 == '011'?' current':'' }">011</li>
</ul>
</div>
</div>
@@ -156,7 +157,7 @@
<div id="regionMainCodeId" class="component-select bottom-sheet" data-props-default="지역 선택"
data-props-type="bottomSheet">
<input type="hidden1" name="regionMainCode" data-type="select" th:value="${userInfo.regionMainCode}">
<input type="hidden" name="regionMainCode" data-type="select" th:value="${userInfo.regionMainCode}">
<button type="button" class="select-box">
<span class="select-txt">선택</span>
</button>
@@ -173,7 +174,7 @@
<th:block th:each="item : ${regionMainList}">
<li class="option" th:data-value="${item.id}"
th:text="${item.codeText}"
th:selected="${item.id eq userInfo.regionMainCode ? 'current' : ''}">option1
th:classappend="${item.id eq userInfo.regionMainCode ? 'current' : ''}">option1
</li>
</th:block>
</ul>
@@ -202,7 +203,9 @@
<ul class="">
<th:block th:each="item : ${regionSubList}">
<li class="option" th:data-value="${item.id}"
th:text="${item.codeText}">option1
th:text="${item.codeText}"
th:classappend="${item.id eq userInfo.regionSubCode ? 'current' : ''}"
>option1
</li>
</th:block>
@@ -278,10 +281,6 @@
<section layout:fragment="script">
<script th:inline="javascript">
$(function() {
//formControl.init();
});
let ENV = {
httpUrl: {
root: /*[[#{uri.front.info.user.path}]]*/'rootUrl',
@@ -291,32 +290,77 @@
module: {
confirmPopup: null
},
select:{
select1:null,
select2:null,
select3:null,
select4:null
},
submitted: false,
};
let formControl = {
init() {
this._bindUI();
ajaxUtil._alert('select 010->10으로 노출\n 최초값 지정 및 값 취득 함수 필요\n 개인정보 작성 필요\n 모달 내부 스크롤 기능 추가 필요', null);
console.log("init")
setTimeout(function(){
formControl._bindUI();
},300);
//ajaxUtil._alert('select 010->10으로 노출\n 최초값 지정 및 값 취득 함수 필요\n 개인정보 작성 필요\n 모달 내부 스크롤 기능 추가 필요', null);
ENV.initialOwnerName = document.querySelector('input[name="ownerName"]').value;
},
_bindUI() {
console.log("bind")
ENV.module.confirmPopup = document.querySelector(".confirmPopup").ui;
const $select1 = document.querySelector('#regionMainCodeId');
const selectboxInstance1 = new etUI.components.SelectBox();
selectboxInstance1.core.init($select1, {
ENV.select.select1 = new etUI.components.SelectBox();
ENV.select.select1.core.init($select1, {
selectItemCallback({selectValue, dataValue}){
console.log('selectItemCallback', selectValue, dataValue)
$('input[name="regionMainCode"]').val(dataValue);
document.querySelector('#regionMainCode').value = dataValue;
}
});
// selectboxInstance1.update();
selectboxInstance1.setValue($('input[name=regionMainCode]').val());
const $select2 = document.querySelector('#regionSubCodeId');
ENV.select.select2 = new etUI.components.SelectBox();
ENV.select.select2.core.init($select2, {
selectItemCallback({selectValue, dataValue}){
document.querySelector('#regionSubCode').value = dataValue;
}
});
const $select3 = document.querySelector('#tel1Id');
ENV.select.select3 = new etUI.components.SelectBox();
ENV.select.select3.core.init($select3, {
selectItemCallback({selectValue, dataValue}){
document.querySelector('#tel1').value = dataValue;
}
});
const $select4 = document.querySelector('#phone1Id');
ENV.select.select4 = new etUI.components.SelectBox();
ENV.select.select4.core.init($select4, {
selectItemCallback({selectValue, dataValue}){
document.querySelector('#phone1').value = dataValue;
}
});
// selectboxInstance1.setValue($('input[name=regionMainCode]').val());
},
confirmPopup() {
ENV.module.confirmPopup.open();
const currentName = document.querySelector('input[name="ownerName"]').value;
// 사용자가 이름을 변경했을 경우에만 개인정보 변경 동의서 모달 띄우기
if (currentName !== ENV.initialOwnerName) {
ENV.module.confirmPopup.open();
} else {
// 이름 그대로면 바로 저장
formControl.updateUserInfo();
}
},
confirmPopupOk() {
ENV.module.confirmPopup.close();
@@ -328,23 +372,30 @@
updateUserInfo() {
const f = document.reqForm;
// TODO 어쩔수 없이 이렇게 하는데..... 콤포넌트값 핸들링 방법 UX에서 지정하면 수정해야함.
const tel1Element = document.getElementById('tel1Id');
const phone1IdElement = document.getElementById('phone1Id');
const regionMainCodeIdElement = document.getElementById('regionMainCodeId');
const regionSubCodeIdElement = document.getElementById('regionSubCodeId');
if (tel1Element && tel1Element.value) {
f.tel1.value = tel1Element.value;
}
if (phone1IdElement && phone1IdElement.value) {
f.phone1.value = phone1IdElement.value;
}
if (regionMainCodeIdElement && regionMainCodeIdElement.value) {
f.regionMainCode.value = regionMainCodeIdElement.value;
}
if (regionSubCodeIdElement && regionSubCodeIdElement.value) {
f.regionSubCode.value = regionSubCodeIdElement.value;
}
// // TODO 어쩔수 없이 이렇게 하는데..... 콤포넌트값 핸들링 방법 UX에서 지정하면 수정해야함.
// const tel1Element = document.getElementById('tel1Id');
// const phone1IdElement = document.getElementById('phone1Id');
// const regionMainCodeIdElement = document.getElementById('regionMainCodeId');
// const regionSubCodeIdElement = document.getElementById('regionSubCodeId');
// if (tel1Element && tel1Element.value) {
// f.tel1.value = tel1Element.value;
// }
// if (phone1IdElement && phone1IdElement.value) {
// f.phone1.value = phone1IdElement.value;
// }
// if (regionMainCodeIdElement && regionMainCodeIdElement.value) {
// f.regionMainCode.value = regionMainCodeIdElement.value;
// }
// if (regionSubCodeIdElement && regionSubCodeIdElement.value) {
// f.regionSubCode.value = regionSubCodeIdElement.value;
// }
f.regionMainCode.value = ENV.select.select1.getValue();
f.regionSubCode.value = ENV.select.select2.getValue();
f.tel1.value = ENV.select.select3.getValue();
f.phone1.value = ENV.select.select4.getValue();
const obj = $(f).serializeObject();
@@ -359,7 +410,8 @@
* TODO
* 내정보에서만 들어온다는 가정하에서 back을 하게함 SB에는 내정보로 이동하게 되어 있음.
*/
history.back()
// history.back();
location.href = '/info';
});
} else if (rstData.code === 'ERROR') {
ajaxUtil._alert('잠시 뒤에 다시 시도해 주세요.', null);

View File

@@ -11,7 +11,7 @@
page content
</div>
<section th:replace="common/components :: floating-totop"></section>
<section th:replace="~{common/components :: floating-totop}"></section>
<div id="bindWrap"><!--/* 공통으로 사용하는 영역 */--></div>
<!--/* 공통으로 사용하는 모달 팝업 */-->

View File

@@ -12,7 +12,7 @@
</div>
<section th:replace="~{common/components :: footer}"></section>
<section th:replace="common/components :: floating-totop"></section>
<section th:replace="~{common/components :: floating-totop}"></section>
<div id="bindWrap"><!--/* 공통으로 사용하는 영역 */--></div>
<!--/* 공통으로 사용하는 모달 팝업 */-->

View File

@@ -12,7 +12,7 @@
</div>
<section th:replace="~{common/components :: footer}"></section>
<section th:replace="common/components :: floating-totop"></section>
<section th:replace="~{common/components :: floating-totop}"></section>
<div id="bindWrap"><!--/* 공통으로 사용하는 영역 */--></div>
<!--/* 공통으로 사용하는 모달 팝업 */-->

View File

@@ -88,7 +88,11 @@
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>