BatchAdjustLotAction.java

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

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
import com.fa.sesa.threadlocal.LocalContext;
import com.mycim.framework.utils.beans.BeanUtils;
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.msg.JsonUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
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.valueobject.wip.LotStatus;
import com.mycim.valueobject.wip.TransReason;
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.*;

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

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

    public Map<String, Object> queryProcessIds(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<String> processIds = prpService.getProcessIdsByProductRrn(productRrn);

        Map<String, Object> result = new HashMap();
        result.put("processIds", processIds);
        result.put("productId", productId);
        result.put("productRrn", productRrn);
        return result;
    }

    public Map<String, Object> queryLots(Map map) {
        String productId = MapUtils.getString(map, "productId");
        HashMap<Object, Object> actionMap = MapUtils.newHashMap();
        if (StringUtils.isNotEmptyTrim(productId)) {
            productId = productId.trim();
            long productRrn = this.getInstanceRrn(productId, LocalContext.getFacilityRrn(), ObjectList.PRODUCT_KEY);
            Assert.isFalse(productRrn <= 0,
                           Errors.create().key(MessageIdList.PRODUCT_PRODUCT_MISSING).content("Product not exist!")
                                 .build());
            actionMap.put("productRrn", new Long(productRrn));
        }
        String processId = MapUtils.getString(map, "processId");
        if (StringUtils.isNotEmptyTrim(processId)) {
            processId = processId.trim();
            long processRrn = this
                    .getInstanceRrn(processId, this.getNamedSpace("WFL", LocalContext.getFacilityRrn()), "WFL",
                                    "ROUTE");
            Assert.isFalse(processRrn <= 0,
                           Errors.create().key(MessageIdList.PROCESS_PROCESS_MISSING).content("Process not exist!")
                                 .build());
            actionMap.put("processRrn", new Long(processRrn));
        }
        Integer processVersion = MapUtils.getInteger(map, "processVersion");
        actionMap.put("processVersion", processVersion);
        List<Map> batchAdjustLots = lotQueryService.getBatchAdjustLots(actionMap);
        Map<String, Object> result = new HashMap();
        result.put("lots", batchAdjustLots);

        return result;
    }

    public Map<String, Object> batchAdjustLotInfo(ActionMapping mapping, HttpServletRequest request, Map map) {
        List<Map> adjustLots = (List<Map>) map.get("dataArray");
        Assert.isFalse(adjustLots.size() <= 0,
                       Errors.create().key(MessageIdList.BATCHBANKSELECT_LOT).content("Please select lot id!").build());
        if (adjustLots.size() > 1) {
            checkHotFlagAndPriority(adjustLots);
        }
        List<String> lotRrns = new ArrayList<>();
        List<Map> batchAdjustInfos = new ArrayList<>();
        for (Map adjustLot : adjustLots) {
            String lotId = MapUtils.getString(adjustLot, "lotId");
            Lot lot = lotQueryService.getLot(lotId, LocalContext.getFacilityRrn());
            validateLot(lot);
            adjustLot.putAll(map);
            Map transMap = buildAdjustLotInfo(adjustLot, lot);
            lotRrns.add(StringUtils.toString(lot.getLotRrn()));
            batchAdjustInfos.add(transMap);
        }
        lotService.batchAdjustLot(batchAdjustInfos, lotRrns);
        Map<String, Object> result = new HashMap();
        result.put("adjustInfos", WebUtils.getCacheObj2String(batchAdjustInfos));
        return result;
    }

    public List<Map<String, String>> getProcessVersionByProcess(Map map) {
        List<Map<String, String>> result = new ArrayList<>();
        String processId = MapUtils.getString(map, "processId");
        if (StringUtils.isNotBlank(processId)) {
            processId = processId.trim();
            long processRrn = this
                    .getInstanceRrn(processId, this.getNamedSpace("WFL", LocalContext.getFacilityRrn()), "WFL",
                                    "ROUTE");
            Assert.isFalse(processRrn <= 0,
                           Errors.create().key(MessageIdList.PROCESS_PROCESS_MISSING).content("Process not exist!")
                                 .build());
            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 void validateLot(Lot lot) {
        Assert.isFalse(!(LotStatus.WAITING.equalsIgnoreCase(lot.getLotStatus()) ||
                               LotStatus.HOLD.equalsIgnoreCase(lot.getLotStatus()) ||
                               LotStatus.RUNNING.equalsIgnoreCase(lot.getLotStatus())),
                       Errors.create().key(MessageIdList.LOT_STATUS_NOT_ALLOW).content("Lot Status Not Allowed!")
                             .build());

    }

    public Map buildAdjustLotInfo(Map adjustLot, Lot lot) {
        HashMap<Object, Object> transInfo = MapUtils.newHashMap();
        transInfo.put("transId", TransactionNames.ADJUST_KEY);
        TransReason transReason = new TransReason();
        String reasonCode = MapUtils.getString(adjustLot, "reasonCode");
        String reason = MapUtils.getString(adjustLot, "reason");
        transReason.setReasonCode(reasonCode);
        transReason.setReason(reason);
        transReason.setTransQty1(lot.getQty1());
        transReason.setTransQty2(lot.getQty2());
        transReason.setResponsibility(LocalContext.getUserId());
        transInfo.put("transReason", transReason);
        transInfo.put("lotRrn",lot.getLotRrn());
        Map transBefore = BeanUtils.copyBeanToMap(lot);
        Map before = MapUtils.newHashMap();
        Map after = MapUtils.newHashMap();
        for (String key : ADJUST_LOT_FIELDS) {
            before.put(key, MapUtils.getString(transBefore, key));
        }
        after = before;
        String hotFlag = MapUtils.getString(adjustLot, "hotFlag");
        if (StringUtils.isNotBlank(hotFlag)) {
            after.put("hotFlag", hotFlag);
            transInfo.put("hotFlag", hotFlag);
        }
        String priority = MapUtils.getString(adjustLot, "priority");
        if (StringUtils.isNotBlank(priority)) {
            Integer intPriority = NumberUtils.toInt(priority);
            after.put("priority", intPriority);
            transInfo.put("priority", intPriority);
        }
        transInfo.put("adjustBeforeJson", JsonUtils.toString(before));
        transInfo.put("adjustAfterJson", JsonUtils.toString(after));
        transInfo.put("facilityRrn", LocalContext.getFacilityRrn());
        transInfo.put("lotId", lot.getLotId());
        transInfo.put("user", LocalContext.getUserId());
        long reticleFamilyRrn = wipQueryService.getReticleFamilyRrnByLot(lot);
        transInfo.put("reticleGroupRrn", reticleFamilyRrn);
        transInfo.put("splitMergeFlag", lot.getSplitMergeFlag());
        transInfo.put("createCategory", lot.getCreateCategory());
        transInfo.put("customerId",
                      StringUtils.isNotBlank(lot.getCustomerId()) ? lot.getCustomerId() : StringUtils.EMPTY);
        transInfo.put("shippingCode",
                      StringUtils.isNotBlank(lot.getShippingCode()) ? lot.getShippingCode() : StringUtils.EMPTY);
        transInfo.put("outerOrderNO",
                      StringUtils.isNotBlank(lot.getOuterOrderNO()) ? lot.getOuterOrderNO() : StringUtils.EMPTY);
        transInfo.put("outOrderType",
                      StringUtils.isNotBlank(lot.getOutOrderType()) ? lot.getOutOrderType() : StringUtils.EMPTY);
        transInfo.put("customerLotId",
                      StringUtils.isNotBlank(lot.getCustomerLotId()) ? lot.getCustomerLotId() : StringUtils.EMPTY);
        return transInfo;
    }

    public void checkHotFlagAndPriority(List<Map> dataArray) {
        List<Integer> hotFlags = new ArrayList<>();
        List<Integer> prioritys = new ArrayList<>();
        for (Map map : dataArray) {
            Integer hotFlag = MapUtils.getInteger(map, "hotFlag");
            hotFlags.add(hotFlag);
            Integer priority = MapUtils.getInteger(map, "priority");
            prioritys.add(priority);
        }
        for (int i = 0; i < hotFlags.size(); i++) {
            int count = 1;
            for (int j = 0; j < hotFlags.size(); j++) {
                if (i == j) {
                    continue;
                }
                if (hotFlags.get(i).equals(hotFlags.get(j))) {
                    count++;
                }
            }
            Assert.isFalse((count == 1), Errors.create().key(MessageIdList.BATCH_AdJUST_ONE_LOT_MATCH)
                                               .content("{} Priority 和 Internal Pri. 和其他lot不同!")
                                               .args(MapUtils.getStringCheckNull(dataArray.get(i), "lotId")).build());
            Assert.isFalse((count != 1 && count != prioritys.size() && count != prioritys.size() - 1),
                           Errors.create().key(MessageIdList.BATCH_AdJUST_MORE_LOTS_MATCH)
                                 .content("The Priority and Internal Pri. of the selected lot must be the same!")
                                 .build());
        }
        for (int i = 0; i < prioritys.size(); i++) {
            int count = 1;
            for (int j = 0; j < prioritys.size(); j++) {
                if (i == j) {
                    continue;
                }
                if (prioritys.get(i).equals(prioritys.get(j))) {
                    count++;
                }
            }
            Assert.isFalse((count == 1), Errors.create().key(MessageIdList.BATCH_AdJUST_ONE_LOT_MATCH)
                                               .content("{} Priority 和 Internal Pri. 和其他lot不同!")
                                               .args(MapUtils.getStringCheckNull(dataArray.get(i), "lotId")).build());
            Assert.isFalse((count != 1 && count != prioritys.size() && count != prioritys.size() - 1),
                           Errors.create().key(MessageIdList.BATCH_AdJUST_MORE_LOTS_MATCH)
                                 .content("The Priority and Internal Pri. of the selected lot must be the same!")
                                 .build());
        }
    }

}