ocr 등록 수입 추가

This commit is contained in:
주수현
2025-07-03 15:06:28 +09:00
parent 5d058f9683
commit 1e643c3c52
30 changed files with 715 additions and 65 deletions

View File

@@ -26,6 +26,8 @@ public class UploadFile extends AuditEntity {
private String originName;
private Long fileLength;
private String ocr;
private Long dailyRecordSeq;
public UploadFile(Long id) {
this.id = id;

View File

@@ -56,10 +56,16 @@ public enum FileUploadType {
AcceptableFileType.TXT,
AcceptableFileType.PDF,
AcceptableFileType.ZIP)),
RECEIPT(
INCOME(
Set.of(FileStorageType.SFTP,FileStorageType.LOCAL),
"/receipt",
"/income",
Set.of(
AcceptableFileType.IMAGE
)
),
EXPENSE(
Set.of(FileStorageType.SFTP,FileStorageType.LOCAL),
"/expense",
Set.of(
AcceptableFileType.IMAGE
)

View File

@@ -29,7 +29,9 @@ class CreateFileDao implements CreateFilePortOut {
command.getPath(),
command.getName(),
command.getOriginName(),
command.getFileLength() );
command.getFileLength(),
command.getOcr(),
command.getDailyRecordSeq());
mapper.insertFile(uploadFile);
@@ -48,6 +50,7 @@ class CreateFileDao implements CreateFilePortOut {
uploadFile.getName()),
// attachment URL 전달
fileUrlPortIn.getAttachment(
FileStorageType.valueOf(uploadStorageType), uploadFile.getId())));
FileStorageType.valueOf(uploadStorageType), uploadFile.getId()),
uploadFile.getOcr()));
}
}

View File

@@ -43,7 +43,9 @@ class CreateFileController {
saveToStorage.getPath(),
saveToStorage.getName(),
saveToStorage.getOriginName(),
saveToStorage.getFileLength()))
saveToStorage.getFileLength(),
null,
null))
.orElseThrow(() -> new RuntimeException("업로드 파일정보 DB 저장에 실패했습니다."));
return ResponseEntity.status(HttpStatus.OK).body(createFile);

View File

@@ -13,6 +13,5 @@ import lombok.Setter;
@AllArgsConstructor
@EqualsAndHashCode
public class CreateFileReqVO {
private FileUploadType fileUploadType;
}

View File

@@ -11,7 +11,6 @@ import lombok.Setter;
@AllArgsConstructor
@EqualsAndHashCode
public class CreateFile {
private Long id;
private FileUploadType type;
private String path;
@@ -20,4 +19,5 @@ public class CreateFile {
private Long fileLength;
private String referURL;
private String attachmentURL;
private String ocr;
}

View File

@@ -17,4 +17,6 @@ public class CreateFileCmd {
private String name;
private String originName;
private Long fileLength;
private Long dailyRecordSeq;
private String ocr;
}

View File

@@ -17,6 +17,7 @@ public class GetFile {
private String originName;
private Long fileLength;
private String localPath;
private String ocr;
private LocalDateTime createdAt;
private String createdBy;
private LocalDateTime updatedAt;

View File

@@ -14,6 +14,7 @@ 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;
import java.io.InputStream;
import java.nio.file.Files;
@@ -32,15 +33,13 @@ public class SftpStorageFileUploadStrategy implements FileUploadStrategy {
private String tmpPath;
private final SftpConnector sftpConnector;
private final AESEncryptUtil aesEncryptUtil; // EncryptUtil 주입
private final AESEncryptUtil aesEncryptUtil;
@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();
// 원격 디렉토리 생성
@@ -77,60 +76,58 @@ public class SftpStorageFileUploadStrategy implements FileUploadStrategy {
@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.");
throw new IllegalArgumentException("파일이 비어 있거나 null입니다.");
}
// 로컬 임시 파일 저장
Path tmpFile = Paths.get(tmpPath, createFilename);
Files.createDirectories(tmpFile.getParent());
try (InputStream inputStream = multipartFile.getInputStream()) {
Files.copy(inputStream, tmpFile, StandardCopyOption.REPLACE_EXISTING);
// 경로 조작 방지를 위해 subPath와 filename 유효성 검사
if (createSubPath == null || createSubPath.contains("..") || createFilename == null || createFilename.contains("..")) {
throw new IllegalArgumentException("잘못된 파일 경로 또는 이름입니다.");
}
// 파일 내용 암호화
Path encryptedFile = Paths.get(tmpPath, "encrypted_" + createFilename);
// 메모리 내에서 파일 암호화
byte[] encryptedContent;
try {
// 파일 읽기
byte[] fileContent = Files.readAllBytes(tmpFile);
// 암호화
byte[] encryptedContent = aesEncryptUtil.encryptAesCbc(fileContent);
// 암호화된 내용을 임시 파일로 저장
Files.write(encryptedFile, encryptedContent);
byte[] fileContent = multipartFile.getBytes(); // 파일을 메모리로 직접 읽음
encryptedContent = aesEncryptUtil.encryptAesCbc(fileContent); // 암호화
} catch (Exception e) {
log.error("Failed to encrypt file: {}", createFilename, e);
throw new IOException("Failed to encrypt file", e);
log.error("파일 암호화 실패: {}", createFilename, e);
throw new IOException("파일 암호화에 실패했습니다.", e);
}
// SFTP 경로 생성
String remotePath = CommonUtil.removeLastChar(publicPath, "/") + createSubPath;
String remoteFilePath = remotePath + "/" + "encrypted_" + createFilename;
String remoteFilePath = remotePath + "/encrypted_" + createFilename;
// SFTP 업로드
try {
// 연결 상태 확인 및 재연결
if (!sftpConnector.isConnected()) {
log.warn("SFTP connection lost, attempting to reconnect");
// 연결 상태 확인 및 재연결 (최대 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 channel is not initialized");
throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP 채널이 초기화되지 않았습니다.");
}
// 암호화된 파일 업로드
try (InputStream encryptedInputStream = Files.newInputStream(encryptedFile)) {
// 암호화된 내용을 SFTP에 직접 업로드
try (ByteArrayInputStream encryptedInputStream = new ByteArrayInputStream(encryptedContent)) {
channelSftp.put(encryptedInputStream, remoteFilePath);
channelSftp.chmod(0644, remoteFilePath); // 권한 변경 (0777 -> 0644로 보안 강화)
log.info("Encrypted file uploaded to SFTP: {}", remoteFilePath);
channelSftp.chmod(0644, remoteFilePath); // 파일 권한 설정
log.info("암호화된 파일이 SFTP에 업로드되었습니다: {}", remoteFilePath);
}
} catch (SftpException | JSchException e) {
throw new RuntimeException("Failed to upload encrypted file to SFTP", e);
} finally {
// 임시 파일 삭제
Files.deleteIfExists(tmpFile);
Files.deleteIfExists(encryptedFile);
log.error("SFTP 업로드 실패: {}", remoteFilePath, e);
throw new IOException("SFTP에 파일 업로드 실패", e);
}
}
@PreDestroy

View File

@@ -15,6 +15,8 @@
path,
type,
file_length,
ocr,
daily_record_seq,
<include refid="common.fields.CreateUpdateBaseColumns"/>
) VALUES(
#{id},
@@ -23,6 +25,8 @@
#{path},
#{type},
#{fileLength},
#{ocr},
#{dailyRecordSeq},
<include refid="common.fields.CreateUpdateBaseValues"/>
)
</insert>

View File

@@ -10,6 +10,7 @@
name,
origin_name,
file_length,
ocr,
created_at,
created_by,
updated_at,