RecipeListAction.java

/*
 *        @ Copyright 2001 FA Software;
 *        All right reserved. No part of this program may be reproduced or
 *        transmitted in any form or by any means, electronic or
 *        mechanical, including photocopying, recording, or by any
 *        information storage or retrieval system without written
 *        permission from FA Software, except for inclusion of brief
 *        quotations in a review.
 */
package com.mycim.webapp.actions.equipment.recipe;

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
import com.fa.sesa.threadlocal.LocalContext;
import com.mycim.framework.utils.lang.BooleanUtils;
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.bas.Relation;
import com.mycim.valueobject.consts.EventName;
import com.mycim.valueobject.consts.LinkTypeList;
import com.mycim.valueobject.ems.Entity;
import com.mycim.valueobject.prp.Recipe;
import com.mycim.valueobject.prp.RecipeStatus;
import com.mycim.webapp.Constants;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.EmsSetupAction;
import com.mycim.webapp.forms.EntityInfoForm;
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.*;

public class RecipeListAction extends EmsSetupAction {
    private static final String FLAG = "1";

    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        EntityInfoForm theform = (EntityInfoForm) form;
        Entity theEntity = getEntity(theform, request);

        if (StringUtils.isNotBlank(WebUtils.getParameter("equipmentReadOnlyFlag", request))) {
            request.setAttribute("equipmentReadOnlyFlag", 1);
        }

        if (BooleanUtils.toBoolean(theEntity.getIsChamberEquip())) {
            if (Objects.nonNull(theEntity.getChamberMode())) {
                return mapping.findForward("chamber");
            }
        }

        List<Map> recipeList = null;
        if (StringUtils.isNotBlank(theform.getSearchRecipeId())) {
            String searchId = StringUtils.trimToUpperCase(theform.getSearchRecipeId());
            recipeList = recipeService
                    .getFullRelationForRecipe(theEntity.getInstanceRrn(), LinkTypeList.ENTITY_TO_RECIPE, searchId);
            theform.setSearchRecipeId(searchId);
        } else {
            recipeList = recipeService
                    .getFullRelationForRecipe(theEntity.getInstanceRrn(), LinkTypeList.ENTITY_TO_RECIPE);
            theform.setSearchRecipeId("");
        }

        recipeList = recipeService.validateRecipeExipreTime(recipeList);
        setRecipeFlag(recipeList);
        
