【业务功能篇23】Springboot+mybatisPlus基于>业务功能篇16 持续补充 CRUD+导出+定时任务功能开发


告警逻辑开发:

controller层 

package com.xxx.QualityBigData.service;

import com.xxx.QualityBigData.model.ResponseVo;
import com.xxx.QualityBigData.model.ProdProblemWarnUpdateParam;
import org.springframework.web.bind.annotation.*;
import com.xxx.QualityBigData.model.ProdProblemWarnQueryParam;
import org.springframework.validation.annotation.Validated;
import com.xxx.QualityBigData.service.matwarn.ProdProblemWarnService;
import com.xxx.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import com.xxx.QualityBigData.model.ProdProblemWarnCol;
import javax.servlet.http.HttpServletResponse;



@RestController
@RequestMapping(value = "/ProdProblemWarn", produces = {"application/json;charset=UTF-8"})
@Validated
public class ProdProblemWarnController {

    @Autowired(required=false) 
    private ProdProblemWarnService delegate;  
	
    @RequestMapping(
    		value = "/canSync", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo canSync(@RequestBody ProdProblemWarnQueryParam queryParam) 
            throws ServiceException {
    	    
		return delegate.canSync(queryParam);
    }

	
    @RequestMapping(
    		value = "/downloadIssureListExcel", 
    		produces = { "application/octet-stream" }, 
    		method = RequestMethod.POST)
    public void downloadIssureListExcel(HttpServletResponse response, @RequestBody ProdProblemWarnQueryParam queryParam) 
            throws ServiceException {
    	    
		
		delegate.downloadIssureListExcel(response, queryParam);
		
    }

	
    @RequestMapping(
    		value = "/downloadIssurePageExcel", 
    		produces = { "application/octet-stream" }, 
    		method = RequestMethod.POST)
    public void downloadIssurePageExcel(HttpServletResponse response, @RequestBody ProdProblemWarnQueryParam queryParam) 
            throws ServiceException {
    	    
		
		delegate.downloadIssurePageExcel(response, queryParam);
		
    }

	
    @RequestMapping(
    		value = "/downloadPageExcel", 
    		produces = { "application/octet-stream" }, 
    		method = RequestMethod.POST)
    public void downloadPageExcel(HttpServletResponse response, @RequestBody ProdProblemWarnQueryParam queryParam) 
            throws ServiceException {
    	    
		
		delegate.downloadPageExcel(response, queryParam);
		
    }

	
    @RequestMapping(
    		value = "/getBusinessKey", 
    		produces = { "application/json" }, 
    		method = RequestMethod.GET)
    public ResponseVo getBusinessKey( @RequestParam(value = "issureNo", required = true) String issureNo) 
            throws ServiceException {
    	    
		return delegate.getBusinessKey(issureNo);
    }

	
    @RequestMapping(
    		value = "/getCountTag", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo getCountTag() 
            throws ServiceException {
    	    
		return delegate.getCountTag();
    }

	
    @RequestMapping(
    		value = "/getDropListByType/{type}", 
    		produces = { "application/json" }, 
    		method = RequestMethod.GET)
    public ResponseVo getDropListByType( @PathVariable("type") String type) 
            throws ServiceException {
    	    
		return delegate.getDropListByType(type);
    }

	
    @RequestMapping(
    		value = "/getEffectiveRate", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo getEffectiveRate(@RequestBody ProdProblemWarnQueryParam queryParam) 
            throws ServiceException {
    	    
		return delegate.getEffectiveRate(queryParam);
    }

	
    @RequestMapping(
    		value = "/getIssureList", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo getIssureList(@RequestBody ProdProblemWarnQueryParam queryParam) 
            throws ServiceException {
    	    
		return delegate.getIssureList(queryParam);
    }

	
    @RequestMapping(
    		value = "/getIssurePage", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo getIssurePage(@RequestBody ProdProblemWarnQueryParam queryParam) 
            throws ServiceException {
    	    
		return delegate.getIssurePage(queryParam);
    }

	
    @RequestMapping(
    		value = "/getQtyStatus", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo getQtyStatus(@RequestBody ProdProblemWarnQueryParam queryParam) 
            throws ServiceException {
    	    
		return delegate.getQtyStatus(queryParam);
    }

	
    @RequestMapping(
    		value = "/getQtyTrends", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo getQtyTrends(@RequestBody ProdProblemWarnQueryParam queryParam) 
            throws ServiceException {
    	    
		return delegate.getQtyTrends(queryParam);
    }

	
    @RequestMapping(
    		value = "/getRepEffectiveRate", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo getRepEffectiveRate(@RequestBody ProdProblemWarnQueryParam queryParam) 
            throws ServiceException {
    	    
		return delegate.getRepEffectiveRate(queryParam);
    }

	
    @RequestMapping(
    		value = "/getRepProcess", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo getRepProcess(@RequestBody ProdProblemWarnQueryParam queryParam) 
            throws ServiceException {
    	    
		return delegate.getRepProcess(queryParam);
    }

	
    @RequestMapping(
    		value = "/getRepQtyStatus", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo getRepQtyStatus(@RequestBody ProdProblemWarnQueryParam queryParam) 
            throws ServiceException {
    	    
		return delegate.getRepQtyStatus(queryParam);
    }

	
    @RequestMapping(
    		value = "/getRepQtyTrends", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo getRepQtyTrends(@RequestBody ProdProblemWarnQueryParam queryParam) 
            throws ServiceException {
    	    
		return delegate.getRepQtyTrends(queryParam);
    }

	
    @RequestMapping(
    		value = "/getRepTopProblem", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo getRepTopProblem(@RequestBody ProdProblemWarnQueryParam queryParam) 
            throws ServiceException {
    	    
		return delegate.getRepTopProblem(queryParam);
    }

	
    @RequestMapping(
    		value = "/getTopTenReason", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo getTopTenReason(@RequestBody ProdProblemWarnQueryParam queryParam) 
            throws ServiceException {
    	    
		return delegate.getTopTenReason(queryParam);
    }

	
    @RequestMapping(
    		value = "/getUserCol", 
    		produces = { "application/json" }, 
    		method = RequestMethod.GET)
    public ResponseVo getUserCol( @RequestParam(value = "user", required = true) String user) 
            throws ServiceException {
    	    
		return delegate.getUserCol(user);
    }

	
    @RequestMapping(
    		value = "/getWarnCardData", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo getWarnCardData() 
            throws ServiceException {
    	    
		return delegate.getWarnCardData();
    }

	
    @RequestMapping(
    		value = "/getWarnInfo", 
    		produces = { "application/json" }, 
    		method = RequestMethod.GET)
    public ResponseVo getWarnInfo( @RequestParam(value = "warnNo", required = true) String warnNo) 
            throws ServiceException {
    	    
		return delegate.getWarnInfo(warnNo);
    }

	
    @RequestMapping(
    		value = "/getWarnPage", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo getWarnPage(@RequestBody ProdProblemWarnQueryParam queryParam) 
            throws ServiceException {
    	    
		return delegate.getWarnPage(queryParam);
    }

	
    @RequestMapping(
    		value = "/saveAnalysis", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo saveAnalysis(@RequestBody ProdProblemWarnUpdateParam updateParam) 
            throws ServiceException {
    	    
		return delegate.saveAnalysis(updateParam);
    }

	
    @RequestMapping(
    		value = "/saveRepTopProblem", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo saveRepTopProblem(@RequestBody ProdProblemWarnQueryParam queryParam) 
            throws ServiceException {
    	    
		return delegate.saveRepTopProblem(queryParam);
    }

	
    @RequestMapping(
    		value = "/saveReview", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo saveReview(@RequestBody ProdProblemWarnUpdateParam updateParam) 
            throws ServiceException {
    	    
		return delegate.saveReview(updateParam);
    }

	
    @RequestMapping(
    		value = "/saveUserCol", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo saveUserCol(@RequestBody ProdProblemWarnCol warnCol) 
            throws ServiceException {
    	    
		return delegate.saveUserCol(warnCol);
    }

	
    @RequestMapping(
    		value = "/transProcessed", 
    		produces = { "application/json" }, 
    		method = RequestMethod.POST)
    public ResponseVo transProcessed(@RequestBody ProdProblemWarnUpdateParam updateParam) 
            throws ServiceException {
    	    
		return delegate.transProcessed(updateParam);
    }
}

service层 接口



package com.xxx.service.matwarn;

import com.xxx.QualityBigData.model.ProdProblemWarnCol;
import com.xxx.QualityBigData.model.ProdProblemWarnQueryParam;
import com.xxx.QualityBigData.model.ProdProblemWarnUpdateParam;
import com.xxx.QualityBigData.model.ResponseVo;

import javax.servlet.http.HttpServletResponse;


public interface ProdProblemWarnService {

    void periodlySyncWarnData();

    void resetMatWarnLock();

    int getLockCount();

    void sendMsOnTen();

    ResponseVo getUserCol(String user);

    ResponseVo saveUserCol(ProdProblemWarnCol warnCol);

    ResponseVo getWarnPage(ProdProblemWarnQueryParam queryParam);

    ResponseVo saveAnalysis(ProdProblemWarnUpdateParam updateParam);

    ResponseVo saveReview(ProdProblemWarnUpdateParam updateParam);

    ResponseVo transProcessed(ProdProblemWarnUpdateParam updateParam);

    ResponseVo getCountTag();

    ResponseVo getIssureList(ProdProblemWarnQueryParam queryParam);

    ResponseVo getIssurePage(ProdProblemWarnQueryParam queryParam);

    ResponseVo getQtyTrends(ProdProblemWarnQueryParam queryParam);

    ResponseVo getQtyStatus(ProdProblemWarnQueryParam queryParam);

    ResponseVo getTopTenReason(ProdProblemWarnQueryParam queryParam);

    ResponseVo getDropListByType(String type);

    void downloadPageExcel(HttpServletResponse response, ProdProblemWarnQueryParam queryParam);

    ResponseVo getEffectiveRate(ProdProblemWarnQueryParam queryParam);

    void downloadIssurePageExcel(HttpServletResponse response, ProdProblemWarnQueryParam queryParam);

    ResponseVo getRepQtyTrends(ProdProblemWarnQueryParam queryParam);

    ResponseVo getRepQtyStatus(ProdProblemWarnQueryParam queryParam);

    ResponseVo getRepEffectiveRate(ProdProblemWarnQueryParam queryParam);

    ResponseVo getRepProcess(ProdProblemWarnQueryParam queryParam);

    ResponseVo getRepTopProblem(ProdProblemWarnQueryParam queryParam);

    ResponseVo getWarnCardData();

    ResponseVo saveRepTopProblem(ProdProblemWarnQueryParam queryParam);

    ResponseVo canSync(ProdProblemWarnQueryParam queryParam);

    ResponseVo getWarnInfo(String warnNo);

    ResponseVo getBusinessKey(String issureNo);
}

service层 实现类



package com.xxx.service.impl.matwarn;

import static com.xxx.service.impl.dao.iservice.matwarn.ProdProblemWarnMsgServiceImpl.MESSAGE_DO_SEND;
import static com.xxx.service.impl.dao.iservice.matwarn.ProdProblemWarnMsgServiceImpl.MESSAGE_NO_SEND;

import com.xxx.xxx.model.DistributionWarnCol;
import com.xxx.xxx.model.DistributionWarnQueryParam;
import com.xxx.xxx.model.ProdProblemWarnCol;
import com.xxx.xxx.model.ProdProblemWarnQueryParam;
import com.xxx.xxx.model.ProdProblemWarnUpdateParam;
import com.xxx.xxx.model.ResponseVo;
import com.xxx.domain.dto.DistributionWarnDto;
import com.xxx.domain.dto.esDto;
import com.xxx.domain.dto.xxTaskDto;
import com.xxx.domain.model.MtProductionProblemLog;
import com.xxx.domain.model.MtProductionProblemMessage;
import com.xxx.domain.model.MtProductionProblemWarn;
import com.xxx.domain.model.QbdReportTopProblem;
import com.xxx.domain.model.TxnyProductProblemManage;
import com.xxx.domain.model.TxnyQualityIssureFeedF;
import com.xxx.service.UserService;
import com.xxx.service.dao.iservice.QbdReportTopProblemService;
import com.xxx.service.dao.iservice.TxnyProductProblemManageService;
import com.xxx.service.dao.iservice.matwarn.MatWarnFieldConfigService;
import com.xxx.service.dao.iservice.matwarn.ProdProblemWarnMsgService;
import com.xxx.service.dao.mapper.TxnyQualityIssureFeedFMapper;
import com.xxx.service.impl.dao.iservice.matwarn.ProdProblemWarnLogServiceImpl;
import com.xxx.service.matwarn.MatWarnService;
import com.xxx.service.matwarn.ProdProblemWarnService;
import com.xxx.utils.EmailUtil;
import com.xxx.utils.JsonUtils;
import com.xxx.utils.MsgUtils;
import com.xxx.utils.MyBeanUtils;
import com.xxx.utils.ResponseUtils;
import com.xxx.utils.SpringBeanUtils;
import com.xxx.utils.excel.ExcelUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@Component("prodProblemWarnService1")
public class ProdProblemWarnServiceImpl implements ProdProblemWarnService {

    @Resource
    private UserService userService;

    @Resource
    private MatWarnService matWarnService;

    @Resource
    private com.xxx.service.impl.dao.iservice.matwarn.ProdProblemWarnServiceImpl prodProblemWarnService;

    @Resource
    private ProdProblemWarnLogServiceImpl prodProblemWarnLogService;

    @Resource
    private ProdProblemWarnMsgService prodProblemWarnMsgService;

    @Resource
    private TxnyQualityIssureFeedFMapper issureFeedFMapper;

    @Resource
    private MatWarnFieldConfigService matWarnFieldConfigService;

    @Resource
    private QbdReportTopProblemService qbdReportTopProblemService;

    @Resource
    private TxnyProductProblemManageService productProblemManageService;

    private final static String TASK_URL = "https://"
        + "xxx/productWarning?warnNo=";

    private final static String TEST_TASK_URL = "https://"
        + "xxx/productWarning?warnNo=";

    /**
     * 测试xx账号
     */
    private final static String TEST_xx_ACCOUNT = "用户名";

    private final static String WARN_TYPE = "不良数量预警";

    @Override
    public ResponseVo getDropListByType(String type) {
        List result = new ArrayList<>();
        switch (type) {
            //预警状态
            case "warnStatus":
                String[] status = new String[] {"未处理", "分析中", "评审中", "已关闭"};
                result.addAll(Arrays.asList(status));
                break;
            //预警级别
            case "warnLev":
                String[] level = new String[] {"一般", "较重", "严重"};
                result.addAll(Arrays.asList(level));
                break;
            //其他 product,project,category,subCategory,warnRea
            default:
                result = prodProblemWarnService.getDropListByType(type);
                break;
        }
        return ResponseUtils.successResponse(result, "获取数据成功");
    }

    @Override
    public void downloadPageExcel(HttpServletResponse response, ProdProblemWarnQueryParam queryParam) {
        String fileName = "生产问题预警";
        String[] heads = new String[] {
            "预警单号", "预警状态", "预警时间", "预警原因", "产品", "项目", "品类", "子品类", "产品编码", "物料编码", "预警描述", "mes+问题单号", "供应商", "不良数",
            "分析人", "评审人", "编码累计预警单数", "在制", "在库", "在途", "在网", "围堵措施", "根因分析-产生原因", "纠正措施-针对产生原因", "纠正措施-针对流出原因", "长期措施",
            "横向排查清零", "是否分析完成", "是否有效预警", "无效预警原因", "评审意见", "是否闭环", "闭环时间"
        };
        File file = new File(fileName);
        //chartOne
        byte[] chartOne = EmailUtil.base64ToByte(queryParam.getChartList().get("1").toString());
        //chartTwo
        byte[] chartTwo = EmailUtil.base64ToByte(queryParam.getChartList().get("2").toString());
        //chartThree
        byte[] chartThree = EmailUtil.base64ToByte(queryParam.getChartList().get("3").toString());
        //chartFour
        byte[] chartFour = EmailUtil.base64ToByte(queryParam.getChartList().get("4").toString());
        //chartFive
        byte[] chartFive = EmailUtil.base64ToByte(queryParam.getChartList().get("5").toString());
        //chartSix
        byte[] chartSix = EmailUtil.base64ToByte(queryParam.getChartList().get("6").toString());
        //chartSeven
        byte[] chartSeven = EmailUtil.base64ToByte(queryParam.getChartList().get("7").toString());
        //res1
        List res1 = prodProblemWarnService.getFilterData(queryParam);
        try (ServletOutputStream out = response.getOutputStream()) {
            HSSFWorkbook workbook = new HSSFWorkbook();
            //表头样式
            HSSFCellStyle style = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setFontHeightInPoints((short) 11);
            font.setBold(true);
            //font3.setFontName("宋体");
            style.setFont(font);
            //背景色
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            // 生成一个表格
            HSSFSheet sh = workbook.createSheet(fileName);
            Row xRow0 = sh.createRow(0);
            for (int i = 0; i < heads.length; i++) {
                Cell cell = xRow0.createCell(i);
                cell.setCellStyle(style);
                cell.setCellValue(heads[i]);
                //自适应宽度
                sh.autoSizeColumn(i, true);
                sh.setColumnWidth(i, sh.getColumnWidth(i) * 17 / 10);
            }
            writePageExcelSheetData(res1, sh);
            int picStart = res1.size() + 1;
            for (int i = picStart; i < picStart + 17; i++) {
                sh.createRow(i).setHeight((short) (200 * 4));
            }
            HSSFClientAnchor anchor1 = new HSSFClientAnchor(0, 0, 0, 0, (short) 0, picStart, (short) 4, picStart + 8);
            ExcelUtil.setPicture(chartOne, workbook, sh, 1, 1, anchor1);
            HSSFClientAnchor anchor2 = new HSSFClientAnchor(0, 0, 0, 0, (short) 4, picStart, (short) 10, picStart + 8);
            ExcelUtil.setPicture(chartTwo, workbook, sh, 1, 1, anchor2);
            HSSFClientAnchor anchor3 = new HSSFClientAnchor(0, 0, 0, 0, (short) 10, picStart, (short) 15, picStart + 8);
            ExcelUtil.setPicture(chartThree, workbook, sh, 1, 1, anchor3);
            HSSFClientAnchor anchor4 = new HSSFClientAnchor(0, 0, 0, 0, (short) 15, picStart, (short) 20, picStart + 8);
            ExcelUtil.setPicture(chartFour, workbook, sh, 1, 1, anchor4);
            HSSFClientAnchor anchor5 = new HSSFClientAnchor(0, 0, 0, 0, (short) 0, picStart + 8, (short) 7,
                picStart + 16);
            ExcelUtil.setPicture(chartFive, workbook, sh, 1, 1, anchor5);
            HSSFClientAnchor anchor6 = new HSSFClientAnchor(0, 0, 0, 0, (short) 7, picStart + 8, (short) 14,
                picStart + 16);
            ExcelUtil.setPicture(chartSix, workbook, sh, 1, 1, anchor6);
            HSSFClientAnchor anchor7 = new HSSFClientAnchor(0, 0, 0, 0, (short) 14, picStart + 8, (short) 20,
                picStart + 16);
            ExcelUtil.setPicture(chartSeven, workbook, sh, 1, 1, anchor7);
            workbook.write(out);
            file = new File(fileName);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
    }

    private void writePageExcelSheetData(List details, HSSFSheet sh) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String mapStr
            = "{\"warnNo\":\"预警单号\",\"warnStatus\":\"预警状态\",\"warnDate\":\"预警时间\",\"warnRea\":\"预警原因\",\"product\":\"产品\",\"project\":\"项目\",\"category\":\"品类\",\"subCategory\":\"子品类\",\"itemCode\":\"产品编码\",\"failItem\":\"物料编码\",\"warnDesc\":\"预警描述\",\"mesNo\":\"mes+问题单号\",\"supplier\":\"供应商\",\"badQty\":\"不良数\",\"analysisBy\":\"分析人\",\"reviewBy\":\"评审人\",\"codeAccQty\":\"编码累计预警单数\",\"inProcess\":\"在制\",\"inStore\":\"在库\",\"inTransit\":\"在途\",\"inNet\":\"在网\",\"encloseMeasure\":\"围堵措施\",\"occurCause\":\"根因分析-产生原因\",\"occurMeasure\":\"纠正措施-针对产生原因\",\"outflowCause\":\"纠正措施-针对流出原因\",\"solution\":\"长期措施\",\"horizontal\":\"横向排查清零\",\"isAnalyseFinish\":\"是否分析完成\",\"isEffective\":\"是否有效预警\",\"invalidReason\":\"无效预警原因\",\"reviewComment\":\"评审意见\",\"isClosed\":\"是否闭环\",\"closedDate\":\"闭环时间\"}";
        Map map = JsonUtils.jsonToObj(mapStr, Map.class);
        List property = new ArrayList<>(map.keySet());
        for (int i = 0; i < details.size(); i++) {
            Field[] fields = details.get(i).getClass().getDeclaredFields();
            List fieldList = Arrays.asList(fields);
            Row xRow = sh.createRow(i + 1);
            xRow.setHeight((short) (200 * 2));
            for (int j = 0; j < property.size(); j++) {
                String val = "";
                Cell cell = xRow.createCell(j);
                String pro = property.get(j).toUpperCase(Locale.ROOT);
                try {
                    Field field = fieldList.stream()
                        .filter(f -> f.getName().toUpperCase(Locale.ROOT).equals(pro))
                        .collect(Collectors.toList())
                        .get(0);
                    AccessController.doPrivileged((PrivilegedAction) () -> {
                        field.setAccessible(true);
                        return null;
                    });
                    Object obj = field.get(details.get(i));
                    if (field.getType().getName().equals("java.util.Date")) {
                        if (obj == null) {
                            val = "";
                        } else {
                            Date date = ((Date) field.get(details.get(i)));
                            val = formatter.format(date);
                        }
                    } else if (field.getType().getName().equals("java.lang.Integer") || field.getType()
                        .getName()
                        .equals("int")) {
                        val = obj == null ? "" : ((Integer) field.get(details.get(i))).toString();
                    } else if (field.getType().getName().equals("java.lang.Double")) {
                        val = obj == null ? "" : ((Double) field.get(details.get(i))).toString();
                    } else {
                        val = obj == null ? "" : (String) field.get(details.get(i));
                    }
                } catch (IllegalAccessException e) {
                    log.error(e.getMessage());
                }
                cell.setCellValue(val);
            }
        }
    }

    @Override
    public ResponseVo getUserCol(String user) {
        return ResponseUtils.successResponse(matWarnFieldConfigService.getUserCol(user, "1"), "获取数据成功");
    }

    @Override
    public ResponseVo saveUserCol(ProdProblemWarnCol warnCol) {
        DistributionWarnCol param = new DistributionWarnCol();
        MyBeanUtils.shallowCopy(warnCol, param);
        param.setDataType("1");
        matWarnFieldConfigService.saveUserCol(param);
        return ResponseUtils.successResponse(null, "保存数据成功");
    }

    @Override
    public ResponseVo getWarnPage(ProdProblemWarnQueryParam queryParam) {
        Page result = prodProblemWarnService.getPagedFilterData(queryParam);
        return ResponseUtils.successResponse(result, "获取数据成功");
    }

    @Override
    public ResponseVo getWarnInfo(String warnNo) {
        MtProductionProblemWarn vo = prodProblemWarnService.findOneByWarnNo(warnNo);
        //查询日志 [存在循环调用SQL问题]
        List logs = prodProblemWarnLogService.findLogsByWarnNo(vo.getWarnNo());
        vo.setLogList(logs);
        //查询mes+单号跳转
        List mesNo = Arrays.asList(vo.getMesNo().split(","));
        List> businessKey = prodProblemWarnService.getBusinessKey(mesNo);
        Map mesKey = new HashMap<>();
        for (Map item : businessKey) {
            mesKey.put(item.get("issure_no"), item.get("business_key"));
        }
        vo.setBusinessKey(mesKey);
        //获取文件列表
        vo.setFiles(prodProblemWarnService.findFile(vo.getWarnNo()));
        return ResponseUtils.successResponse(vo, "获取明细成功");
    }

    @Override
    public ResponseVo getBusinessKey(String issureNo) {
        List> businessKey = prodProblemWarnService.getBusinessKey(Lists.newArrayList(issureNo));
        String res = businessKey.isEmpty() ? null : businessKey.get(0).get("business_key");
        return ResponseUtils.successResponse(res, "");
    }

    @Override
    @Transactional
    public ResponseVo transProcessed(ProdProblemWarnUpdateParam updateParam) {
        List badWarnNo = null;
        String env = SpringBeanUtils.getActiveProfile();
        String jumpUrl = env.equals("test") ? TEST_TASK_URL : TASK_URL;
        if (updateParam.getWarnNobBatch().isEmpty()) {
            updateParam.setWarnNobBatch(Lists.newArrayList(updateParam.getWarnNo()));
        }
        List list = prodProblemWarnService.list(
            new QueryWrapper().in("WARN_NO", updateParam.getWarnNobBatch()));
        badWarnNo = list.stream()
            .filter(item -> !item.getWarnStatus().equals("未处理") && !item.getWarnStatus().equals("分析中"))
            .map(MtProductionProblemWarn::getWarnNo)
            .collect(Collectors.toList());
        if (!badWarnNo.isEmpty()) {
            return ResponseUtils.errorResponse(
                String.format("转处理人失败,预警单号:【%s】,不是未处理/分析中状态!", String.join(",", badWarnNo)));
        }
        badWarnNo = list.stream().filter(item -> {
            List analysis = Arrays.asList(StringUtils.isNotEmpty(item.getProcessedBy())
                ? item.getProcessedBy().split(",")
                : item.getAnalysisBy().split(","));
            analysis = analysis.stream().map(it -> it.toLowerCase(Locale.ROOT)).collect(Collectors.toList());
            return !analysis.contains(updateParam.getOperator().toLowerCase(Locale.ROOT));
        }).map(MtProductionProblemWarn::getWarnNo).collect(Collectors.toList());
        if (!badWarnNo.isEmpty()) {
            return ResponseUtils.errorResponse(String.format("转处理人失败,预警单号:【%s】,你不是分析人!", String.join(",", badWarnNo)));
        }
        for (MtProductionProblemWarn vo : list) {
            //更新预警单
            updateParam.setWarnNo(vo.getWarnNo());
            prodProblemWarnService.updateIssueWhenTransHandler(updateParam);
            //日志
            prodProblemWarnLogService.insertLogWhenTransHandler(updateParam.getWarnNo(), updateParam.getOperator(),
                updateParam.getProcessedBy());
            //分析人删除待办,转处理人生成待办
            insertProcessedUndoWhenTrans(env, jumpUrl, updateParam);
            esDto esDto = new esDto();
            esDto.setTitle("生产问题预警");
            String desc = String.format("当前有一个预警单%s,【编码】%s,【分析人】%s转与%s处理,请%s尽快处理分析", updateParam.getWarnNo(),
                vo.getFailItem(), updateParam.getOperator(), updateParam.getProcessedBy(),
                updateParam.getProcessedBy());
            esDto.setContent(desc);
            esDto.setJumpUrl(jumpUrl + vo.getWarnNo());
            esDto.setToUser(
                env.equals("test") ? getxxAccount(TEST_xx_ACCOUNT) : getxxAccount(updateParam.getProcessedBy()));
            MsgUtils.sendesMessage(esDto);
            prodProblemWarnMsgService.insertAppNotify(esDto, updateParam.getWarnNo(), MESSAGE_DO_SEND);
        }

        return ResponseUtils.successResponse("转处理人成功");
    }

    @Override
    public ResponseVo getCountTag() {
        String xxAccount = "";
        try {
            xxAccount = userService.getUser().getxxAccount();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        // 前端传过来的xx账号格式xx,需要去掉首字母
        xxAccount = xxAccount.substring(1);
        List> list = prodProblemWarnService.getCountTag(xxAccount);
        Map result = new HashMap<>();
        for (Map item : list) {
            result.put(item.get("dataType"), item.get("count"));
        }
        return ResponseUtils.successResponse(result, "获取数据成功!");

    }

    @Override
    public ResponseVo getIssureList(ProdProblemWarnQueryParam queryParam) {
        MtProductionProblemWarn vo = prodProblemWarnService.findOneByWarnNo(queryParam.getWarnNo());
        if (vo == null) {
            return ResponseUtils.errorResponse(Boolean.FALSE, "预警单不存在");
        }
        Page pageInfo = new Page<>();
        pageInfo.setCurrent(queryParam.getPage() == null ? 1 : queryParam.getPage());
        pageInfo.setSize(queryParam.getPageSize() == null ? 10 : queryParam.getPageSize());
        List mesNos = Arrays.asList(vo.getMesNo().split(","));
        Page result = issureFeedFMapper.getIssureFeedPage(vo.getWarnNo(),
            vo.getWarnType().equals("不良数量预警") ? vo.getFailItem() : null, mesNos, pageInfo);
        return ResponseUtils.successResponse(result, "获取数据成功");
    }

    @Override
    public void downloadIssurePageExcel(HttpServletResponse response, ProdProblemWarnQueryParam queryParam) {
        MtProductionProblemWarn vo = prodProblemWarnService.findOneByWarnNo(queryParam.getWarnNo());
        List mesNos = Arrays.asList(vo.getMesNo().split(","));
        List list = issureFeedFMapper.getIssureFeedPage(vo.getWarnNo(),
            vo.getWarnType().equals("不良数量预警") ? vo.getFailItem() : null, mesNos);
        matWarnService.handleIssureListExcel(response, list);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;fileName=" + "问题明细");
    }

    @Override
    public ResponseVo getIssurePage(ProdProblemWarnQueryParam queryParam) {
        Page pageInfo = new Page<>();
        pageInfo.setCurrent(queryParam.getPage() == null ? 1 : queryParam.getPage());
        pageInfo.setSize(queryParam.getPageSize() == null ? 10 : queryParam.getPageSize());
        DistributionWarnQueryParam param = new DistributionWarnQueryParam();
        BeanUtils.copyProperties(queryParam, param);
        pageInfo = issureFeedFMapper.getDetailTable(param, pageInfo);
        return ResponseUtils.successResponse(pageInfo, "获取数据成功!");

    }

    /**
     * 预警数量趋势    横坐标展示 年月  纵坐标展示 预警单数    海洋图
     *
     * @param queryParam
     * @return
     */
    @Override
    public ResponseVo getQtyTrends(ProdProblemWarnQueryParam queryParam) {
        List list = prodProblemWarnService.getQtyTrends(queryParam);
        Map resMap = new HashMap();
        resMap.put("month", list.stream().map(DistributionWarnDto::getKey).collect(Collectors.toList()));
        resMap.put("count", list.stream().map(DistributionWarnDto::getCount).collect(Collectors.toList()));
        return ResponseUtils.successResponse(resMap, "获取数据成功!");
    }

    /**
     * 预警状态分布    饼图 按预警状态 展示多个扇形 饼图 (从大到小顺序排列)
     *
     * @param queryParam
     * @return
     */
    @Override
    public ResponseVo getQtyStatus(ProdProblemWarnQueryParam queryParam) {
        List list = prodProblemWarnService.getQtyStatus(queryParam);
        return ResponseUtils.successResponse(list, "获取数据成功!");
    }

    /**
     * 预警根因Top10 横坐标展示预警原因 纵坐标展示预警单数 柱状图(降序从左到右排列)
     *
     * @param queryParam
     * @return
     */
    @Override
    public ResponseVo getTopTenReason(ProdProblemWarnQueryParam queryParam) {
        List list = prodProblemWarnService.getTopTenReason(queryParam);
        Map resMap = new HashMap();
        resMap.put("name", list.stream().map(DistributionWarnDto::getKey).collect(Collectors.toList()));
        resMap.put("data", list.stream().map(DistributionWarnDto::getCount).collect(Collectors.toList()));
        return ResponseUtils.successResponse(resMap, "获取数据成功!");
    }

    @Override
    public ResponseVo getEffectiveRate(ProdProblemWarnQueryParam queryParam) {
        List list = prodProblemWarnService.getEffectiveRate(queryParam);
        return ResponseUtils.successResponse(list, "获取数据成功!");
    }

    @Override
    public ResponseVo getRepQtyTrends(ProdProblemWarnQueryParam queryParam) {
        List list = prodProblemWarnService.getQtyTrends(queryParam);
        Map resMap = new HashMap();
        resMap.put("key", list.stream().map(DistributionWarnDto::getKey).collect(Collectors.toList()));
        resMap.put("value", list.stream().map(DistributionWarnDto::getCount).collect(Collectors.toList()));
        return ResponseUtils.successResponse(resMap, "获取数据成功!");
    }

    @Override
    public ResponseVo getRepQtyStatus(ProdProblemWarnQueryParam queryParam) {
        List list = prodProblemWarnService.getQtyStatus(queryParam);
        List> list1 = new LinkedList<>();
        for (DistributionWarnDto item : list) {
            Map map = new HashMap<>();
            map.put("dataType", StringUtils.isEmpty(item.getKey()) ? "" : item.getKey());
            map.put("qty", item.getCount());
            list1.add(map);
        }
        return ResponseUtils.successResponse(list1, "获取数据成功!");
    }

    @Override
    public ResponseVo getRepEffectiveRate(ProdProblemWarnQueryParam queryParam) {
        List list = prodProblemWarnService.getEffectiveRate(queryParam);
        List> list1 = new LinkedList<>();
        for (DistributionWarnDto item : list) {
            Map map = new HashMap<>();
            map.put("dataType", StringUtils.isEmpty(item.getKey()) ? "" : item.getKey());
            map.put("qty", item.getCount());
            list1.add(map);
        }
        return ResponseUtils.successResponse(list, "获取数据成功!");
    }

    @Override
    public ResponseVo getRepProcess(ProdProblemWarnQueryParam queryParam) {
        List list = prodProblemWarnService.getQtyStatus(queryParam);
        int total = list.stream().mapToInt(DistributionWarnDto::getCount).sum();
        int closed = list.stream().filter(f -> f.getKey().equals("已关闭")).mapToInt(DistributionWarnDto::getCount).sum();
        double crate = total == 0
            ? 0d
            : new BigDecimal(Double.valueOf(closed) / Double.valueOf(total)).setScale(4, RoundingMode.HALF_UP)
                .doubleValue() * 100;
        List elist = prodProblemWarnService.getEffectiveRate(queryParam);
        int etotal = elist.stream().mapToInt(DistributionWarnDto::getCount).sum();
        int effect = elist.stream()
            .filter(f -> f.getKey().equals("有效预警单数"))
            .mapToInt(DistributionWarnDto::getCount)
            .sum();
        double erate = etotal == 0
            ? 0d
            : new BigDecimal(Double.valueOf(effect) / Double.valueOf(etotal)).setScale(4, RoundingMode.HALF_UP)
                .doubleValue() * 100;
        return ResponseUtils.successResponse(
            String.format("预警管理:%s月预警总数%s,预警闭环数量%s,闭环率%s\n预警效果:预警有效数量%s,有效率%s", queryParam.getMonth(), total, closed,
                crate + "%", effect, erate + "%"));
    }

    @Override
    public ResponseVo getRepTopProblem(ProdProblemWarnQueryParam queryParam) {
        List warnNo = Arrays.asList(queryParam.getWarnNo().split(","));
        List existList = qbdReportTopProblemService.selectDataList(queryParam.getYear(),
            queryParam.getMonth());
        List existWarnNo = existList.stream().map(QbdReportTopProblem::getWarnNo).collect(Collectors.toList());
        List delWarnNo = existWarnNo.stream().filter(f -> !warnNo.contains(f)).collect(Collectors.toList());
        List addWarnNo = warnNo.stream().filter(f -> !existWarnNo.contains(f)).collect(Collectors.toList());
        if (!delWarnNo.isEmpty()) {
            //删除
            qbdReportTopProblemService.delByWarnNo(delWarnNo, queryParam.getYear(), queryParam.getMonth());
        }
        if (!addWarnNo.isEmpty()) {
            //新增
            queryParam.setWarnNo(String.join(",", addWarnNo));
            List list = prodProblemWarnService.getRepTopProblem(queryParam);
            list.forEach(item -> {
                item.setYear(queryParam.getYear());
                item.setMonth(queryParam.getMonth());
            });
            qbdReportTopProblemService.batchInsert(list);
        }
        List result = qbdReportTopProblemService.selectDataList(queryParam.getYear(),
            queryParam.getMonth());
        return ResponseUtils.successResponse(result, "获取数据成功!");
    }

    @Override
    public ResponseVo saveRepTopProblem(ProdProblemWarnQueryParam queryParam) {
        List list = new ArrayList<>();
        queryParam.getTopProblem().forEach(item -> {
            QbdReportTopProblem target = new QbdReportTopProblem();
            MyBeanUtils.shallowCopy(item, target);
            list.add(target);
        });
        qbdReportTopProblemService.batchUpdate(list, queryParam.getYear(), queryParam.getMonth());
        return ResponseUtils.successResponse("数据更新成功!");
    }

    @Override
    public ResponseVo getWarnCardData() {
        List> list = prodProblemWarnService.getWarnCardData();
        Map result = new HashMap<>();
        for (Map item : list) {
            result.put(item.get("dataType"), item.get("count"));
        }
        return ResponseUtils.successResponse(result, "获取数据成功!");
    }

    /**
     * 转处理人生成待办
     */
    private void insertProcessedUndoWhenTrans(String env, String jumpUrl, ProdProblemWarnUpdateParam updateParam) {
        String[] processed = updateParam.getProcessedBy().split(",");
        //查询分析人待办
        List msgs = prodProblemWarnMsgService.selectAnalystUndo(updateParam.getWarnNo());
        for (MtProductionProblemMessage msg : msgs) {
            MsgUtils.deletexxTask(msg.getTaskId());
        }
        for (int i = 0; i < processed.length; i++) {
            xxTaskDto dto = new xxTaskDto();
            dto.setAppUrl(jumpUrl + updateParam.getWarnNo());
            dto.setTaskDesc(String.format("【%s】【转处理】【分析中】-生产问题预警", updateParam.getWarnNo()));
            dto.setTaskURL(jumpUrl + updateParam.getWarnNo());
            dto.setHandler(env.equals("test") ? TEST_xx_ACCOUNT : processed[i]);
            dto.setApplicant("用户名");
            prodProblemWarnMsgService.insertAnalystUndo(dto, updateParam.getWarnNo(), MESSAGE_DO_SEND);
        }
    }

    @Override
    @Transactional
    public ResponseVo saveAnalysis(ProdProblemWarnUpdateParam updateParam) {
        String env = SpringBeanUtils.getActiveProfile();
        String jumpUrl = env.equals("test") ? TEST_TASK_URL : TASK_URL;
        MtProductionProblemWarn vo = prodProblemWarnService.findOneByWarnNo(updateParam.getWarnNo());
        //分析人分析内容,点击提交,且是否分析完成选中了是,应用号推送指定提醒内容给分析人与评审人
        //更新预警单
        prodProblemWarnService.updateIssueWhenSaveAnalysis(updateParam, vo);
        if (updateParam.getIsAnalyseFinish() != null && updateParam.getIsAnalyseFinish().equals("是")) {
            //分析人删除待办,评审人生产待办
            insertUndoWhenAnalyseFinish(env, jumpUrl, updateParam, vo);
            //应用号推送指定提醒内容给分析人与评审人
            //预警单xxx202105140934024408分析完成,请评审人尽快处理评审
            esDto esDto = new esDto();
            esDto.setTitle("生产问题预警");
            String desc = String.format("预警单%s分析完成,请评审人%s尽快处理评审", updateParam.getWarnNo(), vo.getReviewBy());
            esDto.setContent(desc);
            esDto.setJumpUrl(jumpUrl + vo.getWarnNo());
            esDto.setToUser(env.equals("test")
                ? getxxAccount(TEST_xx_ACCOUNT)
                : (getxxAccount(StringUtils.isNotEmpty(vo.getProcessedBy()) ? vo.getProcessedBy() : vo.getAnalysisBy())
                    + "," + getxxAccount(vo.getReviewBy())) + ",xx,xx");
            MsgUtils.sendesMessage(esDto);
            prodProblemWarnMsgService.insertAppNotify(esDto, updateParam.getWarnNo(), MESSAGE_DO_SEND);
        }
        //日志
        //查找最新的日志
        prodProblemWarnLogService.updateAnalyseLog(updateParam);
        //判断是否生成问题单
        if (updateParam.getIsCreate() != null && updateParam.getIsCreate().equals("是")) {
            //获取问题单
            TxnyProductProblemManage productProblem = productProblemManageService.selectOneByWarnNo(
                updateParam.getWarnNo());
            if (Objects.isNull(productProblem)) {
                //insert
                productProblem = new TxnyProductProblemManage();
                productProblem.setHappenedTime(DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDate.now()));
                productProblem.setProduct(vo.getProduct());
                productProblem.setBarcode(updateParam.getWarnNo());
                productProblem.setCauseAnalysis(String.format("【%s %s】%s", productProblem.getHappenedTime(), "SYSTEM",
                    updateParam.getOccurCause()));
                productProblem.setSolution(String.format("【临时措施】: %s\n【长期措施】: %s\n【改善效果】: ",
                    (StringUtils.isEmpty(updateParam.getEncloseMeasure()) ? "" : updateParam.getEncloseMeasure()),
                    (StringUtils.isEmpty(updateParam.getSolution())) ? "" : updateParam.getSolution()));
                productProblem.setStatus("open");
                productProblem.setClosedTime(
                    DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDate.now().plusDays(7)));
                productProblem.setLastUpdateDate(new Date());
                productProblemManageService.insertOne(productProblem);
            } else {
                //update
                productProblem.setHappenedTime(DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDate.now()));
                productProblem.setProduct(vo.getProduct());
                productProblem.setBarcode(updateParam.getWarnNo());
                productProblem.setCauseAnalysis(String.format("【%s %s】%s", productProblem.getHappenedTime(), "SYSTEM",
                    updateParam.getOccurCause()));
                productProblem.setSolution(String.format("【临时措施】: %s\n【长期措施】: %s\n【改善效果】: ",
                    (StringUtils.isEmpty(updateParam.getEncloseMeasure()) ? "" : updateParam.getEncloseMeasure()),
                    (StringUtils.isEmpty(updateParam.getSolution())) ? "" : updateParam.getSolution()));
                productProblem.setClosedTime(
                    DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDate.now().plusDays(7)));
                productProblem.setLastUpdateDate(new Date());
                productProblemManageService.updateProblem(productProblem);
            }
        }
        return ResponseUtils.successResponse("预警单分析成功");
    }

    @Override
    public ResponseVo canSync(ProdProblemWarnQueryParam queryParam) {
        TxnyProductProblemManage productProblem = productProblemManageService.selectOneByWarnNo(queryParam.getWarnNo());
        return ResponseUtils.successResponse(productProblem != null ? 1 : 0,
            productProblem != null ? "当前预警单已经同步生产问题单 是否还要覆盖同步?" : "");
    }

    /**
     * 分析人删除待办,评审人生产待办
     */
    private void insertUndoWhenAnalyseFinish(String env, String jumpUrl, ProdProblemWarnUpdateParam updateParam,
        MtProductionProblemWarn vo) {
        String[] review = vo.getReviewBy().split(",");
        //查询分析人待办
        List msgs = prodProblemWarnMsgService.selectAnalystUndo(updateParam.getWarnNo());
        for (MtProductionProblemMessage msg : msgs) {
            MsgUtils.deletexxTask(msg.getTaskId());
        }
        for (int i = 0; i < review.length; i++) {
            xxTaskDto dto = new xxTaskDto();
            dto.setAppUrl(jumpUrl + updateParam.getWarnNo());
            dto.setTaskDesc(String.format("【%s】【分析人分析完成】-生产问题预警", updateParam.getWarnNo()));
            dto.setTaskURL(jumpUrl + updateParam.getWarnNo());
            dto.setHandler(env.equals("test") ? TEST_xx_ACCOUNT : review[i]);
            dto.setApplicant("用户名");
            prodProblemWarnMsgService.insertReviewerUndo(dto, updateParam.getWarnNo(), MESSAGE_DO_SEND);
        }
    }

    @Override
    @Transactional
    public ResponseVo saveReview(ProdProblemWarnUpdateParam updateParam) {
        String env = SpringBeanUtils.getActiveProfile();
        String remark = "";
        String jumpUrl = env.equals("test") ? TEST_TASK_URL : TASK_URL;
        MtProductionProblemWarn vo = prodProblemWarnService.findOneByWarnNo(updateParam.getWarnNo());
        //更新预警单
        prodProblemWarnService.updateIssueWhenSaveReview(updateParam);
        //评审人评审内容,点击提交,且是否闭环选中了同意,应用号推送指定提醒内容给该品类团队成员
        if (StringUtils.isNotEmpty(updateParam.getIsClosed()) && updateParam.getIsClosed().equals("同意")) {
            remark = "流程结束";
            //评审人删除待办
            List msgs = prodProblemWarnMsgService.selectReviewerUndo(
                updateParam.getWarnNo());
            for (MtProductionProblemMessage msg : msgs) {
                MsgUtils.deletexxTask(msg.getTaskId());
            }
            //预警单xxx202105140934024408评审通过,【评审意见】XXX,请分析人 查看
            esDto esDto = new esDto();
            esDto.setTitle("生产问题预警");
            String desc = String.format("预警单%s评审通过,【评审意见】%s,请分析人%s查看", updateParam.getWarnNo(),
                updateParam.getReviewComment(),
                StringUtils.isNotEmpty(vo.getProcessedBy()) ? vo.getProcessedBy() : vo.getAnalysisBy());
            esDto.setContent(desc);
            esDto.setJumpUrl(jumpUrl + vo.getWarnNo());
            List members = prodProblemWarnService.getMemberList(vo.getCategory());
            members.replaceAll(this::getxxAccount);
            String all = String.join(",", members);
            esDto.setToUser(env.equals("test") ? getxxAccount(TEST_xx_ACCOUNT) : all);
            MsgUtils.sendesMessage(esDto);
            prodProblemWarnMsgService.insertAppNotify(esDto, updateParam.getWarnNo(), MESSAGE_DO_SEND);
        }
        //评审人CD评审内容,点击提交,且是否闭环选中了驳回,应用号推送指定提醒内容给分析人
        if (StringUtils.isNotEmpty(updateParam.getIsClosed()) && updateParam.getIsClosed().equals("驳回")) {
            remark = updateParam.getReviewComment();
            //评审人删除待办,分析人生成待办
            insertUndoWhenReviewClosed(env, jumpUrl, updateParam, vo);
            //预警单xxx202105140934024408评审不通过,【评审意见】XXX,请分析人 尽快处理分析
            esDto esDto = new esDto();
            esDto.setTitle("生产问题预警");
            String desc = String.format("预警单%s评审不通过,【评审意见】%s,请分析人%s尽快处理分析", updateParam.getWarnNo(),
                updateParam.getReviewComment(),
                StringUtils.isNotEmpty(vo.getProcessedBy()) ? vo.getProcessedBy() : vo.getAnalysisBy());
            esDto.setContent(desc);
            esDto.setJumpUrl(jumpUrl + vo.getWarnNo());
            esDto.setToUser(env.equals("test")
                ? getxxAccount(TEST_xx_ACCOUNT)
                : getxxAccount(StringUtils.isNotEmpty(vo.getProcessedBy()) ? vo.getProcessedBy() : vo.getAnalysisBy())
                    + ",xx,xx");
            MsgUtils.sendesMessage(esDto);
            prodProblemWarnMsgService.insertAppNotify(esDto, updateParam.getWarnNo(), MESSAGE_DO_SEND);
        }
        //日志
        //查找最新的日志
        prodProblemWarnLogService.updateReviewLog(updateParam, remark);
        return ResponseUtils.successResponse("预警单评审成功");
    }

    /**
     * 评审人删除待办,分析人生成待办
     */
    private void insertUndoWhenReviewClosed(String env, String jumpUrl, ProdProblemWarnUpdateParam updateParam,
        MtProductionProblemWarn vo) {
        String handler = StringUtils.isNotEmpty(vo.getProcessedBy()) ? vo.getProcessedBy() : vo.getAnalysisBy();
        String[] analysis = handler.split(",");
        //查询评审人待办
        List msgs = prodProblemWarnMsgService.selectReviewerUndo(updateParam.getWarnNo());
        for (MtProductionProblemMessage msg : msgs) {
            MsgUtils.deletexxTask(msg.getTaskId());
        }
        for (int i = 0; i < analysis.length; i++) {
            xxTaskDto dto = new xxTaskDto();
            dto.setAppUrl(jumpUrl + updateParam.getWarnNo());
            dto.setTaskDesc(String.format("【%s】【评审不通过】-生产问题预警", updateParam.getWarnNo()));
            dto.setTaskURL(jumpUrl + updateParam.getWarnNo());
            dto.setHandler(env.equals("test") ? TEST_xx_ACCOUNT : analysis[i]);
            dto.setApplicant("用户名");
            prodProblemWarnMsgService.insertAnalystUndo(dto, updateParam.getWarnNo(), MESSAGE_DO_SEND);
        }
    }

    @Override
    public void periodlySyncWarnData() {
        String[] period = getPeriodArray();
        List listToSync = prodProblemWarnService.getToSyncDataList(period[0], period[1]);
        // 需要处理两个周期的数据
        List listNext = prodProblemWarnService.getToSyncDataList(period[2], period[3]);
        listToSync.addAll(listNext);
        doSyncWarnData(listToSync);
        // 数据commit后处理
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                // 新增超过7天状态还未关闭的应用号信息
                create7DayMsg();
                // 查询发送应用号和xx待办
                sendMsg();
            }
        });
    }

    @Override
    public void resetMatWarnLock() {
        prodProblemWarnService.resetMatWarnLock();
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public int getLockCount() {
        return prodProblemWarnService.updateMatWarnLock();
    }

    @Override
    public void sendMsOnTen() {
        List list = prodProblemWarnMsgService.getSendOnTen();
        for (MtProductionProblemMessage msg : list) {
            // 应用号
            if (msg.getType().equals("10")) {
                esDto esDto = JsonUtils.jsonToObj(msg.getContent(), esDto.class);
                MsgUtils.sendesMessage(esDto);
                msg.setIsSend("1");
                msg.setLastUpdateDate(new Date());
                prodProblemWarnMsgService.updateOneMsg(msg);
            }
        }
    }

    /**
     * 超过7天状态还未关闭,第七天开始往后每天进行一次应用号推送指定提醒内容给分析人AB 评审人CD,直到关闭,则无需再推送
     */
    public void create7DayMsg() {
        String env = SpringBeanUtils.getActiveProfile();
        List list = prodProblemWarnService.getOpenMoreThanSevenDaysIssues("不良测试预警");
        // 当前有一个预警单xxx202105140934024408超过7天还未关闭,【编码】21750013,【预警状态】XX
        // 请分析人XXX 尽快处理分析(状态在评审中则为:请评审人XXX尽快处理评审)。
        for (MtProductionProblemWarn item : list) {
            String jumpUrl = (env.equals("test") ? TEST_TASK_URL : TASK_URL) + item.getWarnNo();
            insertAppNotifyWhenOpenIssueMoreSeven(env, item, jumpUrl);
        }
    }

    /**
     * 超过7天状态还未关闭,第七天开始往后每天进行一次应用号推送指定提醒内容给分析人AB 评审人CD,直到关闭,则无需再推送
     */
    private void insertAppNotifyWhenOpenIssueMoreSeven(String env, MtProductionProblemWarn item, String jumpUrl) {
        esDto esDto = new esDto();
        esDto.setJumpUrl(jumpUrl);
        esDto.setTitle("生产问题预警");
        // 分析中请分析人处理,评审中请评审人处理
        String desc = String.format("当前有一个预警单%s超过7天还未关闭,【编码】%s,【预警状态】%s,\n" + "请%s人%s尽快处理%s。", item.getWarnNo(),
            item.getFailItem(), item.getWarnStatus(), item.getWarnStatus().equals("评审中") ? "评审" : "分析",
            item.getWarnStatus().equals("评审中")
                ? item.getReviewBy()
                : (org.apache.commons.lang3.StringUtils.isNotEmpty(item.getProcessedBy())
                    ? item.getProcessedBy()
                    : item.getAnalysisBy()), item.getWarnStatus().equals("评审中") ? "评审" : "分析");
        esDto.setContent(desc);
        esDto.setToUser(env.equals("test")
            ? getxxAccount(TEST_xx_ACCOUNT)
            : (item.getWarnStatus().equals("评审中")
                ? getxxAccount(item.getReviewBy())
                : getxxAccount((org.apache.commons.lang3.StringUtils.isNotEmpty(item.getProcessedBy())
                    ? item.getProcessedBy()
                    : item.getAnalysisBy()))) + ",xx,xx");
        prodProblemWarnMsgService.insertAppNotify(esDto, item.getWarnNo(), MESSAGE_NO_SEND);
    }

    /**
     * 发送信息
     */
    private void sendMsg() {
        List list = prodProblemWarnMsgService.getTodayNotSend();
        for (MtProductionProblemMessage msg : list) {
            // 应用号
            if (msg.getType().equals("0")) {
                esDto esDto = JsonUtils.jsonToObj(msg.getContent(), esDto.class);
                MsgUtils.sendesMessage(esDto);
                msg.setIsSend("1");
                msg.setLastUpdateDate(new Date());
                prodProblemWarnMsgService.updateOneMsg(msg);
            }
            // 待办
            if (msg.getType().equals("1") || msg.getType().equals("2")) {
                xxTaskDto dto = JsonUtils.jsonToObj(msg.getContent(), xxTaskDto.class);
                String taskId = MsgUtils.postxxTask(dto);
                msg.setIsSend("1");
                msg.setTaskId(taskId);
                msg.setLastUpdateDate(new Date());
                prodProblemWarnMsgService.updateOneMsg(msg);
            }
        }
    }

    private String[] getPeriodArray() {
        LocalDate curCycleStartDate = LocalDate.now().with(DayOfWeek.MONDAY);
        LocalDate curCycleEndDate = curCycleStartDate.plusDays(6);
        LocalDate preCycleStartDate = curCycleStartDate.minusDays(7);
        LocalDate preCycleEndDate = curCycleStartDate.minusDays(1);

        return new String[] {
            preCycleStartDate.toString(), preCycleEndDate.toString(), curCycleStartDate.toString(),
            curCycleEndDate.toString()
        };
    }

    private void doSyncWarnData(List listToSync) {
        String env = SpringBeanUtils.getActiveProfile();
        String jumpUrl = env.equals("test") ? TEST_TASK_URL : TASK_URL;
        int maxWarnNo = prodProblemWarnService.getMaxWarnNo(WARN_TYPE);
        int index = 0;
        for (MtProductionProblemWarn toSyncData : listToSync) {
            String startPeriod = parseDateString(toSyncData.getStartPeriod());
            String endPeriod = parseDateString(toSyncData.getEndPeriod());
            // 预警周期内,相同编码,
            MtProductionProblemWarn existedOne = prodProblemWarnService.findOneDataByFailItemAndPeriod(
                toSyncData.getFailItem(), startPeriod, endPeriod, toSyncData.getWarnType());
            if (existedOne == null) {
                // 同周期内,同编码2起以上才预警
                if (toSyncData.getMesCount() < 2) {
                    continue;
                }
                // 新增预警单
                prodProblemWarnService.insertNewIssueWhenSync("ppWarn", listToSync, toSyncData, (maxWarnNo + index++));
                prodProblemWarnLogService.insertStartLog(toSyncData.getWarnNo());
                insertAppNotifyWhenAddNewIssue(env, jumpUrl, toSyncData);
                insertAnalystUndoWhenAddNewIssue(env, jumpUrl, toSyncData);
                continue;
            }

            // 更新已有预警单
            // 预警周期内,已生成预警单(非已关闭),若新增同类预警的MES+问题单,则在原有预警单进行累加,应用号推送指定提醒内容给该品类团队成员
            // 注意:当前状态若为评审中,则需要修改为分析中
            if (existedOne.getWarnStatus() == null) {
                prodProblemWarnService.updateExistedWarnIssueByStatus(existedOne, toSyncData);
                continue;
            }
            if (!existedOne.getWarnStatus().equals("已关闭")) {
                prodProblemWarnService.updateExistedWarnIssueByStatus(existedOne, toSyncData);
                insertAppNotifyToRemindHandler(env, jumpUrl, toSyncData, existedOne);
                prodProblemWarnLogService.insertAddMesPlusIssueLog(existedOne.getWarnNo(), toSyncData.getMesNo());
                continue;
            }
            // 预警周期内,已生成预警单(已关闭),若新增符同类预警的MES+问题单,则在原有预警单进行累加,应用号推送指定提醒内容给分析人AB和评审人CD
            // 注意:状态需要修改为分析中
            if (existedOne.getWarnStatus().equals("已关闭")) {
                prodProblemWarnService.updateExistedWarnIssueByStatus(existedOne, toSyncData);
                insertAppNotifyWhenRestartIssue(env, jumpUrl, toSyncData, existedOne);
                insertUndoWhenProblemRestart(env, jumpUrl, existedOne);
                prodProblemWarnLogService.insertReStartWarnIssueLog(existedOne.getWarnNo(), toSyncData.getMesNo());
            }
        }
    }

    /**
     * 推送应用号,应用号推送指定提醒内容给该品类团队成员
     */
    private void insertAppNotifyWhenAddNewIssue(String env, String jumpUrl, MtProductionProblemWarn TosyncData) {
        esDto esDto = new esDto();
        esDto.setTitle("生产问题预警");
        String desc = String.format("当前有一个预警单%s,【MES+问题单号】%s,【预警编码】%s, 【不良数】%s,该编码触发预警累计%s次,请分析人%s尽快处理分析。",
            TosyncData.getWarnNo(), TosyncData.getMesNo(), TosyncData.getFailItem(), TosyncData.getBadQty(),
            TosyncData.getCodeAccQty(), TosyncData.getAnalysisBy());
        esDto.setContent(desc);
        esDto.setJumpUrl(jumpUrl + TosyncData.getWarnNo());
        String[] accounts = TosyncData.getMember().split(",");
        for (int i = 0; i < accounts.length; i++) {
            accounts[i] = getxxAccount(accounts[i]);
        }
        esDto.setToUser(env.equals("test") ? getxxAccount(TEST_xx_ACCOUNT) : String.join(",", accounts));
        prodProblemWarnMsgService.insertAppNotify(esDto, TosyncData.getWarnNo(), MESSAGE_NO_SEND);
    }

    /**
     * 分析人生成待办
     */
    private void insertAnalystUndoWhenAddNewIssue(String env, String jumpUrl, MtProductionProblemWarn TosyncData) {
        String[] analysis = TosyncData.getAnalysisBy().split(",");
        for (int i = 0; i < analysis.length; i++) {
            xxTaskDto dto = new xxTaskDto();
            dto.setAppUrl(jumpUrl + TosyncData.getWarnNo());
            dto.setTaskDesc("【" + TosyncData.getWarnNo() + "】【未处理】-生产问题预警");
            dto.setTaskURL(jumpUrl + TosyncData.getWarnNo());
            dto.setHandler(env.equals("test") ? TEST_xx_ACCOUNT : analysis[i]);
            dto.setApplicant("用户名");
            prodProblemWarnMsgService.insertAnalystUndo(dto, TosyncData.getWarnNo(), MESSAGE_NO_SEND);
        }
    }

    /**
     * 问题重启评审人生成代办(新增同类问题)
     */
    private void insertUndoWhenProblemRestart(String env, String jumpUrl, MtProductionProblemWarn vo) {
        String[] review = vo.getReviewBy().split(",");
        for (int i = 0; i < review.length; i++) {
            xxTaskDto dto = new xxTaskDto();
            dto.setAppUrl(jumpUrl + vo.getWarnNo());
            dto.setTaskDesc("【" + vo.getWarnNo() + "】【新增同类问题】-生产问题预警");
            dto.setTaskURL(jumpUrl + vo.getWarnNo());
            dto.setHandler(env.equals("test") ? TEST_xx_ACCOUNT : review[i]);
            dto.setApplicant("用户名");
            prodProblemWarnMsgService.insertReviewerUndo(dto, vo.getWarnNo(), MESSAGE_NO_SEND);
        }
    }

    /**
     * 应用号推送内容提醒分析人尽快处理分析
     */
    private void insertAppNotifyToRemindHandler(String env, String jumpUrl, MtProductionProblemWarn TosyncData,
        MtProductionProblemWarn vo) {
        esDto esDto = new esDto();
        esDto.setTitle("生产问题预警");
        String desc = String.format("当前有一个预警单%s,【编码】%s 新增同类问题:【问题数新增】%s,【MES+问题单号新增】%s,【不良数新增】%s,请分析人尽快处理分析,评审人重点关注",
            vo.getWarnNo(), vo.getFailItem(), TosyncData.getMesCount(), TosyncData.getMesNo(), TosyncData.getBadQty());
        esDto.setContent(desc);
        esDto.setJumpUrl(jumpUrl + vo.getWarnNo());
        String[] accounts = TosyncData.getMember().split(",");
        for (int i = 0; i < accounts.length; i++) {
            accounts[i] = getxxAccount(accounts[i]);
        }
        esDto.setToUser(env.equals("test") ? getxxAccount(TEST_xx_ACCOUNT) : String.join(",", accounts));
        prodProblemWarnMsgService.insertSentOnTen(esDto, vo.getWarnNo(), MESSAGE_NO_SEND);
    }

    /**
     * 重开问题后 应用号推送内容
     */
    private void insertAppNotifyWhenRestartIssue(String env, String jumpUrl, MtProductionProblemWarn TosyncData,
        MtProductionProblemWarn vo) {
        esDto esDto = new esDto();
        esDto.setTitle("生产问题预警");
        String desc = String.format(
            "当前有一个已关闭的预警单%s,【编码】%s\n" + "新增同类问题:【问题数新增】%s,【MES+问题单号新增】%s,【不良数新增】%s,请分析人尽快处理分析,评审人重点关注", vo.getWarnNo(),
            vo.getFailItem(), TosyncData.getMesCount(), TosyncData.getMesNo(), TosyncData.getBadQty());
        esDto.setContent(desc);
        esDto.setJumpUrl(jumpUrl + vo.getWarnNo());
        esDto.setToUser(env.equals("test")
            ? getxxAccount(TEST_xx_ACCOUNT)
            : (getxxAccount(org.apache.commons.lang3.StringUtils.isNotEmpty(vo.getProcessedBy())
                ? vo.getProcessedBy()
                : vo.getAnalysisBy()) + "," + getxxAccount(vo.getReviewBy())) + ",xx,xx");
        prodProblemWarnMsgService.insertSentOnTen(esDto, vo.getWarnNo(), MESSAGE_NO_SEND);
    }

    /**
     * Date类型转字符串
     *
     * @param date
     * @return
     */
    private String parseDateString(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    /**
     * 分解处理xx账号
     *
     * @param usrName xx账号
     * @return 返回
     */
    private String getxxAccount(String usrName) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(usrName)) {
            return usrName;
        }
        String result;
        if (usrName.contains(",")) {
            String[] names = usrName.split(",");
            result = MsgUtils.getxxAccount(names[names.length - 1]);
        } else {
            result = MsgUtils.getxxAccount(usrName);
        }
        return result;
    }

}

mybatisplus 对应的接口和实现类 分别继承对应的接口和类

dao层 接口、接口实现类、Mapper接口、XML映射,在【业务功能篇16】Springboot+mybatisplus+ShedLock框架根据一定的逻辑数据处理规则,定时任务生成告警单_studyday1的博客-CSDN博客

这篇文章中有引用,不再赘述


 日志表 

实体类:


package com.xxx.domain.model;

import java.util.Date;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.NoArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;


@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@NoArgsConstructor
@TableName("dwr_mt_production_problem_log_f")
public class MtProductionProblemLog implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "ID",type = IdType.AUTO)
    private Integer id;

    /**
     * 预警单号
     */
    @TableField("WARN_NO")
    private String warnNo;

    /**
     * 操作节点
     */
    @TableField("OPERATE_NODE")
    private String operateNode;

    /**
     * 操作人
     */
    @TableField("OPERATE_BY")
    private String operateBy;

    /**
     * 操作时间
     */
    @TableField("OPERATE_DATE")
    private Date operateDate;

    /**
     * 备注
     */
    @TableField("REMARK")
    private String remark;

    @TableField("CREATION_DATE")
    private Date creationDate;


}

没有service层 主要就是利用mp的用法 在dao层定义 接口和实现类 ,供具体的告警service实现类调用接口

dao层 接口类:



package com.xxx.xxx.service.dao.iservice.matwarn;

import com.baomidou.mybatisplus.extension.service.IService;
import com.xxx.xxx.xxx.model.ProdProblemWarnUpdateParam;
import com.xxx.xxx.domain.model.MtProductionProblemLog;

import java.util.List;



public interface ProdProblemWarnLogService extends IService {
    
    int insertLogWhenTransHandler(String warnNo, String from, String to);

    MtProductionProblemLog findLatestLogByWarnNo(String warnNo);

    List findLogsByWarnNo(String warnNo);

    void updateAnalyseLog(ProdProblemWarnUpdateParam updateParam);

    void updateReviewLog(ProdProblemWarnUpdateParam updateParam, String remark);

    int insertStartLog(String warnNo);

    int insertAddMesPlusIssueLog(String warnNo, String mesPlusNo);

    int insertReStartWarnIssueLog(String warnNo, String mesPlusNo);

}

dao层 接口实现类:



package com.xxx.service.impl.dao.iservice.matwarn;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxx.QualityBigData.model.ProdProblemWarnUpdateParam;
import com.xxx.domain.model.MtProductionProblemLog;
import com.xxx.service.dao.iservice.matwarn.ProdProblemWarnLogService;
import com.xxx.service.dao.mapper.MtProductionProblemLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;


@Slf4j
@Component
public class ProdProblemWarnLogServiceImpl extends ServiceImpl
    implements ProdProblemWarnLogService {

    @Override
    public int insertLogWhenTransHandler(String warnNo, String from, String to) {
        MtProductionProblemLog logF = new MtProductionProblemLog();
        logF.setWarnNo(warnNo);
        logF.setOperateNode("转处理");
        logF.setOperateBy(from);
        logF.setOperateDate(new Date());
        logF.setCreationDate(new Date());
        logF.setRemark(String.format("%s转给%s", from, to));
        return baseMapper.insert(logF);
    }

    @Override
    public MtProductionProblemLog findLatestLogByWarnNo(String warnNo) {
        return baseMapper.selectOne(new LambdaQueryWrapper()
                .eq(MtProductionProblemLog::getWarnNo, warnNo)
                .orderBy(true, false, MtProductionProblemLog::getCreationDate)
                .last("limit 1"));
    }

    @Override
    public List findLogsByWarnNo(String warnNo) {
        return baseMapper.selectList(new LambdaQueryWrapper()
                .eq(MtProductionProblemLog::getWarnNo, warnNo)
                .orderBy(true, true, MtProductionProblemLog::getCreationDate));
    }

    @Override
    public void updateAnalyseLog(ProdProblemWarnUpdateParam updateParam) {
        MtProductionProblemLog logF = findLatestLogByWarnNo(updateParam.getWarnNo());
        logF.setWarnNo(updateParam.getWarnNo());
        logF.setOperateBy(
                StringUtils.isEmpty(updateParam.getOperator()) ? updateParam.getAnalysisBy() : updateParam.getOperator());
        logF.setOperateDate(new Date());
        logF.setCreationDate(new Date());
        String remark = updateParam.getIsAnalyseFinish() != null && updateParam.getIsAnalyseFinish().equals("是")
                ? "分析完成"
                : "分析中";
        boolean isInsert = !(logF.getOperateNode().equals("分析中") && remark.equals(
                logF.getRemark())); //节点是分析中,意见也是分析中就不录入日志
        logF.setOperateNode("分析中");
        logF.setRemark(remark);
        //2023/04/27如果多次提交分析 选择否 也需要记录一个日志 辅助问题流程处理的排查
        logF.setId(null);
        baseMapper.insert(logF);
    }

    @Override
    public void updateReviewLog(ProdProblemWarnUpdateParam updateParam, String remark) {
        boolean agree = StringUtils.isNotEmpty(updateParam.getIsClosed()) && updateParam.getIsClosed().equals("同意");
        MtProductionProblemLog logF = findLatestLogByWarnNo(updateParam.getWarnNo());
        logF.setWarnNo(updateParam.getWarnNo());
        logF.setId(null);
        logF.setOperateBy(
                StringUtils.isEmpty(updateParam.getOperator()) ? updateParam.getReviewBy() : updateParam.getOperator());
        logF.setOperateDate(new Date());
        logF.setCreationDate(new Date());
        if(agree){
            logF.setRemark(updateParam.getReviewComment());
            logF.setOperateNode("评审中");
            baseMapper.insert(logF);
        }
        logF.setOperateNode(agree ? "已关闭" : "评审中");
        logF.setRemark(remark);
        baseMapper.insert(logF);
    }

    @Override
    public int insertStartLog(String warnNo) {
        MtProductionProblemLog logF = new MtProductionProblemLog();
        logF.setWarnNo(warnNo);
        logF.setOperateNode("开始");
        logF.setOperateBy("system");
        logF.setOperateDate(new Date());
        logF.setCreationDate(new Date());
        logF.setRemark("启动问题处理");
        return baseMapper.insert(logF);
    }

    @Override
    public int insertAddMesPlusIssueLog(String warnNo, String mesPlusNo) {
        MtProductionProblemLog logF = new MtProductionProblemLog();
        logF.setWarnNo(warnNo);
        logF.setOperateNode("提示");
        logF.setOperateBy("system");
        logF.setOperateDate(new Date());
        logF.setCreationDate(new Date());
        logF.setRemark(String.format("【预警单号】%s,新增同类MES+问题单%s", warnNo, mesPlusNo));
        return baseMapper.insert(logF);
    }

    @Override
    public int insertReStartWarnIssueLog(String warnNo, String mesPlusNo) {
        MtProductionProblemLog logF = new MtProductionProblemLog();
        logF.setWarnNo(warnNo);
        logF.setOperateNode("激活");
        logF.setOperateBy("system");
        logF.setOperateDate(new Date());
        logF.setCreationDate(new Date());
        logF.setRemark(String.format("【预警单号】%s,新增同类MES+问题单%s", warnNo, mesPlusNo));
        return baseMapper.insert(logF);
    }
}

 dao层 mapper接口

这里没有写接口,也是需要定义的 因为mybatisplus的用法,就是需要定义一个mapper接口,继承basemapper接口, 然后在实现类会使用到,就是继承的实现类泛型有个参数就是这个mapper接口



package com.xxx.service.dao.mapper;

import com.xxx.domain.model.MtProductionProblemLog;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;


@Mapper
public interface MtProductionProblemLogMapper extends BaseMapper {

}


推送信息表 

实体类



package com.xxx.domain.model;

import java.util.Date;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.NoArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;


@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@NoArgsConstructor
@TableName("dwr_mt_production_problem_message_f")
public class MtProductionProblemMessage implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "ID",type = IdType.AUTO)
    private Integer id;

    /**
     * 预警单号
     */
    @TableField("WARN_NO")
    private String warnNo;

    /**
     * 类型 0:应用号,1:分析人待办,2:评审人待办
     */
    @TableField("TYPE")
    private String type;

    /**
     * 内容,json格式字符串
     */
    @TableField("CONTENT")
    private String content;

    /**
     * xx待办id
     */
    @TableField("TASK_ID")
    private String taskId;

    /**
     * 是否已发送
     */
    @TableField("IS_SEND")
    private String isSend;

    @TableField("CREATION_DATE")
    private Date creationDate;

    @TableField("LAST_UPDATE_DATE")
    private Date lastUpdateDate;


}

没有service层 主要就是利用mp的用法 在dao层定义 接口和实现类 ,供具体的告警service实现类调用接口

dao层 接口 



package com.xxx.service.dao.iservice.matwarn;

import com.baomidou.mybatisplus.extension.service.IService;
import com.xxx.domain.dto.exDto;
import com.xxx.domain.dto.xxTaskDto;
import com.xxx.domain.model.MtProductionProblemMessage;

import java.util.List;


public interface ProdProblemWarnMsgService extends IService {

    List selectAnalystUndo(String warnNo);

    List selectReviewerUndo(String warnNo);

    int insertAnalystUndo(xxTaskDto dto, String warnNo, String sendType);

    int insertReviewerUndo(xxTaskDto dto, String warnNo, String sendType);

    int insertAppNotify(exDto exDto, String warnNo, String sendType);

    int insertSentOnTen(exDto exDto, String warnNo, String sendType);

    List getTodayNotSend();

    List getSendOnTen();

    int updateOneMsg(MtProductionProblemMessage msg);
}

dao层 接口实现类


package com.xxx.service.impl.dao.iservice.matwarn;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxx.domain.dto.esDto;
import com.xxx.domain.dto.xxxTaskDto;
import com.xxx.domain.model.MtProductionProblemMessage;
import com.xxx.service.dao.iservice.matwarn.ProdProblemWarnMsgService;
import com.xxx.service.dao.mapper.MtProductionProblemMessageMapper;
import com.xxx.utils.JsonUtils;
import com.xxx.utils.MsgUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;


@Slf4j
@Component
public class ProdProblemWarnMsgServiceImpl extends ServiceImpl
        implements ProdProblemWarnMsgService {

    /**
     * 早上10点推送应用号
     * 在已有的预警单中,新增同类MES+问题单的推送提示,需要与其他推送逻辑分开时间段  用户方便辨别   推送时间改成上午10点
     */
    public static final String SENT_ON_TEN_TYPE = "10";

    public static final String APP_NOTIFY_TYPE = "0";

    public static final String ANALYST_UNDO_TYPE = "1";

    public static final String REVIEWER_UNDO_TYPE = "2";

    public static final String MESSAGE_NO_SEND = "0";

    public static final String MESSAGE_DO_SEND = "1";


    @Override
    public List selectAnalystUndo(String warnNo) {
        return selectOnyByType(warnNo, ANALYST_UNDO_TYPE);
    }

    @Override
    public List selectReviewerUndo(String warnNo) {
        return selectOnyByType(warnNo, REVIEWER_UNDO_TYPE);
    }

    private List selectOnyByType(String warnNo, String undoType) {
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MtProductionProblemMessage::getWarnNo, warnNo)
                .eq(MtProductionProblemMessage::getType, undoType)
                .orderBy(true, false, MtProductionProblemMessage::getCreationDate);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public int insertAnalystUndo(xxxTaskDto dto, String warnNo, String sendType) {
        String taskId = sendType.equals(MESSAGE_DO_SEND) ? MsgUtils.postxxxTask(dto) : null;
        MtProductionProblemMessage msg1 = new MtProductionProblemMessage();
        msg1.setTaskId(taskId);
        msg1.setWarnNo(warnNo);
        msg1.setType(ANALYST_UNDO_TYPE);//类型 0:应用号,1:分析人待办,2:评审人待办,10:早上10点发送
        msg1.setContent(JsonUtils.objectToJson(dto));
        msg1.setIsSend(sendType);
        msg1.setCreationDate(new Date());
        return baseMapper.insert(msg1);
    }

    @Override
    public int insertReviewerUndo(xxxTaskDto dto, String warnNo, String sendType) {
        String taskId = sendType.equals(MESSAGE_DO_SEND) ? MsgUtils.postxxxTask(dto) : null;
        MtProductionProblemMessage msg1 = new MtProductionProblemMessage();
        msg1.setTaskId(taskId);
        msg1.setWarnNo(warnNo);
        msg1.setType(REVIEWER_UNDO_TYPE);//类型 0:应用号,1:分析人待办,2:评审人待办,10:早上10点发送
        msg1.setContent(JsonUtils.objectToJson(dto));
        msg1.setIsSend(sendType);
        msg1.setCreationDate(new Date());
        return baseMapper.insert(msg1);
    }

    @Override
    public int insertAppNotify(esDto esDto, String warnNo, String sendType) {
        MtProductionProblemMessage msgY = new MtProductionProblemMessage();
        msgY.setWarnNo(warnNo);
        msgY.setType(APP_NOTIFY_TYPE);//类型 0:应用号,1:分析人待办,2:评审人待办,10:早上10点发送
        msgY.setContent(JsonUtils.objectToJson(esDto));
        msgY.setIsSend(sendType);
        msgY.setCreationDate(new Date());
        return baseMapper.insert(msgY);
    }

    @Override
    public int insertSentOnTen(esDto esDto, String warnNo, String sendType) {
        MtProductionProblemMessage msgY = new MtProductionProblemMessage();
        msgY.setWarnNo(warnNo);
        msgY.setType(SENT_ON_TEN_TYPE);//类型 0:应用号,1:分析人待办,2:评审人待办,10:早上10点发送
        msgY.setContent(JsonUtils.objectToJson(esDto));
        msgY.setIsSend(sendType);
        msgY.setCreationDate(new Date());
        return baseMapper.insert(msgY);
    }

    @Override
    public List getTodayNotSend() {
        return baseMapper.getTodayNotSend();
    }

    @Override
    public List getSendOnTen() {
        return baseMapper.getSendOnTen();
    }

    @Override
    public int updateOneMsg(MtProductionProblemMessage msg) {
        return baseMapper.updateById(msg);
    }
}

mapper接口



package com.xxx.service.dao.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xxx.domain.model.MtProductionProblemMessage;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;


@Mapper
public interface MtProductionProblemMessageMapper extends BaseMapper {

    List getTodayNotSend();

    List getSendOnTen();
}

XML映射






    
    
        
        
        
        
        
        
        
        
    

    
    
        ID, WARN_NO, TYPE, CONTENT, TASK_ID, IS_SEND, CREATION_DATE, LAST_UPDATE_DATE
    

    

    



预警过程涉及的 待办电子流生成 以及  应用通知推送信息

这里是通过第三方平台去调用的接口,通过待办接口给指定的员工生成一个待办提醒,承载再第三方平台页面,点击待办可跳转到告警单进行处理

应用推送同样也是调用第三方平台接口,给指定员工生成一个推送信息,承载在第三方平台页面,点击信息同样也可以跳到相应的告警单页面

应用推送&待办工具类:



@Slf4j
public final class MsgUtils {

    //消费者应用ID
    private static final String APPID = "com";
    public static void sendxxxMessage(xxxDto xxxVO) {
        log.info("进入xxx消息推送方法");
        log.info("预警类型:" + xxxVO.getTitle());
        log.info("预警人员:" + xxxVO.getToUser());
//        String env = EnvHolder.getEnv();
//        log.info("当前环境:"+env);
        //生产环境访问地址
        String postUrl = "xxx";
        String environment = "pro";
        try {

            JSONObject params = new JSONObject();

            //发起方账号
            params.put("from_user_account", "");
            //响应方账号
            params.put("to_user_account", xxxVO.getToUser());
            //标题
            params.put("title", xxxVO.getTitle());
       
            //跳转URL
            params.put("jump_url", xxxVO.getJumpUrl());
            //内容
            params.put("content", xxxVO.getContent());
            params.put("type", "1");
            //转换参数为字符串
            String paramsStr = params.toString();

            log.info("xxx消息接口地址:" + postUrl);
            //获取http连接对象,设置请求头参数
            URL url = new URL(postUrl);
            HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setDoOutput(true);
            httpConnection.setDoInput(true);
            httpConnection.setUseCaches(true);
            httpConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            httpConnection.setRequestProperty("Authorization", token);
            //请求方式
            httpConnection.setRequestMethod("POST");
            httpConnection.connect();

            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(httpConnection.getOutputStream(),
                StandardCharsets.UTF_8));
            bufferedWriter.write(paramsStr);
            bufferedWriter.flush();
            InputStream inputStream = null;
            InputStreamReader inputStreamReader = null;
            BufferedReader bufferedReader = null;
            inputStream = httpConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            StringBuilder stringBuilder = new StringBuilder(16);
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            log.info("调用消息推送接口返回数据:" + stringBuilder);
        } catch ( IOException | JSONException e) {
            log.error(e.toString());
        }
    }

    public static String postxxxTask(xxxTaskDto xxxTaskDto) {
         String postUrl = SpringBeanUtils.getActiveProfile().equals("test") ?
                "http://xxx-beta.xxx.com/" :
                "http://xxx.xxx.com/";
        Map map =new HashMap<>();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());
        long taskUUID = System.currentTimeMillis();
        String appName = "xxx";
        String taskId = appName + taskUUID;
        //应用名称
        map.put("appName", StringUtils.isEmpty(xxxTaskDto.getAppName()) ? appName : xxxTaskDto.getAppName());
        //应用URL地址
        map.put("appURL", xxxTaskDto.getAppUrl());
        map.put("type", "J2EE");
        //待办任务的标题
        map.put("taskDesc", xxxTaskDto.getTaskDesc());
        //代办任务链接
        map.put("taskURL", xxxTaskDto.getTaskURL());
        //任务的唯一标识
        map.put("taskUUID", StringUtils.isEmpty(xxxTaskDto.getTaskUuid()) ? taskId : xxxTaskDto.getTaskUuid());
        //任务的创建时间
        map.put("time", time);
        //任务的处理人
        map.put("handler", xxxTaskDto.getHandler());
        //任务的申请人
        map.put("applicant", xxxTaskDto.getApplicant());
        //推送待办的地址:
        log.info("推送待办地址: " + postUrl);

        try {
            String jsonParameter = JsonUtils.objectToJson(map);
            log.info("推送待办参数: " + jsonParameter);
            String result = RestClientUtil.postData(postUrl, jsonParameter);
            log.info("推送待办返回: " + result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map.get("taskUUID");
    }
}

你可能感兴趣的:(Spring,boot,业务场景实例问题,spring,boot,java,算法)