zouyu
8 小时以前 2cf06285f64311722cbf79fd5635b16718635e5e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package com.ruoyi.inspect.service.impl;
 
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.Result;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.enums.ContractType;
import com.ruoyi.common.numgen.NumberGenerator;
import com.ruoyi.common.oa.OAProcess;
import com.ruoyi.common.oa.OAProperty;
import com.ruoyi.common.oa.OAResult;
import com.ruoyi.common.utils.QueryWrappers;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.framework.exception.ErrorException;
import com.ruoyi.inspect.dto.PushOADto;
import com.ruoyi.inspect.dto.UnqualifiedHandlerDto;
import com.ruoyi.inspect.excel.InsUnqualifiedHandlerExcelData;
import com.ruoyi.inspect.mapper.InsOrderMapper;
import com.ruoyi.inspect.mapper.InsSampleMapper;
import com.ruoyi.inspect.mapper.InsUnqualifiedHandlerMapper;
import com.ruoyi.inspect.pojo.CommonOa;
import com.ruoyi.inspect.pojo.InsOrder;
import com.ruoyi.inspect.pojo.InsUnqualifiedHandler;
import com.ruoyi.inspect.pojo.InsUnqualifiedHandlerFile;
import com.ruoyi.inspect.service.CommonOaService;
import com.ruoyi.inspect.service.InsOrderService;
import com.ruoyi.inspect.service.InsUnqualifiedHandlerFileService;
import com.ruoyi.inspect.service.InsUnqualifiedHandlerService;
import com.ruoyi.inspect.vo.UnqualifiedHandlerVO;
import com.ruoyi.system.service.ISysDictTypeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * @author 27233
 * @description 针对表【ins_unqualified_handler(不合格处理表)】的数据库操作Service实现
 * @createDate 2024-07-31 13:38:14
 */