        request.setAttribute("recipeHistoryList",
                             recipeService.getDeleteRelationHistoryByEntityForRecipe(theEntity.getInstanceRrn()));
        //非chamber机台 或者 chamber mode = OFF 的机台,EQP setup 界面的 reciplist 界面按照 recipeID 正序排序
        if(CollectionUtils.isNotEmpty(recipeList)){
            Collections.sort(recipeList, (o1, o2) -> {
                String id1=MapUtils.getString(o1,"recipeId");
                String id2=MapUtils.getString(o2,"recipeId");
                if (StringUtils.isNotEmpty(id1) && StringUtils.isNotEmpty(id2)){
                    return id1.compareTo(id2);
                }
                return 0;
            });
        }
        request.setAttribute("recipeList", recipeList);
        theform.setTransId("modify");
        return mapping.getInputForward();
    }

    public ActionForward updateMembers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                       HttpServletResponse response) throws Exception {
        EntityInfoForm theform = (EntityInfoForm) form;
        Entity theEntity = getEntity(theform, request);
        Assert.state(theform!=null && StringUtils.isNotEmpty(theform.getReason()),
                     Errors.create().key(MessageIdList.ERROR_REASON_IS_EMPTY).content(" Reason is empty").build());
        Long recipeRrn = new Long(request.getParameter(Constants.ITEM_KEY));
        Relation relation = new Relation();
        relation.setLinkType(LinkTypeList.ENTITY_TO_RECIPE);
        relation.setFromRrn(theEntity.getInstanceRrn());
        relation.setToRrn(recipeRrn);

        relation = baseService.getRelation(relation);

        relation.setTransId(Constants.UPDATE_KEY);
        relation.setTransPerformedby(LocalContext.getUserId());

        String status = request.getParameter("status");
        relation.setAttributedata1(RecipeStatus.getContrary(status.toUpperCase()));
        relation.setAttributedata2(String.valueOf(LocalContext.getUserRrn()));
        relation.setAttributedata3(DateUtils.formatDate(new Date()));

        Assert.isFalse(StringUtils.isNotBlank(relation.getAttributedata5()) &&
                               (DateUtils.compareDateStringWithNow(relation.getAttributedata5())) < 0,
                       Errors.create().key(MessageIdList.RECIPE_TIME_IS_EXPIRED)
                             .content("The test recipe time has expired, please check the" + " test recipe time!")
                             .build());

        String recipeId = getInstanceId(recipeRrn);
        isAllowModifyEqptRecipe(theEntity.getInstanceRrn(), recipeRrn, recipeId);

        emsService.updateRel4EntityRecipeToEntity(relation);

        WebUtils.setSuccessMsg(request);
        return init(mapping, theform, request, response);
    }

    private void checkRecipeIsInUse(long entityRrn, Long recipeRrn) {
        Assert.isFalse(wipQueryService.checkLotStatus(recipeRrn, entityRrn),
                       Errors.create().key(MessageIdList.RECIPE_CANT_OPERATION_HAS_RUN_LOT).content(
                               "a lot runing on the" + " " + "EQP by the " + "recipe,this " + "operation cannot " +
                                       "be performed!").build());
    }

    public ActionForward batchUpdateMembers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                            HttpServletResponse response) throws Exception {
        EntityInfoForm theform = (EntityInfoForm) form;
        Assert.state(theform!=null && StringUtils.isNotEmpty(theform.getReason()),Errors.create().key(MessageIdList.ERROR_REASON_IS_EMPTY).content(" Reason is empty").build());
        Entity theEntity = getEntity(theform, request);
        String[] selectUpdateRecipeRrns = request.getParameterValues("selectUpdateStatus");
        //String[] recipeRrns = request.getParameterValues("recipeRrns");
        String status = request.getParameter("changeStatus");
        String comments = WebUtils.getParameter("reason", request);
        //String recipeRrnsString = "";

        /*if (recipeRrns != null) {
            for (int i = 0; i < recipeRrns.length; i++) {
                // 查询该recipeId
                String recipeId = getInstanceId(new Long(recipeRrns[i]));
                isAllowModifyEqptRecipe(theEntity.getInstanceRrn(), new Long(recipeRrns[i]), recipeId);
                recipeRrnsString = recipeRrnsString + recipeRrns[i];
                if (i != recipeRrns.length - 1) {
                    recipeRrnsString += ",";
                }
            }
        }*/
        Assert.isFalse(selectUpdateRecipeRrns == null || selectUpdateRecipeRrns.length == 0,
                       Errors.create().key(MessageIdList.RECIPE_MISSING_RECIPE).content("No recipe selected!").build());

        List<Long> recipeRrns = new ArrayList<>();
        for (String selectUpdateRecipeRrn : selectUpdateRecipeRrns) {
            long recipeRrn = NumberUtils.toLong(selectUpdateRecipeRrn);
            checkRecipeIsInUse(theEntity.getInstanceRrn(), recipeRrn);
            recipeRrns.add(recipeRrn);
        }

        Relation relation = new Relation();
        relation.setTransId(Constants.UPDATE_KEY);
        relation.setFromRrn(theEntity.getInstanceRrn());
        relation.setTransPerformedby(LocalContext.getUserId());
        relation.setLinkType(LinkTypeList.ENTITY_TO_RECIPE);
        relation.setAttributedata2(String.valueOf(LocalContext.getUserRrn()));
        relation.setAttributedata3(DateUtils.formatDate(new Date()));
        recipeService.updateRecipesStatus(LocalContext.getUserId(), RecipeStatus.getContrary(status), status, relation,
                                          recipeRrns,comments);
        WebUtils.setSuccessMsg(request);
        return init(mapping, theform, request, response);
    }

    public ActionForward deleteMembers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                       HttpServletResponse response) throws Exception {
        EntityInfoForm theform = (EntityInfoForm) form;
        Assert.state(theform!=null && StringUtils.isNotEmpty(theform.getReason()),Errors.create().key(MessageIdList.ERROR_REASON_IS_EMPTY).content(" Reason is empty").build());
        Entity theEntity = getEntity(theform, request);


        Long recipeRrn = new Long(request.getParameter(Constants.ITEM_KEY));
        // String transId = Constants.DELETE_KEY;
        Entity entity = getEntity(theform, request);
        Relation relation = baseService.getRelation(entity.getInstanceRrn(), recipeRrn, LinkTypeList.ENTITY_TO_RECIPE);
        relation.setFromRrn(theEntity.getInstanceRrn());
        relation.setToRrn(recipeRrn);
        relation.setLinkType(LinkTypeList.ENTITY_TO_RECIPE);
        relation.setLastUpdatedUser(LocalContext.getUserRrn());
        relation.setTransPerformedby(LocalContext.getUserId());
        relation.setTransId(Constants.DELETE_KEY);

        String recipeId = getInstanceId(recipeRrn);
        isAllowDeleteEqptRecipe(theEntity.getInstanceRrn(), recipeRrn, recipeId);

        emsService.deleteRelation4RecipeToEntity(relation,theform.getReason());

        WebUtils.setSuccessMsg(request);
        return init(mapping, theform, request, response);
    }

    public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                             HttpServletResponse response) throws Exception {
        EntityInfoForm theform = (EntityInfoForm) form;
        Assert.state(theform!=null && StringUtils.isNotEmpty(theform.getReason()),Errors.create().key(MessageIdList.ERROR_REASON_IS_EMPTY).content(" Reason is empty").build());
        Entity theEntity = getEntity(theform, request);

        String recipeId = StringUtils.trimToUpperCase(theform.getRecipeId());
        Assert.isFalse(StringUtils.isBlank(recipeId),
                       Errors.create().key(MessageIdList.RECIPE_INVALID_ID).content("Recipe cannot be empty!").build());

        Recipe recipe = recipeService.getRecipe(recipeId, LocalContext.getFacilityRrn());
        Assert.isFalse(recipe == null || recipe.getInstanceRrn() <= 0,
                       Errors.create().key(MessageIdList.RECIPE_RECIPE_ID_NOT_EXIST)
                             .content("Recipe ID: {} is not " + "exist!").args(recipeId).build());

        List<Relation> recipes = baseService
                .getRelationsUseFromRrn(theEntity.getInstanceRrn(), LinkTypeList.ENTITY_TO_RECIPE);
        if (CollectionUtils.isNotEmpty(recipes)) {
            for (Relation r : recipes) {
                Assert.isFalse(r.getToRrn() == recipe.getInstanceRrn(),
                               Errors.create().key(MessageIdList.RECIPE_RECIPE_EXISTS)
                                     .content("RECIPE {} already exists!").args(theform.getRecipeId()).build());
            }
        }

        Relation relation = new Relation();
        relation.setFromRrn(theEntity.getInstanceRrn());
        relation.setLinkType(LinkTypeList.ENTITY_TO_RECIPE);

        if (StringUtils.isNotBlank(recipe.getAttributeData1())) {
            relation.setAttributedata1(RecipeStatus.EXIST_KEY);
        } else {
            relation.setAttributedata1(RecipeStatus.ON_KEY);
        }

        relation.setAttributedata2(String.valueOf(LocalContext.getUserRrn()));
        relation.setAttributedata3(DateUtils.formatDate(new Date()));
        relation.setToRrn(recipe.getInstanceRrn());
        relation.setTransPerformedby(LocalContext.getUserId());
        relation.setTransId(Constants.ADD_KEY);
        relation.setAttributedata5(recipe.getAttributeData2());

        emsService.insertRelation4RecipeToEntity(relation,theform.getReason());
        theform.setRecipeId("");

        WebUtils.setSuccessMsg(request);
        return init(mapping, theform, request, response);
    }

    private void isAllowDeleteEqptRecipe(long instanceRrn, Long recipeRrn, String recipeId) {
        Assert.isFalse(wipQueryService.checkLotStatus(recipeRrn, instanceRrn),
                       Errors.create().key(MessageIdList.RECIPE_NOT_DELETE_HAS_RUN)
                             .content("cannot delete, a lot " + "runing on the " + "EQP by the " + "recipe( {} )!")
                             .args(recipeId).build());

        Assert.isFalse(StringUtils.equals(emsService.getEntityCurrentStatus(instanceRrn), EventName.RUN),
                       Errors.create().key(MessageIdList.RECIPE_NOT_DELETE_HAS_RUN)
                             .content("Cannot delete, the EQP status is RUN!").build());
    }

    private void isAllowModifyEqptRecipe(long instanceRrn, Long recipeRrn, String recipeId) {
        Assert.isFalse(wipQueryService.checkLotStatus(recipeRrn, instanceRrn),
                       Errors.create().key(MessageIdList.RECIPE_NOT_MODIFY_HAS_RUN)
                             .content("cannot modify, a lot " + "runing on the " + "EQP by the " + "recipe( {} )!")
                             .args(recipeId).build());

        Assert.isFalse(StringUtils.equals(emsService.getEntityCurrentStatus(instanceRrn), EventName.RUN),
                       Errors.create().key(MessageIdList.RECIPE_NOT_MODIFY_HAS_RUN_EQP)
                             .content("Cannot modify, the EQP status is RUN!").build());
    }

    private void setRecipeFlag(List<Map> recipeList) {
        for (Object obj : recipeList) {
            Map map = (Map) obj;
            Recipe recipe = recipeService.getRecipe(MapUtils.getString(map, "recipeId"), LocalContext.getFacilityRrn());
            if (recipe != null) {
                map.put("expireFlag", recipe.getAttributeData1());
            } else {
                map.put("expireFlag", "");
            }

        }
    }

    private Entity getEntity(EntityInfoForm theform, HttpServletRequest request) {
        Entity theEntity = new Entity(theform.getInstanceId(),
                                      getNamedSpace(ObjectList.ENTITY_KEY, LocalContext.getFacilityRrn()),
                                      ObjectList.ENTITY_KEY);

        theEntity = (Entity) getInstance(theEntity);
        Assert.isFalse(null == theEntity,
                       Errors.create().key(MessageIdList.EQUIPMENT_MISSING).content("equipment not exist").build());

        emsService.checkEquipmentRecipeInvalid(theEntity.getInstanceRrn());
        if (StringUtils.isNotBlank(WebUtils.getParameter("equipmentReadOnlyFlag", request))) {
            request.setAttribute("equipmentReadOnlyFlag", 1);
        }

        boolean isSubChamberEquipment =
                (theEntity.getParentEntityRrn() != null && theEntity.getParentEntityRrn() != 0) &&
                        StringUtils.isNotEmpty(theEntity.getChamberType());
        Assert.isFalse(isSubChamberEquipment, Errors.create().key(MessageIdList.RECIPE_CHAMBER_NOT_SET)
                                                    .content("Sub chamber equipment cannot set available recipe!")
                                                    .build());

        return theEntity;
    }

    public ActionForward history(ActionMapping mapping, ActionForm form, HttpServletRequest request) {
        EntityInfoForm theform = (EntityInfoForm) form;
        if (StringUtils.isNotBlank(request.getParameter("flag"))) {
            request.setAttribute("flag", FLAG);
        }
        return mapping.findForward(Constants.HISTORY_KEY);
    }
}