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

2419 lines
81 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.pms.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;
import com.pms.common.JsonUtil;
import com.pms.common.Message;
import com.pms.common.SqlMapConfig;
import com.pms.common.bean.PersonBean;
import com.pms.common.utils.CommonUtils;
import com.pms.common.utils.Constants;
import com.pms.common.utils.SerialNoSyncUtil;
@Service
public class ProductionPlanningService {
/**
* 이슈관리 상세 조회
* @param paramMap
* @return
*/
public Map issueFormPopUp(HttpServletRequest request,Map paramMap){
Map resultMap = new HashMap();
SqlSession sqlSession = null;
try{
sqlSession = SqlMapConfig.getInstance().getSqlSession();
resultMap = sqlSession.selectOne("productionplanning.selectPlanningIssueInfo", paramMap);
}catch(Exception e){
e.printStackTrace();
}finally{
sqlSession.close();
}
return resultMap;
}
/** 이슈등록
* @param request
* @param paramMap
* @return
*/
public Map saveissueInfo(HttpServletRequest request, Map paramMap){
Map resultMap = new HashMap();
SqlSession sqlSession = null;
try{
sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
HttpSession session = request.getSession();
PersonBean person = (PersonBean)session.getAttribute(Constants.PERSON_BEAN);
String writer = CommonUtils.checkNull(person.getUserId());
paramMap.put("writer", writer);
int cnt = sqlSession.update("productionplanning.mergeissueInfo", paramMap);
if(cnt > 0){
resultMap.put("result", true);
resultMap.put("msg", Message.SAVE_SUCCESS);
}
sqlSession.commit();
}catch(Exception e){
sqlSession.rollback();
resultMap.put("result", false);
resultMap.put("msg", Message.SAVE_FAILED);
e.printStackTrace();
}finally{
sqlSession.close();
}
return resultMap;
}
/**
* 이슈 삭제
* @param request
* @param paramMap
* @return
*/
public Map planningDelete(HttpServletRequest request,Map paramMap){
Map resultMap = new HashMap();
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
try{
String checkParam = CommonUtils.checkNull(paramMap.get("checkArr"));
String[] targetObjIdList = checkParam.split(",");
if(null != targetObjIdList && 0 < targetObjIdList.length){
HttpSession session = request.getSession();
sqlSession = SqlMapConfig.getInstance().getSqlSession();
PersonBean person = (PersonBean)session.getAttribute(Constants.PERSON_BEAN);
String userId = person.getUserId();
for(int i=0;i<targetObjIdList.length;i++){
String objId = CommonUtils.checkNull(targetObjIdList[i]);
HashMap sqlParamMap = new HashMap();
sqlParamMap.put("OBJID", objId);
sqlSession.delete("productionplanning.planningDelete",sqlParamMap);
}
sqlSession.commit();
resultMap.put("result", true);
resultMap.put("msg", Message.DELETE_SUCCESS);
}
}catch(Exception e){
resultMap.put("result", false);
resultMap.put("msg", Message.DELETE_FAILED);
sqlSession.rollback();
throw e;
}finally{
sqlSession.close();
}
return resultMap;
}
/**
* 이슈 배포
* @param request
* @param paramMap
* @return
*/
public Map planningRelease(HttpServletRequest request,Map paramMap){
Map resultMap = new HashMap();
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
try{
String checkParam = CommonUtils.checkNull(paramMap.get("checkArr"));
String[] targetObjIdList = checkParam.split(",");
if(null != targetObjIdList && 0 < targetObjIdList.length){
HttpSession session = request.getSession();
sqlSession = SqlMapConfig.getInstance().getSqlSession();
PersonBean person = (PersonBean)session.getAttribute(Constants.PERSON_BEAN);
String userId = person.getUserId();
for(int i=0;i<targetObjIdList.length;i++){
String objId = CommonUtils.checkNull(targetObjIdList[i]);
HashMap sqlParamMap = new HashMap();
sqlParamMap.put("OBJID", objId);
sqlSession.update("productionplanning.planningrelease",sqlParamMap);
}
sqlSession.commit();
resultMap.put("result", true);
resultMap.put("msg", "배포되었습니다");
}
}catch(Exception e){
resultMap.put("result", false);
resultMap.put("msg", "배포에 실패하였습니다");
sqlSession.rollback();
throw e;
}finally{
sqlSession.close();
}
return resultMap;
}
/**
* 출고관리 PopUp 저장
* @param paramMap
* @return
*/
public Map<String,Object> saveReleaseMgmtInfo(HttpServletRequest request,Map paramMap){
Map resultMap = new HashMap();
SqlSession sqlSession = null;
try{
sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
String releaseWriter = CommonUtils.checkNull(paramMap.get("RELEASE_WRITER"));
String releaseDate = CommonUtils.checkNull(paramMap.get("RELEASE_DATE"));
if("".equals(releaseDate)){
paramMap.put("STATUS", "0000200");
}else{
paramMap.put("STATUS", "0000201");
}
paramMap.put("WRITER", releaseWriter);
System.out.println("paramMap :: " + paramMap);
sqlSession.insert("releaseMgmt.saveReleaseMgmtInfo", paramMap);
sqlSession.commit();
resultMap.put("result", true);
resultMap.put("msg", Message.SAVE_SUCCESS);
}catch(Exception e){
sqlSession.rollback();
resultMap.put("result", false);
resultMap.put("msg", Message.SAVE_FAILED);
e.printStackTrace();
}finally{
sqlSession.close();
}
return resultMap;
}
/**
* 조립 WBS
* @param paramMap
* @return
*/
public List getassemblyWbsList(HttpServletRequest request,Map paramMap){
List<Map<String,Object>> spareList = new ArrayList();
List<Map<String,Object>> resultList = new ArrayList();
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession();
try{
spareList = sqlSession.selectList("productionplanning.selectStructureAscendingList", paramMap);
int maxLevel = 0;
if(null != spareList && 0 < spareList.size()){
for(int i=0;i<spareList.size();i++){
Map resultMap = new HashMap();
resultMap = (HashMap)spareList.get(i);
int resultLevel = Integer.parseInt(CommonUtils.checkNull(resultMap.get("LEV"),"0"));
if(maxLevel < resultLevel){
maxLevel = resultLevel;
}
}
for(int i=0;i<spareList.size();i++){
Map resultMap = new HashMap();
resultMap = (HashMap)spareList.get(i);
resultMap.put("MAX_LEVEL", maxLevel);
int level = Integer.parseInt(CommonUtils.checkNull(resultMap.get("LEV"),"0"));
for(int j=0;j<maxLevel;j++){
String levelSymbol = "";
if((j+1) == level){
levelSymbol = "*";
}else{
levelSymbol = "";
}
resultMap.put("LEV_"+Integer.toString((j+1)), levelSymbol);
}
resultList.add(resultMap);
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
sqlSession.close();
}
return CommonUtils.toUpperCaseMapKey(resultList);
}
/** 공정등록
* @param request
* @param paramMap
* @return
*/
public Map saveassemblyList(HttpServletRequest request, Map paramMap){
Map resultMap = new HashMap();
SqlSession sqlSession = null;
try{
sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
HttpSession session = request.getSession();
PersonBean person = (PersonBean)session.getAttribute(Constants.PERSON_BEAN);
String personId = CommonUtils.checkNull(person.getUserId());
String[] targetObjList = request.getParameterValues("PART_OBJID"); //PART_BOM_QTY_OBJID
String[] targetObjList2 = request.getParameterValues("CHILD_OBJID"); //PART_BOM_QTY_OBJID
if(null != targetObjList && 0 < targetObjList.length){
//for(String PART_BOM_QTY_OBJID:targetObjList){
Map saveMap = new HashMap();
Map dateMap = new HashMap();
for(int i=0; i<targetObjList.length; i++){
String objid = CommonUtils.nvl(CommonUtils.getValueInArray(i,request.getParameterValues("OBJID")),CommonUtils.createObjId());
saveMap.put("OBJID", objid);
saveMap.put("CHILD_OBJID", targetObjList2[i]);
saveMap.put("PART_OBJID", targetObjList[i]);
saveMap.put("PARENT_OBJID" , CommonUtils.checkNull(CommonUtils.getValueInArray(i,request.getParameterValues("PARENT_OBJID"))));
//saveMap.put("RECEIVE_DATE" , CommonUtils.checkNull(CommonUtils.getValueInArray(i,request.getParameterValues("RECEIVE_DATE"))));
//saveMap.put("RECEIVE_QTY" , CommonUtils.checkNull(CommonUtils.getValueInArray(i,request.getParameterValues("RECEIVE_QTY"))));
//saveMap.put("RECEIVE_USER_ID" , CommonUtils.checkNull(CommonUtils.getValueInArray(i,request.getParameterValues("RECEIVE_USER_ID"))));
saveMap.put("ASSEMBLY_USER_ID" , CommonUtils.checkNull(CommonUtils.getValueInArray(i,request.getParameterValues("ASSEMBLY_USER_ID"))));
//saveMap.put("TRANSFER_USER_ID" , CommonUtils.checkNull(CommonUtils.getValueInArray(i,request.getParameterValues("TRANSFER_USER_ID"))));
saveMap.put("ASSEMBLY_DATE" , CommonUtils.checkNull(CommonUtils.getValueInArray(i,request.getParameterValues("ASSEMBLY_DATE"))));
saveMap.put("INSOURCING" , CommonUtils.checkNull(paramMap.get("INSOURCING_"+targetObjList[i])));
saveMap.put("OUTSOURCING" , CommonUtils.checkNull(paramMap.get("OUTSOURCING_"+targetObjList[i])));
/*saveMap.put("INSOURCING" , CommonUtils.checkNull(CommonUtils.getValueInArray(i,request.getParameterValues("INSOURCING"))));
saveMap.put("OUTSOURCING" , CommonUtils.checkNull(CommonUtils.getValueInArray(i,request.getParameterValues("OUTSOURCING"))));*/
saveMap.put("WRITER", personId);
saveMap.put("OBJID", objid);
System.out.println("saveMap -->"+saveMap);
sqlSession.update("productionplanning.mergeassemblyList", saveMap);
}
dateMap = sqlSession.selectOne("productionplanning.selectAssemblyDate", paramMap);
dateMap.putAll(paramMap);
sqlSession.update("project.mergeAssemblyDate",dateMap);
}
resultMap.put("result", true);
resultMap.put("msg", Message.SAVE_SUCCESS);
sqlSession.commit();
}catch(Exception e){
sqlSession.rollback();
resultMap.put("result", false);
resultMap.put("msg", Message.SAVE_FAILED);
e.printStackTrace();
}finally{
sqlSession.close();
}
return resultMap;
}
/**
* 담당자별 작업현황 리스트 (프로젝트)
* @param paramMap
* @return
*/
public List getWorkStatusByImployeeList(HttpServletRequest request,Map paramMap){
List<Map<String,Object>> resultList = new ArrayList();
SqlSession sqlSession = null;
try{
sqlSession = SqlMapConfig.getInstance().getSqlSession();
String countPerPage = CommonUtils.checkNull(request.getParameter("countPerPage"), Constants.ADMIN_COUNT_PER_PAGE+"");
paramMap.put("COUNT_PER_PAGE", Integer.parseInt(countPerPage));
//Map pageMap = (HashMap)sqlSession.selectOne("productionplanning.workStatusByImployeeListCnt", paramMap);
//pageMap = (HashMap)CommonUtils.setPagingInfo(request, pageMap);
///paramMap.put("PAGE_END", CommonUtils.checkNull(pageMap.get("PAGE_END")));
//paramMap.put("PAGE_START", CommonUtils.checkNull(pageMap.get("PAGE_START")));
resultList = (ArrayList)sqlSession.selectList("productionplanning.workStatusByImployeeList", paramMap);
}catch(Exception e){
e.printStackTrace();
}finally{
sqlSession.close();
}
return CommonUtils.toUpperCaseMapKey(resultList);
}
/**
* 담당자별 작업현황 리스트 (비프로젝트)
* @param paramMap
* @return
*/
public List getWorkStatusByImployeeNPList(HttpServletRequest request,Map paramMap){
List<Map<String,Object>> resultList = new ArrayList();
SqlSession sqlSession = null;
try{
sqlSession = SqlMapConfig.getInstance().getSqlSession();
String countPerPage = CommonUtils.checkNull(request.getParameter("countPerPage"), Constants.ADMIN_COUNT_PER_PAGE+"");
paramMap.put("COUNT_PER_PAGE", Integer.parseInt(countPerPage));
resultList = (ArrayList)sqlSession.selectList("productionplanning.workStatusByImployeeNPList", paramMap);
}catch(Exception e){
e.printStackTrace();
}finally{
sqlSession.close();
}
return CommonUtils.toUpperCaseMapKey(resultList);
}
/**
* 프로젝트별 작업현황 리스트
* @param paramMap
* @return
*/
public List getworkStatusByProjectList(HttpServletRequest request,Map paramMap){
List<Map<String,Object>> resultList = new ArrayList();
SqlSession sqlSession = null;
try{
sqlSession = SqlMapConfig.getInstance().getSqlSession();
String countPerPage = CommonUtils.checkNull(request.getParameter("countPerPage"), Constants.ADMIN_COUNT_PER_PAGE+"");
paramMap.put("COUNT_PER_PAGE", Integer.parseInt(countPerPage));
//Map pageMap = (HashMap)sqlSession.selectOne("productionplanning.workStatusByImployeeListCnt", paramMap);
//pageMap = (HashMap)CommonUtils.setPagingInfo(request, pageMap);
///paramMap.put("PAGE_END", CommonUtils.checkNull(pageMap.get("PAGE_END")));
//paramMap.put("PAGE_START", CommonUtils.checkNull(pageMap.get("PAGE_START")));
resultList = (ArrayList)sqlSession.selectList("productionplanning.workStatusByProjectList", paramMap);
}catch(Exception e){
e.printStackTrace();
}finally{
sqlSession.close();
}
return CommonUtils.toUpperCaseMapKey(resultList);
}
/**
* 생산관리 -> 공정실적 등록 History 조회
* @param paramMap
* @return
*/
public List getAssemblyWbsHistoryInfo(HttpServletRequest request, Map paramMap){
List<Map<String,Object>> resultList = new ArrayList();
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession();
try{
resultList = sqlSession.selectList("productionplanning.getAssemblyWbsHistoryList", paramMap);
}catch(Exception e){
e.printStackTrace();
}finally{
sqlSession.close();
}
return CommonUtils.toUpperCaseMapKey(resultList);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public Map deleteassemblyWbsHistoryList(HttpServletRequest request, Map paramMap){
Map resultMap = new HashMap();
SqlSession sqlSession = null;
try{
sqlSession = SqlMapConfig.getInstance().getSqlSession();
int cnt = sqlSession.update("productionplanning.deleteassemblyWbsHistoryList", paramMap);
if(cnt > 0){
resultMap.put("result", true);
resultMap.put("msg", Message.DELETE_SUCCESS);
}
}catch(Exception e){
resultMap.put("result", false);
resultMap.put("msg", Message.DELETE_FAILED);
e.printStackTrace();
}finally{
sqlSession.close();
}
return resultMap;
}
/** 인수인계 History 내용을 저장한다.
* @param request
* @param paramMap
* @return
*/
public Map saveAssemblyWbsHistory(HttpServletRequest request, Map paramMap){
Map resultMap = new HashMap();
SqlSession sqlSession = null;
try{
sqlSession = SqlMapConfig.getInstance().getSqlSession();
PersonBean person = (PersonBean)request.getSession().getAttribute(Constants.PERSON_BEAN);
paramMap.put("WRITER", person.getUserId());
String parentObjId = CommonUtils.checkNull(request.getParameter("projectObjId"));
String partObjList[] = request.getParameterValues("OBJID");
if(parentObjId != null){
HashMap sqlParamMap = new HashMap();
sqlParamMap.put("parentObjId", parentObjId);
sqlSession.delete("productionplanning.deleteAllAssemblyHistoryList",sqlParamMap);
}
if(null != partObjList && 0 < partObjList.length){
for(String targetObjId:partObjList){
Map sqlParamMep = new HashMap();
sqlParamMep.put("OBJID" , targetObjId);
sqlParamMep.put("PART_OBJID" , CommonUtils.checkNull(request.getParameter("PART_OBJID_"+targetObjId )));
sqlParamMep.put("PARENT_OBJID" , CommonUtils.checkNull(request.getParameter("PARENT_OBJID_"+targetObjId )));
sqlParamMep.put("TRANSFER_USER_ID" , CommonUtils.checkNull(request.getParameter("TRANSFER_USER_ID_"+targetObjId )));
sqlParamMep.put("RECEIVE_DATE" , CommonUtils.checkNull(request.getParameter("RECEIVE_DATE_"+targetObjId )));
sqlParamMep.put("RECEIVE_QTY" , CommonUtils.checkNull(request.getParameter("RECEIVE_QTY_"+targetObjId )));
sqlParamMep.put("RECEIVE_USER_ID" , CommonUtils.checkNull(request.getParameter("RECEIVE_USER_ID_"+targetObjId )));
sqlParamMep.put("WRITER" , paramMap.get("WRITER"));
System.out.println("sqlParamMep::"+sqlParamMep);
sqlSession.update("productionplanning.saveAssemblyWbsHistory", sqlParamMep);
}
}
resultMap.put("result", true);
resultMap.put("msg", Message.SAVE_SUCCESS);
sqlSession.commit();
}catch(Exception e){
sqlSession.rollback();
resultMap.put("result", false);
resultMap.put("msg", Message.SAVE_FAILED);
e.printStackTrace();
}finally{
sqlSession.close();
}
return resultMap;
}
/**
* 작업일지 상세 조회
* @param paramMap
* @return
*/
public Map workDiaryFormPopUp(HttpServletRequest request,Map paramMap){
Map resultMap = new HashMap();
SqlSession sqlSession = null;
try{
sqlSession = SqlMapConfig.getInstance().getSqlSession();
resultMap = sqlSession.selectOne("productionplanning.selectWorkDiaryInfo", paramMap);
}catch(Exception e){
e.printStackTrace();
}finally{
sqlSession.close();
}
return resultMap;
}
/** 작업일지 등록
* @param request
* @param paramMap
* @return
*/
public Map saveWorkDiaryInfo(HttpServletRequest request,Map paramMap){
Map resultMap = new HashMap();
SqlSession sqlSession = null;
List resultTempList = new ArrayList();
try{
sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
PersonBean person = (PersonBean)request.getSession().getAttribute(Constants.PERSON_BEAN);
List<Map<String, Object>> dataList = JsonUtil.JsonToList(CommonUtils.checkNull(paramMap.get("dataListJson")));
if(CommonUtils.isNotEmpty(dataList)){
for (Map<String, Object> data : dataList) {
String OBJID = CommonUtils.checkNull(data.get("OBJID"));
if (OBJID.isEmpty()) {
OBJID = CommonUtils.createObjId();
}
paramMap.put("objId" , OBJID);
paramMap.put("division" , data.get("DIVISION"));
paramMap.put("project_objid" , data.get("CONTRACT_OBJID"));
paramMap.put("unit_code" , data.get("UNIT_CODE"));
paramMap.put("task_name" , data.get("TASK_NAME"));
paramMap.put("work_start_date" , data.get("WORK_START_DATE"));
paramMap.put("work_end_date" , data.get("WORK_END_DATE"));
paramMap.put("work_hour" , data.get("WORK_HOUR"));
paramMap.put("sourcing_type" , data.get("SOURCING_TYPE"));
paramMap.put("worker_id" , data.get("WORKER_ID"));
paramMap.put("remark" , data.get("REMARK"));
paramMap.put("production_type" , data.get("PRODUCTION_TYPE"));
paramMap.put("writer" , person.getUserId());
sqlSession.insert("productionplanning.mergeWorkDiaryInfo", paramMap);
}
}
resultMap.put("result", true);
resultMap.put("msg", Message.SAVE_SUCCESS);
sqlSession.commit();
}catch(Exception e){
sqlSession.rollback();
resultMap.put("result", false);
resultMap.put("msg", Message.SAVE_FAILED);
e.printStackTrace();
}finally{
sqlSession.close();
}
return resultMap;
}
/**
* 작업일지 삭제
* @param request
* @param paramMap
* @return
*/
public Map workDiaryDelete(HttpServletRequest request,Map paramMap){
Map resultMap = new HashMap();
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
try{
String checkParam = CommonUtils.checkNull(paramMap.get("checkArr"));
String[] targetObjIdList = checkParam.split(",");
if(null != targetObjIdList && 0 < targetObjIdList.length){
HttpSession session = request.getSession();
sqlSession = SqlMapConfig.getInstance().getSqlSession();
PersonBean person = (PersonBean)session.getAttribute(Constants.PERSON_BEAN);
String userId = person.getUserId();
for(int i=0;i<targetObjIdList.length;i++){
String objId = CommonUtils.checkNull(targetObjIdList[i]);
HashMap sqlParamMap = new HashMap();
sqlParamMap.put("OBJID", objId);
sqlSession.delete("productionplanning.workDiaryDelete",sqlParamMap);
}
sqlSession.commit();
resultMap.put("result", true);
resultMap.put("msg", Message.DELETE_SUCCESS);
}
}catch(Exception e){
resultMap.put("result", false);
resultMap.put("msg", Message.DELETE_FAILED);
sqlSession.rollback();
throw e;
}finally{
sqlSession.close();
}
return resultMap;
}
/**
* 작업일지 팀장 확인
* @param request
* @param paramMap
* @return
*/
public Map workDiaryConfirm(HttpServletRequest request,Map paramMap){
Map resultMap = new HashMap();
SqlSession sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
try{
String checkParam = CommonUtils.checkNull(paramMap.get("checkArr"));
String[] targetObjIdList = checkParam.split(",");
if(null != targetObjIdList && 0 < targetObjIdList.length){
HttpSession session = request.getSession();
sqlSession = SqlMapConfig.getInstance().getSqlSession();
PersonBean person = (PersonBean)session.getAttribute(Constants.PERSON_BEAN);
String userId = person.getUserId();
for(int i=0;i<targetObjIdList.length;i++){
String objId = CommonUtils.checkNull(targetObjIdList[i]);
HashMap sqlParamMap = new HashMap();
sqlParamMap.put("OBJID", objId);
sqlSession.update("productionplanning.workDiaryConfirm",sqlParamMap);
}
sqlSession.commit();
resultMap.put("result", true);
resultMap.put("msg", "확인되었습니다");
}
}catch(Exception e){
resultMap.put("result", false);
resultMap.put("msg", "확인에 실패하였습니다");
sqlSession.rollback();
throw e;
}finally{
sqlSession.close();
}
return resultMap;
}
/**
* E-BOM을 PROJECT_MGMT에 할당
* @param projectMgmtObjid
* @param bomReportObjid
* @return
* @throws Exception
*/
public int assignEbomToProject(String projectMgmtObjid, String bomReportObjid) throws Exception {
SqlSession sqlSession = null;
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession();
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("projectMgmtObjid", projectMgmtObjid);
paramMap.put("bomReportObjid", bomReportObjid);
int result = sqlSession.update("productionplanning.assignEbomToProject", paramMap);
sqlSession.commit();
return result;
} catch(Exception e) {
if(sqlSession != null) {
sqlSession.rollback();
}
throw e;
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
}
/**
* E-BOM 정보 조회
* @param bomReportObjid
* @return
*/
public Map<String, Object> getEbomInfo(String bomReportObjid) {
Map<String, Object> resultMap = new HashMap<>();
SqlSession sqlSession = null;
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession();
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("objid", bomReportObjid);
resultMap = sqlSession.selectOne("productionplanning.getEbomInfo", paramMap);
} catch(Exception e) {
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return resultMap;
}
/**
* M-BOM 저장
* @param request
* @param mbomData
* @param partNo
* @param partName
* @return
*/
public int saveMbom(HttpServletRequest request, List<Map<String, Object>> mbomData, String partNo, String partName) {
return saveMbom(request, mbomData, partNo, partName, "", false);
}
public int saveMbom(HttpServletRequest request, List<Map<String, Object>> mbomData, String partNo, String partName, String mbomPartNo, boolean isUpdate) {
SqlSession sqlSession = null;
int result = 0;
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
HttpSession session = request.getSession();
PersonBean person = (PersonBean)session.getAttribute(Constants.PERSON_BEAN);
String userId = CommonUtils.checkNull(person.getUserId());
if(isUpdate && !"".equals(mbomPartNo)) {
// M-BOM 수정: 기존 데이터 삭제 후 재저장 (동일 품번 유지)
// 기존 M-BOM 상세 데이터 삭제
Map<String, Object> deleteParam = new HashMap<>();
deleteParam.put("MBOM_PART_NO", mbomPartNo);
sqlSession.delete("productionplanning.deleteMbomDetailByPartNo", deleteParam);
// M-BOM 헤더 업데이트
Map<String, Object> headerMap = new HashMap<>();
headerMap.put("MBOM_PART_NO", mbomPartNo);
headerMap.put("PART_NO", partNo);
headerMap.put("PART_NAME", partName);
headerMap.put("UPDATE_USER", userId);
sqlSession.update("productionplanning.updateMbomHeader", headerMap);
// M-BOM 상세 데이터 재저장
for(Map<String, Object> item : mbomData) {
item.put("MBOM_PART_NO", mbomPartNo);
item.put("CREATE_USER", userId);
item.put("UPDATE_USER", userId);
sqlSession.insert("productionplanning.insertMbomDetail", item);
}
} else {
// M-BOM 신규 저장
// M-BOM 헤더 정보 생성
Map<String, Object> headerMap = new HashMap<>();
headerMap.put("PART_NO", partNo);
headerMap.put("PART_NAME", partName);
headerMap.put("CREATE_USER", userId);
headerMap.put("UPDATE_USER", userId);
// M-BOM 헤더 저장
sqlSession.insert("productionplanning.insertMbomHeader", headerMap);
String mbomHeaderObjid = (String) headerMap.get("OBJID");
// M-BOM 상세 데이터 저장
for(Map<String, Object> item : mbomData) {
item.put("MBOM_HEADER_OBJID", mbomHeaderObjid);
item.put("CREATE_USER", userId);
item.put("UPDATE_USER", userId);
sqlSession.insert("productionplanning.insertMbomDetail", item);
}
}
sqlSession.commit();
result = 1;
} catch(Exception e) {
if(sqlSession != null) {
sqlSession.rollback();
}
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return result;
}
/**
* M-BOM Part 연결 (E-BOM의 relatePartInfo와 동일한 로직)
* @param request
* @param paramMap
* @param partList
* @return
*/
public boolean relateMbomPartInfo(HttpServletRequest request, Map paramMap, List<String> partList){
boolean result = false;
SqlSession sqlSession = null;
try{
HttpSession session = request.getSession();
sqlSession = SqlMapConfig.getInstance().getSqlSession();
PersonBean person = (PersonBean)session.getAttribute(Constants.PERSON_BEAN);
Map info = person.getLoginInfo();
String userId = CommonUtils.checkNull(info.get("userId"));
Map sqlParamMap = new HashMap();
sqlParamMap.put("BOM_REPORT_OBJID", CommonUtils.checkNull(paramMap.get("BOM_REPORT_OBJID")));
sqlParamMap.put("PARENT_OBJID", CommonUtils.checkNull(paramMap.get("leftObjId")));
sqlParamMap.put("PARENT_PART_OBJID", CommonUtils.checkNull(paramMap.get("leftObjId")));
sqlParamMap.put("PARENT_PART_NO", CommonUtils.checkNull(paramMap.get("leftPartNoQty")));
sqlParamMap.put("PARENT_QTY_CHILD_OBJID", CommonUtils.checkNull(paramMap.get("leftPartChildObjId")));
sqlParamMap.put("QTY", 1);
sqlParamMap.put("QTY_TEMP", 1);
sqlParamMap.put("STATUS", "adding");
sqlParamMap.put("WRITER", userId);
// 각 Part를 BOM_PART_QTY 테이블에 삽입
for(String partObjId : partList){
sqlParamMap.put("OBJID", CommonUtils.createObjId());
sqlParamMap.put("CHILD_OBJID", CommonUtils.createObjId());
sqlParamMap.put("PART_NO", partObjId);
sqlSession.insert("partMng.relatePartInfo", sqlParamMap);
// 히스토리 저장
sqlParamMap.put("OBJID", CommonUtils.checkNull(partObjId));
sqlParamMap.put("OBJID_LEFT", CommonUtils.checkNull(paramMap.get("partObjId")));
sqlParamMap.put("CHANGE_TYPE", CommonUtils.checkNull(paramMap.get("CHANGE_TYPE")));
sqlParamMap.put("HIS_STATUS", "ADD");
sqlParamMap.put("CHANGE_OPTION", CommonUtils.checkNull(paramMap.get("CHANGE_OPTION")));
sqlSession.update("partMng.insertPartMngHistory",sqlParamMap);
}
// BOM 상태 변경
sqlSession.insert("partMng.changeStatusBomReport", sqlParamMap);
sqlSession.commit();
result = true;
}catch(Exception e){
if(sqlSession != null) {
sqlSession.rollback();
}
e.printStackTrace();
}finally{
if(sqlSession != null) {
sqlSession.close();
}
}
return result;
}
/**
* M-BOM Part 연결 해제 (E-BOM의 deleteStatusPartRelateInfo와 동일한 로직)
* @param request
* @param paramMap
* @return
*/
public boolean deleteMbomPartRelateInfo(HttpServletRequest request, Map paramMap){
boolean result = false;
SqlSession sqlSession = null;
try{
HttpSession session = request.getSession();
sqlSession = SqlMapConfig.getInstance().getSqlSession();
PersonBean person = (PersonBean)session.getAttribute(Constants.PERSON_BEAN);
Map info = person.getLoginInfo();
String userId = CommonUtils.checkNull(info.get("userId"));
Map sqlParamMap = new HashMap();
sqlParamMap.put("BOM_REPORT_OBJID", CommonUtils.checkNull(paramMap.get("BOM_REPORT_OBJID")));
sqlParamMap.put("OBJID", CommonUtils.checkNull(paramMap.get("leftObjId")));
sqlParamMap.put("PART_OBJID", CommonUtils.checkNull(paramMap.get("partObjId")));
sqlParamMap.put("leftPartChildObjId", CommonUtils.checkNull(paramMap.get("leftPartChildObjId")));
sqlParamMap.put("leftParentPartNo", CommonUtils.checkNull(paramMap.get("leftParentPartNo")));
sqlParamMap.put("leftParentObjId", CommonUtils.checkNull(paramMap.get("leftParentObjId")));
sqlParamMap.put("STATUS", "deleting");
sqlParamMap.put("WRITER", userId);
// BOM_PART_QTY 테이블에서 상태를 'deleting'으로 변경
sqlSession.update("partMng.deleteStatusPartRelateInfo", sqlParamMap);
// 히스토리 저장
sqlParamMap.put("HIS_STATUS", "DELETE");
sqlSession.update("partMng.insertPartMngHistory", sqlParamMap);
// BOM 상태 변경
sqlSession.insert("partMng.changeStatusBomReport", sqlParamMap);
sqlSession.commit();
result = true;
}catch(Exception e){
if(sqlSession != null) {
sqlSession.rollback();
}
e.printStackTrace();
}finally{
if(sqlSession != null) {
sqlSession.close();
}
}
return result;
}
/**
* M-BOM Part 변경 (E-BOM의 changeRelatePartInfo와 동일한 로직)
* @param request
* @param paramMap
* @return
*/
public boolean changeMbomPartInfo(HttpServletRequest request, Map paramMap){
boolean result = false;
SqlSession sqlSession = null;
try{
HttpSession session = request.getSession();
sqlSession = SqlMapConfig.getInstance().getSqlSession();
PersonBean person = (PersonBean)session.getAttribute(Constants.PERSON_BEAN);
Map info = person.getLoginInfo();
String userId = CommonUtils.checkNull(info.get("userId"));
Map sqlParamMap = new HashMap();
sqlParamMap.put("BOM_REPORT_OBJID", CommonUtils.checkNull(paramMap.get("BOM_REPORT_OBJID")));
sqlParamMap.put("OBJID", CommonUtils.checkNull(paramMap.get("OBJID")));
sqlParamMap.put("rightObjId", CommonUtils.checkNull(paramMap.get("rightObjId")));
sqlParamMap.put("leftObjId", CommonUtils.checkNull(paramMap.get("leftObjId")));
sqlParamMap.put("leftPartNoQty", CommonUtils.checkNull(paramMap.get("leftPartNoQty")));
sqlParamMap.put("leftPartChildObjId", CommonUtils.checkNull(paramMap.get("leftPartChildObjId")));
sqlParamMap.put("leftPartObjid", CommonUtils.checkNull(paramMap.get("leftPartObjid")));
sqlParamMap.put("rightPartNo", CommonUtils.checkNull(paramMap.get("rightPartNo")));
sqlParamMap.put("rightPartRev", CommonUtils.checkNull(paramMap.get("rightPartRev")));
sqlParamMap.put("WRITER", userId);
// BOM_PART_QTY 테이블에서 Part 변경
sqlSession.update("partMng.changeRelatePartInfo", sqlParamMap);
// 히스토리 저장
sqlParamMap.put("HIS_STATUS", "CHANGE");
sqlSession.update("partMng.insertPartMngHistory", sqlParamMap);
// BOM 상태 변경
sqlSession.insert("partMng.changeStatusBomReport", sqlParamMap);
sqlSession.commit();
result = true;
}catch(Exception e){
if(sqlSession != null) {
sqlSession.rollback();
}
e.printStackTrace();
}finally{
if(sqlSession != null) {
sqlSession.close();
}
}
return result;
}
/**
* BOM 할당 정보 저장
*/
public boolean saveBomAssignment(HttpServletRequest request, Map<String, Object> paramMap) {
SqlSession sqlSession = null;
boolean result = false;
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession(false); // 수동 커밋
String projectObjId = CommonUtils.checkNull(paramMap.get("projectObjId"));
// 1. 기존 M-BOM 데이터 비활성화 (새로운 BOM 할당 시 초기화)
if(!"".equals(projectObjId)) {
// 해당 프로젝트의 기존 활성 M-BOM HEADER 조회
Map<String, Object> queryParam = new HashMap<>();
queryParam.put("projectObjId", projectObjId);
List<Map<String, Object>> existingMboms = sqlSession.selectList("productionplanning.getActiveMbomsByProjectId", queryParam);
if(existingMboms != null && !existingMboms.isEmpty()) {
System.out.println("========== 기존 M-BOM 비활성화 ==========");
System.out.println("Project OBJID: " + projectObjId);
System.out.println("비활성화할 M-BOM 개수: " + existingMboms.size());
for(Map<String, Object> mbom : existingMboms) {
String mbomHeaderObjid = CommonUtils.checkNull(mbom.get("OBJID"));
if(!"".equals(mbomHeaderObjid)) {
Map<String, Object> inactivateParam = new HashMap<>();
inactivateParam.put("mbomHeaderObjid", mbomHeaderObjid);
// M-BOM DETAIL 비활성화
sqlSession.update("productionplanning.inactivateMbomDetail", inactivateParam);
// M-BOM HEADER 비활성화
sqlSession.update("productionplanning.inactivateMbomHeader", inactivateParam);
System.out.println("M-BOM 비활성화 완료: " + mbomHeaderObjid);
}
}
}
}
// 2. PROJECT_MGMT 업데이트 (새로운 BOM 할당 정보)
int updateCount = sqlSession.update("productionplanning.saveBomAssignment", paramMap);
result = (updateCount > 0);
sqlSession.commit();
} catch(Exception e) {
if(sqlSession != null) {
sqlSession.rollback();
}
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return result;
}
/**
* M-BOM 할당 정보 조회
*/
public Map<String, Object> getMbomAssignment(String projectObjId) {
SqlSession sqlSession = null;
Map<String, Object> result = null;
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession();
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("projectObjId", projectObjId);
result = sqlSession.selectOne("productionplanning.getMbomAssignment", paramMap);
} catch(Exception e) {
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return result;
}
/**
* M-BOM 품번 생성
* E-BOM 기준: M-{E-BOM품번}-YYMMDD-01
* M-BOM 기준: {기존품번앞부분}-YYMMDD-01
*/
public String generateMbomNo(HttpServletRequest request, String sourceBomType, String baseBomPartNo) {
SqlSession sqlSession = null;
String mbomNo = "";
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession();
mbomNo = generateMbomNo(sqlSession, sourceBomType, baseBomPartNo);
} catch(Exception e) {
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return mbomNo;
}
/**
* M-BOM 품번 생성 (기존 트랜잭션 공유)
*/
public String generateMbomNo(SqlSession sqlSession, String sourceBomType, String baseBomPartNo) {
String mbomNo = "";
try {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyMMdd");
String dateStr = sdf.format(new java.util.Date());
String mbomPrefix = "";
if("EBOM".equals(sourceBomType)) {
String cleanPartNo = baseBomPartNo;
if(cleanPartNo.startsWith("M-")) {
cleanPartNo = cleanPartNo.substring(2);
}
mbomPrefix = "M-" + cleanPartNo + "-" + dateStr;
} else if("TEMPLATE".equals(sourceBomType)) {
String cleanPartNo = baseBomPartNo.trim();
if(cleanPartNo.startsWith("M-")) {
cleanPartNo = cleanPartNo.substring(2);
}
mbomPrefix = "M-" + cleanPartNo + "-" + dateStr;
} else if("MBOM".equals(sourceBomType)) {
String basePart = baseBomPartNo;
while(basePart.startsWith("M-M-") || basePart.startsWith("M-E-")) {
basePart = "M-" + basePart.substring(4);
}
while(true) {
int lastDashIndex = basePart.lastIndexOf("-");
if(lastDashIndex > 0) {
String suffix = basePart.substring(lastDashIndex + 1);
if(suffix.matches("\\d{2}") || suffix.matches("\\d{6}")) {
basePart = basePart.substring(0, lastDashIndex);
} else {
break;
}
} else {
break;
}
}
mbomPrefix = basePart + "-" + dateStr;
}
Map<String, Object> seqParam = new HashMap<>();
seqParam.put("mbomPrefix", mbomPrefix);
Integer maxSeq = (Integer) sqlSession.selectOne("productionplanning.getMaxMbomSeqByDate", seqParam);
int nextSeq = (maxSeq != null ? maxSeq : 0) + 1;
mbomNo = mbomPrefix + "-" + String.format("%02d", nextSeq);
System.out.println("생성된 M-BOM 품번: " + mbomNo);
} catch(Exception e) {
e.printStackTrace();
}
return mbomNo;
}
/**
* M-BOM 저장
* 최초 저장: MBOM_HEADER, MBOM_DETAIL 생성
* 수정 저장: 기존 데이터 업데이트 + MBOM_HISTORY 이력 저장
*/
public boolean saveMbom(HttpServletRequest request, Map<String, Object> paramMap) {
SqlSession sqlSession = null;
boolean result = false;
try {
// 트랜잭션 처리를 위해 autoCommit = false로 설정
sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
// 세션에서 사용자 정보 가져오기
HttpSession session = request.getSession();
PersonBean person = (PersonBean)session.getAttribute(Constants.PERSON_BEAN);
String userId = CommonUtils.checkNull(person.getUserId());
paramMap.put("sessionUserId", userId);
boolean isUpdate = (Boolean) paramMap.get("isUpdate");
String mbomNo = (String) paramMap.get("mbomNo");
if(isUpdate) {
// 수정: 기존 M-BOM 조회 (최신 버전)
System.out.println("========== UPDATE M-BOM ==========");
System.out.println("projectObjId: " + paramMap.get("projectObjId"));
System.out.println("mbomNo: " + paramMap.get("mbomNo"));
Map<String, Object> existingMbom = sqlSession.selectOne("productionplanning.getMbomByNo", paramMap);
if(existingMbom != null) {
System.out.println("조회된 기존 M-BOM:");
System.out.println(" OBJID: " + existingMbom.get("OBJID"));
System.out.println(" MBOM_NO: " + existingMbom.get("MBOM_NO"));
System.out.println(" REGDATE: " + existingMbom.get("REGDATE"));
// 기존 M-BOM 상세 데이터 조회
Map<String, Object> detailParam = new HashMap<>();
detailParam.put("mbomHeaderObjid", existingMbom.get("OBJID"));
List<Map<String, Object>> existingDetails = sqlSession.selectList("productionplanning.getMbomDetailList", detailParam);
System.out.println("기존 M-BOM 상세 항목 수: " + existingDetails.size());
// 새 데이터
List<Map<String, Object>> mbomData = (List<Map<String, Object>>) paramMap.get("mbomData");
// 변경 사항 비교 (childObjid 기준)
Map<String, Map<String, Object>> beforeMap = new HashMap<>();
Map<String, Map<String, Object>> afterMap = new HashMap<>();
// 기존 데이터 매핑
System.out.println("========== 기존 데이터 매핑 (beforeMap) ==========");
for(Map<String, Object> detail : existingDetails) {
String childObjid = CommonUtils.checkNull(detail.get("CHILD_OBJID"));
if(!"".equals(childObjid)) {
beforeMap.put(childObjid, detail);
System.out.println("Before - childObjid: " + childObjid + ", partNo: " + detail.get("PART_NO"));
}
}
// 새 데이터 매핑
System.out.println("========== 새 데이터 매핑 (afterMap) ==========");
if(mbomData != null) {
for(Map<String, Object> item : mbomData) {
String childObjid = CommonUtils.checkNull(item.get("childObjid"));
if(!"".equals(childObjid)) {
afterMap.put(childObjid, item);
System.out.println("After - childObjid: " + childObjid + ", partNo: " + item.get("partNo"));
}
}
}
// 변경된 항목만 추출
List<Map<String, Object>> changedItems = new ArrayList<>();
System.out.println("========== 변경 사항 비교 ==========");
System.out.println("기존 항목 수 (beforeMap): " + beforeMap.size());
System.out.println("새 항목 수 (afterMap): " + afterMap.size());
// 추가된 항목
for(String childObjid : afterMap.keySet()) {
if(!beforeMap.containsKey(childObjid)) {
Map<String, Object> change = new HashMap<>();
change.put("changeType", "ADD");
change.put("childObjid", childObjid);
change.put("afterData", afterMap.get(childObjid));
changedItems.add(change);
System.out.println("추가된 항목: " + childObjid + " - " + afterMap.get(childObjid).get("partNo"));
}
}
// 삭제된 항목
for(String childObjid : beforeMap.keySet()) {
if(!afterMap.containsKey(childObjid)) {
Map<String, Object> change = new HashMap<>();
change.put("changeType", "DELETE");
change.put("childObjid", childObjid);
change.put("beforeData", beforeMap.get(childObjid));
changedItems.add(change);
System.out.println("삭제된 항목: " + childObjid + " - " + beforeMap.get(childObjid).get("PART_NO"));
}
}
// 수정된 항목
for(String childObjid : afterMap.keySet()) {
if(beforeMap.containsKey(childObjid)) {
Map<String, Object> before = beforeMap.get(childObjid);
Map<String, Object> after = afterMap.get(childObjid);
// 필드별 비교 (실제 편집 가능한 필드만)
List<Map<String, Object>> fieldChanges = new ArrayList<>();
// [DB 필드명, JSP 전송 필드명] 매핑
// JSP getMbomTreeData()에서 전송하는 필드명 기준
String[][] fieldMapping = {
{"PART_OBJID", "partObjid"}, // 파트 변경 감지
{"PART_NO", "partNo"}, // 파트 변경 감지
{"PART_NAME", "partName"}, // 파트 변경 감지
{"SUPPLY_TYPE", "supplyType"},
{"RAW_MATERIAL", "rawMaterial"},
{"RAW_MATERIAL_SIZE", "rawMaterialSize"},
{"RAW_MATERIAL_PART_NO", "rawMaterialPartNo"},
{"REQUIRED_QTY", "requiredQty"},
{"PRODUCTION_QTY", "productionQty"},
{"PROCESSING_VENDOR", "processingVendor"},
{"PROCESSING_DEADLINE", "processingDeadline"},
{"GRINDING_DEADLINE", "grindingDeadline"}
};
for(String[] mapping : fieldMapping) {
String dbField = mapping[0];
String jsField = mapping[1];
// before는 DB에서 대문자로, after는 JSP에서 camelCase로
Object beforeObj = before.get(dbField);
Object afterObj = after.get(jsField);
String beforeValue = (beforeObj == null) ? "" : String.valueOf(beforeObj);
String afterValue = (afterObj == null) ? "" : String.valueOf(afterObj);
// 숫자 필드는 소수점 정규화 (1.0000 vs 1 비교 문제 해결)
if(dbField.contains("QTY") || dbField.equals("QTY")) {
try {
double beforeNum = Double.parseDouble(beforeValue);
double afterNum = Double.parseDouble(afterValue);
if(Math.abs(beforeNum - afterNum) < 0.0001) {
continue; // 실질적으로 같은 값
}
} catch(Exception e) {
// 숫자 변환 실패 시 문자열 비교
}
}
if(!beforeValue.equals(afterValue)) {
Map<String, Object> fieldChange = new HashMap<>();
fieldChange.put("field", dbField);
fieldChange.put("before", beforeValue);
fieldChange.put("after", afterValue);
fieldChanges.add(fieldChange);
System.out.println("필드 변경 감지: " + dbField + " - Before: [" + beforeValue + "] After: [" + afterValue + "]");
}
}
if(!fieldChanges.isEmpty()) {
Map<String, Object> change = new HashMap<>();
change.put("changeType", "MODIFY");
change.put("childObjid", childObjid);
change.put("partNo", after.get("partNo"));
change.put("partName", after.get("partName"));
change.put("fieldChanges", fieldChanges);
changedItems.add(change);
System.out.println("변경된 항목 추가: " + after.get("partNo") + " - " + fieldChanges.size() + "개 필드 변경");
}
}
}
// M-BOM 헤더 업데이트
paramMap.put("mbomHeaderObjid", existingMbom.get("OBJID"));
sqlSession.update("productionplanning.updateMbomHeader", paramMap);
// 기존 데이터 조회
Map<String, Object> queryParam = new HashMap<>();
queryParam.put("mbomHeaderObjid", existingMbom.get("OBJID"));
List<Map> oldMbomDetails = sqlSession.selectList("productionplanning.getMbomDetailList", queryParam);
// 기존 OBJID Set 생성
java.util.Set<String> existingObjids = new java.util.HashSet<>();
Map<String, Map> existingDataMap = new HashMap<>();
if(oldMbomDetails != null) {
for(Map detail : oldMbomDetails) {
detail = CommonUtils.toUpperCaseMapKey(detail);
String objid = CommonUtils.checkNull(detail.get("OBJID"));
if(!objid.isEmpty()) {
existingObjids.add(objid);
existingDataMap.put(objid, detail);
}
}
}
// JSP에서 넘어온 OBJID Set 생성
java.util.Set<String> newObjids = new java.util.HashSet<>();
// UPSERT 처리
if(mbomData != null && !mbomData.isEmpty()) {
for(Map<String, Object> item : mbomData) {
item.put("mbomHeaderObjid", existingMbom.get("OBJID"));
item.put("sessionUserId", userId);
// SEQ 기본값
if(item.get("seq") == null || "".equals(item.get("seq"))) {
item.put("seq", 999);
}
String objid = CommonUtils.checkNull(item.get("objid"));
String childObjid = CommonUtils.checkNull(item.get("childObjid"));
// 신규 항목: objid가 비어있을 때만
if("".equals(objid)) {
objid = CommonUtils.createObjId();
item.put("objid", objid);
}
if("".equals(childObjid)) {
childObjid = objid;
item.put("childObjid", childObjid);
}
newObjids.add(objid);
// 기존 데이터에서 보존할 값 복원
Map existingData = existingDataMap.get(objid);
if(existingData != null) {
if(item.get("proposalDate") == null || "".equals(item.get("proposalDate"))) {
Object val = existingData.get("PROPOSAL_DATE");
if(val != null) item.put("proposalDate", val);
}
if(item.get("vendor") == null || "".equals(item.get("vendor"))) {
Object val = existingData.get("VENDOR");
if(val != null) item.put("vendor", val);
}
if(item.get("netQty") == null || "".equals(item.get("netQty"))) {
Object val = existingData.get("NET_QTY");
if(val != null) item.put("netQty", val);
}
if(item.get("poQty") == null || "".equals(item.get("poQty"))) {
Object val = existingData.get("PO_QTY");
if(val != null) item.put("poQty", val);
}
}
// LEVEL 기본값
if(item.get("level") == null || "".equals(item.get("level"))) {
item.put("level", 1);
}
// UPSERT: 기존 항목이면 UPDATE, 신규면 INSERT
if(existingObjids.contains(objid)) {
sqlSession.update("productionplanning.updateMbomDetail", item);
} else {
sqlSession.insert("productionplanning.insertMbomDetail", item);
}
}
}
// DELETE: DB에 있는데 JSP에 없는 항목 삭제
for(String existingObjid : existingObjids) {
if(!newObjids.contains(existingObjid)) {
Map<String, Object> deleteParam = new HashMap<>();
deleteParam.put("objid", existingObjid);
sqlSession.delete("productionplanning.deleteMbomDetailByObjid", deleteParam);
}
}
// 변경 사항이 있을 때만 이력 저장
if(!changedItems.isEmpty()) {
String historyObjid = CommonUtils.createObjId();
Map<String, Object> historyParam = new HashMap<>();
historyParam.put("objid", historyObjid);
historyParam.put("mbomHeaderObjid", existingMbom.get("OBJID"));
historyParam.put("changeType", "UPDATE");
historyParam.put("changeDescription", changedItems.size() + "개 항목 변경");
historyParam.put("beforeData", new com.google.gson.Gson().toJson(changedItems));
historyParam.put("afterData", "{}");
historyParam.put("sessionUserId", userId);
sqlSession.insert("productionplanning.insertMbomHistory", historyParam);
}
result = true;
}
} else {
// 최초 저장: 새 M-BOM 생성
String newObjid = CommonUtils.createObjId();
paramMap.put("objid", newObjid);
paramMap.put("mbomNo", mbomNo);
// sourceBomType에 따라 sourceEbomObjid 또는 sourceMbomObjid 설정
String sourceBomType = (String) paramMap.get("sourceBomType");
String sourceBomObjId = (String) paramMap.get("sourceBomObjId");
if("EBOM".equals(sourceBomType)) {
paramMap.put("sourceEbomObjid", sourceBomObjId);
paramMap.put("sourceMbomObjid", null);
} else if("MBOM".equals(sourceBomType)) {
paramMap.put("sourceEbomObjid", null);
paramMap.put("sourceMbomObjid", sourceBomObjId);
} else if("TEMPLATE".equals(sourceBomType)) {
// 템플릿 기반 저장: 할당 정보 없음
paramMap.put("sourceEbomObjid", null);
paramMap.put("sourceMbomObjid", null);
}
// MBOM_HEADER 삽입
sqlSession.insert("productionplanning.insertMbomHeader", paramMap);
// MBOM_DETAIL 삽입
List<Map<String, Object>> mbomData = (List<Map<String, Object>>) paramMap.get("mbomData");
if(mbomData != null && !mbomData.isEmpty()) {
// CHILD_OBJID 매핑 (기존 E-BOM의 CHILD_OBJID -> 새 M-BOM의 CHILD_OBJID)
Map<String, String> childObjidMap = new HashMap<>();
// 1단계: 모든 항목에 대해 새 CHILD_OBJID 생성
for(Map<String, Object> item : mbomData) {
String oldChildObjid = CommonUtils.checkNull(item.get("childObjid"));
if(!"".equals(oldChildObjid) && !childObjidMap.containsKey(oldChildObjid)) {
String newChildObjid = CommonUtils.createObjId();
childObjidMap.put(oldChildObjid, newChildObjid);
}
}
// 2단계: PARENT_OBJID와 CHILD_OBJID를 새 ID로 매핑하여 삽입
for(Map<String, Object> item : mbomData) {
String oldChildObjid = CommonUtils.checkNull(item.get("childObjid"));
String oldParentObjid = CommonUtils.checkNull(item.get("parentObjid"));
// 새 CHILD_OBJID 설정
String newChildObjid = childObjidMap.get(oldChildObjid);
if(newChildObjid == null) {
newChildObjid = CommonUtils.createObjId();
}
// 새 PARENT_OBJID 설정 (부모가 있는 경우에만)
String newParentObjid = "";
if(!"".equals(oldParentObjid)) {
newParentObjid = childObjidMap.get(oldParentObjid);
if(newParentObjid == null) {
newParentObjid = oldParentObjid; // 매핑 실패 시 원본 유지
}
}
item.put("mbomHeaderObjid", newObjid);
item.put("objid", newChildObjid); // OBJID = CHILD_OBJID
item.put("childObjid", newChildObjid);
item.put("parentObjid", newParentObjid);
item.put("sessionUserId", userId);
// SEQ 유지 (JSP에서 전송된 seq 사용)
if(item.get("seq") == null || "".equals(item.get("seq"))) {
item.put("seq", 999); // 임시값
}
// LEVEL이 없으면 기본값 1 설정
if(item.get("level") == null || "".equals(item.get("level"))) {
item.put("level", 1);
}
System.out.println("INSERT M-BOM DETAIL: seq=" + item.get("seq") +
", level=" + item.get("level") +
", partNo=" + item.get("partNo") +
", parentObjid=" + newParentObjid +
", childObjid=" + newChildObjid);
sqlSession.insert("productionplanning.insertMbomDetail", item);
}
}
// 이력 저장 (생성)
String historyObjid = CommonUtils.createObjId();
paramMap.put("objid", historyObjid); // MBOM_HISTORY의 OBJID
paramMap.put("mbomHeaderObjid", newObjid);
paramMap.put("changeType", "CREATE");
paramMap.put("afterData", new com.google.gson.Gson().toJson(paramMap));
sqlSession.insert("productionplanning.insertMbomHistory", paramMap);
// PROJECT_MGMT 업데이트 (MBOM_STATUS = 'Y')
sqlSession.update("productionplanning.updateProjectMbomStatus", paramMap);
result = true;
}
sqlSession.commit();
} catch(Exception e) {
if(sqlSession != null) {
sqlSession.rollback();
}
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return result;
}
/**
* 동일 품번의 최신 M-BOM을 새 프로젝트에 자동 복사 (독립 트랜잭션)
*/
public String copyMbomFromTemplate(HttpServletRequest request, String projectObjId,
String templateHeaderObjId, String partNo, String partName, int orderQuantity) {
SqlSession sqlSession = null;
String newHeaderObjid = null;
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
HttpSession session = request.getSession();
PersonBean person = (PersonBean)session.getAttribute(Constants.PERSON_BEAN);
String userId = CommonUtils.checkNull(person.getUserId());
newHeaderObjid = copyMbomFromTemplate(sqlSession, userId, projectObjId, templateHeaderObjId, partNo, partName, orderQuantity);
if(newHeaderObjid != null) {
sqlSession.commit();
}
} catch(Exception e) {
if(sqlSession != null) sqlSession.rollback();
newHeaderObjid = null;
e.printStackTrace();
} finally {
if(sqlSession != null) sqlSession.close();
}
return newHeaderObjid;
}
/**
* 동일 품번의 최신 M-BOM을 새 프로젝트에 자동 복사 (기존 트랜잭션 공유)
* 수주 확정 → 프로젝트 자동생성 시 ContractMgmtService에서 호출
*/
public String copyMbomFromTemplate(SqlSession sqlSession, String userId, String projectObjId,
String templateHeaderObjId, String partNo, String partName, int orderQuantity) {
String newHeaderObjid = null;
try {
// 1. 새 MBOM_HEADER 생성 (M-BOM 품번 규칙 적용)
newHeaderObjid = CommonUtils.createObjId();
String mbomNo = generateMbomNo(sqlSession, "TEMPLATE", partNo);
Map<String, Object> headerParam = new HashMap<>();
headerParam.put("objid", newHeaderObjid);
headerParam.put("mbomNo", mbomNo);
headerParam.put("sourceBomType", "TEMPLATE");
headerParam.put("sourceEbomObjid", null);
headerParam.put("sourceMbomObjid", templateHeaderObjId);
headerParam.put("projectObjId", projectObjId);
headerParam.put("partNo", partNo);
headerParam.put("partName", partName);
headerParam.put("sessionUserId", userId);
sqlSession.insert("productionplanning.insertMbomHeader", headerParam);
// 2. 템플릿의 MBOM_DETAIL 조회
Map<String, Object> detailParam = new HashMap<>();
detailParam.put("mbomHeaderObjid", templateHeaderObjId);
List<Map<String, Object>> templateDetails = sqlSession.selectList("productionplanning.getMbomDetailList", detailParam);
if(templateDetails != null && !templateDetails.isEmpty()) {
// 3. CHILD_OBJID 매핑 생성 (old → new)
Map<String, String> childObjidMap = new HashMap<>();
for(Map<String, Object> detail : templateDetails) {
detail = CommonUtils.toUpperCaseMapKey(detail);
String oldObjid = CommonUtils.checkNull(detail.get("OBJID"));
String oldChildObjid = CommonUtils.checkNull(detail.get("CHILD_OBJID"));
if(!"".equals(oldObjid)) {
childObjidMap.put(oldObjid, CommonUtils.createObjId());
}
if(!"".equals(oldChildObjid) && !childObjidMap.containsKey(oldChildObjid)) {
childObjidMap.put(oldChildObjid, CommonUtils.createObjId());
}
}
// 4. 매핑 적용하여 MBOM_DETAIL 복사 (수주/제작 수량은 초기화)
for(Map<String, Object> detail : templateDetails) {
detail = CommonUtils.toUpperCaseMapKey(detail);
String oldObjid = CommonUtils.checkNull(detail.get("OBJID"));
String oldChildObjid = CommonUtils.checkNull(detail.get("CHILD_OBJID"));
String oldParentObjid = CommonUtils.checkNull(detail.get("PARENT_OBJID"));
String newObjid = childObjidMap.containsKey(oldObjid) ? childObjidMap.get(oldObjid) : CommonUtils.createObjId();
String newChildObjid = childObjidMap.containsKey(oldChildObjid) ? childObjidMap.get(oldChildObjid) : newObjid;
String newParentObjid = !"".equals(oldParentObjid)
? (childObjidMap.containsKey(oldParentObjid) ? childObjidMap.get(oldParentObjid) : oldParentObjid) : "";
Map<String, Object> insertParam = new HashMap<>();
insertParam.put("objid", newObjid);
insertParam.put("mbomHeaderObjid", newHeaderObjid);
insertParam.put("parentObjid", newParentObjid);
insertParam.put("childObjid", newChildObjid);
insertParam.put("seq", detail.get("SEQ"));
insertParam.put("level", detail.get("LEVEL"));
insertParam.put("partObjid", detail.get("PART_OBJID"));
insertParam.put("partNo", detail.get("PART_NO"));
insertParam.put("partName", detail.get("PART_NAME"));
insertParam.put("qty", detail.get("QTY"));
insertParam.put("unit", detail.get("UNIT"));
insertParam.put("supplyType", detail.get("SUPPLY_TYPE"));
insertParam.put("makeOrBuy", detail.get("MAKE_OR_BUY"));
insertParam.put("rawMaterialPartNo", detail.get("RAW_MATERIAL_PART_NO"));
insertParam.put("rawMaterialSpec", detail.get("RAW_MATERIAL_SPEC"));
insertParam.put("rawMaterial", detail.get("RAW_MATERIAL"));
insertParam.put("rawMaterialSize", detail.get("RAW_MATERIAL_SIZE"));
insertParam.put("processingVendor", detail.get("PROCESSING_VENDOR"));
insertParam.put("processingDeadline", detail.get("PROCESSING_DEADLINE"));
insertParam.put("grindingDeadline", detail.get("GRINDING_DEADLINE"));
// REQUIRED_QTY(소요량)는 원본 복사, 나머지 수량은 수주수량 기준 재계산
double requiredQty = 0;
try {
Object reqObj = detail.get("REQUIRED_QTY");
if(reqObj != null) requiredQty = Double.parseDouble(String.valueOf(reqObj));
} catch(Exception ignore) {}
double productionQty = requiredQty * orderQuantity;
insertParam.put("requiredQty", detail.get("REQUIRED_QTY"));
insertParam.put("orderQty", null);
insertParam.put("productionQty", productionQty > 0 ? productionQty : null);
insertParam.put("stockQty", null);
insertParam.put("shortageQty", null);
insertParam.put("netQty", null);
insertParam.put("poQty", null);
insertParam.put("vendor", detail.get("VENDOR"));
insertParam.put("unitPrice", detail.get("UNIT_PRICE"));
insertParam.put("processingUnitPrice", detail.get("PROCESSING_UNIT_PRICE"));
insertParam.put("totalPrice", null);
insertParam.put("currency", detail.get("CURRENCY"));
insertParam.put("leadTime", detail.get("LEAD_TIME"));
insertParam.put("minOrderQty", detail.get("MIN_ORDER_QTY"));
insertParam.put("proposalDate", null);
insertParam.put("remark", detail.get("REMARK"));
insertParam.put("sessionUserId", userId);
sqlSession.insert("productionplanning.insertMbomDetail", insertParam);
}
}
// 5. PROJECT_MGMT MBOM_STATUS 업데이트
Map<String, Object> statusParam = new HashMap<>();
statusParam.put("projectObjId", projectObjId);
statusParam.put("sessionUserId", userId);
sqlSession.update("productionplanning.updateProjectMbomStatus", statusParam);
// 6. 이력 저장
String historyObjid = CommonUtils.createObjId();
Map<String, Object> historyParam = new HashMap<>();
historyParam.put("objid", historyObjid);
historyParam.put("mbomHeaderObjid", newHeaderObjid);
historyParam.put("changeType", "COPY_FROM_TEMPLATE");
historyParam.put("changeDescription", "동일 품번(" + partNo + ") M-BOM 자동 복사");
historyParam.put("beforeData", "{}");
historyParam.put("afterData", "{\"sourceHeaderObjid\":\"" + templateHeaderObjId + "\"}");
historyParam.put("sessionUserId", userId);
sqlSession.insert("productionplanning.insertMbomHistory", historyParam);
System.out.println("========== M-BOM 자동 복사 완료 ==========");
System.out.println("프로젝트: " + projectObjId);
System.out.println("원본 템플릿: " + templateHeaderObjId);
System.out.println("새 M-BOM: " + newHeaderObjid);
} catch(Exception e) {
newHeaderObjid = null;
e.printStackTrace();
}
return newHeaderObjid;
}
/**
* MBOM_HEADER 테이블에 해당 OBJID가 존재하는지 확인
* @param objId
* @return
*/
public boolean isMbomHeader(String objId) {
SqlSession sqlSession = null;
boolean result = false;
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession();
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("objid", objId);
System.out.println("========== isMbomHeader 체크 시작 ==========");
System.out.println("objId: [" + objId + "]");
System.out.println("objId length: " + (objId != null ? objId.length() : "null"));
Integer count = sqlSession.selectOne("productionplanning.checkMbomHeaderExists", paramMap);
result = (count != null && count > 0);
System.out.println("count: " + count);
System.out.println("isMbomHeader result: " + result);
System.out.println("========== isMbomHeader 체크 종료 ==========");
} catch(Exception e) {
System.out.println("isMbomHeader 에러 발생:");
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return result;
}
/**
* M-BOM 트리 조회 (MBOM_DETAIL 테이블)
* @param mbomHeaderObjid
* @return
*/
public List<Map> getSavedMbomTreeList(String mbomHeaderObjid) {
SqlSession sqlSession = null;
List<Map> resultList = new ArrayList<>();
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession();
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("mbomHeaderObjid", mbomHeaderObjid);
resultList = sqlSession.selectList("productionplanning.getSavedMbomTreeList", paramMap);
// 대문자 변환 (JSP에서 사용하기 위해)
resultList = CommonUtils.keyChangeUpperList(resultList);
// MAX_LEVEL 계산
int maxLevel = 0;
for(Map item : resultList) {
Integer level = (Integer) item.get("LEVEL");
if(level != null && level > maxLevel) {
maxLevel = level;
}
}
// 모든 항목에 MAX_LEVEL 추가
for(Map item : resultList) {
item.put("MAX_LEVEL", maxLevel);
}
System.out.println("getSavedMbomTreeList - mbomHeaderObjid: " + mbomHeaderObjid + ", count: " + resultList.size() + ", maxLevel: " + maxLevel);
} catch(Exception e) {
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return resultList;
}
/**
* 생산계획 정보 조회
* @param prodPlanObjid
* @return
*/
public Map getProdPlanInfo(String prodPlanObjid) {
Map resultMap = new HashMap();
SqlSession sqlSession = null;
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession();
Map paramMap = new HashMap();
paramMap.put("objid", prodPlanObjid);
resultMap = sqlSession.selectOne("productionplanning.getProdPlanInfo", paramMap);
} catch(Exception e) {
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return resultMap;
}
/**
* 프로젝트 정보 조회 (생산계획 폼용)
* @param paramMap
* @return
*/
public Map getProdPlanProjectInfo(Map<String, Object> paramMap) {
Map resultMap = new HashMap();
SqlSession sqlSession = null;
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession();
resultMap = sqlSession.selectOne("productionplanning.getProdPlanProjectInfo", paramMap);
} catch(Exception e) {
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return resultMap;
}
/**
* 생산계획 저장
* @param paramMap
* @return
*/
public boolean saveProdPlan(Map<String, Object> paramMap) {
boolean result = false;
SqlSession sqlSession = null;
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession(false);
String objid = CommonUtils.nullToEmpty((String)paramMap.get("OBJID"));
String actionType = CommonUtils.nullToEmpty((String)paramMap.get("actionType"));
if("regist".equals(actionType) || "".equals(objid)) {
paramMap.put("OBJID", CommonUtils.createObjId());
sqlSession.insert("productionplanning.insertProdPlan", paramMap);
} else {
sqlSession.update("productionplanning.updateProdPlan", paramMap);
}
// S/N → CONTRACT_ITEM_SERIAL 동기화 (프로젝트 연결 시)
String projectNo = CommonUtils.nullToEmpty((String)paramMap.get("PROJECT_NO"));
String serialNo = CommonUtils.nullToEmpty((String)paramMap.get("SERIAL_NO"));
String writer = CommonUtils.nullToEmpty((String)paramMap.get("userId"));
if(!projectNo.isEmpty()) {
SerialNoSyncUtil.syncSerialToContractItemSerial(
sqlSession, projectNo, serialNo, writer);
}
sqlSession.commit();
result = true;
} catch(Exception e) {
e.printStackTrace();
if(sqlSession != null) {
sqlSession.rollback();
}
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return result;
}
/**
* 생산실적 목록 조회
*/
public List getProdResultList(Map<String, Object> paramMap) {
List resultList = new ArrayList();
SqlSession sqlSession = null;
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession();
resultList = sqlSession.selectList("productionplanning.getProdResultList", paramMap);
} catch(Exception e) {
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return resultList;
}
/**
* 생산실적 저장 (리스트)
*/
@SuppressWarnings("unchecked")
public boolean saveProdResultList(Map<String, Object> paramMap) {
boolean result = false;
SqlSession sqlSession = null;
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession();
String projectObjid = CommonUtils.nullToEmpty((String)paramMap.get("projectObjid"));
String userId = CommonUtils.nullToEmpty((String)paramMap.get("userId"));
List<Map<String, Object>> resultList = (List<Map<String, Object>>)paramMap.get("resultList");
if(resultList != null && resultList.size() > 0) {
for(Map<String, Object> row : resultList) {
row.put("PROJECT_OBJID", projectObjid);
row.put("userId", userId);
String objid = CommonUtils.nullToEmpty((String)row.get("OBJID"));
if("".equals(objid)) {
// 신규 등록
row.put("OBJID", CommonUtils.createObjId());
sqlSession.insert("productionplanning.insertProdResult", row);
} else {
// 수정
sqlSession.update("productionplanning.updateProdResult", row);
}
}
}
sqlSession.commit();
result = true;
} catch(Exception e) {
e.printStackTrace();
if(sqlSession != null) {
sqlSession.rollback();
}
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return result;
}
/**
* M-BOM 기준 반제품 소요량 조회
* - 여러 M-BOM을 입력받아 범주가 '부품', '조립품'인 항목만 조회
* - 동일 품번은 합산하여 반환
* @param paramMap - mbomItems: [{mbomObjid, qty}, ...]
* @return 품번별 합산된 소요량 목록
*/
public List getSemiProductRequirementList(Map paramMap) {
SqlSession sqlSession = null;
List resultList = new ArrayList();
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession();
// 입력받은 M-BOM 목록
List<Map<String, Object>> mbomItems = (List<Map<String, Object>>) paramMap.get("mbomItems");
if(mbomItems == null || mbomItems.isEmpty()) {
return resultList;
}
// 품번별 소요량을 합산하기 위한 Map (key: PART_NO, value: {품번정보, 소요량합계})
Map<String, Map<String, Object>> partNoMap = new LinkedHashMap<>();
// 각 M-BOM별로 조회하여 합산
for(Map<String, Object> mbomItem : mbomItems) {
String mbomObjid = CommonUtils.nullToEmpty((String)mbomItem.get("mbomObjid"));
int inputQty = 0;
Object qtyObj = mbomItem.get("qty");
if(qtyObj != null) {
if(qtyObj instanceof Number) {
inputQty = ((Number)qtyObj).intValue();
} else {
try {
inputQty = Integer.parseInt(qtyObj.toString());
} catch(NumberFormatException e) {
inputQty = 0;
}
}
}
if("".equals(mbomObjid) || inputQty <= 0) {
continue;
}
// M-BOM 항목 조회 (범주가 '부품', '조립품'인 것만)
Map<String, Object> queryParam = new HashMap<>();
queryParam.put("mbomHeaderObjid", mbomObjid);
List<Map<String, Object>> bomItems = sqlSession.selectList("productionplanning.getMbomSemiProductItems", queryParam);
// 소요량 합산 (PostgreSQL은 소문자 키로 반환)
for(Map<String, Object> bomItem : bomItems) {
String partNo = CommonUtils.nullToEmpty((String)bomItem.get("part_no"));
if("".equals(partNo)) continue;
// M-BOM의 항목수량
int itemQty = 0;
Object itemQtyObj = bomItem.get("item_qty");
if(itemQtyObj != null) {
if(itemQtyObj instanceof Number) {
itemQty = ((Number)itemQtyObj).intValue();
} else {
try {
itemQty = Integer.parseInt(itemQtyObj.toString());
} catch(NumberFormatException e) {
itemQty = 0;
}
}
}
// 소요량 = 입력수량 × 항목수량
int requiredQty = inputQty * itemQty;
if(partNoMap.containsKey(partNo)) {
// 기존 품번이면 소요량만 합산
Map<String, Object> existingItem = partNoMap.get(partNo);
int existingQty = (Integer)existingItem.get("REQUIRED_QTY");
existingItem.put("REQUIRED_QTY", existingQty + requiredQty);
} else {
// 새로운 품번이면 추가
Map<String, Object> newItem = new LinkedHashMap<>();
newItem.put("PART_NO", partNo);
newItem.put("PART_NAME", bomItem.get("part_name"));
newItem.put("CATEGORY_NAME", bomItem.get("category_name"));
newItem.put("UNIT", bomItem.get("unit"));
newItem.put("MATERIAL", bomItem.get("material"));
newItem.put("SPEC", bomItem.get("spec"));
newItem.put("REQUIRED_QTY", requiredQty);
partNoMap.put(partNo, newItem);
}
}
}
// Map -> List 변환
resultList = new ArrayList(partNoMap.values());
} catch(Exception e) {
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return resultList;
}
/**
* M-BOM 기준 원자재(구매품 + 원소재) 소요량 조회
* - 여러 M-BOM을 입력받아 PART_TYPE이 '0000063'(구매품)인 항목 조회
* - RAW_MATERIAL_PART_NO가 있는 항목은 "원소재"로 별도 조회
* - 동일 품번은 합산하여 반환
* @param paramMap - mbomItems: [{mbomObjid, qty}, ...]
* @return 품번별 합산된 소요량 목록
*/
public List getRawMaterialRequirementList(Map paramMap) {
SqlSession sqlSession = null;
List resultList = new ArrayList();
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession();
// 입력받은 M-BOM 목록
List<Map<String, Object>> mbomItems = (List<Map<String, Object>>) paramMap.get("mbomItems");
if(mbomItems == null || mbomItems.isEmpty()) {
return resultList;
}
// 구매품 품번별 소요량 Map
Map<String, Map<String, Object>> purchasePartNoMap = new LinkedHashMap<>();
// 원소재 품번별 소요량 Map
Map<String, Map<String, Object>> rawSourcePartNoMap = new LinkedHashMap<>();
// 각 M-BOM별로 조회하여 합산
for(Map<String, Object> mbomItem : mbomItems) {
String mbomObjid = CommonUtils.nullToEmpty((String)mbomItem.get("mbomObjid"));
int inputQty = 0;
Object qtyObj = mbomItem.get("qty");
if(qtyObj != null) {
if(qtyObj instanceof Number) {
inputQty = ((Number)qtyObj).intValue();
} else {
try {
inputQty = Integer.parseInt(qtyObj.toString());
} catch(NumberFormatException e) {
inputQty = 0;
}
}
}
if("".equals(mbomObjid) || inputQty <= 0) {
continue;
}
Map<String, Object> queryParam = new HashMap<>();
queryParam.put("mbomHeaderObjid", mbomObjid);
// 1. 구매품 조회
List<Map<String, Object>> purchaseItems = sqlSession.selectList("productionplanning.getMbomRawMaterialItems", queryParam);
for(Map<String, Object> bomItem : purchaseItems) {
String partNo = CommonUtils.nullToEmpty((String)bomItem.get("part_no"));
if("".equals(partNo)) continue;
int itemQty = getIntValue(bomItem.get("item_qty"));
int requiredQty = inputQty * itemQty;
if(purchasePartNoMap.containsKey(partNo)) {
Map<String, Object> existingItem = purchasePartNoMap.get(partNo);
int existingQty = (Integer)existingItem.get("REQUIRED_QTY");
existingItem.put("REQUIRED_QTY", existingQty + requiredQty);
} else {
Map<String, Object> newItem = new LinkedHashMap<>();
newItem.put("PART_NO", partNo);
newItem.put("PART_NAME", bomItem.get("part_name"));
newItem.put("CATEGORY_NAME", bomItem.get("category_name"));
newItem.put("UNIT", bomItem.get("unit"));
// 구매품은 소재 관련 컬럼 전부 빈값
newItem.put("MATERIAL", "");
newItem.put("SPEC", "");
newItem.put("REQUIRED_QTY", requiredQty);
newItem.put("RAW_MATERIAL", "");
newItem.put("RAW_MATERIAL_SIZE", "");
newItem.put("MATERIAL_PART_NO", "");
newItem.put("MATERIAL_REQUIRED_QTY", "");
purchasePartNoMap.put(partNo, newItem);
}
}
// 2. 원소재 조회 (RAW_MATERIAL_PART_NO가 있는 항목)
// 원소재는 소재품번 기준으로 합산 (소수점 합산 후 올림)
List<Map<String, Object>> rawSourceItems = sqlSession.selectList("productionplanning.getMbomRawSourceItems", queryParam);
for(Map<String, Object> bomItem : rawSourceItems) {
String materialPartNo = CommonUtils.nullToEmpty((String)bomItem.get("raw_material_part_no"));
if("".equals(materialPartNo)) continue;
double itemQty = getDoubleValue(bomItem.get("item_qty"));
double requiredQty = inputQty * itemQty;
if(rawSourcePartNoMap.containsKey(materialPartNo)) {
Map<String, Object> existingItem = rawSourcePartNoMap.get(materialPartNo);
double existingQty = (Double)existingItem.get("MATERIAL_REQUIRED_QTY_RAW");
existingItem.put("MATERIAL_REQUIRED_QTY_RAW", existingQty + requiredQty);
} else {
Map<String, Object> newItem = new LinkedHashMap<>();
// 원소재는 품번, 품명, 소요량 빈값
newItem.put("PART_NO", "");
newItem.put("PART_NAME", "");
newItem.put("CATEGORY_NAME", "원소재");
newItem.put("UNIT", "");
newItem.put("MATERIAL", bomItem.get("raw_material"));
newItem.put("SPEC", bomItem.get("raw_material_size"));
newItem.put("REQUIRED_QTY", "");
// 원소재 관련 컬럼만 표시
newItem.put("RAW_MATERIAL", bomItem.get("raw_material"));
newItem.put("RAW_MATERIAL_SIZE", bomItem.get("raw_material_size"));
newItem.put("MATERIAL_PART_NO", materialPartNo);
newItem.put("MATERIAL_REQUIRED_QTY_RAW", requiredQty); // 합산용 (소수점)
rawSourcePartNoMap.put(materialPartNo, newItem);
}
}
}
// 구매품 먼저 추가
resultList.addAll(purchasePartNoMap.values());
// 원소재는 소수점 합산 후 올림 처리하여 추가
for(Map<String, Object> item : rawSourcePartNoMap.values()) {
double rawQty = (Double)item.get("MATERIAL_REQUIRED_QTY_RAW");
int ceilQty = (int)Math.ceil(rawQty); // 올림 처리
item.put("MATERIAL_REQUIRED_QTY", ceilQty);
item.remove("MATERIAL_REQUIRED_QTY_RAW"); // 임시 필드 제거
resultList.add(item);
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return resultList;
}
/**
* Object를 int로 변환하는 유틸 메서드
*/
private int getIntValue(Object obj) {
if(obj == null) return 0;
if(obj instanceof Number) {
return ((Number)obj).intValue();
}
try {
return Integer.parseInt(obj.toString());
} catch(NumberFormatException e) {
return 0;
}
}
/**
* Object를 double로 변환하는 유틸 메서드
*/
private double getDoubleValue(Object obj) {
if(obj == null) return 0.0;
if(obj instanceof Number) {
return ((Number)obj).doubleValue();
}
try {
return Double.parseDouble(obj.toString());
} catch(NumberFormatException e) {
return 0.0;
}
}
/**
* M-BOM 목록 조회 (품명 포함)
* 원자재소요량/반제품소요량 화면에서 품명 자동 입력용
* @return M-BOM 목록 (OBJID, MBOM_NO, PART_NAME)
*/
public List<Map> getMbomListWithPartName() {
List<Map> resultList = new ArrayList<>();
SqlSession sqlSession = null;
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession();
resultList = sqlSession.selectList("productionplanning.getMbomListWithPartName", new HashMap<>());
// JSP에서 대문자 키로 접근하므로 변환
resultList = CommonUtils.keyChangeUpperList(resultList);
} catch(Exception e) {
e.printStackTrace();
} finally {
if(sqlSession != null) sqlSession.close();
}
return resultList;
}
/**
* 생산실적 날짜별 조회
*/
public List getProdResultListByDate(Map<String, Object> paramMap) {
List resultList = new ArrayList();
SqlSession sqlSession = null;
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession();
resultList = sqlSession.selectList("productionplanning.getProdResultListByDate", paramMap);
} catch(Exception e) {
e.printStackTrace();
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return resultList;
}
/**
* 생산실적 날짜별 저장
* - 기존 데이터 전체 삭제 후 새로 입력
*/
@SuppressWarnings("unchecked")
public boolean saveProdResultByDate(Map<String, Object> paramMap) {
boolean result = false;
SqlSession sqlSession = null;
try {
sqlSession = SqlMapConfig.getInstance().getSqlSession();
String projectObjid = CommonUtils.nullToEmpty((String)paramMap.get("projectObjid"));
String userId = CommonUtils.nullToEmpty((String)paramMap.get("userId"));
String userName = CommonUtils.nullToEmpty((String)paramMap.get("userName"));
List<Map<String, Object>> resultList = (List<Map<String, Object>>)paramMap.get("resultList");
// 기존 데이터 전체 삭제
Map<String, Object> deleteParam = new HashMap<String, Object>();
deleteParam.put("projectObjid", projectObjid);
sqlSession.delete("productionplanning.deleteProdResultByProject", deleteParam);
// 새로 입력 (행별로 ROW_SEQ 부여)
if(resultList != null && resultList.size() > 0) {
int rowSeq = 1; // 행 순번
for(Map<String, Object> row : resultList) {
String resultDate = CommonUtils.nullToEmpty((String)row.get("RESULT_DATE"));
if("".equals(resultDate)) continue;
int assemblyQty = getIntValue(row.get("ASSEMBLY_QTY"));
int inspectionQty = getIntValue(row.get("INSPECTION_QTY"));
int shipWaitQty = getIntValue(row.get("SHIP_WAIT_QTY"));
String remark = CommonUtils.nullToEmpty((String)row.get("REMARK"));
// 완조립 수량 입력 (0이어도 입력)
Map<String, Object> insertParam = new HashMap<String, Object>();
insertParam.put("OBJID", CommonUtils.createObjId());
insertParam.put("PROJECT_OBJID", projectObjid);
insertParam.put("RESULT_TYPE", "ASSEMBLY");
insertParam.put("RESULT_DATE", resultDate);
insertParam.put("RESULT_QTY", assemblyQty);
insertParam.put("ROW_SEQ", rowSeq);
insertParam.put("WORKER_NAME", userName);
insertParam.put("REMARK", remark);
insertParam.put("userId", userId);
sqlSession.insert("productionplanning.insertProdResult", insertParam);
// 검사 수량 입력 (0이어도 입력)
insertParam = new HashMap<String, Object>();
insertParam.put("OBJID", CommonUtils.createObjId());
insertParam.put("PROJECT_OBJID", projectObjid);
insertParam.put("RESULT_TYPE", "INSPECTION");
insertParam.put("RESULT_DATE", resultDate);
insertParam.put("RESULT_QTY", inspectionQty);
insertParam.put("ROW_SEQ", rowSeq);
insertParam.put("WORKER_NAME", userName);
insertParam.put("REMARK", remark);
insertParam.put("userId", userId);
sqlSession.insert("productionplanning.insertProdResult", insertParam);
// 출하대기 수량 입력 (0이어도 입력)
insertParam = new HashMap<String, Object>();
insertParam.put("OBJID", CommonUtils.createObjId());
insertParam.put("PROJECT_OBJID", projectObjid);
insertParam.put("RESULT_TYPE", "SHIP_WAIT");
insertParam.put("RESULT_DATE", resultDate);
insertParam.put("RESULT_QTY", shipWaitQty);
insertParam.put("ROW_SEQ", rowSeq);
insertParam.put("WORKER_NAME", userName);
insertParam.put("REMARK", remark);
insertParam.put("userId", userId);
sqlSession.insert("productionplanning.insertProdResult", insertParam);
rowSeq++; // 다음 행
}
}
sqlSession.commit();
result = true;
} catch(Exception e) {
e.printStackTrace();
if(sqlSession != null) {
sqlSession.rollback();
}
} finally {
if(sqlSession != null) {
sqlSession.close();
}
}
return result;
}
}