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,

View File

@@ -11,8 +11,10 @@ import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
@@ -81,4 +83,14 @@ public class FrontWebMvcConfig implements WebMvcConfigurer {
lci.setParamName("lang");
return lci;
}
@Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(5000);
factory.setReadTimeout(10000);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(factory);
return restTemplate;
}
}

View File

@@ -0,0 +1,16 @@
package app.module.front.usecase.daily.income.adapters.web.model;
import app.module.front.usecase.daily.receipt.adapters.web.model.ReceiptItem;
import lombok.Data;
import java.util.List;
@Data
public class ReceiptReqVO {
private String date;
private String cardOrCash;
private String storeName;
private List<ReceiptItem> items;
private int totalPrice;
private String responseBody;
}

View File

@@ -114,7 +114,9 @@ public class DailyIncomeService implements DailyIncomePortIn {
formVO.getPrice(),
formVO.getEstimatedValue()));
portOut.create(findCmd, command);
formVO.setId(command.getId());
dailyRecordPortIn.updateByAllStatus(findCmd.getSearchMonth(), findCmd.getGroupNo(), findCmd.getHouseholdSeq());
}

View File

@@ -0,0 +1,25 @@
package app.module.front.usecase.daily.receipt.adapters.persistence;
import app.module.core.config.application.annotation.CreateCommand;
import app.module.front.usecase.daily.receipt.adapters.web.model.CreateReceiptHasFileReqVO;
import app.module.front.usecase.daily.receipt.ports.DailyReceiptPortOut;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Slf4j
@Service
@RequiredArgsConstructor
public class DailyReceiptDao implements DailyReceiptPortOut {
private final DailyReceiptMapper dailyReceiptMapper;
@Override
@Transactional
@CreateCommand
public void insertReceiptMappingFile(CreateReceiptHasFileReqVO command) {
dailyReceiptMapper.insertReceiptMappingFile(command);
}
}

View File

@@ -0,0 +1,19 @@
package app.module.front.usecase.daily.receipt.adapters.persistence;
import app.module.front.usecase.daily.receipt.adapters.web.model.CreateReceiptHasFileReqVO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface DailyReceiptMapper {
/**
* 일계부 수입 파일 매핑
*
* @param command 검색 조건
* @return 중복 개수
*/
Integer insertReceiptMappingFile(CreateReceiptHasFileReqVO command);
}

View File

