ApiInterface 파일 업로드 시 중복체크 기능 추가

This commit is contained in:
eactive
2025-11-25 15:54:44 +09:00
parent 48fe41794b
commit 7bcb641c1c
4 changed files with 174 additions and 62 deletions
@@ -233,43 +233,129 @@
window.alert('이관 대상 API 성공['+successCount+']건, 실패['+failedCount+']건 서버에 다운로드 완료');
});
buttonControl();
buttonControl();
FilePond.registerPlugin(FilePondPluginFileValidateType);
// FilePond 인스턴스 생성
const pond = FilePond.create(document.querySelector('.filepond'), {
instantUpload: false, // 파일을 즉시 업로드하지 않음
allowRevert: false,
acceptedFileTypes: ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/json'],
// 서버 설정
server: {
process: {
url: url_file + '?cmd=LIST_IMPORT_FILE&serviceType=' + sessionStorage["serviceType"],
method: 'POST',
// 필요한 경우 headers나 다른 설정 추가
// 25.11.25 파일 가져오기 할 때 중복 검사 기능추가.
FilePond.registerPlugin(FilePondPluginFileValidateType);
let uploadErrors = [];
let processedCount = 0;
let totalFiles = 0;
// FilePond 인스턴스 생성
const pond = FilePond.create(document.querySelector('.filepond'), {
instantUpload: false,
allowRevert: false,
acceptedFileTypes: ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/json'],
// 서버 설정
server: {
process: {
url: url_file + '?cmd=LIST_IMPORT_FILE&serviceType=' + sessionStorage["serviceType"],
method: 'POST',
ondata: (formData) => {
const chkBox = document.querySelector('#uploadModal input[name="importDupliCheck"]');
const isChecked = chkBox ? chkBox.checked : false;
formData.append('importDupliCheck', isChecked);
return formData;
},
// revert, load, restore, fetch 설정 (필요한 경우)
},
// 다른 필요한 옵션 추가
});
pond.on('processfiles', () => {
// 여기에 모든 파일 업로드 완료 후 실행할 코드를 작성
console.debug('모든 파일의 처리가 완료되었습니다.');
$('#btn_search').click();
});
// "업로드 시작" 버튼 클릭 이벤트 핸들러
document.getElementById('uploadButton').addEventListener('click', function () {
pond.processFiles(); // 선택된 모든 파일을 업로드
});
// 모달 닫기 이벤트 핸들러
$('#uploadModal').on('hidden.bs.modal', function (e) {
pond.removeFiles(); // 모달이 닫힐 때 파일 목록에서 모든 파일 제거
});
onerror: (response) => {
return response;
}
}
}
});
// 파일 처리 결과 수신
pond.on('processfile', (error, file) => {
processedCount++;
if (error) {
let errorMsg = '';
if (error.body) {
errorMsg = error.body;
} else if (typeof error === 'string') {
errorMsg = error;
} else {
errorMsg = '가져오기 중 오류가 발생 했습니다.';
}
let fileName = 'UnKnown';
if (file) {
if(file.filename) fileName = file.filename;
else if (file.file && file.file.name) fileName = file.file.name;
}
uploadErrors.push('파일명 [ ' + fileName + '] \n MESSAGE : ' + errorMsg);
}
// 모든 파일 처리 완료 시
if (processedCount >= totalFiles) {
setTimeout(() => {
if (uploadErrors.length > 0) {
const msg = "파일 처리 중 오류가 발생했습니다. \n" + uploadErrors.join('\n');
// 실패 시 변수 초기화
uploadErrors = [];
processedCount = 0;
$('#btn_search').click();
alert(msg);
} else {
alert('모든 파일이 성공적으로 업로드 되었습니다.');
$('#uploadModal').modal('hide');
$('#btn_search').click();
}
}, 100);
}
});
// 업로드 버튼 클릭 이벤트
document.getElementById('uploadButton').addEventListener('click', function(e) {
e.stopPropagation();
uploadErrors = [];
processedCount = 0;
const currentFiles = pond.getFiles();
totalFiles = currentFiles.length;
if (totalFiles === 0) {
alert("업로드 할 파일을 선택하세요.");
return;
}
const chkBox = document.getElementById('importDupliCheck');
if (chkBox && !chkBox.checked) {
if (!confirm("중복검사를 체크하지 않는 경우 기존 값은 덮어 씌워집니다. \n진행하시겠습니까?")) {
return;
}
}
pond.processFiles();
});
// 모달이 닫힐 때만 초기화
$('#uploadModal').on('hidden.bs.modal', function(e) {
resetPond();
});
function resetPond() {
pond.removeFiles();
const chkBox = document.getElementById('importDupliCheck');
if (chkBox) chkBox.checked = false;
processedCount = 0;
totalFiles = 0;
uploadErrors = [];
}
});
</script>
</head>
<body>
@@ -329,6 +415,10 @@
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<!-- 파일 업로드 시 중복체크 -->
<input type="checkbox" id="importDupliCheck" name="importDupliCheck">
<label class="form-check-label" for="importDupliCheck">중복검사</label>
<input type="file" class="filepond" name="file" multiple data-allow-reorder="true"
data-max-file-size="3MB" data-max-files="10">
</div>
@@ -1239,15 +1239,17 @@
});
});
$("#btn_excel_export").click(function () {
const url = url_excel + '?cmd=DETAIL_EXPORT_TO_EXCEL';
const params = new URLSearchParams();
params.append('eaiSvcName', getFullSvcName());
downloadFiles(url, params);
return false;
});
// 25.11.25 엑셀다운로드 사용안함.
// $("#btn_excel_export").click(function () {
// const url = url_excel + '?cmd=DETAIL_EXPORT_TO_EXCEL';
// const params = new URLSearchParams();
// params.append('eaiSvcName', getFullSvcName());
// downloadFiles(url, params);
// return false;
// });
// JSON 다운로드
$("#btn_json_export").click(function () {
const uri = url + '?cmd=DETAIL_EXPORT_TO_JSON';
const params = new URLSearchParams();
@@ -21,6 +21,7 @@ import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@@ -208,7 +209,6 @@ public class ApiInterfaceController extends OnlBaseAnnotationController {
}
}
@PostMapping(value = "/onl/transaction/apim/apiInterfaceMan.excel", params = "cmd=DETAIL_EXPORT_TO_EXCEL")
public ResponseEntity<byte[]> detailExportToExcel(@RequestParam(name = "eaiSvcName") String eaiSvcName) throws Exception {
// 단일 파일 처리
@@ -228,20 +228,22 @@ public class ApiInterfaceController extends OnlBaseAnnotationController {
}
@PostMapping(value = "/onl/transaction/apim/apiInterfaceMan.file", params = "cmd=LIST_IMPORT_FILE")
public ResponseEntity<?> listImportFromExcel(@RequestParam("file") MultipartFile file) {
public ResponseEntity<?> listImportFromJson(@RequestParam("file") MultipartFile file, boolean importDupliCheck) {
try {
if (file != null) {
String extension = FilenameUtils.getExtension(file.getOriginalFilename()).toLowerCase();
if("xls".equals(extension) || "xlsx".equals(extension)){
ApiInterfaceReloadSyncSet apiInterfaceExportSetUI = service.importInterfaceFromExcel(file);
reloadSync(apiInterfaceExportSetUI.getApiInterfaceUI());
return ResponseEntity.ok().body("File successfully imported");
} else if("json".equals(extension)) {
ApiInterfaceReloadSyncSet apiInterfaceExportSetUI = service.importInterfaceFromJson(file);
if("json".equals(extension)) {
ApiInterfaceReloadSyncSet apiInterfaceExportSetUI = service.importInterfaceFromJson(file, importDupliCheck);
reloadSync(apiInterfaceExportSetUI.getApiInterfaceUI());
return ResponseEntity.ok().body("File successfully imported");
} else {
throw new IllegalStateException("파일 [ " + file.getOriginalFilename() + " ] 의 확장자가 JSON 이 아닙니다. 다시 시도하세요.");
}
}
} catch (IllegalStateException dupEx) {
return ResponseEntity
.status(HttpStatus.CONFLICT)
.body(dupEx.getMessage());
} catch (Exception e) {
logger.error("Error processing file", e);
return ResponseEntity.internalServerError().body("Error processing file - "+e.getMessage() );
@@ -269,10 +271,10 @@ public class ApiInterfaceController extends OnlBaseAnnotationController {
}
@PostMapping(value = "/onl/transaction/apim/apiInterfaceMan.json", params = "cmd=CLONE")
public ResponseEntity<?> cloneApiInterface(String orgApiInterfaceId, String newBizCode, String newApiInterfaceId, String newInboundHttpMethod, String newInboundRestPath) throws BizException {
public ResponseEntity<?> cloneApiInterface(String orgApiInterfaceId, String newBizCode, String newApiInterfaceId, String newInboundHttpMethod, String newInboundRestPath, boolean importDupliCheck) throws BizException {
try {
ApiInterfaceUI orgApiInterfaceUI = service.selectDetail(orgApiInterfaceId);
ApiInterfaceUI apiInterfaceUI = service.cloneApiInterface(orgApiInterfaceUI, newBizCode, newApiInterfaceId, newInboundHttpMethod, newInboundRestPath);
ApiInterfaceUI apiInterfaceUI = service.cloneApiInterface(orgApiInterfaceUI, newBizCode, newApiInterfaceId, newInboundHttpMethod, newInboundRestPath, importDupliCheck);
Map<String, Object> resultMap = reloadSync(apiInterfaceUI);
return ResponseEntity.ok(resultMap);
} catch(Exception e) {
@@ -836,7 +836,8 @@ public class ApiInterfaceService extends OnlBaseService {
apiInterfaceUI.setSendRecvType(sendRecvType);
apiInterfaceUI.setInOutType(inOutType);
}
/* 25.11.25 광주은행 엑셀 가져오기 기능 사용안함.
public ApiInterfaceUI importInterfaceExcelSheet(Sheet sheet) throws Exception {
String bizCode = PoiUtils.getCellValue(sheet, 1, 3);
String elinkServiceId = PoiUtils.getCellValue(sheet, 1, 5);
@@ -910,16 +911,27 @@ public class ApiInterfaceService extends OnlBaseService {
return apiInterfaceUI;
}
*/
private void importApiInterfaceUi(ApiInterfaceUI apiInterfaceUI) throws Exception {
private void importApiInterfaceUi(ApiInterfaceUI apiInterfaceUI, boolean importDupliCheck) throws Exception {
String elinkServiceId = apiInterfaceUI.getEaiSvcName();
if (!eaiMessageQueryService.existsById(elinkServiceId)) {
insert(apiInterfaceUI);
// 중복검사 실시
boolean elinkServiceIdExists = eaiMessageQueryService.existsById(elinkServiceId);
// 아이디가 중복 일 경우, 중복검사 체크여부에 따라 업데이트 진행.
if (elinkServiceIdExists) {
// 중복검사 체크시 반환시킴
if (importDupliCheck) {
throw new IllegalStateException("ApiInterfaceId already exists [ " + elinkServiceId + " ]" );
} else {
update(apiInterfaceUI);
}
} else {
update(apiInterfaceUI);
insert(apiInterfaceUI);
}
}
/* 25.11.25 광주은행 엑셀 가져오기 기능 사용안함.
public ApiInterfaceReloadSyncSet importInterfaceFromExcel(MultipartFile file) throws Exception {
if (file.isEmpty()) {
throw new IOException("File is empty");
@@ -958,8 +970,9 @@ public class ApiInterfaceService extends OnlBaseService {
}
return apiInterfaceReloadSyncSet;
}
*/
public ApiInterfaceReloadSyncSet importInterfaceFromJson(MultipartFile file) throws Exception {
public ApiInterfaceReloadSyncSet importInterfaceFromJson(MultipartFile file, boolean importDupliCheck) throws Exception {
if (file.isEmpty()) {
throw new IOException("File is empty");
}
@@ -983,7 +996,7 @@ public class ApiInterfaceService extends OnlBaseService {
importAndAddReloadSetTransform(transformUIList, apiInterfaceExportSetUI.getRequestTransform());
importAndAddReloadSetTransform(transformUIList, apiInterfaceExportSetUI.getResponseTransform());
importApiInterfaceUi(apiInterfaceExportSetUI.getApiInterfaceUI());
importApiInterfaceUi(apiInterfaceExportSetUI.getApiInterfaceUI(), importDupliCheck);
apiInterfaceReloadSyncSet.setApiInterfaceUI(apiInterfaceExportSetUI.getApiInterfaceUI());
return apiInterfaceReloadSyncSet;
@@ -1108,12 +1121,17 @@ public class ApiInterfaceService extends OnlBaseService {
return updatedString;
}
public ApiInterfaceUI cloneApiInterface(ApiInterfaceUI orgApiInterfaceUI, String newBizCd, String newApiInterfaceId, String newInboundHttpMethod, String newInboundRestPath) throws Exception {
public ApiInterfaceUI cloneApiInterface(ApiInterfaceUI orgApiInterfaceUI, String newBizCd,
String newApiInterfaceId, String newInboundHttpMethod,
String newInboundRestPath, boolean importDupliCheck) throws Exception {
Optional<EAIMessageEntity> optional = eaiMessageQueryService.findById(newApiInterfaceId);
if (optional.isPresent()) {
String bzwkDstcd = optional.get().getEaibzwkdstcd();
throw new BizException("[" + bzwkDstcd + "][" + newApiInterfaceId + "]로 이미 등록된 인터페이스입니다.\n조회가 되지 않을 시 담당자에게 문의바랍니다.");
}
importDupliCheck = false; // 중복검사 완료.
ApiInterfaceUI apiInterfaceUI = orgApiInterfaceUI;
apiInterfaceUI.setEaiBzwkDstcd(newBizCd);
@@ -1132,7 +1150,7 @@ public class ApiInterfaceService extends OnlBaseService {
apiInterfaceUI.setResponseTransform(changeToTargetTransformUI(transform2Service.getTransformUiToExport(apiInterfaceUI.getResponseTransform()), newBizCd, newApiInterfaceId, apiInterfaceUI.getOutboundResponseLayout(), apiInterfaceUI.getInboundResponseLayout()));
}
importApiInterfaceUi(apiInterfaceUI);
importApiInterfaceUi(apiInterfaceUI, importDupliCheck);
return apiInterfaceUI;
}