LotSamplingAction.java

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

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
import com.fa.sesa.i18n.I18nUtils;
import com.fa.sesa.threadlocal.LocalContext;
import com.mycim.framework.file.excel.im.ExcelImport;
import com.mycim.framework.file.excel.im.ExcelParser;
import com.mycim.framework.file.excel.im.ExcelRow;
import com.mycim.framework.jdbc.Page;
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.math.NumberUtils;
import com.mycim.framework.utils.lang.time.DateUtils;
import com.mycim.utils.CheckRegexUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.wip.LotSamplingInfo;
import com.mycim.webapp.Constants;
import com.mycim.webapp.ResponseMsgBuilder;
import com.mycim.webapp.TemplateLocation;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.WipSetupAction;
import com.mycim.webapp.forms.lot.LotSamplingForm;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author can.yang
 * @date 2021/6/23
 */
public class LotSamplingAction extends WipSetupAction{

    public static final String LOT_SAMPLING_INFO_CACHE_KEY = "lotSamplingCacheInfos";
    public static final String LOT_SAMPLING_INFO_KEY = "lotSamplings";
    public static final String DEFAULT_STEP_TYPE_KEY = "Y";
    public static final String CONTAIN_ALL_START_KEY = "*,";
    public static final String CONTAIN_ALL_MIDDLE_KEY = ",*,";
    public static final String CONTAIN_ALL_END_KEY = ",*";
    public static final String LOTSAMPLING_IMP_VALID="LOTSAMPLING_IMP_VALID";
    public static final String LOTSAMPLING_IMPORT_TEMPLATE = "LotSampling_import_template_Info-version.xls";
    public static final String CHILD_LOT_ID_SPLIT = ".";
    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        int currentPage = WebUtils.getParameterInt("currentPage", request);
        int pageSize = WebUtils.getParameterInt("pageSize", request);
        if(currentPage <= 0){
            currentPage = 1;
        }
        if(pageSize <= 0){
            pageSize = 20;
        }
        LotSamplingInfo samplingInfo = new LotSamplingInfo();
        Page page = new Page(currentPage, pageSize);
        samplingInfo.setStepType(DEFAULT_STEP_TYPE_KEY);
        page = lotSamplingService.getLotSamplingInfo(page, samplingInfo);
        request.setAttribute(LOT_SAMPLING_INFO_KEY, page.getResults());
        request.setAttribute("currentPage", page.getPageNo());
        request.setAttribute("lastPage", page.getTotalPages());
        request.setAttribute("perPage", page.getPrePage());
        request.setAttribute("nextPage", page.getNextPage());
        return mapping.findForward(Constants.INIT_KEY);
    }
    public ActionForward export(HttpServletRequest request,ActionMapping mapping, ActionForm form,HttpServletResponse response) throws Exception {
        int currentPage = WebUtils.getParameterInt("currentPage", request);
        if(currentPage <= 0){
            currentPage = 1;
        }
        LotSamplingInfo samplingInfo = new LotSamplingInfo();
        Page page = new Page(currentPage, Integer.MAX_VALUE);
        BeanUtils.copyProperties(form, samplingInfo);
        Assert.isFalse(StringUtils.isEmpty(samplingInfo.getStepType()), Errors.create().key(MessageIdList.LOTSAMPLINGCHOSE_STEP_TYPE)
                                                       .content("Please chose step type!").build());
        page = lotSamplingService.getLotSamplingInfo(page, samplingInfo);
        List<LotSamplingInfo> samplingInfoList = (List<LotSamplingInfo>) page.getResults();

        List<Map> list = new ArrayList();
        int i = 1;

        for (LotSamplingInfo sampling : samplingInfoList){
            Map<String, Object> map = BeanUtils.copyBeanToMap(sampling);
            map.put("sequence", i++);
            list.add(map);
        }
        String exportDateTime = DateUtils.getNowTime(DateUtils.DATE_FORMAT4NOSPLICING);
        Map<String, Object> titles = WebUtils.getExportTitles(request);
        String fileName = "LotSampling_" + exportDateTime + ".xls";
        WebUtils.exportExcel(fileName, titles, list, TemplateLocation.LOT_SAMPLING_INFO, response);
        return WebUtils.NULLActionForward;
    }

    public void validateLotSamplingInfo(ActionMapping mapping, LotSamplingForm form,
                                                    HttpServletRequest request, HttpServletResponse response) {

        Long facilityRrn = LocalContext.getFacilityRrn();
        boolean isCn = StringUtils.equalsIgnoreCase(I18nUtils.getCurrentLanguage().toString(), "CN");

        StringBuffer sb = new StringBuffer();


        String stepType = StringUtils.trim(form.getStepType());
        valideImportInfo(stepType, isCn,  (isCn ? "工步类型" : "Step Type"), sb, false);

        String eqpGroupId = StringUtils.trim(form.getEqpGroupId());
        valideImportInfo(eqpGroupId, isCn,  (isCn ? "设备组" : "EQP Grp. ID"), sb, false);

        long instanceRrn = getInstanceRrn(eqpGroupId, getNamedSpace(ObjectList.ENTITYGROUP_KEY, facilityRrn),
                                              ObjectList.ENTITYGROUP_KEY);
        if(instanceRrn <= 0){
            sb.append((isCn ? "设备组无效!<br>" : "EQP Grp. ID  invalidate!<br>"));
        }
        String productId = StringUtils.trim(form.getProductId());
        valideImportInfo(productId, isCn,  (isCn ? "产品" : "Product ID"), sb, true);

        String lotIdList = StringUtils.trim(form.getLotIdList());
        valideImportInfo(lotIdList, isCn,  (isCn ? "批次" : "	Lot ID"), sb, true);

        if(StringUtils.indexOf(lotIdList, CHILD_LOT_ID_SPLIT) >= 0){
            sb.append(isCn ? "批次只需匹配主批次号!<br>" : "lot only match main lot id!<br>");
        }
        String recipe = StringUtils.trim(form.getRecipe());
        valideImportInfo(recipe, isCn,  "Recipe ID", sb, true);

        String stageId = StringUtils.trim(form.getStageId());
        valideImportInfo(stageId, isCn,  "Stage Id", sb, false);

        String flowSeq = StringUtils.trim(form.getFlowSeq());
        valideImportInfo(flowSeq, isCn,  (isCn ? "流程序号" : "Flow seq"), sb, false);

        Assert.isTrue(StringUtils.isBlank(sb),
                       Errors.create().content(sb.toString()).build());

    }

    public ActionForward createImport(ActionMapping mapping, LotSamplingForm form,
                                                    HttpServletRequest request, HttpServletResponse response) {
        String user = LocalContext.getUserId();

        List<LotSamplingInfo> samplingInfoList = (List<LotSamplingInfo>) WebUtils.getCacheString2Obj(WebUtils.getParameter(LOT_SAMPLING_INFO_CACHE_KEY, request));

        lotSamplingService.createImportLotSampling(samplingInfoList, user);
        LotSamplingInfo lotSamplingInfo = new LotSamplingInfo();
        int currentPage = WebUtils.getParameterInt("currentPage", request);
        int pageSize = WebUtils.getParameterInt("pageSize", request);
        if(currentPage <= 0){
            currentPage = 1;
        }
        if(pageSize <= 0){
            pageSize = 20;
        }

        Page page = new Page(currentPage, pageSize);
        lotSamplingInfo.setStepType(DEFAULT_STEP_TYPE_KEY);
        page = lotSamplingService.getLotSamplingInfo(page, lotSamplingInfo);
        request.setAttribute(LOT_SAMPLING_INFO_KEY, page.getResults());
        request.setAttribute("currentPage", page.getPageNo());
        request.setAttribute("lastPage", page.getTotalPages());
        request.setAttribute("perPage", page.getPrePage());
        request.setAttribute("nextPage", page.getNextPage());

        return mapping.findForward(Constants.INIT_KEY);
    }

    public ActionForward importLotSamplingInfo(ActionMapping mapping, LotSamplingForm form,
                                                  HttpServletRequest request, HttpServletResponse response) throws Exception {

        boolean isChN = StringUtils.equalsIgnoreCase(I18nUtils.getCurrentLanguage().toString(), "CN");
        Long facilityRrn = LocalContext.getFacilityRrn();
        boolean flag = false;
        boolean isValid=true;
        FormFile excelFile = form.getFormFile();

        Assert.isFalse(!StringUtils.endsWith(excelFile.getFileName(), ".xls") || excelFile.getFileSize() < 1,
                       Errors.create().key(MessageIdList.IMPORT_ERROR_NAME).content("Only import .xls files!").build());
        //解析导入的数据
        List<LotSamplingInfo> samplingInfoList = this.setLotSamplingExcelData(excelFile);
        if (CollectionUtils.isEmpty(samplingInfoList)) {
            isValid = false;
        }
        //对导入的数据集进行校验,并判断是否存在导入重复数据
        for (int i = NumberUtils.INTEGER_ZERO; i < CollectionUtils.size(samplingInfoList); i++) {
            this.valideLotSamplingExcelData(samplingInfoList.get(i), isChN, facilityRrn);
            flag = false;
            for (int j = NumberUtils.INTEGER_ZERO; j < CollectionUtils.size(samplingInfoList); j++) {
                if (i==j) {
                    continue;
                } else {
                    if(samplingInfoList.get(j).equals(samplingInfoList.get(i))){
                        flag = true;
                    }
                }
            }
            if(flag){
                samplingInfoList.get(i).setComments(samplingInfoList.get(i).getComments() + (isChN ? "存在相同的导入信息!" : "Have same import info!"));
            }
            if (StringUtils.isBlank(samplingInfoList.get(i).getComments())){
                isValid=false;
            }
        }

        request.setAttribute(LOT_SAMPLING_INFO_KEY, samplingInfoList);
        request.setAttribute(LOT_SAMPLING_INFO_CACHE_KEY, WebUtils.getCacheObj2String(samplingInfoList));
        request.setAttribute(LOTSAMPLING_IMP_VALID, isValid);
        return mapping.findForward("doImport");
    }

    public void  valideLotSamplingExcelData( LotSamplingInfo samplingInfo,
                                           boolean isCn, Long facilityRrn) throws Exception {
        StringBuffer sb = new StringBuffer();

        if (!StringUtils.isEqual(DEFAULT_STEP_TYPE_KEY,samplingInfo.getStepType())){
            sb.append("stepType invalidate!");
        }
        valideImportInfo(samplingInfo.getStepType(), isCn,  (isCn ? "工步类型" : "stepType"), sb, false);

        valideImportInfo(samplingInfo.getEqpGroupId(), isCn,  (isCn ? "设备组" : "eqpGroup"), sb, false);
        long instanceRrn = getInstanceRrn(samplingInfo.getEqpGroupId(), getNamedSpace(ObjectList.ENTITYGROUP_KEY, facilityRrn),
                                          ObjectList.ENTITYGROUP_KEY);
        if(instanceRrn <= 0){
            sb.append((isCn ? "设备组无效!" : "eqpGroup invalidate!"));
        }

        valideImportInfo(samplingInfo.getProductId(), isCn,  (isCn ? "产品" : "productId"), sb, true);

        valideImportInfo(samplingInfo.getLotIdList(), isCn,  (isCn ? "批次" : "lotList"), sb, true);

        valideImportInfo(samplingInfo.getRecipe(), isCn,  "recipe", sb, true);

        valideImportInfo(samplingInfo.getStageId(), isCn,  "stageId", sb, false);

        valideImportInfo(samplingInfo.getFlowSeq(), isCn,  (isCn ? "流程序号" : "flowSeq"), sb, false);

        samplingInfo.setComments(sb.toString());
    }

    public void valideImportInfo(String info, boolean isCn, String name, StringBuffer sb, boolean splitFlag){

        if(StringUtils.isEmpty(info)){
            sb.append(name).append(isCn ? "不能为空!" : " cannot be empty!");
        }else if(StringUtils.indexOf(info, CONTAIN_ALL_MIDDLE_KEY) >= 0
                || StringUtils.startsWith(info, CONTAIN_ALL_START_KEY)
                || StringUtils.endsWithIgnoreCase(info, CONTAIN_ALL_END_KEY)){
            sb.append(name).append(isCn ? "条件包含全匹配!" : " contain all match!<br>");
        }

        if(!splitFlag && StringUtils.indexOf(info, CheckRegexUtils.LOT_SAMPLING_SPLIT_KEY) != -1){
            sb.append(name).append(isCn ? "不能设置多条件!" : " can't more condition!<br>");
        }
    }

    public ActionForward delete(ActionMapping mapping, LotSamplingForm form,
                                                  HttpServletRequest request, HttpServletResponse response) {
        String user = LocalContext.getUserId();
        int pageSize = WebUtils.getParameterInt("pageSize", request);

        Page page = new Page(1, pageSize);
        LotSamplingInfo samplingInfo = new LotSamplingInfo();

        BeanUtils.copyProperties(form, samplingInfo);
        samplingInfo.setOperator(user);
        samplingInfo.setComments("Delete by:"+user);

        lotSamplingService.deleteLotSamplingInfo(samplingInfo);
        samplingInfo.setLotSamplingRrn(null);
        page = lotSamplingService.getLotSamplingInfo(page, samplingInfo);

        request.setAttribute(LOT_SAMPLING_INFO_KEY, page.getResults());
        request.setAttribute("currentPage", page.getPageNo());
        request.setAttribute("lastPage", page.getTotalPages());
        request.setAttribute("perPage", page.getPrePage());
        request.setAttribute("nextPage", page.getNextPage());

        return mapping.findForward(Constants.INIT_KEY);
    }

    public ActionForward modify(ActionMapping mapping, LotSamplingForm form,
                                                  HttpServletRequest request, HttpServletResponse response) {
        validateLotSamplingInfo(mapping,form,request,response);
        String user = LocalContext.getUserId();

        int currentPage = WebUtils.getParameterInt("currentPage", request);
        int pageSize = WebUtils.getParameterInt("pageSize", request);
        if(currentPage <= 0){
            currentPage = 1;
        }
        if(pageSize <= 0){
            pageSize = 20;
        }

        LotSamplingInfo samplingInfo = new LotSamplingInfo();
        LotSamplingInfo querySamplingInfo = new LotSamplingInfo();

        Page page = new Page(currentPage, pageSize);

        querySamplingInfo = copyPropertiesForTirm(form);
        querySamplingInfo.setStepDesc(null);
        querySamplingInfo.setLotSamplingRrn(null);
        page = lotSamplingService.getLotSamplingInfo(page, querySamplingInfo);
        Assert.isFalse(CollectionUtils.isNotEmpty(page.getResults()),
                       Errors.create().key(MessageIdList.LOTSAMPLINGSAMPLING_EXIST).content("Have same lot sampling exsit!").build());

        samplingInfo = copyPropertiesForTirm(form);
        samplingInfo.setOperator(user);
        samplingInfo.setComments("Modify by:"+user);
        lotSamplingService.modifyLotSamplingInfo(samplingInfo);
        LotSamplingInfo lotSamplingInfo = new LotSamplingInfo();
        lotSamplingInfo.setStepType(samplingInfo.getStepType());
        page = lotSamplingService.getLotSamplingInfo(page, lotSamplingInfo);
        request.setAttribute(LOT_SAMPLING_INFO_KEY, page.getResults());
        request.setAttribute("currentPage", page.getPageNo());
        request.setAttribute("lastPage", page.getTotalPages());
        request.setAttribute("perPage", page.getPrePage());
        request.setAttribute("nextPage", page.getNextPage());
        return mapping.findForward(Constants.INIT_KEY);
    }

    public ActionForward create(ActionMapping mapping, LotSamplingForm form,
                                                  HttpServletRequest request, HttpServletResponse response) {
        validateLotSamplingInfo(mapping,form,request,response);
        String user = LocalContext.getUserId();
        int currentPage = WebUtils.getParameterInt("currentPage", request);
        int pageSize = WebUtils.getParameterInt("pageSize", request);
        if(currentPage <= 0){
            currentPage = 1;
        }
        if(pageSize <= 0){
            pageSize = 20;
        }

        Page page = new Page(currentPage, pageSize);

        LotSamplingInfo samplingInfo = copyPropertiesForTirm(form);
        samplingInfo.setOperator(user);
        samplingInfo.setStepDesc(StringUtils.EMPTY);
        samplingInfo.setComments("Create by:"+user);
        page = lotSamplingService.getLotSamplingInfo(page, samplingInfo);
        Assert.isFalse(CollectionUtils.isNotEmpty(page.getResults()),
                       Errors.create().key(MessageIdList.LOTSAMPLINGSAMPLING_EXIST).content("Have same lot sampling exsit!").build());
        lotSamplingService.createLotSamplingInfo(samplingInfo);

        LotSamplingInfo lotSamplingInfo = new LotSamplingInfo();
        lotSamplingInfo.setStepType(samplingInfo.getStepType());
        page = lotSamplingService.getLotSamplingInfo(page, lotSamplingInfo);

        request.setAttribute(LOT_SAMPLING_INFO_KEY, page.getResults());
        request.setAttribute("currentPage", page.getPageNo());
        request.setAttribute("lastPage", page.getTotalPages());
        request.setAttribute("perPage", page.getPrePage());
        request.setAttribute("nextPage", page.getNextPage());
        return mapping.findForward(Constants.INIT_KEY);
    }

    public ActionForward view(ActionMapping mapping, LotSamplingForm form,
                                                     HttpServletRequest request, HttpServletResponse response) {

        LotSamplingInfo samplingInfo = new LotSamplingInfo();
        Page page = new Page(1, 1);
        BeanUtils.copyProperties(form,samplingInfo);
        if (!StringUtils.isBlank(StringUtils.toString(samplingInfo.getLotSamplingRrn()))) {
            page = lotSamplingService.getLotSamplingInfo(page, samplingInfo);
            if (page.getResults() != null && page.getResults().size() > 0) {
                samplingInfo = (LotSamplingInfo) page.getResults().iterator().next();
            }
        }
        request.setAttribute("samplingInfo", samplingInfo);

        return mapping.findForward(Constants.VIEW_KEY);
    }

    public ActionForward doImport(ActionMapping mapping, LotSamplingForm form,
                              HttpServletRequest request, HttpServletResponse response) {
        return mapping.findForward("doImport");
    }

    private String getContentFromSheetNoTrim(String excelRowContent) {

        if (NumberUtils.isCreatable(excelRowContent)) {
            String regEx = "\\.0+$";
            return StringUtils.trimToEmpty(excelRowContent.replaceAll(regEx, ""));
        } else {
            return StringUtils.trimToEmpty(excelRowContent);
        }
    }

    private String getContentFromSheet(String excelRowContent) {

        return StringUtils.trimToUpperCase(this.getContentFromSheetNoTrim(excelRowContent));
    }

    private List<LotSamplingInfo> setLotSamplingExcelData(FormFile upFile) throws IOException {

        List<LotSamplingInfo> results = new ExcelImport().attributeFrom(0).attributeTo(0).tableFrom(1)
                                                          .mapper(new ExcelParser<Object, LotSamplingInfo>() {

                                                              @Override
                                                              public Object attributeMapper(
                                                                      List<ExcelRow> attributeRows, int attributeFrom,
                                                                      int attributeTo) {
                                                                  return null;
                                                              }

                                                              @Override
                                                              public LotSamplingInfo tableRowMapper(ExcelRow excelRow,
                                                                                                     int rowNum,
                                                                                                     Object attributeDatas) {
                                                                  LotSamplingInfo lotSamplingExcelDataForm =
                                                                          new LotSamplingInfo();
                                                                  lotSamplingExcelDataForm.setStepType(
                                                                          getContentFromSheetNoTrim(
                                                                                  excelRow.getString(0)));
                                                                  lotSamplingExcelDataForm.setEqpGroupId(
                                                                          getContentFromSheet(excelRow.getString(1)));
                                                                  lotSamplingExcelDataForm.setProductId(
                                                                          getContentFromSheet(excelRow.getString(2)));
                                                                  lotSamplingExcelDataForm.setLotIdList(
                                                                          getContentFromSheet(excelRow.getString(3)));
                                                                  lotSamplingExcelDataForm.setRecipe(
                                                                          getContentFromSheet(excelRow.getString(4)));
                                                                  lotSamplingExcelDataForm.setStageId(
                                                                          getContentFromSheet(
                                                                                  excelRow.getString(5)));
                                                                  lotSamplingExcelDataForm.setFlowSeq(
                                                                          getContentFromSheet(excelRow.getString(6)));
                                                                  lotSamplingExcelDataForm.setStepDesc(
                                                                          getContentFromSheet(excelRow.getString(7)));
                                                                  if (StringUtils.isBlank(lotSamplingExcelDataForm.getFlowSeq())
                                                                          && StringUtils.isBlank(lotSamplingExcelDataForm.getLotIdList())
                                                                          && StringUtils.isBlank(lotSamplingExcelDataForm.getEqpGroupId())
                                                                          && StringUtils.isBlank(lotSamplingExcelDataForm.getProductId())
                                                                          && StringUtils.isBlank(lotSamplingExcelDataForm.getRecipe())
                                                                          && StringUtils.isBlank(lotSamplingExcelDataForm.getStageId())
                                                                          && StringUtils.isBlank(lotSamplingExcelDataForm.getStepType())
                                                                  ) {
                                                                      return null;
                                                                  }
                                                                  return lotSamplingExcelDataForm;
                                                              }

                                                          }).file(upFile.getInputStream()).getTableDataList();

        return results;
    }

    public void downloadTemplate(HttpServletResponse response) throws Exception {
        WebUtils.exportExcel(LOTSAMPLING_IMPORT_TEMPLATE, new HashMap<>(), new ArrayList(), TemplateLocation.LOTSAMPLING_IMPORT_TEMPLATE, 1, 1,
                             response);
    }

    public LotSamplingInfo copyPropertiesForTirm(LotSamplingForm form){
        LotSamplingInfo samplingInfo = new LotSamplingInfo();
        samplingInfo.setLotSamplingRrn(form.getLotSamplingRrn());
        samplingInfo.setStepType(StringUtils.upperCase(StringUtils.trim(form.getStepType())));
        samplingInfo.setEqpGroupId(StringUtils.upperCase(StringUtils.trim(form.getEqpGroupId())));
        samplingInfo.setLotIdList(StringUtils.upperCase(StringUtils.trim(form.getLotIdList())));
        samplingInfo.setProductId(StringUtils.upperCase(StringUtils.trim(form.getProductId())));
        samplingInfo.setRecipe(StringUtils.upperCase(StringUtils.trim(form.getRecipe())));
        samplingInfo.setStageId(StringUtils.upperCase(StringUtils.trim(form.getStageId())));
        samplingInfo.setFlowSeq(StringUtils.upperCase(StringUtils.trim(form.getFlowSeq())));
        samplingInfo.setStepDesc(StringUtils.trim(form.getStepDesc()));
        return samplingInfo;
    }
}