@@ -0,0 +1,182 @@
package app.module.front.usecase.daily.receipt.adapters.web;
import app.module.core.config.application.exception.NoRecordDataException;
import app.module.core.usecase.daily.record.adapters.persistence.model.DailyRecordDto;
import app.module.core.usecase.daily.record.ports.DailyRecordPortIn;
import app.module.core.usecase.file.createFile.ports.CreateFilePortIn;
import app.module.core.usecase.file.createFile.ports.application.domain.CreateFile;
import app.module.core.usecase.file.createFile.ports.application.domain.CreateFileCmd;
import app.module.core.usecase.file.saveToStorage.ports.SaveToStoragePortIn;
import app.module.core.usecase.file.saveToStorage.ports.application.domain.SaveToStorage;
import app.module.front.usecase.daily.income.adapters.web.model.CreateDailyIncomeReqVO;
import app.module.front.usecase.daily.income.adapters.web.model.DailyInputType;
import app.module.front.usecase.daily.income.ports.DailyIncomePortIn;
import app.module.front.usecase.daily.receipt.adapters.web.model.*;
import app.module.front.usecase.daily.receipt.ports.DailyReceiptPortIn;
import app.module.front.usecase.daily.record.adapters.web.model.DailyUIReqVO;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@Slf4j
@RestController
@RequiredArgsConstructor
public class DailyReceiptController {
private final DailyRecordPortIn dailyRecordPortIn;
private final DailyIncomePortIn dailyIncomePortIn;
private final SaveToStoragePortIn saveToStoragePortIn;
private final CreateFilePortIn createFilePortIn;
private final RestTemplate restTemplate;
private final DailyReceiptPortIn dailyReceiptPortIn;
/**
* 일계부 영수증 등록
*/
@PostMapping(path = "/api/record/receipt")
ResponseEntity<?> operate( @RequestPart(value = "file") MultipartFile file) throws IOException {
// 파일 유효성 검사
if (file == null || file.isEmpty()) {
log.warn("파일이 비어 있거나 null입니다.");
return ResponseEntity.badRequest().body(new ReceiptResVO("파일이 비어 있습니다."));
}
if (file.getName() == null || file.getName().isEmpty() || file.getName().contains("..")) {
log.warn("잘못된 파일 이름: {}", file.getName());
return ResponseEntity.badRequest().body(new ReceiptResVO("잘못된 파일 이름입니다."));
}
String originalFilename = file.getOriginalFilename();
ReceiptResVO receiptResponse = new ReceiptResVO();
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", file.getResource());
body.add("file_name", originalFilename);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> response = restTemplate.postForEntity(
"http://115.68.193.117:9870/receipt?file_name=" + "?file_name=" + originalFilename, requestEntity, String.class);
if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
receiptResponse = mapper.readValue(response.getBody(), ReceiptResVO.class);
receiptResponse.setResponseBody(response.getBody());
log.info("파싱된 ReceiptResVO: {}", mapper.writeValueAsString(receiptResponse));
log.info("OCR API SUCCESS : fileName={}", originalFilename);
return ResponseEntity.status(HttpStatus.OK).body(receiptResponse);
} else {
log.error("OCR API FAIL: status={}", response.getStatusCode());
receiptResponse.setError("OCR API FAIL: HTTP " + response.getStatusCodeValue());
return ResponseEntity.status(response.getStatusCodeValue()).body(receiptResponse);
}
} catch (HttpClientErrorException e) {
log.error("OCR API FAIL : status={}, message={}", e.getStatusCode(), e.getResponseBodyAsString());
receiptResponse.setError("OCR API FAIL: " + e.getStatusCode() + " - " + e.getResponseBodyAsString());
return ResponseEntity.status(e.getStatusCode().value()).body(receiptResponse);
} catch (Exception e) {
log.error("OCR API FAIL : fileName={}, error={}", file.getName(), e.getMessage());
receiptResponse.setError("OCR API FAIL: " + e.getMessage());
return ResponseEntity.status(500).body(receiptResponse);
}
}
/**
* 일계부 영수증 수입 등록 처리
*
* @param searchMonth 검색 월(yyyyMM)
* @param groupNo 검색 그룹
* @param id 수입 일련번호
* @param reqVOList 영수증 데이터
*/
@PostMapping(path = "/api/record/income/receipt/{searchMonth}/{groupNo}/form/{id}")
ResponseEntity<?> createReceipt(@PathVariable("searchMonth") String searchMonth, @PathVariable("groupNo") String groupNo
, @PathVariable("id") String id,
@RequestPart(value = "reqVO") List<CreateReceiptFileReqVO> reqVOList,
@RequestPart(value = "file") List<MultipartFile> files ) throws IOException {
DailyRecordDto dailyRecord = this.vaildGetDailyRecord(searchMonth, groupNo);
for (int i = 0; i < files.size(); i++) {
MultipartFile file = files.get(i);
CreateReceiptFileReqVO createReceiptFileReqVO = reqVOList.get(i);
// storage 에 물리적 파일 저장. `LOCAL` or `S3`
SaveToStorage saveToStorage =
saveToStoragePortIn
.operate(createReceiptFileReqVO.getFileUploadType(), file)
.orElseThrow(() -> new RuntimeException("물리적 파일 저장에 실패했습니다."));
// DB 에 파일정보 저장
CreateFile createFile =
createFilePortIn
.operate(
new CreateFileCmd(
saveToStorage.getType(),
saveToStorage.getPath(),
saveToStorage.getName(),
saveToStorage.getOriginName(),
saveToStorage.getFileLength(),
dailyRecord.getId(),
createReceiptFileReqVO.getOcr().getResponseBody()
))
.orElseThrow(() -> new RuntimeException("업로드 파일정보 DB 저장에 실패했습니다."));
// 1. 레코드 저장
for(ReceiptItem item : createReceiptFileReqVO.getOcr().getItems()){
CreateDailyIncomeReqVO formVO = new CreateDailyIncomeReqVO();
formVO.setSearchMonth(searchMonth);
formVO.setGroupNo(Integer.parseInt(groupNo));
formVO.setId(Long.parseLong(id));
formVO.setDailyRecordSeq(dailyRecord.getId());
formVO.setInputType(DailyInputType.OCR);
formVO.setCredit(false);
formVO.setSourcePurpose(createReceiptFileReqVO.getOcr().getStoreName());
formVO.setIncomeKind(item.getName());
formVO.setQuantity((double) item.getQuantity());
formVO.setPrice((long) item.getTotalPrice());
log.debug("formVO: {}", formVO);
dailyIncomePortIn.create(formVO);
//has 파일에 매핑 시키기
dailyReceiptPortIn.insertReceiptMappingFile(new CreateReceiptHasFileReqVO("INCOME",formVO.getId(),createFile.getId()));
}
}
return ResponseEntity.status(HttpStatus.OK).body("");
}
/**
* 일계부 유효성 체크 및 데이터 조회
*
* @param searchMonth 검색 월(yyyyMM)
* @param groupNo 검색 그룹
*/
private DailyRecordDto vaildGetDailyRecord(String searchMonth, String groupNo) {
DailyUIReqVO reqVO = new DailyUIReqVO(searchMonth, groupNo);
log.debug("getRecordUIReq: {}", reqVO);
DailyRecordDto dailyRecord = dailyRecordPortIn.detail(reqVO.getSearchMonth(), reqVO.getGroupNo(), reqVO.getHouseholdSeq());
if (dailyRecord == null || dailyRecord.getId() == null) {
throw new NoRecordDataException();
}
return dailyRecord;
}
}

