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.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 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> 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(); } /** * 사원 정보만 동기화 (수동 실행) * @return 성공 여부 Map */ public Map syncEmployeeDataManual() { Map result = new HashMap(); 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; } /** * 부서 정보만 동기화 (수동 실행) * @return 성공 여부 Map */ public Map syncDepartmentDataManual() { Map result = new HashMap(); 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 syncCustomerDataManual() { Map result = new HashMap(); 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; } /** * 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); 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> customerList = parseCustomerJson(jsonResponse); int processCount = 0; // 처음 10건 로그 출력 System.out.println("===================================="); System.out.println("거래처 데이터 샘플 (최대 10건)"); System.out.println("===================================="); for (Map 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> deptList = parseDepartmentJson(jsonResponse); int processCount = 0; // 처음 10건 로그 출력 System.out.println("===================================="); System.out.println("부서 데이터 샘플 (최대 10건)"); System.out.println("===================================="); for (Map 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> empList = parseEmployeeJson(jsonResponse); int processCount = 0; // 처음 10건 로그 출력 System.out.println("===================================="); System.out.println("사원 데이터 샘플 (최대 10건)"); System.out.println("===================================="); for (Map 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); } } /** * 거래처 JSON 파싱 */ private List> parseCustomerJson(String jsonResponse) { List> customerList = new ArrayList>(); 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 customer = parseCustomerObject(customerJson); if (customer != null) { customerList.add(customer); } startIdx = -1; } } } } catch (Exception e) { System.err.println("거래처 JSON 파싱 오류: " + e.getMessage()); } return customerList; } /** * 거래처 객체 파싱 (실제 테이블 컬럼에 맞춤) */ private Map parseCustomerObject(String json) { Map customer = new HashMap(); // 기본 정보 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> parseDepartmentJson(String jsonResponse) { List> deptList = new ArrayList>(); 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 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 parseDepartmentObject(String json) { Map dept = new HashMap(); // 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> parseEmployeeJson(String jsonResponse) { List> empList = new ArrayList>(); 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 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 parseEmployeeObject(String json) { Map emp = new HashMap(); // JSON 필드 → user_info 테이블 컬럼 매핑 emp.put("sabun", extractJsonValue(json, "empCd")); // 사번 (empCd) emp.put("user_id", extractJsonValue(json, "empCd")); // 사용자ID (empCd) 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("(주)RPS", 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; } } }