NpwBankAction.java

package com.mycim.webapp.actions.npwbank;

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
import com.fa.sesa.exception.SystemIllegalArgumentException;
import com.fa.sesa.i18n.I18nUtils;
import com.fa.sesa.threadlocal.LocalContext;
import com.mycim.framework.utils.lang.StringUtils;
import com.mycim.framework.utils.lang.collections.CollectionUtils;
import com.mycim.framework.utils.lang.collections.MapUtils;
import com.mycim.framework.utils.lang.math.NumberUtils;
import com.mycim.framework.utils.lang.time.DateUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.consts.TransactionNames;
import com.mycim.valueobject.npw.NpwConstants;
import com.mycim.valueobject.prp.ProcessLoopInfo;
import com.mycim.valueobject.wip.Lot;
import com.mycim.valueobject.wip.LotStatus;
import com.mycim.valueobject.wip.NpwBank;
import com.mycim.valueobject.wip.Unit;
import com.mycim.webapp.Constants;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.NpwSetupAction;
import com.mycim.webapp.forms.NpwBankInfoForm;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author shijie.deng
 * @version 6.0.0
 * @date 2019/11/14
 **/
public class NpwBankAction extends NpwSetupAction {

    private static final String BANKIN = "npwbankin";

    private static final String BANKOUT = "npwbankout";

    private static final Integer PAGESIZE = 20;