View File

@@ -0,0 +1,15 @@
package app.module.front.usecase.daily.receipt.adapters.web.model;
import app.module.core.config.application.enums.FileUploadType;
import app.module.front.usecase.daily.income.adapters.web.model.ReceiptReqVO;
import lombok.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class CreateReceiptFileReqVO {
private FileUploadType fileUploadType;
private ReceiptReqVO ocr;
}

View File

@@ -0,0 +1,16 @@
package app.module.front.usecase.daily.receipt.adapters.web.model;
import app.module.core.config.adapters.persistence.component.AuditCommand;
import app.module.core.config.application.enums.DailyInputType;
import app.module.core.config.application.enums.FileUploadType;
import lombok.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class CreateReceiptHasFileReqVO extends AuditCommand {
private String type;
private Long receiptId;
private Long fileId;
}

View File

@@ -0,0 +1,14 @@
package app.module.front.usecase.daily.receipt.adapters.web.model;
import app.module.core.config.adapters.persistence.component.AuditCommand;
import app.module.core.config.application.enums.FileUploadType;
import lombok.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class CreateReceiptUploadFileReqVO extends AuditCommand {
private Long fileId;
private Long dailyRecordSeq;
}

View File

@@ -0,0 +1,16 @@
package app.module.front.usecase.daily.receipt.adapters.web.model;
import com.fasterxml.jackson.annotation.JsonAlias;
import lombok.*;
@Getter
@Setter
@NoArgsConstructor
public class ReceiptItem {
private String name;
private int price;
private int quantity;
@JsonAlias("total_price")
private int totalPrice;
}

View File

@@ -0,0 +1,35 @@
package app.module.front.usecase.daily.receipt.adapters.web.model;
import com.fasterxml.jackson.annotation.JsonAlias;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
@NoArgsConstructor
public class ReceiptResVO {
@JsonAlias("date")
private String date;
@JsonAlias("card/cash")
private String cardOrCash;
@JsonAlias("store_name")
private String storeName;
private List<ReceiptItem> items;
@JsonAlias("total_price")
private int totalPrice;
private String responseBody;
private String error;
public ReceiptResVO(String error) {
this.error = error;
}
}

