Files
wace_plm/src/com/pms/service/BatchService.java

1760 lines
64 KiB
Java

package com.pms.service;
import java.io.File;
import java.sql.Clob;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.ibatis.session.SqlSession;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import com.pms.api.CustomerApiClient;
import com.pms.api.DepartmentApiClient;
import com.pms.api.EmployeeApiClient;
import com.pms.api.WarehouseApiClient;
import com.pms.api.PartErpApiClient;
import com.pms.api.PartErpDeleteApiClient;
import com.pms.api.PartErpUpdateApiClient;
import com.pms.api.AmaranthUserApiClient;
import com.pms.common.Message;
import com.pms.common.SqlMapConfig;
import com.pms.common.bean.PersonBean;
import com.pms.common.service.BaseService;
import com.pms.common.utils.CommonUtils;
import com.pms.common.utils.Constants;
import com.pms.common.utils.EncryptUtil;
@Service
public class BatchService extends BaseService {
/**
* 첨부파일 연결 대상이 되는 파트의 목록을 가져온다.
* @param request
* @param paramMap
* @return
* @throws Exception
*/
// 파트 도면 파일 자동 연결 배치 - 주석 처리
/*
static List<File> targetFileList = new ArrayList();
@Scheduled(cron="0 59 23 * * ?")
public void partConnectDrawingFile1(){
partConnectDrawingFile();
}
@Scheduled(cron="0 0 04 * * ?")
public void partConnectDrawingFile2(){
partConnectDrawingFile();
}
public void partConnectDrawingFile(){
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
List<Map<String,Object>> partList = new ArrayList();
getFileList(Constants.PART_DRAWING_STORAGE);
try{
//도면파일이 연결되지 않은 파트의 목록을 가져온다.
partList = sqlSession.selectList("partMng.getBatchTargetPartList");
for(Map partMap:partList){
System.out.println("partMap:"+partMap);
String partObjId = CommonUtils.checkNull(partMap.get("objid"));
String partNo = CommonUtils.checkNull(partMap.get("part_no"));
String revision = CommonUtils.checkNull(partMap.get("revision"));
int cu1Cnt = Integer.parseInt(CommonUtils.checkNull(partMap.get("cu01_cnt"),"0"));
int cu2Cnt = Integer.parseInt(CommonUtils.checkNull(partMap.get("cu02_cnt"),"0"));
int cu3Cnt = Integer.parseInt(CommonUtils.checkNull(partMap.get("cu03_cnt"),"0"));
String targetFileName = partNo+revision;
int revNum = 0;
String revName = "";
if(!"".equals(revision)){
revNum = Integer.parseInt(revision.toUpperCase().replaceAll("R", ""));
revName = "R"+revNum;
}
String targetFileName2 = partNo+revName;
for(File targetFile:targetFileList){
String realFileName = CommonUtils.checkNull(targetFile.getName());
String ext = realFileName.substring(realFileName.lastIndexOf(".") + 1);
String fileName = realFileName.replaceAll("."+ext, "");
ext = ext.toUpperCase();
String fileSize = CommonUtils.checkNull(targetFile.length());
System.out.println("targetFileName:"+targetFileName2);
System.out.println("fileName:"+fileName);
if(targetFileName2.equals(fileName)){
String docType = "";
String docTypeName = "";
if(ext.equals("DWG") && 0 == cu2Cnt){
docType = "2D_DRAWING_CAD";
docTypeName = "2D(Drawing) CAD 첨부파일";
}
if(ext.equals("PDF") && 0 == cu3Cnt){
docType = "2D_PDF_CAD";
docTypeName = "2D(PDF) CAD 첨부파일";
}
if(ext.equals("IPT") && 0 == cu1Cnt){
docType = "3D_CAD";
docTypeName = "3D CAD 첨부파일";
}
if(!"".equals(docType) && !"".equals(docTypeName)){
Map connectFileMap = new HashMap();
connectFileMap.put("objId", CommonUtils.createObjId());
connectFileMap.put("targetObjId", partObjId);
connectFileMap.put("savedFileName", realFileName);
connectFileMap.put("realFileName", realFileName);
connectFileMap.put("docType", docType);
connectFileMap.put("docTypeName", docTypeName);
connectFileMap.put("fileSize", fileSize);
connectFileMap.put("fileExt", ext);
connectFileMap.put("filePath", targetFile.getParent());
connectFileMap.put("writer", "batch_plm_admin");
System.out.println("connectFileMap:"+connectFileMap);
sqlSession.insert("common.insertUploadFileInfo", connectFileMap);
}
}
}
}
sqlSession.commit();
}catch(Exception e){
sqlSession.rollback();
throw e;
}finally{
sqlSession.close();
}
}
public static List getFileList(String dirPath){
File dir = new File(dirPath);
File files[] = dir.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
getFileList(file.getPath());
} else {
targetFileList.add(file);
}
}
return targetFileList;
}
*/
/**
* ERP API 데이터 동기화 배치 (매일 새벽 00시 실행)
* 거래처, 부서, 사원 정보를 ERP API로부터 가져와 DB에 저장
*/
@Scheduled(cron="0 0 0 * * ?")
public void syncErpData() {
System.out.println("====================================");
System.out.println("ERP 데이터 동기화 배치 시작 (자동)");
System.out.println("====================================");
executeSyncErpData();
}
/**
* LoginId 업데이트 자동 배치 (매일 새벽 00시 10분 실행)
* ERP 사원 동기화 이후 실행되어 Amaranth10 loginId를 user_info.user_id에 업데이트
*/
@Scheduled(cron="0 10 0 * * ?")
public void updateLoginIdAuto() {
System.out.println("====================================");
System.out.println("LoginId 업데이트 배치 시작 (자동)");
System.out.println("====================================");
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
try {
String baseUrl = "https://erp.rps-korea.com";
// Amaranth10 API로 전체 사용자 정보 조회 (empSeq, loginId)
AmaranthUserApiClient apiClient = new AmaranthUserApiClient();
String jsonResponse = apiClient.getAllUserInfo(baseUrl);
// JSON 파싱
List<Map<String, Object>> amaranthUserList = parseAmaranthUserJson(jsonResponse);
if (amaranthUserList == null || amaranthUserList.isEmpty()) {
System.out.println("API 응답에서 사용자 정보를 찾을 수 없습니다.");
return;
}
System.out.println("" + amaranthUserList.size() + "건의 사용자 정보 처리 시작");
int updateCount = 0;
int skipCount = 0;
// empseq 기준으로 user_id 업데이트
for (Map<String, Object> amaranthUser : amaranthUserList) {
String empSeq = (String) amaranthUser.get("empSeq");
String loginId = (String) amaranthUser.get("loginId");
if (empSeq != null && !empSeq.isEmpty() && loginId != null && !loginId.isEmpty()) {
Map<String, Object> updateParam = new HashMap<String, Object>();
updateParam.put("empseq", empSeq);
updateParam.put("login_id", loginId);
int updated = sqlSession.update("batch.updateLoginId", updateParam);
if (updated > 0) {
updateCount++;
if (updateCount <= 10) {
System.out.println("[업데이트 " + updateCount + "] empseq: " + empSeq + " → loginId: " + loginId);
}
} else {
skipCount++;
}
} else {
skipCount++;
}
}
sqlSession.commit();
System.out.println("====================================");
System.out.println("LoginId 업데이트 완료 (자동)");
System.out.println("업데이트: " + updateCount + "");
System.out.println("스킵: " + skipCount + "");
System.out.println("====================================");
} catch (Exception e) {
sqlSession.rollback();
System.err.println("LoginId 업데이트 오류 (자동): " + e.getMessage());
e.printStackTrace();
} finally {
sqlSession.close();
}
}
/**
* 사원 정보만 동기화 (수동 실행)
* @return 성공 여부 Map
*/
public Map<String, Object> syncEmployeeDataManual() {
Map<String, Object> result = new HashMap<String, Object>();
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
System.out.println("====================================");
System.out.println("ERP 사원 정보 동기화 시작 (수동)");
System.out.println("====================================");
try {
String baseUrl = "https://erp.rps-korea.com";
String coCd = "1000";
syncEmployeeData(sqlSession, baseUrl, coCd);
sqlSession.commit();
result.put("success", true);
result.put("message", "사원 정보 동기화가 완료되었습니다.");
System.out.println("ERP 사원 정보 동기화 완료");
} catch (Exception e) {
sqlSession.rollback();
result.put("success", false);
result.put("message", "사원 정보 동기화 중 오류가 발생했습니다: " + e.getMessage());
System.err.println("사원 정보 동기화 오류: " + e.getMessage());
e.printStackTrace();
} finally {
sqlSession.close();
}
return result;
}
/**
* LoginId 업데이트 전용 배치 (수동 실행)
* Amaranth10 API로 전체 사용자 정보를 조회하여 empseq 기준으로 user_id 업데이트
* @return 성공 여부 Map
*/
public Map<String, Object> updateLoginIdManual() {
Map<String, Object> result = new HashMap<String, Object>();
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
System.out.println("====================================");
System.out.println("LoginId 업데이트 배치 시작 (수동)");
System.out.println("====================================");
try {
String baseUrl = "https://erp.rps-korea.com";
// Amaranth10 API로 전체 사용자 정보 조회 (empSeq, loginId)
// 파라미터 없이 전체 조회
AmaranthUserApiClient apiClient = new AmaranthUserApiClient();
String jsonResponse = apiClient.getAllUserInfo(baseUrl);
// JSON 파싱
List<Map<String, Object>> amaranthUserList = parseAmaranthUserJson(jsonResponse);
if (amaranthUserList == null || amaranthUserList.isEmpty()) {
result.put("success", false);
result.put("message", "Amaranth10 API에서 사용자 정보를 가져올 수 없습니다.");
System.out.println("API 응답에서 사용자 정보를 찾을 수 없습니다.");
return result;
}
System.out.println("" + amaranthUserList.size() + "건의 사용자 정보 처리 시작");
int updateCount = 0;
int skipCount = 0;
// empseq 기준으로 user_id 업데이트
for (Map<String, Object> amaranthUser : amaranthUserList) {
String empSeq = (String) amaranthUser.get("empSeq");
String loginId = (String) amaranthUser.get("loginId");
if (empSeq != null && !empSeq.isEmpty() && loginId != null && !loginId.isEmpty()) {
Map<String, Object> updateParam = new HashMap<String, Object>();
updateParam.put("empseq", empSeq);
updateParam.put("login_id", loginId);
int updated = sqlSession.update("batch.updateLoginId", updateParam);
if (updated > 0) {
updateCount++;
if (updateCount <= 10) {
System.out.println("[업데이트 " + updateCount + "] empseq: " + empSeq + " → loginId: " + loginId);
}
} else {
skipCount++;
}
} else {
skipCount++;
}
}
sqlSession.commit();
result.put("success", true);
result.put("message", "LoginId 업데이트가 완료되었습니다. (업데이트: " + updateCount + "건, 스킵: " + skipCount + "건)");
System.out.println("====================================");
System.out.println("LoginId 업데이트 완료");
System.out.println("업데이트: " + updateCount + "");
System.out.println("스킵: " + skipCount + "");
System.out.println("====================================");
} catch (Exception e) {
sqlSession.rollback();
result.put("success", false);
result.put("message", "LoginId 업데이트 중 오류가 발생했습니다: " + e.getMessage());
System.err.println("LoginId 업데이트 오류: " + e.getMessage());
e.printStackTrace();
} finally {
sqlSession.close();
}
return result;
}
/**
* Amaranth10 사용자 정보 JSON 파싱
* resultData 배열에서 직접 empSeq, loginId 추출
*/
private List<Map<String, Object>> parseAmaranthUserJson(String jsonResponse) {
List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
try {
// resultData 배열 추출
int resultDataStart = jsonResponse.indexOf("\"resultData\"");
if (resultDataStart == -1) {
System.err.println("resultData를 찾을 수 없습니다.");
return userList;
}
int arrayStart = jsonResponse.indexOf("[", resultDataStart);
if (arrayStart == -1) {
System.err.println("resultData 배열을 찾을 수 없습니다.");
return userList;
}
// 매칭되는 닫는 괄호 찾기
int arrayEnd = findMatchingBracket(jsonResponse, arrayStart);
if (arrayEnd == -1) {
System.err.println("resultData 배열의 끝을 찾을 수 없습니다.");
return userList;
}
String arrayContent = jsonResponse.substring(arrayStart + 1, arrayEnd);
// resultData 배열의 각 사용자 객체 파싱
int braceCount = 0;
int objStart = -1;
for (int i = 0; i < arrayContent.length(); i++) {
char c = arrayContent.charAt(i);
if (c == '{') {
if (braceCount == 0) {
objStart = i;
}
braceCount++;
} else if (c == '}') {
braceCount--;
if (braceCount == 0 && objStart != -1) {
String objStr = arrayContent.substring(objStart, i + 1);
Map<String, Object> user = parseAmaranthUserObject(objStr);
if (user != null && user.get("empSeq") != null && user.get("loginId") != null) {
userList.add(user);
}
objStart = -1;
}
}
}
System.out.println("파싱된 사용자 수: " + userList.size());
} catch (Exception e) {
System.err.println("Amaranth 사용자 JSON 파싱 오류: " + e.getMessage());
e.printStackTrace();
}
return userList;
}
/**
* Amaranth10 사용자 객체 파싱
*/
private Map<String, Object> parseAmaranthUserObject(String jsonObject) {
Map<String, Object> user = new HashMap<String, Object>();
try {
// empSeq 추출
String empSeq = extractJsonValue(jsonObject, "empSeq");
if (empSeq != null && !empSeq.isEmpty()) {
user.put("empSeq", empSeq);
}
// loginId 추출
String loginId = extractJsonValue(jsonObject, "loginId");
if (loginId != null && !loginId.isEmpty()) {
user.put("loginId", loginId);
}
} catch (Exception e) {
System.err.println("Amaranth 사용자 객체 파싱 오류: " + e.getMessage());
return null;
}
return user;
}
/**
* 매칭되는 괄호 찾기
*/
private int findMatchingBracket(String str, int startIndex) {
int count = 1;
for (int i = startIndex + 1; i < str.length(); i++) {
if (str.charAt(i) == '[') {
count++;
} else if (str.charAt(i) == ']') {
count--;
if (count == 0) {
return i;
}
}
}
return -1;
}
/**
* 부서 정보만 동기화 (수동 실행)
* @return 성공 여부 Map
*/
public Map<String, Object> syncDepartmentDataManual() {
Map<String, Object> result = new HashMap<String, Object>();
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
System.out.println("====================================");
System.out.println("ERP 부서 정보 동기화 시작 (수동)");
System.out.println("====================================");
try {
String baseUrl = "https://erp.rps-korea.com";
String coCd = "1000";
syncDepartmentData(sqlSession, baseUrl, coCd);
sqlSession.commit();
result.put("success", true);
result.put("message", "부서 정보 동기화가 완료되었습니다.");
System.out.println("ERP 부서 정보 동기화 완료");
} catch (Exception e) {
sqlSession.rollback();
result.put("success", false);
result.put("message", "부서 정보 동기화 중 오류가 발생했습니다: " + e.getMessage());
System.err.println("부서 정보 동기화 오류: " + e.getMessage());
e.printStackTrace();
} finally {
sqlSession.close();
}
return result;
}
/**
* 거래처 정보만 동기화 (수동 실행)
* @return 성공 여부 Map
*/
public Map<String, Object> syncCustomerDataManual() {
Map<String, Object> result = new HashMap<String, Object>();
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
System.out.println("====================================");
System.out.println("ERP 거래처 정보 동기화 시작 (수동)");
System.out.println("====================================");
try {
String baseUrl = "https://erp.rps-korea.com";
String coCd = "1000";
syncCustomerData(sqlSession, baseUrl, coCd);
sqlSession.commit();
result.put("success", true);
result.put("message", "거래처 정보 동기화가 완료되었습니다.");
System.out.println("ERP 거래처 정보 동기화 완료");
} catch (Exception e) {
sqlSession.rollback();
result.put("success", false);
result.put("message", "거래처 정보 동기화 중 오류가 발생했습니다: " + e.getMessage());
System.err.println("거래처 정보 동기화 오류: " + e.getMessage());
e.printStackTrace();
} finally {
sqlSession.close();
}
return result;
}
/**
* 창고 정보만 동기화 (수동 실행)
* @return 성공 여부 Map
*/
public Map<String, Object> syncWarehouseDataManual() {
Map<String, Object> result = new HashMap<String, Object>();
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
System.out.println("====================================");
System.out.println("ERP 창고 정보 동기화 시작 (수동)");
System.out.println("====================================");
try {
String baseUrl = "https://erp.rps-korea.com";
String coCd = "1000";
syncWarehouseData(sqlSession, baseUrl, coCd);
sqlSession.commit();
result.put("success", true);
result.put("message", "창고 정보 동기화가 완료되었습니다.");
System.out.println("ERP 창고 정보 동기화 완료");
} catch (Exception e) {
sqlSession.rollback();
result.put("success", false);
result.put("message", "창고 정보 동기화 중 오류가 발생했습니다: " + e.getMessage());
System.err.println("창고 정보 동기화 오류: " + e.getMessage());
e.printStackTrace();
} finally {
sqlSession.close();
}
return result;
}
/**
* ERP 데이터 동기화 실제 실행 로직
*/
private void executeSyncErpData() {
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
try {
// API 기본 URL 및 회사코드 설정
String baseUrl = "https://erp.rps-korea.com";
String coCd = "1000";
// 1. 거래처 정보 동기화
syncCustomerData(sqlSession, baseUrl, coCd);
// 2. 부서 정보 동기화
syncDepartmentData(sqlSession, baseUrl, coCd);
// 3. 사원 정보 동기화
syncEmployeeData(sqlSession, baseUrl, coCd);
// 4. 창고 정보 동기화
syncWarehouseData(sqlSession, baseUrl, coCd);
sqlSession.commit();
System.out.println("ERP 데이터 동기화 배치 완료");
} catch (Exception e) {
sqlSession.rollback();
System.err.println("ERP 데이터 동기화 중 오류 발생: " + e.getMessage());
e.printStackTrace();
throw new RuntimeException(e);
} finally {
sqlSession.close();
}
}
/**
* 거래처 정보 동기화
*/
private void syncCustomerData(SqlSession sqlSession, String baseUrl, String coCd) {
try {
System.out.println("거래처 정보 동기화 시작...");
CustomerApiClient customerClient = new CustomerApiClient();
String jsonResponse = customerClient.getCustomerList(baseUrl, coCd);
// JSON 파싱 및 DB 저장
List<Map<String, Object>> customerList = parseCustomerJson(jsonResponse);
int processCount = 0;
// 처음 10건 로그 출력
System.out.println("====================================");
System.out.println("거래처 데이터 샘플 (최대 10건)");
System.out.println("====================================");
for (Map<String, Object> customer : customerList) {
// 처음 10건만 로그 출력
if (processCount < 10) {
System.out.println("[거래처 " + (processCount + 1) + "]");
System.out.println(" - CLIENT_CD: " + customer.get("client_cd"));
System.out.println(" - CLIENT_NM: " + customer.get("client_nm"));
System.out.println(" - CEO_NM: " + customer.get("ceo_nm"));
System.out.println(" - TEL_NO: " + customer.get("tel_no"));
System.out.println(" - EMAIL: " + customer.get("email"));
System.out.println("---");
}
// UPSERT 실행
sqlSession.insert("batch.upsertCustomer", customer);
processCount++;
}
System.out.println("====================================");
System.out.println("거래처 정보 동기화 완료 - 처리: " + processCount + "");
} catch (Exception e) {
System.err.println("거래처 정보 동기화 실패: " + e.getMessage());
throw new RuntimeException(e);
}
}
/**
* 부서 정보 동기화
*/
private void syncDepartmentData(SqlSession sqlSession, String baseUrl, String coCd) {
try {
System.out.println("부서 정보 동기화 시작...");
DepartmentApiClient deptClient = new DepartmentApiClient();
String jsonResponse = deptClient.getDepartmentList(baseUrl, coCd, null);
// JSON 파싱 및 DB 저장
List<Map<String, Object>> deptList = parseDepartmentJson(jsonResponse);
int processCount = 0;
// 처음 10건 로그 출력
System.out.println("====================================");
System.out.println("부서 데이터 샘플 (최대 10건)");
System.out.println("====================================");
for (Map<String, Object> dept : deptList) {
// 처음 10건만 로그 출력
if (processCount < 10) {
System.out.println("[부서 " + (processCount + 1) + "]");
System.out.println(" - DEPT_CODE: " + dept.get("dept_code"));
System.out.println(" - DEPT_NAME: " + dept.get("dept_name"));
System.out.println(" - PARENT_DEPT_CODE: " + dept.get("parent_dept_code"));
System.out.println(" - STATUS: " + dept.get("status"));
System.out.println("---");
}
// UPSERT 실행
sqlSession.insert("batch.upsertDepartment", dept);
processCount++;
}
System.out.println("====================================");
System.out.println("부서 정보 동기화 완료 - 처리: " + processCount + "");
} catch (Exception e) {
System.err.println("부서 정보 동기화 실패: " + e.getMessage());
throw new RuntimeException(e);
}
}
/**
* 사원 정보 동기화
*/
private void syncEmployeeData(SqlSession sqlSession, String baseUrl, String coCd) {
try {
System.out.println("사원 정보 동기화 시작...");
EmployeeApiClient empClient = new EmployeeApiClient();
String jsonResponse = empClient.getEmployeeList(baseUrl, coCd);
// JSON 파싱 및 DB 저장
List<Map<String, Object>> empList = parseEmployeeJson(jsonResponse);
int processCount = 0;
// 처음 10건 로그 출력
System.out.println("====================================");
System.out.println("사원 데이터 샘플 (최대 10건)");
System.out.println("====================================");
for (Map<String, Object> emp : empList) {
// 처음 10건만 로그 출력
if (processCount < 10) {
System.out.println("[사원 " + (processCount + 1) + "]");
System.out.println(" - USER_ID: " + emp.get("user_id"));
System.out.println(" - USER_NAME: " + emp.get("user_name"));
System.out.println(" - USER_NAME_ENG: " + emp.get("user_name_eng"));
System.out.println(" - DEPT_CODE: " + emp.get("dept_code"));
System.out.println(" - DEPT_NAME: " + emp.get("dept_name"));
System.out.println(" - EMAIL: " + emp.get("email"));
System.out.println(" - CELL_PHONE: " + emp.get("cell_phone"));
System.out.println(" - STATUS: " + emp.get("status"));
System.out.println("---");
}
// UPSERT 실행
sqlSession.insert("batch.upsertEmployee", emp);
processCount++;
}
System.out.println("====================================");
System.out.println("사원 정보 동기화 완료 - 처리: " + processCount + "");
} catch (Exception e) {
System.err.println("사원 정보 동기화 실패: " + e.getMessage());
throw new RuntimeException(e);
}
}
/**
* 창고 정보 동기화
*/
private void syncWarehouseData(SqlSession sqlSession, String baseUrl, String coCd) {
try {
System.out.println("창고 정보 동기화 시작...");
WarehouseApiClient warehouseClient = new WarehouseApiClient();
String jsonResponse = warehouseClient.getWarehouseList(baseUrl, coCd, "0");
// JSON 파싱 및 DB 저장
List<Map<String, Object>> warehouseList = parseWarehouseJson(jsonResponse);
int processCount = 0;
// 처음 10건 로그 출력
System.out.println("====================================");
System.out.println("창고 데이터 샘플 (최대 10건)");
System.out.println("====================================");
for (Map<String, Object> warehouse : warehouseList) {
// 처음 10건만 로그 출력
if (processCount < 10) {
System.out.println("[창고 " + (processCount + 1) + "]");
System.out.println(" - LOCATION_CODE: " + warehouse.get("location_code"));
System.out.println(" - LOCATION_NAME: " + warehouse.get("location_name"));
System.out.println(" - OUT_CODE: " + warehouse.get("out_code"));
System.out.println(" - USE_STATUS: " + warehouse.get("use_status"));
System.out.println("---");
}
// UPSERT 실행
sqlSession.insert("batch.upsertWarehouse", warehouse);
processCount++;
}
System.out.println("====================================");
System.out.println("창고 정보 동기화 완료 - 처리: " + processCount + "");
} catch (Exception e) {
System.err.println("창고 정보 동기화 실패: " + e.getMessage());
throw new RuntimeException(e);
}
}
/**
* 거래처 JSON 파싱
*/
private List<Map<String, Object>> parseCustomerJson(String jsonResponse) {
List<Map<String, Object>> customerList = new ArrayList<Map<String, Object>>();
try {
// resultData 배열 찾기
int dataStart = jsonResponse.indexOf("\"resultData\":[");
if (dataStart == -1) {
return customerList;
}
String dataSection = jsonResponse.substring(dataStart + 14);
int bracketCount = 0;
int startIdx = -1;
for (int i = 0; i < dataSection.length(); i++) {
char c = dataSection.charAt(i);
if (c == '{') {
if (bracketCount == 0) {
startIdx = i;
}
bracketCount++;
} else if (c == '}') {
bracketCount--;
if (bracketCount == 0 && startIdx != -1) {
String customerJson = dataSection.substring(startIdx, i + 1);
Map<String, Object> customer = parseCustomerObject(customerJson);
if (customer != null) {
customerList.add(customer);
}
startIdx = -1;
}
}
}
} catch (Exception e) {
System.err.println("거래처 JSON 파싱 오류: " + e.getMessage());
}
return customerList;
}
/**
* 거래처 객체 파싱 (실제 테이블 컬럼에 맞춤)
*/
private Map<String, Object> parseCustomerObject(String json) {
Map<String, Object> customer = new HashMap<String, Object>();
// 기본 정보
customer.put("client_cd", extractJsonValue(json, "trCd")); // 거래처코드
customer.put("client_nm", extractJsonValue(json, "trNm")); // 거래처명
customer.put("tr_nmk", extractJsonValue(json, "trNm")); // 거래처명(한글)
customer.put("client_nmk", extractJsonValue(json, "trNm")); // 거래처명(한글)
customer.put("attr_nmk", extractJsonValue(json, "attrNm")); // 거래처약칭
customer.put("client_type", extractJsonValue(json, "trFg")); // 거래처분류
customer.put("bus_reg_no", extractJsonValue(json, "regNb")); // 사업자등록번호
customer.put("resident_no", extractJsonValue(json, "pplNb")); // 주민번호
customer.put("ceo_nm", extractJsonValue(json, "ceoNm")); // 대표자명
customer.put("ceo_nmk", extractJsonValue(json, "ceoNm")); // 대표자명(한글)
customer.put("bus_type", extractJsonValue(json, "business")); // 업태
customer.put("bus_item", extractJsonValue(json, "jongmok")); // 종목
customer.put("post_no", extractJsonValue(json, "zip")); // 우편번호
customer.put("addr1", extractJsonValue(json, "divAddr1")); // 주소1
customer.put("addr2", extractJsonValue(json, "addr2")); // 주소2
customer.put("tel_no", extractJsonValue(json, "tel")); // 전화번호
customer.put("fax_no", extractJsonValue(json, "fax")); // 팩스번호
customer.put("homepage", extractJsonValue(json, "homepage")); // 홈페이지
customer.put("email", extractJsonValue(json, "email")); // 이메일
customer.put("liq_rs", extractJsonValue(json, "liqRs")); // 주류코드
customer.put("tr_fg", extractJsonValue(json, "trFg")); // 거래처분류
customer.put("country_nm", extractJsonValue(json, "nationNm")); // 국가명
customer.put("class_cd", extractJsonValue(json, "trgrpCd")); // 거래처분류코드
customer.put("class_nm", extractJsonValue(json, "trgrpNm")); // 거래처분류명
customer.put("grade_cd", extractJsonValue(json, "trratFg")); // 거래처등급코드
customer.put("grade_nm", extractJsonValue(json, "trratNm")); // 거래처등급명
customer.put("collect_client_cd", extractJsonValue(json, "clttrCd")); // 수금거래처코드
customer.put("collect_client_nm", extractJsonValue(json, "clttrNm")); // 수금거래처명
customer.put("region_cd", extractJsonValue(json, "localCd")); // 지역코드
customer.put("region_nm", extractJsonValue(json, "localNm")); // 지역명
customer.put("trade_start_dt", extractJsonValue(json, "frDt")); // 거래시작일
customer.put("trade_end_dt", extractJsonValue(json, "toDt")); // 거래종료일
customer.put("use_yn", extractJsonValue(json, "useYn")); // 사용여부
customer.put("contract_start_dt", extractJsonValue(json, "interDt")); // 계약시작일
customer.put("contract_end_dt", extractJsonValue(json, "dueDt")); // 계약종료일
customer.put("trade_type", extractJsonValue(json, "trsoFg")); // 거래형태
customer.put("discount_rate", extractJsonValue(json, "interRt")); // 할인율
customer.put("contract_amt", extractJsonValue(json, "limitAm")); // 계약금액
customer.put("monthly_fee", extractJsonValue(json, "interAm")); // 월용역비
customer.put("payment_term", extractJsonValue(json, "payconDc")); // 결제조건
customer.put("rcp_tp", extractJsonValue(json, "doudate1Fg")); // 예정일구분
customer.put("credit_limit", extractJsonValue(json, "creditAm")); // 여신한도액
customer.put("limit_return_day", extractJsonValue(json, "returnDt")); // 한도회귀일
// 매입 금융기관 정보
customer.put("pur_bank_cd", extractJsonValue(json, "jiroCd")); // 매입은행코드
customer.put("pur_bank_nm", extractJsonValue(json, "jiroNm")); // 매입은행명
customer.put("pur_branch_nm", extractJsonValue(json, "placeNm")); // 매입지점명
customer.put("pur_account_no", extractJsonValue(json, "baNb")); // 매입계좌번호
customer.put("pur_account_holder", extractJsonValue(json, "depositor")); // 매입예금주
customer.put("pur_pay_plan", extractJsonValue(json, "stOutSettlePay")); // 매입지급예정일
customer.put("pur_slip_type", extractJsonValue(json, "stOutAcct1Fg")); // 매입전표유형
customer.put("pur_tax_type", extractJsonValue(json, "stOutTax1Fg")); // 매입세무구분
// 매출 금융기관 정보
customer.put("sale_bank_cd", extractJsonValue(json, "btrCd")); // 매출은행코드
customer.put("sale_bank_nm", extractJsonValue(json, "btrCd")); // 매출은행명
customer.put("sale_branch_nm", extractJsonValue(json, "stInDummy2")); // 매출지점명
customer.put("sale_account_no", extractJsonValue(json, "stInBaNb")); // 매출계좌번호
customer.put("sale_collect_plan", extractJsonValue(json, "stInSettlePay")); // 매출수금예정일
customer.put("sale_slip_type", extractJsonValue(json, "stInAcct1Fg")); // 매출전표유형
customer.put("sale_tax_type", extractJsonValue(json, "stInTax1Fg")); // 매출세무구분
// 거래처 담당자 정보
customer.put("vendor_dept_nm", extractJsonValue(json, "stempgrpTrchargeDept")); // 거래처부서명
customer.put("vendor_position", extractJsonValue(json, "stempgrpTrchargeTitle")); // 거래처직급
customer.put("vendor_duty", extractJsonValue(json, "stempgrpTrchargeJop")); // 거래처담당업무
customer.put("vendor_manager_nm", extractJsonValue(json, "stempgrpTrchargeEmp")); // 거래처담당자명
customer.put("vendor_tel", extractJsonValue(json, "stempgrpTrchargeTel")); // 거래처전화번호
customer.put("vendor_ext", extractJsonValue(json, "stempgrpTrchargeExt")); // 거래처내선
customer.put("vendor_mobile", extractJsonValue(json, "stempgrpTrchargeHp")); // 거래처휴대폰
customer.put("vendor_email", extractJsonValue(json, "stempgrpTrchargeEmail")); // 거래처이메일
// 관리담당자 정보
customer.put("mgr_dept_cd", extractJsonValue(json, "stempDeptCd")); // 관리부서코드
customer.put("mgr_dept_nm", extractJsonValue(json, "stempDeptNm")); // 관리부서명
customer.put("mgr_position", extractJsonValue(json, "stempTitleDc")); // 관리직급
customer.put("mgr_duty", extractJsonValue(json, "stempJobDc")); // 관리담당업무
customer.put("mgr_emp_cd", extractJsonValue(json, "stempEmpCd")); // 관리사원코드
customer.put("mgr_emp_nm", extractJsonValue(json, "stempEmpNm")); // 관리사원명
customer.put("mgr_tel", extractJsonValue(json, "stempTel")); // 관리전화번호
customer.put("mgr_ext", extractJsonValue(json, "stempTelDc")); // 관리내선
customer.put("mgr_mobile", extractJsonValue(json, "stempHp")); // 관리휴대폰
customer.put("mgr_email", extractJsonValue(json, "stempEmail")); // 관리이메일
customer.put("mgr_remark", extractJsonValue(json, "stempRmkDc")); // 관리비고
// 수신처 정보
customer.put("rec_remark", extractJsonValue(json, "streceiveRmkDc")); // 수신처비고
customer.put("rec_post_no", extractJsonValue(json, "streceiveZip")); // 수신처우편번호
customer.put("rec_addr1", extractJsonValue(json, "streceiveAddr1")); // 수신처주소1
customer.put("rec_addr2", extractJsonValue(json, "streceiveAddr2")); // 수신처주소2
customer.put("rec_tel", extractJsonValue(json, "streceiveTel")); // 수신처전화번호
customer.put("rec_fax", extractJsonValue(json, "streceiveFax")); // 수신처팩스
// 프로젝트 정보
customer.put("project_cd", extractJsonValue(json, "pjtCd")); // 프로젝트코드
customer.put("project_nm", extractJsonValue(json, "pjtNm")); // 프로젝트명
customer.put("pjt_nmk", extractJsonValue(json, "pjtNm")); // 프로젝트명(한글)
// 기타 정보
customer.put("ext_data_cd", extractJsonValue(json, "linkCd")); // 외부데이터코드
customer.put("e_tax_yn", extractJsonValue(json, "jeonjaYn")); // 전자세금계산서여부
customer.put("unit_report_client", extractJsonValue(json, "reptrCd")); // 단위신고거래처
customer.put("sub_bus_no", extractJsonValue(json, "apprNb")); // 종사업장번호
customer.put("procurement_yn", extractJsonValue(json, "ppsFg")); // 조달청다수공급자
customer.put("use_fg", extractJsonValue(json, "liqFg")); // 용도구분
customer.put("for_yn", extractJsonValue(json, "forYn")); // 내외국인여부
customer.put("plan_day_type", extractJsonValue(json, "doudate1Fg")); // 예정일구분
customer.put("plan_day", extractJsonValue(json, "doudate1Dd")); // 예정일
customer.put("purpose_type", extractJsonValue(json, "liqFg")); // 용도구분
// 등록/수정 정보
customer.put("insert_dt", extractJsonValue(json, "insertDt")); // 삽입일자
customer.put("modify_dt", extractJsonValue(json, "modifyDt")); // 수정일
customer.put("insert_id", "batch_system"); // 등록자
customer.put("modify_id", "batch_system"); // 수정자
return customer;
}
/**
* 부서 JSON 파싱
*/
private List<Map<String, Object>> parseDepartmentJson(String jsonResponse) {
List<Map<String, Object>> deptList = new ArrayList<Map<String, Object>>();
try {
int dataStart = jsonResponse.indexOf("\"resultData\":[");
if (dataStart == -1) {
return deptList;
}
String dataSection = jsonResponse.substring(dataStart + 14);
int bracketCount = 0;
int startIdx = -1;
for (int i = 0; i < dataSection.length(); i++) {
char c = dataSection.charAt(i);
if (c == '{') {
if (bracketCount == 0) {
startIdx = i;
}
bracketCount++;
} else if (c == '}') {
bracketCount--;
if (bracketCount == 0 && startIdx != -1) {
String deptJson = dataSection.substring(startIdx, i + 1);
Map<String, Object> dept = parseDepartmentObject(deptJson);
if (dept != null) {
deptList.add(dept);
}
startIdx = -1;
}
}
}
} catch (Exception e) {
System.err.println("부서 JSON 파싱 오류: " + e.getMessage());
}
return deptList;
}
/**
* 부서 객체 파싱 (실제 JSON 응답 기준으로 dept_info 테이블 매핑)
*/
private Map<String, Object> parseDepartmentObject(String json) {
Map<String, Object> dept = new HashMap<String, Object>();
// JSON 필드 → dept_info 테이블 컬럼 매핑
dept.put("dept_code", extractJsonValue(json, "deptCd")); // 부서코드 (deptCd)
dept.put("parent_dept_code", extractJsonValue(json, "parentDeptCd")); // 상위부서코드 (parentDeptCd)
dept.put("dept_name", extractJsonValue(json, "deptNm")); // 부서명 (deptNm)
dept.put("status", "active"); // 상태 (기본값 active)
dept.put("data_type", "ERP"); // 데이터유형
return dept;
}
/**
* 사원 JSON 파싱
*/
private List<Map<String, Object>> parseEmployeeJson(String jsonResponse) {
List<Map<String, Object>> empList = new ArrayList<Map<String, Object>>();
try {
int dataStart = jsonResponse.indexOf("\"resultData\":[");
if (dataStart == -1) {
return empList;
}
String dataSection = jsonResponse.substring(dataStart + 14);
int bracketCount = 0;
int startIdx = -1;
for (int i = 0; i < dataSection.length(); i++) {
char c = dataSection.charAt(i);
if (c == '{') {
if (bracketCount == 0) {
startIdx = i;
}
bracketCount++;
} else if (c == '}') {
bracketCount--;
if (bracketCount == 0 && startIdx != -1) {
String empJson = dataSection.substring(startIdx, i + 1);
Map<String, Object> emp = parseEmployeeObject(empJson);
if (emp != null) {
empList.add(emp);
}
startIdx = -1;
}
}
}
} catch (Exception e) {
System.err.println("사원 JSON 파싱 오류: " + e.getMessage());
}
return empList;
}
/**
* 사원 객체 파싱 (실제 JSON 응답 기준으로 user_info 테이블 매핑)
*/
private Map<String, Object> parseEmployeeObject(String json) {
Map<String, Object> emp = new HashMap<String, Object>();
// JSON 필드 → user_info 테이블 컬럼 매핑
emp.put("sabun", extractJsonValue(json, "empCd")); // 사번 (empCd)
emp.put("empseq", extractJsonValue(json, "empSeq")); // 사원 시퀀스 (empSeq) - Amaranth10 전자결재용
// user_id는 별도 LoginId 업데이트 배치에서 처리 (Amaranth10 API 사용)
emp.put("user_password", "5715e7d798fd421c7100c435e7547e82"); // 기본 비밀번호 (MD5 해시)
emp.put("user_name", extractJsonValue(json, "korNm")); // 사용자명 (korNm)
emp.put("user_name_eng", extractJsonValue(json, "enlsNm")); // 영문명 (enlsNm)
emp.put("dept_code", extractJsonValue(json, "deptCd")); // 부서코드 (deptCd)
emp.put("dept_name", extractJsonValue(json, "deptNm")); // 부서명 (deptNm)
emp.put("position_code", extractJsonValue(json, "hclsCd")); // 직급코드 (hclsCd)
emp.put("position_name", extractJsonValue(json, "hclsNm")); // 직급명 (hclsNm)
emp.put("rank", extractJsonValue(json, "hrspNm")); // 직책명 (hrspNm - 사원, 대리 등)
emp.put("email", extractJsonValue(json, "emalAdd")); // 이메일 (emalAdd)
emp.put("cell_phone", extractJsonValue(json, "emgcTel")); // 휴대폰 (emgcTel)
emp.put("user_type", extractJsonValue(json, "enrlFg")); // 사용자유형 (enrlFg - J01:재직)
emp.put("user_type_name", extractJsonValue(json, "enrlNm")); // 사용자유형명 (enrlNm)
// 재직구분에 따른 상태 설정 (J01:재직=active, 그 외=inActive)
String enrlFg = extractJsonValue(json, "enrlFg");
emp.put("status", "J01".equals(enrlFg) ? "active" : "inActive"); // 상태
// 퇴직일자 (rtrDt)
emp.put("end_date", extractJsonValue(json, "rtrDt")); // 종료일 (퇴직일)
emp.put("data_type", "ERP"); // 데이터유형
return emp;
}
/**
* JSON에서 특정 필드 값 추출
*/
private String extractJsonValue(String json, String fieldName) {
String searchKey = "\"" + fieldName + "\":";
int startIdx = json.indexOf(searchKey);
if (startIdx == -1) {
return "";
}
startIdx += searchKey.length();
// 공백 제거
while (startIdx < json.length() && Character.isWhitespace(json.charAt(startIdx))) {
startIdx++;
}
if (startIdx >= json.length()) {
return "";
}
char firstChar = json.charAt(startIdx);
// 문자열 값인 경우
if (firstChar == '"') {
int endIdx = json.indexOf('"', startIdx + 1);
if (endIdx == -1) return "";
return json.substring(startIdx + 1, endIdx);
}
// 숫자나 null인 경우
else {
int endIdx = startIdx;
while (endIdx < json.length() &&
(Character.isDigit(json.charAt(endIdx)) ||
json.charAt(endIdx) == '.' ||
json.charAt(endIdx) == '-' ||
json.charAt(endIdx) == 'n' ||
json.charAt(endIdx) == 'u' ||
json.charAt(endIdx) == 'l')) {
endIdx++;
}
String value = json.substring(startIdx, endIdx).trim();
if (value.startsWith("null")) {
return "";
}
return value;
}
}
/**
* 창고 JSON 파싱
*/
private List<Map<String, Object>> parseWarehouseJson(String jsonResponse) {
List<Map<String, Object>> warehouseList = new ArrayList<Map<String, Object>>();
try {
// resultData 배열 찾기
int dataStart = jsonResponse.indexOf("\"resultData\":[");
if (dataStart == -1) {
return warehouseList;
}
String dataSection = jsonResponse.substring(dataStart + 14);
int bracketCount = 0;
int startIdx = -1;
for (int i = 0; i < dataSection.length(); i++) {
char c = dataSection.charAt(i);
if (c == '{') {
if (bracketCount == 0) {
startIdx = i;
}
bracketCount++;
} else if (c == '}') {
bracketCount--;
if (bracketCount == 0 && startIdx != -1) {
String warehouseJson = dataSection.substring(startIdx, i + 1);
Map<String, Object> warehouse = parseWarehouseObject(warehouseJson);
if (warehouse != null) {
warehouseList.add(warehouse);
}
startIdx = -1;
}
}
}
} catch (Exception e) {
System.err.println("창고 JSON 파싱 오류: " + e.getMessage());
}
return warehouseList;
}
/**
* 창고 객체 파싱
*/
private Map<String, Object> parseWarehouseObject(String json) {
Map<String, Object> warehouse = new HashMap<String, Object>();
// location_code를 objid에도 동일하게 저장
String locationCode = extractJsonValue(json, "baselocCd");
warehouse.put("objid", locationCode);
warehouse.put("location_code", locationCode);
// 기본 정보
warehouse.put("location_name", extractJsonValue(json, "baselocNm"));
warehouse.put("location_description", extractJsonValue(json, "baselocDc"));
warehouse.put("out_code", extractJsonValue(json, "outlocCd"));
warehouse.put("out_co_name", extractJsonValue(json, "outlocNm"));
// 상태 정보
String baselocFg = extractJsonValue(json, "baselocFg");
warehouse.put("fit_status", baselocFg);
String useYn = extractJsonValue(json, "useYn");
warehouse.put("available_status", useYn);
warehouse.put("use_status", "1".equals(useYn) ? "Y" : "N");
// 추가 정보
warehouse.put("base_loc_cd", extractJsonValue(json, "baselocCd"));
warehouse.put("co_cd", extractJsonValue(json, "coCd"));
warehouse.put("loc_nmk", extractJsonValue(json, "baselocNm"));
warehouse.put("attr_nmk", extractJsonValue(json, "inlocNm"));
// 시스템 정보
warehouse.put("insert_id", "batch_system");
warehouse.put("writer", "batch_system");
warehouse.put("status", "active");
return warehouse;
}
/**
* 전체 PART 정보를 ERP로 전송 (수동 실행)
* @return 성공 여부 Map
*/
public Map<String, Object> sendAllPartsToErp() {
Map<String, Object> result = new HashMap<String, Object>();
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
System.out.println("====================================");
System.out.println("전체 PART 정보 ERP 전송 시작");
System.out.println("====================================");
try {
String baseUrl = "https://erp.rps-korea.com";
// DB에서 전체 PART 목록 조회
List<Map<String, Object>> partList = sqlSession.selectList("partMng.selectAllPartListForErp");
if (partList == null || partList.isEmpty()) {
result.put("success", false);
result.put("message", "전송할 PART 정보가 없습니다.");
return result;
}
PartErpApiClient partErpClient = new PartErpApiClient();
int successCount = 0;
int failCount = 0;
StringBuilder errorMessages = new StringBuilder();
System.out.println("" + partList.size() + "건의 PART를 ERP로 전송합니다...");
for (int i = 0; i < partList.size(); i++) {
Map<String, Object> part = partList.get(i);
try {
// DB에서 가져온 값
String itemCd = CommonUtils.checkNull(part.get("part_no"));
String itemNm = CommonUtils.checkNull(part.get("part_name"));
String acctFg = CommonUtils.checkNull(part.get("acctfg"));
String odrFg = CommonUtils.checkNull(part.get("odrfg"));
String itemDc = CommonUtils.checkNull(part.get("spec"));
// 회사코드 고정값
String coCd = "1000";
// DB에서 가져온 ERP 연동 필드
String unitDc = CommonUtils.checkNull(part.get("unit_dc"));
String unitmangDc = CommonUtils.checkNull(part.get("unitmang_dc"));
String unitchngNbStr = CommonUtils.checkNull(part.get("unitchng_nb"));
int unitchngNb = 0;
try {
if (!unitchngNbStr.isEmpty()) {
unitchngNb = (int) Double.parseDouble(unitchngNbStr);
}
} catch (Exception e) {
// 변환 실패 시 0 유지
}
String lotFg = CommonUtils.checkNull(part.get("lot_fg"));
String qcFg = CommonUtils.checkNull(part.get("qc_fg"));
String reqFg = CommonUtils.checkNull(part.get("req_fg"));
String setitemFg = CommonUtils.checkNull(part.get("setitem_fg"));
String useYn = CommonUtils.checkNull(part.get("use_yn"));
// 필수값 체크 - 모든 필수 필드가 있어야 ERP 전송
if (itemCd.isEmpty() || itemNm.isEmpty() || acctFg.isEmpty() || odrFg.isEmpty() ||
unitDc.isEmpty() || unitmangDc.isEmpty() || unitchngNb == 0 ||
lotFg.isEmpty() || qcFg.isEmpty() || reqFg.isEmpty() || setitemFg.isEmpty() || useYn.isEmpty()) {
failCount++;
continue;
}
// 진행 상황 로그 (100건마다)
if ((i + 1) % 100 == 0) {
System.out.println("진행 중... " + (i + 1) + "/" + partList.size() + " (성공: " + successCount + ", 실패: " + failCount + ")");
}
// ERP로 전송
String response = partErpClient.sendPartToErp(baseUrl, coCd, itemCd, itemNm,itemDc,
acctFg, odrFg, unitDc, unitmangDc, unitchngNb, lotFg, qcFg, reqFg, setitemFg, useYn);
// 응답 확인
if (response.contains("\"resultCode\":0") || response.contains("\"resultCode\":\"0\"")) {
successCount++;
} else {
failCount++;
if (failCount <= 5) {
errorMessages.append(itemCd).append(": ").append(response).append("\n");
}
}
} catch (Exception e) {
failCount++;
if (failCount <= 5) {
errorMessages.append(CommonUtils.checkNull(part.get("part_no"))).append(": ")
.append(e.getMessage()).append("\n");
}
}
}
result.put("success", true);
result.put("message", "PART 전송 완료 - 성공: " + successCount + "건, 실패: " + failCount + "");
if (errorMessages.length() > 0) {
result.put("errors", errorMessages.toString());
}
System.out.println("====================================");
System.out.println("PART 전송 완료 - 성공: " + successCount + "건, 실패: " + failCount + "");
System.out.println("====================================");
} catch (Exception e) {
result.put("success", false);
result.put("message", "PART 전송 중 오류가 발생했습니다: " + e.getMessage());
System.err.println("PART 전송 오류: " + e.getMessage());
e.printStackTrace();
} finally {
sqlSession.close();
}
return result;
}
/**
* 단일 PART 정보를 ERP로 전송
* @param partObjid PART OBJID
* @return 성공 여부 Map
*/
public Map<String, Object> sendSinglePartToErp(String partObjid) {
Map<String, Object> result = new HashMap<String, Object>();
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
try {
String baseUrl = "https://erp.rps-korea.com";
// DB에서 PART 정보 조회
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("objid", partObjid);
Map<String, Object> part = sqlSession.selectOne("partMng.selectPartByObjid", paramMap);
if (part == null) {
result.put("success", false);
result.put("message", "PART 정보를 찾을 수 없습니다.");
return result;
}
// DB에서 가져온 값
String itemCd = CommonUtils.checkNull(part.get("part_no"));
String itemNm = CommonUtils.checkNull(part.get("part_name"));
String acctFg = CommonUtils.checkNull(part.get("acctfg"));
String odrFg = CommonUtils.checkNull(part.get("odrfg"));
String itemDc = CommonUtils.checkNull(part.get("spec"));
// 회사코드 고정값
String coCd = "1000";
// DB에서 가져온 ERP 연동 필드
String unitDc = CommonUtils.checkNull(part.get("unit_dc"));
String unitmangDc = CommonUtils.checkNull(part.get("unitmang_dc"));
String unitchngNbStr = CommonUtils.checkNull(part.get("unitchng_nb"));
int unitchngNb = 0;
try {
if (!unitchngNbStr.isEmpty()) {
unitchngNb = (int) Double.parseDouble(unitchngNbStr);
}
} catch (Exception e) {
// 변환 실패 시 0 유지
}
String lotFg = CommonUtils.checkNull(part.get("lot_fg"));
String qcFg = CommonUtils.checkNull(part.get("qc_fg"));
String reqFg = CommonUtils.checkNull(part.get("req_fg"));
String setitemFg = CommonUtils.checkNull(part.get("setitem_fg"));
String useYn = CommonUtils.checkNull(part.get("use_yn"));
// 필수값 체크 - 모든 필수 필드가 있어야 ERP 전송
if (itemCd.isEmpty() || itemNm.isEmpty()) {
result.put("success", false);
result.put("message", "품번 또는 품명이 없습니다.");
return result;
}
if (acctFg.isEmpty() || odrFg.isEmpty()) {
result.put("success", false);
result.put("message", "계정구분 또는 조달구분이 없습니다.");
return result;
}
if (unitDc.isEmpty() || unitmangDc.isEmpty() || unitchngNb == 0) {
result.put("success", false);
result.put("message", "재고단위, 관리단위, 환산수량이 없습니다.");
return result;
}
if (lotFg.isEmpty() || qcFg.isEmpty() || reqFg.isEmpty() || setitemFg.isEmpty() || useYn.isEmpty()) {
result.put("success", false);
result.put("message", "LOT구분, 검사여부, 의뢰여부, SET품여부, 사용여부가 없습니다.");
return result;
}
// ERP로 전송 - 전송 데이터 로그 출력
System.out.println("====== ERP 전송 데이터 ======");
System.out.println("coCd: " + coCd);
System.out.println("itemCd(품번): " + itemCd);
System.out.println("itemNm(품명): " + itemNm);
System.out.println("itemDc(규격): " + itemDc);
System.out.println("acctFg(계정구분): " + acctFg);
System.out.println("odrFg(조달구분): " + odrFg);
System.out.println("unitDc(재고단위): " + unitDc);
System.out.println("unitmangDc(관리단위): " + unitmangDc);
System.out.println("unitchngNb(환산수량): " + unitchngNb);
System.out.println("lotFg(LOT구분): " + lotFg);
System.out.println("qcFg(검사여부): " + qcFg);
System.out.println("reqFg(의뢰여부): " + reqFg);
System.out.println("setitemFg(SET품여부): " + setitemFg);
System.out.println("useYn(사용여부): " + useYn);
System.out.println("=============================");
PartErpApiClient partErpClient = new PartErpApiClient();
String response = partErpClient.sendPartToErp(baseUrl, coCd, itemCd, itemNm, itemDc,
acctFg, odrFg, unitDc, unitmangDc, unitchngNb, lotFg, qcFg, reqFg, setitemFg, useYn);
System.out.println("ERP 응답: " + response);
// 응답 확인
if (response.contains("\"resultCode\":0") || response.contains("\"resultCode\":\"0\"")) {
result.put("success", true);
result.put("message", "PART 정보가 ERP로 전송되었습니다.");
} else {
result.put("success", false);
result.put("message", "ERP 전송 실패: " + response);
}
} catch (Exception e) {
result.put("success", false);
result.put("message", "PART 전송 중 오류가 발생했습니다: " + e.getMessage());
System.err.println("PART 전송 오류: " + e.getMessage());
e.printStackTrace();
} finally {
sqlSession.close();
}
return result;
}
/**
* major_category를 acctFg로 변환
* 0:원재료,1:부재료,2:제품,4:반제품,5:상품,6:저장품,7:비용,8:수익
*/
private String convertAcctFg(String majorCategory) {
if (majorCategory == null || majorCategory.isEmpty()) {
return "7"; // 기본값: 비용
}
// major_category 값에 따라 매핑
if (majorCategory.contains("원재료")) return "0";
if (majorCategory.contains("부재료")) return "1";
if (majorCategory.contains("제품")) return "2";
if (majorCategory.contains("반제품")) return "4";
if (majorCategory.contains("상품")) return "5";
if (majorCategory.contains("저장품")) return "6";
if (majorCategory.contains("비용")) return "7";
if (majorCategory.contains("수익")) return "8";
return "7"; // 기본값: 비용
}
/**
* sub_category를 odrFg로 변환
* 0:구매,1:생산,8:Phantom
*/
private String convertOdrFg(String subCategory) {
if (subCategory == null || subCategory.isEmpty()) {
return "0"; // 기본값: 구매
}
// sub_category 값에 따라 매핑
if (subCategory.contains("구매")) return "0";
if (subCategory.contains("생산")) return "1";
if (subCategory.contains("Phantom") || subCategory.contains("phantom")) return "8";
return "0"; // 기본값: 구매
}
/*
// ERP에서 PART 정보 삭제 (주석처리: ERP 전송된 데이터는 삭제하면 안됨)
public Map<String, Object> deletePartFromErp(String partNo) {
Map<String, Object> result = new HashMap<String, Object>();
try {
String baseUrl = "https://erp.rps-korea.com";
String coCd = "1000";
if (partNo == null || partNo.trim().isEmpty()) {
result.put("success", false);
result.put("message", "품번이 없습니다.");
return result;
}
// ERP에서 삭제
PartErpDeleteApiClient deleteClient = new PartErpDeleteApiClient();
String response = deleteClient.deletePartFromErp(baseUrl, coCd, partNo);
// 응답 확인
if (response.contains("\"resultCode\":0") || response.contains("\"resultCode\":\"0\"")) {
result.put("success", true);
result.put("message", "PART 정보가 ERP에서 삭제되었습니다.");
System.out.println("ERP PART 삭제 성공: " + partNo);
} else {
result.put("success", false);
result.put("message", "ERP 삭제 실패: " + response);
System.err.println("ERP PART 삭제 실패: " + partNo + " - " + response);
}
} catch (Exception e) {
result.put("success", false);
result.put("message", "PART 삭제 중 오류가 발생했습니다: " + e.getMessage());
System.err.println("PART 삭제 오류: " + e.getMessage());
e.printStackTrace();
}
return result;
}
*/
/**
* ERP에 PART 단건 수정
* @param partObjid PART OBJID
* @return 성공 여부 Map
*/
public Map<String, Object> updatePartToErp(String partObjid) {
Map<String, Object> result = new HashMap<String, Object>();
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
try {
String baseUrl = "https://erp.rps-korea.com";
// DB에서 PART 정보 조회
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("objid", partObjid);
Map<String, Object> part = sqlSession.selectOne("partMng.selectPartByObjid", paramMap);
if (part == null) {
result.put("success", false);
result.put("message", "PART 정보를 찾을 수 없습니다.");
return result;
}
// DB에서 가져온 값
String itemCd = CommonUtils.checkNull(part.get("part_no"));
String itemNm = CommonUtils.checkNull(part.get("part_name"));
String acctFg = CommonUtils.checkNull(part.get("acctfg"));
String odrFg = CommonUtils.checkNull(part.get("odrfg"));
String itemDc = CommonUtils.checkNull(part.get("spec"));
// 하드코딩 고정값
String coCd = "1000"; // 회사코드
String unitDc = "1"; // 단위
String unitmangDc = "1"; // 단위관리
int unitchngNb = 1; // 단위변환
String lotFg = "0"; // LOT구분
String qcFg = "0"; // 검사구분
String reqFg = "0"; // 청구구분
String setitemFg = "0"; // 세트품목구분
String useYn = "1"; // 사용여부
// 필수값 체크
if (itemCd.isEmpty() || itemNm.isEmpty()) {
result.put("success", false);
result.put("message", "품번 또는 품명이 없습니다.");
return result;
}
// ERP로 수정 전송
PartErpUpdateApiClient updateClient = new PartErpUpdateApiClient();
String response = updateClient.updatePartToErp(baseUrl, coCd, itemCd, itemNm, itemDc,
acctFg, odrFg, unitDc, unitmangDc, unitchngNb, lotFg, qcFg, reqFg, setitemFg, useYn);
// 응답 확인
if (response.contains("\"resultCode\":0") || response.contains("\"resultCode\":\"0\"")) {
result.put("success", true);
result.put("message", "PART 정보가 ERP에서 수정되었습니다.");
System.out.println("ERP PART 단건 수정 성공: " + itemCd);
} else {
result.put("success", false);
result.put("message", "ERP 수정 실패: " + response);
System.err.println("ERP PART 단건 수정 실패: " + itemCd + " - " + response);
}
} catch (Exception e) {
result.put("success", false);
result.put("message", "PART 수정 중 오류가 발생했습니다: " + e.getMessage());
System.err.println("PART 단건 수정 오류: " + e.getMessage());
e.printStackTrace();
} finally {
sqlSession.close();
}
return result;
}
/**
* ERP에 모든 PART 전체 수정 (DB의 모든 release 상태 PART)
* @return 성공 여부 Map
*/
public Map<String, Object> updateAllPartsToErp() {
Map<String, Object> result = new HashMap<String, Object>();
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
try {
String baseUrl = "https://erp.rps-korea.com";
System.out.println("====================================");
System.out.println("전체 PART 정보 ERP 수정 시작");
System.out.println("====================================");
// DB에서 모든 release 상태 PART 조회
List<Map<String, Object>> partList = sqlSession.selectList("partMng.selectAllPartListForErp");
if (partList == null || partList.isEmpty()) {
result.put("success", false);
result.put("message", "수정할 PART가 없습니다.");
return result;
}
System.out.println("" + partList.size() + "건의 PART를 ERP에 수정 전송합니다.");
int successCount = 0;
int failCount = 0;
StringBuilder errorMessages = new StringBuilder();
// 하드코딩 고정값
String coCd = "1000";
String unitDc = "1";
String unitmangDc = "1";
int unitchngNb = 1;
String lotFg = "0";
String qcFg = "0";
String reqFg = "0";
String setitemFg = "0";
String useYn = "1";
PartErpUpdateApiClient updateClient = new PartErpUpdateApiClient();
for (int i = 0; i < partList.size(); i++) {
Map<String, Object> part = partList.get(i);
try {
// DB에서 가져온 값
String itemCd = CommonUtils.checkNull(part.get("part_no"));
String itemNm = CommonUtils.checkNull(part.get("part_name"));
String acctFg = CommonUtils.checkNull(part.get("acctfg"));
String odrFg = CommonUtils.checkNull(part.get("odrfg"));
String itemDc = CommonUtils.checkNull(part.get("spec"));
// 100건마다 진행 상황 출력
if ((i + 1) % 100 == 0) {
System.out.println("진행 중: " + (i + 1) + "/" + partList.size() + " (성공: " + successCount + ", 실패: " + failCount + ")");
}
// 필수값 체크
if (itemCd.isEmpty() || itemNm.isEmpty()) {
failCount++;
if (failCount <= 5) {
errorMessages.append(itemCd).append(": 품번 또는 품명이 없습니다.\n");
}
continue;
}
// ERP로 수정 전송
String response = updateClient.updatePartToErp(baseUrl, coCd, itemCd, itemNm, itemDc,
acctFg, odrFg, unitDc, unitmangDc, unitchngNb, lotFg, qcFg, reqFg, setitemFg, useYn);
// 응답 확인
if (response.contains("\"resultCode\":0") || response.contains("\"resultCode\":\"0\"")) {
successCount++;
} else {
failCount++;
if (failCount <= 5) {
errorMessages.append(itemCd).append(": ").append(response).append("\n");
}
}
} catch (Exception e) {
failCount++;
if (failCount <= 5) {
errorMessages.append(CommonUtils.checkNull(part.get("part_no"))).append(": ")
.append(e.getMessage()).append("\n");
}
}
}
result.put("success", true);
result.put("message", "PART 전체 수정 완료 - 성공: " + successCount + "건, 실패: " + failCount + "");
if (errorMessages.length() > 0) {
result.put("errors", errorMessages.toString());
}
System.out.println("====================================");
System.out.println("PART 전체 수정 완료 - 성공: " + successCount + "건, 실패: " + failCount + "");
System.out.println("====================================");
} catch (Exception e) {
result.put("success", false);
result.put("message", "PART 전체 수정 중 오류가 발생했습니다: " + e.getMessage());
System.err.println("PART 전체 수정 오류: " + e.getMessage());
e.printStackTrace();
} finally {
sqlSession.close();
}
return result;
}
}