RecipeVersionSaveAction.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.recipe;

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
import com.fa.sesa.threadlocal.LocalContext;
import com.mycim.framework.utils.beans.PropertyUtils;
import com.mycim.framework.utils.lang.StringUtils;
import com.mycim.framework.utils.lang.collections.CollectionUtils;
import com.mycim.framework.utils.lang.math.NumberUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.bas.NamedObject;
import com.mycim.valueobject.bas.ObjectVersion;
import com.mycim.valueobject.consts.SessionNames;
import com.mycim.valueobject.consts.VersionStatus;
import com.mycim.valueobject.prp.Recipe;
import com.mycim.valueobject.prp.RecipeVersion;
import com.mycim.valueobject.sys.Facility;
import com.mycim.webapp.Constants;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.RecipeSetupAction;
import com.mycim.webapp.forms.RecipeVersionInfoForm;
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.*;

/**
 * Recipe Version
 *
 * @author pinyan.song
 * @version 6.0.0
 * @date 2019-9-3 21:43
 **/
public class RecipeVersionSaveAction extends RecipeSetupAction {
    private static final String RECIPE_VERSIONS = "version";

    private static final String RECIPEVERSIONSAVE_ACTION = "/recipeversionsave.do";

    /**
     * add version
     */
    public ActionForward addVersionWithEcn(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                           HttpServletResponse response) throws Exception {
        RecipeVersionInfoForm theform = (RecipeVersionInfoForm) form;
        Recipe recipe = getRecipeInfo(theform);
        List versions = recipeService.getRecipeVersions(recipe.getInstanceRrn());
        boolean versionEdit = checkVersionEditEnable(versions);
        Assert.isFalse(versionEdit,
                       Errors.create().key(MessageIdList.VERSION_HAS_NOT_ACTIVE_VERSION).content("版本没有激活").build());
        RecipeVersion recipeVersion = new RecipeVersion();
        recipeVersion.copyNamedObject(recipe);

        int newVersionId = recipe.getCurrentVersion() == null ? 1 : recipe.getCurrentVersion() + 1;
        recipeVersion.setInstanceVersion(newVersionId);
        recipeVersion.setVersionId(Integer.toString(newVersionId));
        recipeVersion.setVersionDesc("Automatic schema generation");
        recipeVersion.setTransId(Constants.CREATE_KEY);
        recipeVersion.setTransPerformedby(LocalContext.getUserId());
        request.setAttribute("chamberTypes", new ArrayList());
        recipeService.createRecipeVersion(recipeVersion);
        theform.setTransId(Constants.MODIFY_KEY);
        return init(mapping, theform, request, response);
    }

    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) throws Exception {

        RecipeVersionInfoForm theform = (RecipeVersionInfoForm) form;
        Recipe recipe = getRecipeInfo(theform);

        List<ObjectVersion> versions = (List<ObjectVersion>) recipe.getVersions();

        // 获取facility
        Facility facility = sysService.getFacility(LocalContext.getFacilityRrn());
        request.setAttribute(SessionNames.FACILITY_INFO_KEY, facility);

        request.setAttribute("editaction", RECIPEVERSIONSAVE_ACTION);
        request.setAttribute("initaction", "/recipesave.do");

        request.setAttribute(RECIPE_VERSIONS, versions);

        if (CollectionUtils.isEmpty(versions)) {
            // add version
            theform.setInstanceVersion(1);
            theform.setTransId(Constants.CREATE_KEY);
            return mapping.findForward(Constants.ADDVERSION_KEY);
        } else {
            RecipeVersion recipeVersion = new RecipeVersion();
            if (theform.getInstanceVersion() != 0) {
                for (ObjectVersion objectVersion : versions) {
                    if (objectVersion.getInstanceVersion() == theform.getInstanceVersion()) {
                        recipeVersion.copyObjectVersion(objectVersion);
                        break;
                    }
                }
            } else {
                recipeVersion.copyObjectVersion(versions.get(0));
            }
            recipeVersion = (RecipeVersion) getInstance(recipeVersion);
            recipeVersion.copyNamedObject(recipe);

            List<Map> chamberTypes = new ArrayList<Map>();
            if (StringUtils.isNotBlank(recipeVersion.getChamberTypes()) &&
                    StringUtils.isNotEmpty(recipeVersion.getChamberTypes()) &&
                    !StringUtils.isEqual(RecipeVersion.CHAMBERSEPARATOR, recipeVersion.getChamberTypes())) {
                chamberTypes = recipeService.getChamberTypes(Arrays.asList(
                        StringUtils.split(recipeVersion.getChamberTypes(), RecipeVersion.CHAMBERSEPARATOR)));
                theform.setChamberJoin(chamberTypes.get(0).get("chamberTypeKey").toString());
            }
            request.setAttribute("chamberTypes", chamberTypes);
            request.setAttribute(SessionNames.RECIPE_VERSION_KEY, recipeVersion);

            PropertyUtils.copyProperties(theform, recipeVersion);
            theform.setVersionEditEnable(String.valueOf(checkVersionEditEnable(recipeVersion)));
            theform.setObjectDeleteEnable(checkObjectDeleteEnable(versions));
            theform.setTransId(Constants.MODIFY_KEY);
            theform.setEqptCapability(recipeService.queryRecipeVersionExt(recipeVersion.getInstanceRrn()));
            return mapping.findForward(Constants.MODIFY_KEY);
        }
    }

    @Override
    public ActionForward cancel(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                HttpServletResponse response) {
        RecipeVersionInfoForm theform = (RecipeVersionInfoForm) form;
        request.setAttribute(mapping.getAttribute(), theform);
        return mapping.findForward(Constants.BACK_KEY);

    }

    public ActionForward version(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
        RecipeVersionInfoForm theform = (RecipeVersionInfoForm) form;
        theform.setInstanceVersion(WebUtils.getParameterInt("instanceVersion", request));
        return init(mapping, theform, request, response);
    }

    public ActionForward addChambers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                     HttpServletResponse response) throws Exception {
        RecipeVersionInfoForm theform = (RecipeVersionInfoForm) form;
        Recipe recipe = getRecipeInfo(theform);
        RecipeVersion recipeVersion = getRecipeVersion(recipe, NumberUtils.toInt(theform.getVersionId()));
        Assert.isFalse(recipeVersion == null, Errors.create().key(MessageIdList.VERSION_RECIPE_VERSION_NO_EXITS)
                                                    .content("recipe version no exits").build());

        String chamberJoin = theform.getChamberJoin();

        Assert.isFalse(StringUtils.isNotEmpty(chamberJoin), Errors.create().key(MessageIdList.VERSION_HAS_CHAMBER)
                                                                  .content("A version only allows adding a " +
                                                                                   "Chamber combination, please " +
                                                                                   "delete" + " before adding.")
                                                                  .build());

        String[] chamberType = StringUtils.split(theform.getChamberTypes(), RecipeVersion.CHAMBERSEPARATOR);
        StringBuilder chambers = new StringBuilder();

        for (int i = 0; i < chamberType.length; i++) {
            chambers.append(chamberType[i]);
            if (i != chamberType.length - 1) {
                chambers.append(",");
            }
        }
        chambers.append(RecipeVersion.CHAMBERSEPARATOR);

        recipeVersion.setChamberTypes(chambers.toString());

        modifyRecipeVersion(recipeVersion, theform, recipe);

        theform.setTransId(Constants.MODIFY_KEY);
        request.setAttribute(mapping.getAttribute(), theform);
        WebUtils.setSuccessMsg(request);
        return init(mapping, theform, request, response);
    }

    public ActionForward versionInfo(ActionMapping mapping, RecipeVersionInfoForm form, HttpServletRequest request,
                                     HttpServletResponse response) throws Exception {

        String rrn = request.getParameter("versionRrn");
        String version = request.getParameter("version");


        int ver = Integer.parseInt(version);
        long versionRrn = Long.parseLong(rrn);

        NamedObject namedObject = new NamedObject();
        namedObject.setInstanceRrn(versionRrn);
        namedObject = baseService.getNamedObject(namedObject);

        ObjectVersion pv = baseService.getObjectVersion(versionRrn, ver);
        pv.copyNamedObject(namedObject);

        request.setAttribute("historys",
                             baseService.getObjectVersionHistoryList(pv.getInstanceRrn(), pv.getInstanceVersion()));
        PropertyUtils.copyProperties(form, pv);

        form.setTransId(Constants.MODIFY_KEY);
        request.setAttribute("actionedit", RECIPEVERSIONSAVE_ACTION);

        return (mapping.findForward("detail"));

    }

    public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        RecipeVersionInfoForm theform = (RecipeVersionInfoForm) form;
        Recipe recipe = getRecipeInfo(theform);
        RecipeVersion recipeVersion = getRecipeVersion(recipe, NumberUtils.toInt(theform.getVersionId()));

        if (recipeVersion != null) {
            recipeVersion.setTransId(Constants.DELETE_KEY);
            recipeVersion.setTransPerformedby(LocalContext.getUserId());

            recipeService.deleteRecipeVersion(recipeVersion);
        }

        recipe = getRecipeInfo(theform);

        WebUtils.setSuccessMsg(request);
        if (CollectionUtils.isEmpty(recipe.getVersions())) {
            return init(mapping, theform, request, response);
        } else {
            request.setAttribute(RECIPE_VERSIONS, recipe.getVersions());
            request.setAttribute("editaction", RECIPEVERSIONSAVE_ACTION);
            request.setAttribute("initaction", "/recipesave.do");
            return mapping.findForward(Constants.VERSION_KEY);
        }
    }

    public ActionForward activate(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
        RecipeVersionInfoForm theform = (RecipeVersionInfoForm) form;
        Recipe recipe = getRecipeInfo(theform);
        RecipeVersion recipeVersion = getRecipeVersion(recipe, NumberUtils.toInt(theform.getVersionId()));

        Assert.isFalse(recipeVersion == null,
                       Errors.create().key(MessageIdList.RECIPEVERSION_IS_NULL).content("recipeVersion is null!")
                             .build());

        //        ecnService.activateEcn(recipeVersion.getEcnRrn());
        recipeVersion.setTransId(VersionStatus.ACTIVE_KEY);
        recipeVersion.setVersionStatus(VersionStatus.ACTIVE_KEY);
        recipeService.updateRecipeVersionStatus(recipeVersion);

        recipe = getRecipeInfo(theform);

        PropertyUtils.copyProperties(theform, recipeVersion);

        theform.setVersionStatus(VersionStatus.ACTIVE_KEY);
        theform.setVersionEditEnable(String.valueOf(checkVersionEditEnable(recipeVersion)));
        theform.setObjectDeleteEnable(checkObjectDeleteEnable((List<ObjectVersion>) recipe.getVersions()));
        theform.setTransId(Constants.MODIFY_KEY);

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

    public ActionForward delChambers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                     HttpServletResponse response) throws Exception {
        RecipeVersionInfoForm theform = (RecipeVersionInfoForm) form;
        Recipe recipe = getRecipeInfo(theform);
        RecipeVersion recipeVersion = getRecipeVersion(recipe, NumberUtils.toInt(theform.getVersionId()));
        Assert.isFalse(recipeVersion == null, Errors.create().key(MessageIdList.VERSION_RECIPE_VERSION_NO_EXITS)
                                                    .content("recipe version no exits").build());

        recipeVersion.setChamberTypes(StringUtils.EMPTY);
        modifyRecipeVersion(recipeVersion, theform, recipe);

        theform.setTransId(Constants.MODIFY_KEY);
        theform.setChamberJoin(StringUtils.EMPTY);
        request.setAttribute(mapping.getAttribute(), theform);
        WebUtils.setSuccessMsg(request);
        return init(mapping, theform, request, response);
    }

    public ActionForward modify(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        RecipeVersionInfoForm theform = (RecipeVersionInfoForm) form;
        Recipe recipe = getRecipeInfo(theform);
        RecipeVersion recipeVersion = getRecipeVersion(recipe, NumberUtils.toInt(theform.getVersionId()));

        Assert.isFalse(recipeVersion == null, Errors.create().key(MessageIdList.VERSION_RECIPE_VERSION_NO_EXITS)
                                                    .content("recipe version no exits").build());

        Assert.isFalse(recipeVersion == null, Errors.create().build());

        StringBuilder sb = new StringBuilder();
        String chamberJoin = theform.getChamberJoin();
        sb.append(chamberJoin).append(RecipeVersion.CHAMBERSEPARATOR);
        recipeVersion.setChamberTypes(sb.toString());
        modifyRecipeVersion(recipeVersion, theform, recipe);

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

    public ActionForward versionShow(ActionMapping mapping, ActionForm form, HttpServletRequest request) {
        RecipeVersionInfoForm theform = (RecipeVersionInfoForm) form;
        Recipe recipe = getRecipeInfo(theform);
        List versions = recipeService.getRecipeVersions(recipe.getInstanceRrn());
        request.setAttribute(RECIPE_VERSIONS, versions);
        request.setAttribute("editaction", RECIPEVERSIONSAVE_ACTION);
        request.setAttribute("initaction", "/recipesave.do");
        request.setAttribute("versionedit", Boolean.toString(checkVersionEditEnable(versions)));
        request.setAttribute("systemUsed", recipe.getSystemUsed());

        Facility facility = sysService.getFacility(LocalContext.getFacilityRrn());
        request.setAttribute(SessionNames.FACILITY_INFO_KEY, facility);

        request.setAttribute(mapping.getAttribute(), theform);
        return mapping.findForward(Constants.VERSION_KEY);
    }

    private void modifyRecipeVersion(RecipeVersion recipeVersion, RecipeVersionInfoForm theform, Recipe recipe) {

        String ppid = theform.getPpid();
        List<RecipeVersion> list = recipeService.getRecipeVersionListWithPpid(ppid, getNamedSpace(ObjectList.RECIPE_KEY,
                                                                                                  LocalContext
                                                                                                          .getFacilityRrn()));
        for (RecipeVersion version : list) {
            Assert.isFalse(version.getInstanceRrn() != recipe.getInstanceRrn(),
                           Errors.create().key(MessageIdList.RECIPEVERSION_PPID_HAS_RECIPE)
                                 .content("This ppid had " + "been used for " + "other recipe").build());
        }
        long ppidRrn = getInstanceRrn(ppid, LocalContext.getFacilityRrn(), ObjectList.RECIPE_KEY);
        Assert.isFalse(ppidRrn > 0 && ppidRrn != recipe.getInstanceRrn(),
                       Errors.create().key(MessageIdList.PPID_IS_SET_MES).content("This ppid had been set in MES")
                             .build());

        recipeVersion.setPpid(theform.getPpid());
        recipeVersion.setRecipeComments(theform.getRecipeComments());
        recipeVersion.setSetupId(theform.getSetupId());
        recipeVersion.setProcessTimePerUnit(theform.getProcessTimePerUnit());
        recipeVersion.setProcessTimePerHour(theform.getProcessTimePerHour());

        if (StringUtils.isNotEmpty(theform.getEquipmentModelId())) {
            long equipmentModelRrn = this.getInstanceRrn(theform.getEquipmentModelId().toUpperCase().trim(),
                                                         this.getNamedSpace(ObjectList.EQUIPMENTMODEL_KEY,
                                                                            LocalContext.getFacilityRrn()),
                                                         ObjectList.EQUIPMENTMODEL_KEY);

            Assert.isFalse(equipmentModelRrn <= 0, Errors.create().key(MessageIdList.EQUIPMENT_IS_NOT_EXIST)
                                                         .content("Equipment Model is not Exist").build());

            recipeVersion.setEquipmentModelRrn(equipmentModelRrn);
        }

        recipeVersion.setTransId(Constants.MODIFY_KEY);
        recipeVersion.setTransPerformedby(LocalContext.getUserId());

        recipeService.updateRecipeVersion(recipeVersion, theform.getEqptCapability());
    }

    private RecipeVersion getRecipeVersion(Recipe recipe, int version) {
        List<ObjectVersion> versions = (List<ObjectVersion>) recipe.getVersions();
        ObjectVersion objectVersion = null;
        for (ObjectVersion o : versions) {
            if (o.getInstanceVersion() == version) {
                objectVersion = o;
                break;
            }
        }
        if (objectVersion != null) {
            RecipeVersion recipeVersion = new RecipeVersion();

            recipeVersion.copyObjectVersion(objectVersion);

            recipeVersion = recipeService.getRecipeVersion(recipeVersion);
            recipeVersion.copyNamedObject(recipe);

            return recipeVersion;
        }
        return null;
    }

    private List<Map> processChamberJoin(String chamberJoin) {
        String[] chamberType = StringUtils.split(chamberJoin, StringUtils.COMMA_SIGN);
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < chamberType.length; i++) {
            String chamber = chamberType[i];
            sb.append(chamber);
            if (i != chamberType.length - 1) {
                sb.append("+");
            }
        }

        Map<String, Object> map = new HashMap<String, Object>(1);
        map.put("chamberType", sb.toString());

        List<Map> types = new ArrayList<Map>();
        types.add(map);

        return types;
    }

}