View File

@@ -0,0 +1,14 @@
package app.module.front.usecase.daily.receipt.ports;
import app.module.front.usecase.daily.receipt.adapters.web.model.CreateReceiptHasFileReqVO;
public interface DailyReceiptPortIn {
/**
* 일계부 수입 파일 매핑 추가
*
*/
void insertReceiptMappingFile(CreateReceiptHasFileReqVO formVO);
}

View File

@@ -0,0 +1,15 @@
package app.module.front.usecase.daily.receipt.ports;
import app.module.front.usecase.daily.receipt.adapters.web.model.CreateReceiptHasFileReqVO;
public interface DailyReceiptPortOut {
/**
* 일계부 수입 영수증 매핑
*
* @param command 수입 영수증 매핑 검색 조건
*/
void insertReceiptMappingFile(CreateReceiptHasFileReqVO command);
}

View File

@@ -0,0 +1,19 @@
package app.module.front.usecase.daily.receipt.ports.application;
import app.module.front.usecase.daily.receipt.adapters.web.model.CreateReceiptHasFileReqVO;
import app.module.front.usecase.daily.receipt.ports.DailyReceiptPortIn;
import app.module.front.usecase.daily.receipt.ports.DailyReceiptPortOut;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class DailyReceiptService implements DailyReceiptPortIn {
private final DailyReceiptPortOut portOut;
@Override
public void insertReceiptMappingFile(CreateReceiptHasFileReqVO formVO) {
portOut.insertReceiptMappingFile(formVO);
}
}

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="app.module.front.usecase.daily.receipt.adapters.persistence.DailyReceiptMapper">
<insert id="insertReceiptMappingFile" >
insert into receipt_has_record(
receipt_type_id,
file_id,
"type",
<include refid="common.fields.CreateUpdateBaseColumns"/>
) values (
#{receiptId},
#{fileId},
#{type},
<include refid="common.fields.CreateUpdateBaseValues"/>
)
</insert>
</mapper>

View File

