BatchCancelFutureHold.java

package com.mycim.webapp.actions.lot.batchcancelfuturehold;

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
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.ListUtils;
import com.mycim.framework.utils.lang.collections.MapUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.consts.ContextNames;
import com.mycim.valueobject.consts.TransactionNames;
import com.mycim.valueobject.prp.ProcessPlanning;
import com.mycim.valueobject.prp.ProcessVersion;
import com.mycim.valueobject.wip.Lot;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.WipSetupAction;
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.*;
import java.util.stream.Collectors;

/**
 * @author can.yang
 * @date 2021/10/19
 */
public class BatchCancelFutureHold extends WipSetupAction {

    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        return mapping.getInputForward();
    }

    public Map<String, Object> queryLots(Map map) {
        long facilityRrn = LocalContext.getFacilityRrn();
        String productId = StringUtils.trimToUpperCase(MapUtils.getString(map, "productId"));
        Assert.isFalse(StringUtils.isBlank(productId),
                       Errors.create().key(MessageIdList.BATCHFUTUREHOLDLOT_SELECT_PRODUCTID)
                             .content("The Part Have Not Select Or KeyIn!").build());

        long productRrn = getInstanceRrn(productId, getNamedSpace(ObjectList.PRODUCT_KEY, facilityRrn),
                                         ObjectList.PRODUCT_KEY);
        Assert.isFalse(productRrn <= 0,
                       Errors.create().key(MessageIdList.PRODUCT_PRODUCT_MISSING).content("产品不存在!").build());
        List<Map> processIdList = new ArrayList<>();
        List<String> processIds = prpService.getProcessIdsByProductRrn(productRrn);
        for (String processId : processIds) {
            Map processIdMap = new HashMap(processIds.size());
            processIdMap.put("processId", processId);
            processIdMap.put("processRrn", getInstanceRrn(processId, facilityRrn, ObjectList.WFL_KEY));
            processIdList.add(processIdMap);
        }
        Map<String, Object> result = new HashMap();
        //result.put("lots", lotsList); //此处不查询了 qryLots方法 查询批次信息
        result.put("processIds", processIdList);
        result.put("productId", productId);
        result.put("productRrn", productRrn);
        return result;
    }

    public List<Map> qryLots(Map map) {
        int processVersion = MapUtils.getIntValue(map, "processVersion");
        long processRrn = MapUtils.getLongValue(map, "processRrn");
        String productId = StringUtils.trimToUpperCase(MapUtils.getString(map, "productId"));
        long productRrn = 0L;
        if (StringUtils.isNotEmpty(productId)) {
            productRrn = getInstanceRrn(productId, getNamedSpace(ObjectList.PRODUCT_KEY, LocalContext.getFacilityRrn()),
                                        ObjectList.PRODUCT_KEY);
            Assert.isFalse(productRrn <= 0,
                           Errors.create().key(MessageIdList.PRODUCT_PRODUCT_MISSING).content("产品不存在!").build());
        }
        if (productRrn <= 0 || processRrn <= 0 || processVersion <= 0) {
            return ListUtils.newArrayList();
        }
        Assert.isFalse(baseService.isExisted(processRrn) == null,
                       Errors.create().key(MessageIdList.PROCESS_PROCESS_MISSING).content("流程不存在!").build());
        HashMap<Object, Object> actionMap = MapUtils.newHashMap();
        String routeId = MapUtils.getString(map, "routeId");
        if (StringUtils.isNotEmptyTrim(routeId)) {
            routeId = routeId.trim();
            long routeRrn = this
                    .getInstanceRrn(routeId, this.getNamedSpace("WFL", LocalContext.getFacilityRrn()), "WFL", "ROUTE");
            Assert.isFalse(routeRrn <= 0,
                           Errors.create().key(MessageIdList.ROUTE_ROUTE_MISSING).content("路径号不存在!").build());
            actionMap.put("routeRrn", new Long(routeRrn));
        }
        String operationId = MapUtils.getString(map, "operationId");
        if (StringUtils.isNotEmptyTrim(operationId)) {
            operationId = operationId.trim();
            long operationRrn = this
                    .getInstanceRrn(operationId, this.getNamedSpace("OPERATION", LocalContext.getFacilityRrn()),
                                    "OPERATION");
            Assert.isFalse(operationRrn <= 0,
                           Errors.create().key(MessageIdList.INSTRUCTIONEDIT_OPERATION_MISSING).content("步骤号不存在!")
                                 .build());
            actionMap.put("operationRrn", new Long(operationRrn));
        }
        actionMap.put("processVersion", processVersion);
        actionMap.put("processRrn", processRrn);
        actionMap.put("productRrn", productRrn);
        long refRrn = getInstanceRrn(ContextNames.EEN_CONTEXT_HOLDLOT, LocalContext.getFacilityRrn(),
                                     ObjectList.CONTEXT_KEY);
        List<Map> lotsList = lotQueryService.getBatchCancelFutureHoldLots(actionMap, refRrn);

        return lotsList;
    }

    public List<Map<String, String>> getProcessVersionByProcess(Map map) throws Exception {
        List<Map<String, String>> result = new ArrayList<>();
        long processRrn = MapUtils.getLongValue(map, "processRrn");
        if (processRrn > 0) {
            ProcessPlanning processPlanning = new ProcessPlanning(processRrn);
            List<ProcessVersion> processVersions = prpService.getProcessVersions(processPlanning);
            Assert.isFalse(CollectionUtils.isEmpty(processVersions),
                           Errors.create().key(MessageIdList.PROCESS_NO_VERSION)
                                 .content("There is no version under the " + "process!").build());
            processVersions.forEach(processVersion -> {
                String key = String.valueOf(processVersion.getInstanceVersion());
                String text = key + "(" + processVersion.getVersionStatus() + ")";
                Map<String, String> m = new LinkedHashMap<>(2);
                m.put("key", key);
                m.put("text", text);
                result.add(m);
            });
        }
        return result;
    }

    public Map<String, Object> batchCancelFutureHoldInfo(ActionMapping mapping, HttpServletRequest request, Map map) {
        List<Map> cancelFutureHoldLots = (List<Map>) map.get("dataArray");
        String comments = MapUtils.getString(map, "comments");
        Assert.isFalse(cancelFutureHoldLots.size() <= 0,
                       Errors.create().key(MessageIdList.BATCHBANKSELECT_LOT).content("Please select lot id!").build());
        Assert.isFalse(StringUtils.isBlank(comments),
                       Errors.create().key(MessageIdList.CARRIER_COMMENTS_EMPTY).content("Comments can not be empty!")
                             .build());
        if (cancelFutureHoldLots.size() > 1) {
            checkHoldCodeAndReason(cancelFutureHoldLots);
        }
        List<Map> batchCancelFutureHoldInfos = new ArrayList<>();
        for (Map cancelFutureHoldLot : cancelFutureHoldLots) {
            cancelFutureHoldLot.put("comments", comments);
            Map transMap = buildLot(cancelFutureHoldLot);
            batchCancelFutureHoldInfos.add(transMap);
        }
        wipService.batchDeleteFutureHold(batchCancelFutureHoldInfos);
        Map<String, Object> result = new HashMap();
        result.put("adjustInfos", WebUtils.getCacheObj2String(batchCancelFutureHoldInfos));
        return result;
    }

    public void validateLot(Lot lot) {
        Assert.isFalse(lot.getLotRrn() <= 0,
                       Errors.create().key(MessageIdList.LOT_LOTRRN_NOT_FOUND).content("批次不存在!").build());
    }

    public Map buildLot(Map map) {
        String lotId = MapUtils.getString(map, "lotId");
        String comments = MapUtils.getString(map, "comments");
        String routeId = MapUtils.getString(map, "routeId");
        String operationId = MapUtils.getString(map, "operationId");
        String actionRrn = MapUtils.getString(map, "actionRrn");
        String seqNum = MapUtils.getString(map, "seqNum");
        long refRrn = getInstanceRrn(ContextNames.EEN_CONTEXT_HOLDLOT, LocalContext.getFacilityRrn(),
                                     ObjectList.CONTEXT_KEY);
        Long facilityRrn = LocalContext.getFacilityRrn();
        long userRrn = LocalContext.getUserRrn();
        String userId = LocalContext.getUserId();
        String delSeq = MapUtils.getString(map, "flowSeq");
        String holdCode = MapUtils.getString(map, "holdCode");
        String holdReason = MapUtils.getString(map, "holdReason");
        if (StringUtils.isEmpty(holdReason)) {
            holdReason = StringUtils.EMPTY;
        }

        long routeRrn = this.getInstanceRrn(routeId, this.getNamedSpace("WFL", facilityRrn), "WFL", "ROUTE");
        long operationRrn = this.getInstanceRrn(operationId, this.getNamedSpace("OPERATION", facilityRrn), "OPERATION");

        Lot lot = lotQueryService.getLot(lotId, facilityRrn);
        validateLot(lot);

        Map transInfo = new HashMap();
        transInfo.put("actionRrn", new Long(actionRrn));
        transInfo.put("refRrn", new Long(refRrn));
        transInfo.put("routeRrn", new Long(routeRrn));
        transInfo.put("operationRrn", new Long(operationRrn));
        transInfo.put("lotRrn", lot.getLotRrn());
        transInfo.put("comments", comments);
        transInfo.put("type", "lot");
        transInfo.put("transBy", userId);
        transInfo.put("seqNum", Integer.valueOf(seqNum));
        transInfo.put("userRrn", userRrn);
        transInfo.put("byLotFlag", "Y");
        transInfo.put("lot", lot);
        StringBuffer transComments = new StringBuffer(TransactionNames.BY_LOT_DELETE_FUTURE_HOLD);
        transComments.append(", Flow seq:").append(delSeq).append(" Hold Code:").append(holdCode)
                     .append(" Hold Comment:").append(holdReason);
        transInfo.put("transComments", transComments);

        return transInfo;
    }

    public void checkHoldCodeAndReason(List<Map> dataArray) {
        List<String> holdCodes = new ArrayList<>();
        List<String> reasons = new ArrayList<>();
        for (Map map : dataArray) {
            String holdCode = MapUtils.getString(map, "holdCode", StringUtils.EMPTY);
            holdCodes.add(holdCode);
            String reason = MapUtils.getString(map, "holdReason", StringUtils.EMPTY);
            reasons.add(reason);
        }
        for (int i = 0; i < holdCodes.size(); i++) {
            int count = 1;
            for (int j = 0; j < holdCodes.size(); j++) {
                if (i == j) {
                    continue;
                }
                if (StringUtils.equals(holdCodes.get(i), holdCodes.get(j))) {
                    count++;
                }
            }
            Assert.isFalse((count == 1), Errors.create().key(MessageIdList.BATCH_CANCELFUTUREHOLD_LOTS_MATCH)
                                               .content("{}  hold code and reason are different from others!")
                                               .args(MapUtils.getStringCheckNull(dataArray.get(i), "lotId")).build());
            Assert.isFalse((count != 1 && count != holdCodes.size() && count != holdCodes.size() - 1),
                           Errors.create().key(MessageIdList.BATCH_CANACELFUTUREHOLD_MORE_LOTS_MATCH)
                                 .content("The holdCode and reason of the selected lot must be the same!").build());
        }
        for (int i = 0; i < reasons.size(); i++) {
            int count = 1;
            for (int j = 0; j < reasons.size(); j++) {
                if (i == j) {
                    continue;
                }
                if (StringUtils.equals(reasons.get(i), reasons.get(j))) {
                    count++;
                }
            }
            Assert.isFalse((count == 1), Errors.create().key(MessageIdList.BATCH_CANCELFUTUREHOLD_LOTS_MATCH)
                                               .content("{}  hold code and reason are different from others!")
                                               .args(MapUtils.getStringCheckNull(dataArray.get(i), "lotId")).build());
            Assert.isFalse((count != 1 && count != holdCodes.size() && count != holdCodes.size() - 1),
                           Errors.create().key(MessageIdList.BATCH_CANACELFUTUREHOLD_MORE_LOTS_MATCH)
                                 .content("The holdCode and reason of the selected lot must be the same!").build());
        }
    }

}