@Service
@Slf4j
public class InsUnqualifiedHandlerServiceImpl extends ServiceImpl<InsUnqualifiedHandlerMapper, InsUnqualifiedHandler>
        implements InsUnqualifiedHandlerService {
 
    @Resource
    private CommonOaService commonOaService;
    @Resource
    private OAProperty oaProperty;
    @Resource
    private InsUnqualifiedHandlerFileService insUnqualifiedHandlerFileService;
    @Resource
    private InsSampleMapper insSampleMapper;
    @Resource
    private ISysDictTypeService sysDictTypeService;
    @Resource
    private NumberGenerator<InsUnqualifiedHandler> insUnqualifiedHandlerNumberGenerator;
 
 
    @Override
    public IPage<UnqualifiedHandlerVO> pageList(Page page, UnqualifiedHandlerDto unqualifiedHandlerDto) {
        String feedbackStartDate = unqualifiedHandlerDto.getFeedbackStartTime();
        String feedbackEndDate = unqualifiedHandlerDto.getFeedbackEndTime();
        unqualifiedHandlerDto.setFeedbackStartTime(null);
        unqualifiedHandlerDto.setFeedbackEndTime(null);
        return baseMapper.selectPageList(page, QueryWrappers.queryWrappers(unqualifiedHandlerDto),feedbackStartDate,feedbackEndDate);
    }
 
    @Override
    public void exportUnqualifiedHandler(UnqualifiedHandlerDto unqualifiedHandlerDto, HttpServletResponse response) {
        response.reset();
        try{
            //查询字典
            List<SysDictData> materialPropType = sysDictTypeService.selectDictDataByType("material_prop_type");//物料属性
            List<SysDictData> categoriesNoConformities = sysDictTypeService.selectDictDataByType("categories_no_conformities");//不合格分类
            List<SysDictData> attributionNoConformities = sysDictTypeService.selectDictDataByType("attribution_no_conformities");// 不合格归属
            //查询不合格处理记录
            IPage<UnqualifiedHandlerVO> pageList = pageList(new Page<>(-1, -1), unqualifiedHandlerDto);
            List<InsUnqualifiedHandlerExcelData> records = pageList.getRecords().stream().map(m->{
                InsUnqualifiedHandlerExcelData handlerExcelData = new InsUnqualifiedHandlerExcelData();
                BeanUtil.copyProperties(m,handlerExcelData);
                handlerExcelData.setMaterialProp(materialPropType.stream().filter(f-> StringUtils.equals(f.getDictValue(),handlerExcelData.getMaterialProp())).findFirst().orElse(new SysDictData()).getDictLabel());
                handlerExcelData.setClassification(categoriesNoConformities.stream().filter(f-> StringUtils.equals(f.getDictValue(),handlerExcelData.getClassification())).findFirst().orElse(new SysDictData()).getDictLabel());
                handlerExcelData.setOffGradeAscription(attributionNoConformities.stream().filter(f-> StringUtils.equals(f.getDictValue(),handlerExcelData.getOffGradeAscription())).findFirst().orElse(new SysDictData()).getDictLabel());
                return handlerExcelData;
            }).collect(Collectors.toList());
            //设置response
            String fileName = "不合格处理记录" + ExcelTypeEnum.XLSX.getValue();
            fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            //导出
 
            EasyExcel.write(response.getOutputStream(), InsUnqualifiedHandlerExcelData.class)
                    .sheet()
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .doWrite(records);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("不合格处理记录导出失败");
        }
 
    }
 
    @Override
    public List<Integer> getList() {
        return baseMapper.selectList(null).stream().map(InsUnqualifiedHandler::getInsOrderId).collect(Collectors.toList());
    }
 
    @Override
    public Result pushOA(PushOADto pushOADto) {
        //获取不合格处理记录
        UnqualifiedHandlerVO vo = baseMapper.findByGroupId(pushOADto.getGroupId(),pushOADto.getHandlerId());
 
        //提交oa相关字段赋值
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        Map<String, String> mainFields = new HashMap<>();
        mainFields.put("gysmcsuppliername", vo.getSupplierName());//供应商名称
        mainFields.put("wlmcmaterialname", vo.getMaterialName());//物料名称
        mainFields.put("scpcproductionbatch", vo.getProductionBatch());//生产批次
        mainFields.put("dhslcargoquantity", vo.getCargoQuantity() + vo.getBuyUnitMeas());//到货数量
        mainFields.put("ggxhspecificationsmodels", vo.getSpecsModels());//规格型号
        mainFields.put("bjrqdeclarationinspectdate", vo.getInspectTime().format(formatter));//报检日期
        mainFields.put("fkrprovideroffeedback", SecurityUtils.getUsername());//反馈人
        mainFields.put("fkrqfeedbacktime", vo.getFeedbackTime().format(formatter));//反馈日期
        mainFields.put("flclassification", vo.getClassification());//分类
        mainFields.put("bhggsoffgradeascription", vo.getOffGradeAscription());//不合格归属
        mainFields.put("bhgqkmsunqualifieddescription", vo.getUnqualifiedDesc());//不合格情况描述
 
        //查询附件
        List<InsUnqualifiedHandlerFile> handlerFiles = insUnqualifiedHandlerFileService.list(Wrappers.<InsUnqualifiedHandlerFile>lambdaQuery()
                .eq(InsUnqualifiedHandlerFile::getUnqualifiedId, vo.getHandlerId()));
        if (CollectionUtils.isNotEmpty(handlerFiles)) {
            StringBuilder fileUrl = new StringBuilder();
            for (int i = 0; i < handlerFiles.size(); i++) {
                String path = handlerFiles.get(i).getType().equals(1) ? "/img/" : "/word/";
                if (i == handlerFiles.size() - 1) {
                    fileUrl.append("<a href='" + oaProperty.getProdIp()).append(path + handlerFiles.get(i).getFileUrl()
                            + "'target='_blank'>" + handlerFiles.get(i).getFileName() + "</a>");
                } else {
                    fileUrl.append("<a href='" + oaProperty.getProdIp()).append(path + handlerFiles.get(i).getFileUrl()
                            + "'target='_blank'>" + handlerFiles.get(i).getFileName() + "</a>").append("<br/>");
                }
            }
            mainFields.put("fjlj", fileUrl.toString());
        }
        //流程标题
        String requestName = vo.getHeadline();
        //发起OA
        boolean oa = false;
        try {
            log.info("发起不合格处理OA审核流程");
            String unqualifiedProcessId = oaProperty.getUnqualifiedProcessId();
            OAResult oaResult = OAProcess.start(mainFields, requestName, unqualifiedProcessId,SecurityUtils.getUsername());
            log.info("不合格流程ID:{},不合格处理OA审核流程发起成功->{}",unqualifiedProcessId,oaResult);
            oa = oaResult.success();
            if (oa) {
                String addWorkflowResult = oaResult.getAddWorkflowResult();
                baseMapper.update(null, new LambdaUpdateWrapper<InsUnqualifiedHandler>()
                        .set(InsUnqualifiedHandler::getRequestId, addWorkflowResult)
                        .set(InsUnqualifiedHandler::getOaState, 2)
                        .eq(InsUnqualifiedHandler::getGroupId, pushOADto.getGroupId()));
            } else {
                return Result.fail("提交oa失败: " + oaResult.getErrorMsg());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.success();
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unqualifiedHandlerOACallback(Long oaWorkId, String checkResult, JSONObject response) {
        // 没有这个就结束
        Long count1 = baseMapper.selectCount(Wrappers.<InsUnqualifiedHandler>lambdaQuery()
                .eq(InsUnqualifiedHandler::getRequestId, Integer.valueOf(String.valueOf(oaWorkId))));
        if (count1 == 0) {
            return;
        }
        //处理措施map
        Map<String, String> clcsMap = new HashMap<>();
        clcsMap.put("0","让步放行");
        clcsMap.put("1","退货");
        clcsMap.put("2","部分退货");
        clcsMap.put("3","降级使用");
        //oa状态:3通过 4驳回
        Integer oaState = "1".equals(checkResult) ? 3 : 4;
        baseMapper.update(null, new LambdaUpdateWrapper<InsUnqualifiedHandler>()
                .set(InsUnqualifiedHandler::getOaState, oaState)
                .set(InsUnqualifiedHandler::getClassification,response.getString("flclassification"))
                .eq(InsUnqualifiedHandler::getRequestId, Integer.valueOf(String.valueOf(oaWorkId))));
        //保存oa审批流程记录
        List<CommonOa> commonOaList = new ArrayList<>();
        JSONArray workflowRequestLogs = JSONArray.parseArray(JSONObject.toJSONString(response.get("workflowRequestLogs")));
        for (Object workflowRequestLog : workflowRequestLogs) {
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(workflowRequestLog));
            CommonOa oa = new CommonOa();
            oa.setApprover(jsonObject.getString("operatorName"));
            oa.setOperateId(jsonObject.getLong("operateId"));
            oa.setWorkflowId(oaWorkId);
            oa.setOperation(jsonObject.getString("operateType"));
            oa.setApprovalDate(jsonObject.getString("operateDate"));
            oa.setNodeName(jsonObject.getString("nodeName"));
            oa.setApprovalTime(jsonObject.getString("operateTime"));
            //设置各节点的处理意见
            if(StringUtils.isNotBlank(oa.getNodeName())){
                if(oa.getNodeName().contains("质量")){
                    oa.setOperation(clcsMap.get(response.getString("clcs1")));
                    oa.setApprovalOpinion(response.getString("dbhgcpdclyqdealwiththenonconfo"));//1.对不合格产品的处理要求
                }else if(oa.getNodeName().contains("工艺")){
                    oa.setApprovalOpinion(response.getString("gjyqimprovementrequirements"));//2.改进要求
                }else if(oa.getNodeName().contains("技术")){
                    oa.setOperation(clcsMap.get(response.getString("clcs2")));
                    oa.setApprovalOpinion(response.getString("csyqactionrequirement"));//3.措施要求
                }else if(oa.getNodeName().contains("总经理")){
                    oa.setOperation(clcsMap.get(response.getString("clcs3")));
                    oa.setApprovalOpinion(response.getString("zzclyqfinaltreatmentrequiremen"));//4.最终处理要求
                }else if(oa.getNodeName().contains("核算")){
                    oa.setApprovalOpinion(response.getString("spyqcompensationrequirement"));//5.索赔要求
                }else{
                    oa.setApprovalOpinion(jsonObject.getString("remark"));
                }
            }
 
            //查询判断之前是否添加过
            long count = commonOaService.count(Wrappers.<CommonOa>lambdaQuery()
                    .eq(CommonOa::getWorkflowId, oaWorkId)
                    .eq(CommonOa::getOperateId, oa.getOperateId()));
            // 没有重复添加
            if (count == 0) {
                commonOaList.add(oa);
            }
        }
        commonOaService.saveBatch(commonOaList);
 
    }
 
    /**
     * 查看oa流程
     * @param id
     * @return
     */
    @Override
    public List<CommonOa> getOaFlow(Integer id) {
        return baseMapper.getOaFlow(id);
    }
 
    /**
     * 新增不合格处理
     * @param unqualifiedHandlerDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addUnqualifiedHandler(UnqualifiedHandlerDto unqualifiedHandlerDto) {
        long count = this.count(Wrappers.<InsUnqualifiedHandler>lambdaQuery()
                .in(InsUnqualifiedHandler::getInsOrderId, unqualifiedHandlerDto.getSelectOrderIds()));
        if (count > 0) {
            throw new ErrorException("存在已提交过不合格处理的订单");
        }
        //生成分组id
        String groupId = insUnqualifiedHandlerNumberGenerator.generateNumberWithPrefix(6, "GROUP", InsUnqualifiedHandler::getGroupId);
        // 原材料编号切割
        for (Integer selectOrderId : unqualifiedHandlerDto.getSelectOrderIds()) {
            InsUnqualifiedHandler insUnqualifiedHandler = new InsUnqualifiedHandler();
            BeanUtils.copyProperties(unqualifiedHandlerDto, insUnqualifiedHandler);
            Map<String, Object> orderMap = insSampleMapper.selectInsOrder(selectOrderId);
            insUnqualifiedHandler.setNo(orderMap.get("entrustCode").toString());
            insUnqualifiedHandler.setInventoryQuantityId(Integer.valueOf(orderMap.get("inventoryQuantityId").toString()));
            insUnqualifiedHandler.setInsOrderId(selectOrderId);
            insUnqualifiedHandler.setGroupId(groupId);
            insUnqualifiedHandler.setProductionBatch(orderMap.get("updateBatchNo").toString());
            insUnqualifiedHandler.setCargoQuantity(Double.parseDouble(orderMap.get("qtyArrived").toString()));
            insUnqualifiedHandler.setBuyUnitMeas(orderMap.get("buyUnitMeas").toString());
 
            this.save(insUnqualifiedHandler);
            if (CollectionUtils.isNotEmpty(unqualifiedHandlerDto.getUnqualifiedHandlerFiles())) {
                for (InsUnqualifiedHandlerFile unqualifiedHandlerFile : unqualifiedHandlerDto.getUnqualifiedHandlerFiles()) {
                    unqualifiedHandlerFile.setGroupId(insUnqualifiedHandler.getGroupId());
                }
                insUnqualifiedHandlerFileService.updateBatchById(unqualifiedHandlerDto.getUnqualifiedHandlerFiles());
            }
        }
        return true;
    }
 
    /**
     * 编辑不合格处理
     * @param unqualifiedHandlerDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class,isolation = Isolation.READ_COMMITTED)
    public boolean updateUnqualifiedHandler(UnqualifiedHandlerDto unqualifiedHandlerDto) {
        // 删除附件, 重新添加
        insUnqualifiedHandlerFileService.remove(Wrappers.<InsUnqualifiedHandlerFile>lambdaQuery()
                .eq(InsUnqualifiedHandlerFile::getUnqualifiedId, unqualifiedHandlerDto.getId()));
        if (CollectionUtils.isNotEmpty(unqualifiedHandlerDto.getUnqualifiedHandlerFiles())) {
            for (InsUnqualifiedHandlerFile unqualifiedHandlerFile : unqualifiedHandlerDto.getUnqualifiedHandlerFiles()) {
                unqualifiedHandlerFile.setUnqualifiedId(unqualifiedHandlerDto.getId());
            }
            insUnqualifiedHandlerFileService.updateBatchById(unqualifiedHandlerDto.getUnqualifiedHandlerFiles());
        }
        boolean isUpdated = this.updateById(unqualifiedHandlerDto);
        if(isUpdated){
            //推送OA
            PushOADto pushOADto = new PushOADto();
            pushOADto.setHandlerId(unqualifiedHandlerDto.getId());
            pushOADto.setContract(unqualifiedHandlerDto.getContract());
            pushOA(pushOADto);
        }
        return true;
    }
 
    /**
     * 查看不合格处理界面
     * @param id
     * @return
     */
    @Override
    public UnqualifiedHandlerDto getUnqualifiedHandler(Integer id) {
        InsUnqualifiedHandler insUnqualifiedHandler = this.getById(id);
        UnqualifiedHandlerDto unqualifiedHandlerDto = new UnqualifiedHandlerDto();
        BeanUtil.copyProperties(insUnqualifiedHandler, unqualifiedHandlerDto);
        // 查看附件
        List<InsUnqualifiedHandlerFile> list = insUnqualifiedHandlerFileService.list(Wrappers.<InsUnqualifiedHandlerFile>lambdaQuery()
                .eq(InsUnqualifiedHandlerFile::getGroupId, unqualifiedHandlerDto.getGroupId()));
        unqualifiedHandlerDto.setUnqualifiedHandlerFiles(list);
        return unqualifiedHandlerDto;
    }
 
    /**
     * 删除不合格
     * @param groupId
     * @return
     */
    @Override
    public boolean deleteUnqualifiedHandler(String groupId) {
        insUnqualifiedHandlerFileService.remove(Wrappers.<InsUnqualifiedHandlerFile>lambdaQuery()
                .eq(InsUnqualifiedHandlerFile::getGroupId, groupId));
        return this.remove(Wrappers.<InsUnqualifiedHandler>lambdaQuery().eq(InsUnqualifiedHandler::getGroupId, groupId));
    }
}