@@ -5603,19 +5603,19 @@ button.swiper-pagination-bullet {
-webkit-box-align: center;
-webkit-align-items: center;
align-items: center;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
justify-content: space-between;
gap: 1.2rem;
}
.component-file .file-list .file-item {
position: relative;
max-height: 10.8rem;
border-radius: 0.8rem;
overflow: hidden;
-webkit-box-flex: 1;
-webkit-flex: 1;
flex: 1;
position: relative;
max-width: 10.8rem;
max-height: 10.8rem;
height: 10.8rem;
width: 10.8rem;
border-radius: 0.8rem;
overflow: hidden;
}
.component-file .file-list .file-item .btn-delete {
position: absolute;

View File

@@ -214,21 +214,9 @@
</div>
<div class="component-segment">
<div class="component-file">
<div class="file-list">
<div class="file-item">
<img class="profile-image-add" src="../../assets/images/acco/file_sample.png" alt="이미지샘플" />
<button type="button" class="btn-delete"><span class="hide-txt">삭제</span></button>
</div>
<div class="file-item">
<img class="profile-image-add" src="../../assets/images/acco/file_sample.png" alt="이미지샘플" />
<button type="button" class="btn-delete"><span class="hide-txt">삭제</span></button>
</div>
<div class="file-item">
<img class="profile-image-add" src="../../assets/images/acco/file_sample.png" alt="이미지샘플" />
<button type="button" class="btn-delete"><span class="hide-txt">삭제</span></button>
</div>
<div class="file-list" id="file-upload-container">
</div>
<button type="button" class="btn btn-m btn-link btn-full">
<button type="button" class="btn btn-m btn-link btn-full" onclick="modalControl.addFileInput();">
<i class="ico-add ico-small" aria-hidden="true"></i>
<span class="btn-txt">사진 첨부</span>
</button>
@@ -246,7 +234,7 @@
<div class="component-btns">
<div class="btns-row">
<!-- 버튼비활성 스타일 속성에 disabled 추가 -->
<button type="button" class="btn btn-full btn-l btn-primary">
<button type="button" onclick="modalControl.onSubmitReceiptFile();" class="btn btn-full btn-l btn-primary">
<span class="btn-txt">등록</span>
</button>
</div>

View File

@@ -162,6 +162,8 @@
create: /*[[|/api/record/income/${reqVO.searchMonth}/${reqVO.groupNo}/form/{id}|]]*/'createUrl',
remove: /*[[|/api/record/income/${reqVO.searchMonth}/${reqVO.groupNo}/remove|]]*/'removeUrl',
reset: /*[[|/api/record/income/${reqVO.searchMonth}/${reqVO.groupNo}/reset|]]*/'resetUrl',
receipt: /*[[|/api/record/receipt|]]*/'receiptUrl',
receiptCreate: /*[[|/api/record/income/receipt/${reqVO.searchMonth}/${reqVO.groupNo}/form/{id}|]]*/'receiptCreateUrl',
},
modal: {
// 등록 버튼
@@ -179,7 +181,7 @@
krip.daily.baseBindUI();
},
};
let uploadedReceipt =[];
let modalControl = {
_bindModelUI() {
const $select1 = document.querySelector('#cropCode');
@@ -265,6 +267,225 @@
},
);
},
addFileInput() {
// 새로운 input type="file" 요소 생성
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = 'image/*';
fileInput.style.display = 'none';
fileInput.name = 'file';
// 파일 선택 시 이벤트 처리
fileInput.addEventListener('change', (event) => {
const files = event.target.files;
const previewContainer = $('#file-upload-container');
if (files.length === 0) {
const para = document.createElement('p');
para.textContent = '선택된 파일이 없습니다.';
para.classList.add('error');
previewContainer.append(para);
return;
}
Array.from(files).forEach(file => {
if (!file.type.startsWith('image/')) {
const para = document.createElement('p');
para.textContent = `파일 ${file.name}: 유효한 이미지 파일이 아닙니다.`;
para.classList.add('error');
previewContainer.append(para);
return;
}
let formData = new FormData();
formData.append('file', file);
ajaxUtil._showWaiting();
$.ajax({
method: 'POST',
url: '/api/record/receipt',
data: formData,
contentType: false,
processData: false,
enctype: 'multipart/form-data',
beforeSend: function(xhr) {
xhr.setRequestHeader(
$("meta[name='_csrf_header']").attr("content"),
$("meta[name='_csrf']").attr("content")
);
},
success(res) {
// 썸네일 생성
const imgSrc = URL.createObjectURL(file);
const fileItemId = `file-item-${Math.random().toString(36).substr(2, 9)}`;
const fileItem = $(`
<div class="file-item" id="${fileItemId}">
<img class="profile-image-add" src="${imgSrc}" alt="${file.name}"/>
<button type="button" class="btn-delete"><span class="hide-txt">삭제</span></button>
</div>
`);
previewContainer.append(fileItem);
// 파일 정보와 서버 응답 저장
uploadedReceipt.push({
fileId: fileItemId,
file: file,
receiptResVO: res
});
// 삭제 버튼 이벤트 추가
fileItem.find('.btn-delete').on('click', function() {
modalControl.deleteFile(fileItemId);
fileItem.remove()
});
ajaxUtil._hideWaiting();
},
error: function(xhr) {
const resJson = xhr.responseJSON || {};
const errorMessage = resJson.error || `HTTP ${xhr.status}: 요청 처리 중 오류가 발생했습니다.`;
console.error('영수증 업로드 실패:', xhr, errorMessage);
etUI.dialog.alert({
title: '영수증 업로드 실패',
message: '정상적으로 인식되지 않은 사진이 있습니다. 정확한 사진을 첨부해주세요.',
type: 'alert',
callback: function () {
fileInput.value = '';
},
});
ajaxUtil._hideWaiting();
}
});
});
});
// 입력 필드 초기화
fileInput.value = '';
const container = document.getElementById('file-upload-container');
container.appendChild(fileInput);
// 파일 선택 창 열기
fileInput.click();
},
deleteFile(fileItemId) {
const index = uploadedReceipt.findIndex(item => item.fileId === fileItemId);
if (index !== -1) {
URL.revokeObjectURL(uploadedReceipt[index].imgSrc); // 메모리 해제
$(`#${fileItemId}`).remove();
uploadedReceipt.splice(index, 1);
}
},
onSubmitReceiptFile(){
const receiptDataList = uploadedReceipt;
if (!receiptDataList.length) {
etUI.dialog.alert({
title: '등록 실패',
message: '등록할 영수증 데이터가 없습니다.',
type: 'alert',
callback: function () {
},
});
return;
}
const f = document.reqModalForm;
let formData = new FormData();
const reqVOList = receiptDataList.map(item => ({
file: { name: item.file.name },
fileUploadType: 'INCOME',
ocr: item.receiptResVO
}));
receiptDataList.forEach(item => {
formData.append('file', item.file);
});
formData.append('reqVO', new Blob([JSON.stringify(reqVOList)], { type: 'application/json' }));
ajaxUtil._showWaiting();
console.log("receiptDataList",receiptDataList);
$.ajax({
method: 'POST',
url: ENV.httpUrl.receiptCreate.replace('{id}', f.id.value ? f.id.value : '0'),
data: formData,
contentType: false, // * 중요 *
processData: false, // * 중요 *
enctype: 'multipart/form-data', // * 중요 *
beforeSend: function (xhr) {
xhr.setRequestHeader(
$("meta[name='_csrf_header']").attr("content"),
$("meta[name='_csrf']").attr("content"));
},
success(res) {
etUI.dialog.alert({
title: '등록',
message: '영수증이 성공적으로 등록되었습니다.',
type: 'alert',
callback: function () {
// 초기화
uploadedReceipt.forEach(item => URL.revokeObjectURL(item.imgSrc));
uploadedReceipt.length = 0;
$('#file-upload-container').empty();
location.reload();
},
});
},
statusCode: {
400: function (res) {
const resJson = res.responseJSON || {};
const errorMessage = resJson.error || '잘못된 요청입니다.';
etUI.dialog.alert({
title: '등록 실패',
message: '영수증이 등록 실패하였습니다.',
type: 'alert',
callback: function () {
// 초기화
uploadedReceipt.forEach(item => URL.revokeObjectURL(item.imgSrc));
uploadedReceipt.length = 0;
$('#file-upload-container').empty();
location.reload();
},
});
},
500: function (res) {
const resJson = res.responseJSON || {};
const errorMessage = resJson.error || '서버 오류가 발생했습니다.';
console.log(`서버 오류: ${errorMessage}`);
etUI.dialog.alert({
title: '등록 실패',
message: '영수증이 등록 실패하였습니다.',
type: 'alert',
callback: function () {
// 초기화
uploadedReceipt.forEach(item => URL.revokeObjectURL(item.imgSrc));
uploadedReceipt.length = 0;
$('#file-upload-container').empty();
location.reload();
},
});
},
},
error: function (xhr) {
const errorMessage = xhr.responseJSON?.error || `HTTP ${xhr.status}`;
console.log(`영수증 업로드 실패: ${errorMessage}`);
etUI.dialog.alert({
title: '등록 실패',
message: '영수증이 등록 실패하였습니다.',
type: 'alert',
callback: function () {
// 초기화
uploadedReceipt.forEach(item => URL.revokeObjectURL(item.imgSrc));
uploadedReceipt.length = 0;
$('#file-upload-container').empty();
location.reload();
},
});
}
});
ajaxUtil._hideWaiting();
},
};
</script>
</section>

View File

@@ -93,6 +93,10 @@
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>