UnShipLotAction.java

package com.mycim.webapp.actions.unit.shipandunshiplot;

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.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.consts.CompletedssConstants;
import com.mycim.valueobject.prp.Operation;
import com.mycim.valueobject.wip.Lot;
import com.mycim.valueobject.wip.LotStatus;
import com.mycim.valueobject.wip.TransReason;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liuji.li
 * @version 6.0.0
 * @date 2019/9/29
 **/
public class UnShipLotAction extends WipSetupAction {
    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) throws Exception {

        return mapping.getInputForward();
    }

    public Map<String, Object> unaddmemberlot(Map map) {
        Map<String, Object> result = new HashMap<String, Object>();
        long facilityRrn = LocalContext.getFacilityRrn();
        String lotId = MapUtils.getString(map, "lotId");
        List<Map<String, Object>> lots = new ArrayList<Map<String, Object>>();
        Lot lot = null;
        String shipStatus = StringUtils.trimToUpperCase(MapUtils.getString(map, "shipstatus"));
        Assert.isTrue(StringUtils.isNotBlank(lotId),
                      Errors.create().key(MessageIdList.SHIPLOT_ENTER_LOTID).content("Please enter lot Id!").build());
        lot = lotQueryService.getLot(lotId, facilityRrn);
        Lot completedssLotInfo = lotQueryService.getCompletedssLotInfo(lotId);
        Assert.isFalse((lot == null) || (lot.getLotRrn() <= 0),
                       Errors.create().key(MessageIdList.UNSHIPLOT_LOT_NOT_EXISTS).content("This lot does not exist!")
                             .build());
        Assert.isTrue(("S".equalsIgnoreCase(lot.getLastScheduleFlag())) &&
                              LotStatus.COMPLETEDSS.equalsIgnoreCase(lot.getLotStatus()) &&
                              CompletedssConstants.COMPLETEDSS_TYPE_WAFER
                                      .equalsIgnoreCase(completedssLotInfo.getCompletedssType()),
                      Errors.create().key(MessageIdList.UNSHIPLOT_NOT_STATUS)
                            .content("Lot: {} can't do unship! Please check lot " + "status!").args(lotId).build());
        String carrierId = StringUtils.trimToUpperCase(MapUtils.getString(map, "carrierId"));
        if (StringUtils.isNotBlank(shipStatus) && StringUtils.equalsIgnoreCase(shipStatus, LotStatus.HOLD)) {
            Assert.isFalse(StringUtils.isEmpty(carrierId), Errors.create().key(MessageIdList.UNSHIPLOT_WHEN_HOLD)
                                                                 .content("When the state is equal to HOLD, " +
                                                                                  "please specify the Cassette id!")
                                                                 .build());
        }
        Long operationRrn = lot.getOperationRrn();
        Operation myoperation = prpService.getOperation(operationRrn);
        Assert.nonNull(myoperation, Errors.create().key(MessageIdList.UNSHIPLOT_CHECK_OPERA)
                                          .content("Lot: {} can't do unship! Please check operation!").args(lotId)
                                          .build());
        if (StringUtils.isNotBlank(carrierId)) {
            // check 晶舟的category和type
            carrierService.compareRealAndDummyCarrierAndCheckRealCarrierAvailabile(facilityRrn, lot.getCarrierId(),
                                                                                   carrierId);
            Long carrierRrn = this.getInstanceRrn(carrierId, getNamedSpace(ObjectList.ENTITY_KEY, facilityRrn),
                                                  ObjectList.ENTITY_KEY);
            if (carrierRrn != null || carrierRrn.longValue() > 0) {
                lot.setCarrierId(carrierId);
                lot.setCarrierRrn(carrierRrn);
            }
        }
        Assert.isFalse(workOrderService.getErpPackageCount(lot.getLotRrn()) > 0,
                       Errors.create().key(MessageIdList.UNSCRAP_EXIST_LOT_PACKAGE)
                             .content("Lot package info " + "exists!").build());
        Map<String, Object> resultMap = BeanUtils.copyBeanToMap(lot);
        resultMap.put("shipStatus", shipStatus);
        lots.add(resultMap);
        result.put("lots", lots);
        return result;
    }

    public void unShipLot(Map unShipMap) {
        String user = LocalContext.getUserId();
        Long facilityRrn = LocalContext.getFacilityRrn();
        String fromFacilityId = getInstanceId(facilityRrn);
        String toFacilityId = getInstanceId(MapUtils.getLong(unShipMap, "toFacilityRrn"));
        String reason = MapUtils.getString(unShipMap, "reason");
        unShipMap.put("transPerformedBy", user);
        unShipMap.put("transComments", reason);
        TransReason transReason = new TransReason();
        transReason.setReason(reason);
        transReason.setResponsibility(user);
        unShipMap.put("transReason", transReason);
        List dataArray = (ArrayList) unShipMap.get("dataArray");
        List<String>lots=new ArrayList<>();
        if(CollectionUtils.isNotEmpty(dataArray)){
            lots = (List<String>) dataArray.stream().map((e)->{
                if(e instanceof  HashMap&&((HashMap<?, ?>) e).containsKey("lotRrn")){
                    return StringUtils.toString(((HashMap) e).get("lotRrn")) ;
                }
                return "";
            }).collect(Collectors.toList());
        }
        lots.remove("");
        Assert.isFalse(CollectionUtils.isEmpty(lots), Errors.create().key(MessageIdList.LOT_LOTRRN_NOT_FOUND)
                                                               .content("LotRrns is Empty").build());
        boolean completeLotFlag = checkFacilityProperty(fromFacilityId, toFacilityId);
        lotService.unShipLot(unShipMap,lots);
        if (completeLotFlag) {
            lotService.completeLot(unShipMap,lots);
        } else {
            List<Map> unShipLotList = (List<Map>) unShipMap.get("dataArray");
            for (Map map : unShipLotList) {
                long lotRrn = MapUtils.getLongValue(map, "lotRrn");
                Lot lot = lotQueryService.getLot(lotRrn);
                if (StringUtils.equalsIgnoreCase(lot.getLotStatus(), LotStatus.WAITING)) {
                    Map holdMap = new HashMap();
                    holdMap.put("holdcode", "UNSHIP");
                    holdMap.put("lotId", lot.getLotId());
                    holdMap.put("transPerformedBy", "SYSTEM");
                    holdMap.put("lotRrn", lot.getLotRrn());
                    holdMap.put("holdBy", String.valueOf(0));
                    holdMap.put("holdPassword", "");
                    holdMap.put("transComments", "");
                    TransReason holdTransReason = new TransReason();
                    holdTransReason.setReason("Auto hold after unshipping.");
                    holdTransReason.setReasonCategory("UNSHIP");
                    holdTransReason.setReasonCode("UNSHIP");
                    holdTransReason.setResponsibility("SYSTEM");
                    holdTransReason.setTransQty1(lot.getQty1());
                    holdMap.put("transReason", holdTransReason);
                    lotService.holdLot(holdMap);
                    Map changeProcessInfo = new HashMap();
                    changeProcessInfo.put("lotRrn", new Long(lot.getLotRrn()));
                    changeProcessInfo.put("lotId", lot.getLotId());
                    changeProcessInfo.put("lotStatus", lot.getLotStatus());
                    changeProcessInfo.put("qty", "" + lot.getQty1());
                    changeProcessInfo.put("lotOwner", lot.getLotOwner());
                    changeProcessInfo.put("currOperation", lot.getOperationId());
                    changeProcessInfo.put("transPerformedBy", user);
                    changeProcessInfo.put("productRrn", lot.getProductRrn());
                    changeProcessInfo.put("transReason", transReason);
                    // end
                    if (MapUtils.getString(map, "productId") != null) {
                        changeProcessInfo.put("productId", MapUtils.getString(map, "productId").toUpperCase());
                    }
                    changeProcessInfo.put("processRrn", lot.getProcessRrn());
                    // check if technology is valid for product specified
                    Assert.isTrue(isTechnologyValid4Product((Long) changeProcessInfo.get("productRrn"),
                                                            (Long) changeProcessInfo.get("processRrn")),
                                  Errors.create().content("Invalid technology!").build());
                    String stepNumber = "";
                    List<Map<String, Object>> list = prpService
                            .getProcessAllStepInfo(lot.getProcessRrn(), lot.getProcessVersion(), null, null,
                                                   new Long(99999), null, null, 0);
                    for (Map<String, Object> processInfoMap : list) {
                        long routeRrn = MapUtils.getLong(processInfoMap, "routeRrn");
                        long operationRrn = MapUtils.getLong(processInfoMap, "operationRrn");
                        if (routeRrn == lot.getRouteRrn().longValue() &&
                                operationRrn == lot.getOperationRrn().longValue()) {
                            stepNumber = lot.getProcessRrn() + "." + lot.getProcessVersion() + "." +
                                    MapUtils.getLongValue(processInfoMap, "routeStepRrn") + "|" + lot.getRouteRrn() +
                                    "." + MapUtils.getIntValue(processInfoMap, "routeVersion") + "." +
                                    MapUtils.getLong(processInfoMap, "operationStepRrn");
                        }
                    }
                    Map tempInfo = getStepsInfoByLot(lot, lot.getProcessRrn(), stepNumber);

                    changeProcessInfo.put("stageId", tempInfo.get("stageId"));
                    changeProcessInfo.put("layerId", tempInfo.get("layerId"));
                    changeProcessInfo.put("executionRrn", tempInfo.get("executionRrn"));
                    changeProcessInfo.put("operationRrn", tempInfo.get("operationRrn"));

                    Long operationRrn = (Long) tempInfo.get("operationRrn");

                    Assert.isTrue(checkOperationInFacility(operationRrn, facilityRrn), Errors.create().content(
                            "The new " + "subplan" + "/step" + "  " + "is not " + "in " + "current" + " facility!")
                                                                                             .build());

                    changeProcessInfo
                            .put("operationId", getInstanceId(((Long) tempInfo.get("operationRrn")).longValue()));

                    changeProcessInfo.put("operationVer", tempInfo.get("operationVer"));
                    changeProcessInfo.put("processStepVersion", tempInfo.get("processStepVersion"));
                    changeProcessInfo.put("processVersion", tempInfo.get("processVersion"));

                    changeProcessInfo.put("processStepIdVersion", tempInfo.get("processStepIdVersion"));
                    changeProcessInfo.put("processStepVersion4wfl", tempInfo.get("processStepVersion4wfl"));
                    changeProcessInfo.put("nextoperationRrn1", tempInfo.get("nextoperationRrn1"));
                    changeProcessInfo.put("nextoperationRrn2", tempInfo.get("nextoperationRrn2"));
                    changeProcessInfo.put("nextprocessStepVersion1", tempInfo.get("nextprocessStepVersion1"));
                    changeProcessInfo.put("nextprocessStepIdVersion1", tempInfo.get("nextprocessStepIdVersion1"));
                    changeProcessInfo.put("nextprocessStepVersion2", tempInfo.get("nextprocessStepVersion2"));
                    changeProcessInfo.put("nextprocessStepIdVersion2", tempInfo.get("nextprocessStepIdVersion2"));

                    String temp = (String) tempInfo.get("processStepVersion");
                    String route = "";

                    if (temp != null) {
                        int i = 0;
                        int j = 0;
                        i = temp.indexOf("|");
                        if (i != -1) {
                            j = temp.indexOf("|", i + 1);

                            if (j > 0) {
                                route = temp.substring(i + 1, j);
                            } else if (i > 0) {
                                route = temp.substring(0, i);
                            }
                        }
                    }
                    route = route.replace(',', '.');
                    changeProcessInfo.put("route", route);
                    tempInfo = prpService.getOperationInfo((Long) tempInfo.get("operationRrn"),
                                                           (Integer) tempInfo.get("operationVer"));
                    changeProcessInfo.put("trackUnitFlag", tempInfo.get("trackUnitFlag"));
                    changeProcessInfo.put("keepUnitHistoryFlag", tempInfo.get("keepUnitHistoryFlag"));

                    // get Context info
                    tempInfo = new HashMap();
                    tempInfo.put("productRrn", changeProcessInfo.get("productRrn"));
                    // tempInfo.put("routeId", null);
                    tempInfo.put("routeRrn", parseRouteRrn((String) changeProcessInfo.get("processStepVersion")) + "");
                    tempInfo.put("recipeRrn", null);
                    tempInfo.put("operationRrn", changeProcessInfo.get("operationRrn"));
                    tempInfo.put("technologyRrn", changeProcessInfo.get("processRrn"));
                    tempInfo.put("lotRrn", changeProcessInfo.get("lotRrn"));

                    changeProcessInfo.put("borRrn", ctxExecService.getBomRrn(tempInfo));
                    changeProcessInfo.put("reticleRrn", tempInfo.get("reticleRrn"));
                    changeProcessInfo.put("transPerformedBy", user);
                    changeProcessInfo.put("transComments", reason);

                    lotService.changeLotProcess(changeProcessInfo);
                    String lotStatus = lot.getLotStatus();
                    if (lotStatus.equals(LotStatus.WAITING)) {
                        lotService.updateLotStatus(lot.getLotRrn(), "HOLD");
                        Long dummyCarrierRrn = this
                                .getInstanceRrn("DUMMY" + lot.getLotId(), facilityRrn, ObjectList.ENTITY_KEY);

                        // 因为 Removed CST 和 Install CST 的功能,DUMMY 的 Carrier 不应该被删除,如果 ship
                        // 的时候,把真实Carrier 变更为
                        // DUMMY Carrier,那应该在 Unship 时,指定一个真实晶舟。
                        // 待后续需求确认功能完善时修改,By Qiansheng.Wang
                        /*
                         * if (dummyCarrierRrn != null && dummyCarrierRrn != 0) { Carrier dummyCarrier =
                         * this.getEmsSetupManager().getCarrier(dummyCarrierRrn); TransactionLog
                         * transactionLog
                         * = this.getBaseManager().startTransactionLog(user, TransactionNames
                         * .DELETE_KEY); //
                         * 删除逻辑替换,删除named_object_ext表中数据 //
                         * this.getCarrierManager().deleteCarrier(transactionLog.getTransRrn(), //
                         * dummyCarrier); this.getEmsManager().deleteCarrier(transactionLog.getTransRrn(),
                         * dummyCarrier, transactionLog); }
                         */

                    }

                }
            }
        }
    }

    private boolean checkFacilityProperty(String fromFacility, String toFacility) {
        String data_1_value = sysService
                .referenceDetailExchangeNull("$SHIPFACILITYLIST", fromFacility, toFacility, "DATA_1_VALUE");

        if (data_1_value != null && data_1_value.trim().equalsIgnoreCase("1")) {
            return true;
        } else {
            return false;
        }
    }

}