    private static final String THISPAGE_KEY = "thisPage";

    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        NpwBankInfoForm theform = (NpwBankInfoForm) form;
        String transId = BANKIN;
        if (request.getParameter("npwbankin") != null) {
            transId = BANKIN;
        } else if (request.getParameter("npwbankout") != null) {
            transId = BANKOUT;
        }
        theform.setTransId(transId);
        theform.setCacheCollection(WebUtils.getCacheObj2String(new ArrayList()));
        request.setAttribute("lots", new ArrayList());
        request.setAttribute("TransId", transId);
        return (mapping.findForward("modify"));
    }

    public ActionForward bankInAdd(ActionMapping mapping, NpwBankInfoForm theform, HttpServletRequest request,
                                   HttpServletResponse response) {
        List lots = (List) WebUtils.getCacheString2Obj(theform.getCacheCollection());
        if (lots == null) {
            lots = new ArrayList();
        }
        String lotId = theform.getLotId().trim().toUpperCase();
        String operationId = theform.getOperationId().trim().toUpperCase();
        Long operationRrn = getInstanceRrn(operationId, LocalContext.getFacilityRrn(), ObjectList.OPERATION_KEY);
        Lot lot = lotQueryService.getLot(lotId, LocalContext.getFacilityRrn());
        if (validateLot(operationRrn, lots, theform, lot)) {
            lots.add(lot);
        }
        theform.setLotId("");
        theform.setLots(lots);
        theform.setCacheCollection(WebUtils.getCacheObj2String(lots));
        request.setAttribute("lots", lots);
        return (mapping.findForward("modify"));
    }

    public ActionForward bankOutAdd(ActionMapping mapping, NpwBankInfoForm theform, HttpServletRequest request,
                                    HttpServletResponse response) {
        List lots = (List) WebUtils.getCacheString2Obj(theform.getCacheCollection());
        if (lots == null) {
            lots = new ArrayList();
        }
        String lotId = theform.getLotId().trim().toUpperCase();
        Lot lot = lotQueryService.getLot(lotId, LocalContext.getFacilityRrn());
        Assert.isFalse(lot.getLotRrn() <= 0,
                       Errors.create().key(MessageIdList.LOT_MISSING_ID).content("No such lotId!").build());
        Assert.isTrue(isNPWLot(lot.getLotId()),
                      Errors.create().key(MessageIdList.BANK_NOT_BANK).content("The lot is not in the lot bank!")
                            .build());

        //拦截MonitorSource创建的测机批次不允许bankout
        Map condition = new HashMap();
        condition.put("lotId", lotId);
        List<NpwBank> bankInfos = lotQueryService.getNPWBankLot(condition);
        Assert.isFalse(CollectionUtils.isNotEmpty(bankInfos) &&
                               NpwConstants.LOT_TYPE_IN_BANK_SUB.equalsIgnoreCase(bankInfos.get(0).getLotTypeInBank()),
                       Errors.create().key(MessageIdList.NPWBANK_CHILDLOT_CANT_BANKOUT)
                             .content("MonitorSource的子批不允许在此操作!").build());

        if (!dmmService.checkNpwBankOut(lot.getLotId())) {
            lots.add(lot);
        } else {
            throw new SystemIllegalArgumentException(
                    Errors.create().key(MessageIdList.BANK_EXIST_CHILD_LOTS).content("Lot:{} had child lots in bank!")
                          .args(lot.getLotId()).build());
        }
        theform.setLotId("");
        theform.setLots(lots);
        theform.setCacheCollection(WebUtils.getCacheObj2String(lots));
        request.setAttribute("lots", lots);
        return (mapping.findForward("modify"));
    }

    public ActionForward doBankIn(ActionMapping mapping, NpwBankInfoForm theform, HttpServletRequest request,
                                  HttpServletResponse response) {
        List lots = (List) WebUtils.getCacheString2Obj(theform.getCacheCollection());
        Map transMap = new HashMap();
        String operationId = theform.getOperationId().trim().toUpperCase();
        String eqptId = theform.getEqptId().trim().toUpperCase();
        Assert.isFalse(CollectionUtils.isEmpty(lots),
                       Errors.create().key(MessageIdList.BANK_PLEASE_ADD_LOTS).content("Please add lots!").build());
        Assert.isFalse(StringUtils.isBlank(eqptId),
                       Errors.create().key(MessageIdList.BANK_PLEASE_SELECT_EQPT).content("Please select a equipment!")
                             .build());

        transMap.put("lots", lots);
        transMap.put("transId", TransactionNames.NPW_BANK_IN);
        transMap.put("transComments", theform.getTransComments());
        transMap.put("eqptId", eqptId);
        transMap.put("eqptRrn", getInstanceRrn(eqptId, LocalContext.getFacilityRrn(), ObjectList.ENTITY_KEY));
        transMap.put("operationId", operationId);
        transMap.put("operationRrn",
                     getInstanceRrn(operationId, LocalContext.getFacilityRrn(), ObjectList.OPERATION_KEY));
        transMap.put("userRrn", LocalContext.getUserRrn());
        transMap.put("userId", LocalContext.getUserId());
        transMap.put("facilityRrn", LocalContext.getFacilityRrn());
        transMap.put("lotTypeInBank", "main");
        transMap.put("status", "PROCESSING");
        transMap.put("subStatus", "WAITING");
        dmmService.bankIn(transMap);
        request.setAttribute("lots", new ArrayList());
        theform.setLots(new ArrayList());
        theform.setCacheCollection(WebUtils.getCacheObj2String(new ArrayList()));
        theform.setTransComments("");
        request.setAttribute("bankInSucess", "1");
        return (mapping.findForward("modify"));
    }

    public ActionForward doBankOut(ActionMapping mapping, NpwBankInfoForm theform, HttpServletRequest request,
                                   HttpServletResponse response) {
        List lots = (List) WebUtils.getCacheString2Obj(theform.getCacheCollection());
        Assert.isFalse(CollectionUtils.isEmpty(lots),
                       Errors.create().key(MessageIdList.BANK_PLEASE_ADD_LOTS).content("Please add lots!").build());
        Map transMap = new HashMap();
        transMap.put("lots", lots);
        transMap.put("userId", LocalContext.getUserId());
        transMap.put("userRrn", LocalContext.getUserRrn());
        transMap.put("facilityRrn", LocalContext.getFacilityRrn());
        transMap.put("transId", TransactionNames.NPW_BANK_OUT);
        for (int i = 0; i < lots.size(); i++) {
            Lot lot = (Lot) lots.get(i);
            Assert.isFalse(dmmService.checkNpwBankOut(lot.getLotId()),
                           Errors.create().key(MessageIdList.BANK_EXIST_CHILD_LOTS)
                                 .content("Lot:{} had child lots in " + "bank!").args(lot.getLotId()).build());
        }
        dmmService.npwBankOut(transMap);
        theform.setLots(new ArrayList());
        theform.setTransComments("");
        theform.setEqptId("");
        theform.setCacheCollection(WebUtils.getCacheObj2String(new ArrayList()));
        request.setAttribute("bankOutSucess", "1");
        request.setAttribute("lots", new ArrayList());
        return (mapping.findForward("modify"));
    }

    public ActionForward deleteLot(ActionMapping mapping, NpwBankInfoForm theform, HttpServletRequest request,
                                   HttpServletResponse response) {
        List lots = (List) WebUtils.getCacheString2Obj(theform.getCacheCollection());
        Iterator it = lots.iterator();
        Lot _temp_lot = null;
        long _delete_lot_rrn = Long.parseLong(request.getParameter(Constants.ITEM_KEY));

        while (it.hasNext()) {
            _temp_lot = (Lot) it.next();

            if (_temp_lot.getLotRrn() == _delete_lot_rrn) {
                lots.remove(_temp_lot);
                break;
            }
        }
        theform.setLots(lots);
        theform.setCacheCollection(WebUtils.getCacheObj2String(lots));
        request.setAttribute("lots", lots);
        return (mapping.findForward("modify"));
    }

    public ActionForward bankinLot(ActionMapping mapping, NpwBankInfoForm theform, HttpServletRequest request,
                                   HttpServletResponse response) {
        request.setAttribute("lots", new ArrayList());
        request.setAttribute("currentPage", 1);
        request.setAttribute("pageSize", PAGESIZE);
        request.setAttribute("maxPage", 0);
        request.setAttribute("lotId", "");
        request.setAttribute("carrierId", "");
        request.setAttribute("startDate", "");
        request.setAttribute("endDate", "");

        return mapping.findForward("query");
    }

    public ActionForward getBankedInLotInfo(ActionMapping mapping, NpwBankInfoForm theform, HttpServletRequest request,
                                            HttpServletResponse response) {
        String lotId = WebUtils.getParameterUpperCase("lotId", request);
        String carrierId = WebUtils.getParameterUpperCase("carrierId", request);
        String startDate = WebUtils.getParameter("startDate", request);
        String endDate = WebUtils.getParameter("endDate", request);

        int current = 1;

        if (StringUtils.isNotEmptyTrim(WebUtils.getParameter("page", request))) {
            current = 1;
        }
        if (StringUtils.isEmpty(WebUtils.getParameter("page", request)) &&
                StringUtils.isNotEmpty(request.getParameter(THISPAGE_KEY))) {
            current = (int) NumberUtils.toDouble(request.getParameter(THISPAGE_KEY));
        }

        int currentPage = current * PAGESIZE;
        Assert.isTrue(StringUtils.isEmpty(startDate) && !DateUtils.isTimeYearMonthDay(startDate),
                      Errors.create().key(MessageIdList.BANK_ILLEGAL_START_DATE).content("Illegal start date!")
                            .build());

        Assert.isTrue(StringUtils.isEmpty(endDate) && !DateUtils.isTimeYearMonthDay(endDate),
                      Errors.create().key(MessageIdList.BANK_ILLEGAL_END_DATE).content("Illegal end date!").build());

        Map<String, String> queryInfo = new HashMap<String, String>();
        queryInfo.put("lotId", lotId);
        queryInfo.put("carrierId", carrierId);
        queryInfo.put("startDate", startDate);
        queryInfo.put("endDate", endDate);

        List lotsListCollection = dmmLotService.getNPWBankLot(queryInfo);
        request.setAttribute("lots", (lotsListCollection).subList(currentPage - PAGESIZE, currentPage >
                lotsListCollection.size() ? lotsListCollection.size() : currentPage));
        request.setAttribute("currentPage", current);
        request.setAttribute("pageSize", PAGESIZE);
        request.setAttribute("maxPage", Math.ceil((double) lotsListCollection.size() / PAGESIZE));
        request.setAttribute("lotId", lotId);
        request.setAttribute("carrierId", carrierId);
        request.setAttribute("startDate", startDate);
        request.setAttribute("endDate", endDate);
        return mapping.findForward("query");
    }

    private boolean validateLot(Long operationRrn, List lots, NpwBankInfoForm theform, Lot lot) {
        Assert.isTrue(lot.getLotRrn() != 0,
                      Errors.create().key(MessageIdList.LOT_MISSING_ID).content("No such lotId!").build());
        theform.setLotId("");
        theform.setOrder_Id("");
        String message = "";
        boolean check = true;

        if (StringUtils.equalsIgnoreCase(theform.getTransId(), BANKIN)) {
            if (!StringUtils.equalsIgnoreCase(lot.getLotStatus(), LotStatus.WAITING)) {
                check = false;
                message = I18nUtils.getMessage("bank.status_must_waiting");
            }
            /**
             * 增加判断该LOT是否属于这个operation下的,不属于不能bank in
             */
            if (!lot.getOperationRrn().equals(operationRrn)) {
                check = false;
                message = I18nUtils.getMessage("bank.lot_not_in_bank");
            }
        } else {

            if (!StringUtils.equalsIgnoreCase(lot.getLotStatus(), LotStatus.WAITING)) {
                check = false;
                message = I18nUtils.getMessage("lot_prossing_cant_bankout");
            }
        }

        Assert.isTrue(check, Errors.create().content(message).build());

        return check;
    }

    private void bankIn(Map transInfo) {
        dmmService.npwBankIn(transInfo);
        List lots = (List) transInfo.get("lots");
        for (int i = 0; i < lots.size(); i++) {
            Lot lot = (Lot) lots.get(i);
            List<Unit> list = wipQueryService.getUnitList(lot.getCarrierRrn());
            if (CollectionUtils.isEmpty(list)) {
                Integer count = prpService.getProductSumLoopCount(lot.getProductRrn());
                if (count == null) {
                    count = 0;
                }
                ProcessLoopInfo loopInfo = new ProcessLoopInfo();
                loopInfo.setLoopCount(count + "");
                loopInfo.setProcessRrn(lot.getProcessRrn());
                Map<String, Object> loopCountInfo = new HashMap<String, Object>();
                loopCountInfo.put("lotRrn", lot.getLotRrn());
                loopCountInfo.put("count", count);
                loopCountInfo.put("loopInfo", loopInfo);
                loopCountInfo.put("transType", TransactionNames.NPWUNITSINIT);
                loopCountInfo.put("reasonCode", "DUMMY-BANKIN");
                loopCountInfo.put("user", MapUtils.getString(transInfo, "userId"));
                loopCountInfo.put("reason", "DUMMY BANK IN-units usage 初始化");
                loopCountInfo.put("comments", "DUMMY BANK IN");
                loopCountInfo.put("userRrn", MapUtils.getLong(transInfo, "userRrn"));
                dmmLotService.initDMMUnitCounts(loopCountInfo);
            }
        }
    }

}