李林
2023-10-07 658d4927d468c47208fd012d9128b09249c07eff
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
/*
 *    Copyright (c) 2018-2025, ztt All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: ztt
 */
package com.chinaztt.mes.warehouse.service.impl;
 
 
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.BooleanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaztt.mes.common.numgen.NumberGenerator;
import com.chinaztt.mes.warehouse.dto.InventoryMainDTO;
import com.chinaztt.mes.warehouse.entity.InventoryDetail;
import com.chinaztt.mes.warehouse.entity.InventoryMain;
import com.chinaztt.mes.warehouse.excel.InventoryData;
import com.chinaztt.mes.warehouse.mapper.InventoryDetailMapper;
import com.chinaztt.mes.warehouse.mapper.InventoryMainMapper;
import com.chinaztt.mes.warehouse.mapper.StockMapper;
import com.chinaztt.mes.warehouse.service.InventoryDetailService;
import com.chinaztt.mes.warehouse.service.InventoryMainService;
import com.chinaztt.mes.warehouse.state.constant.InventoryMainState;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
/**
 * 新盘点主表
 *
 * @author yangyao
 * @date 2022-10-13 11:06:00
 */
@AllArgsConstructor
@Service
public class InventoryMainServiceImpl extends ServiceImpl<InventoryMainMapper, InventoryMain> implements InventoryMainService {
 
    private NumberGenerator<InventoryMain> numberGenerator;
 
    private StockMapper stockMapper;
 
    private InventoryDetailService inventoryDetailService;
 
    private InventoryDetailMapper inventoryDetailMapper;
 
 
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean fullSave(InventoryMainDTO inventoryMainDTO) {
        if(CollectionUtil.isEmpty(inventoryMainDTO.getWarehouseIds())){
            throw new RuntimeException("没有选择仓库!");
        }
        inventoryMainDTO.setInyNo(numberGenerator.generateNumberWithPrefix(InventoryMain.DIGIT, InventoryMain.PREFIX, InventoryMain::getInyNo));
        inventoryMainDTO.setInyStatus(InventoryMainState.DRAFT.getCode());
        baseMapper.insert(inventoryMainDTO);
        List<InventoryDetail> stockByInventoryList = stockMapper.getStockByInventory(inventoryMainDTO.getLocationIds(), inventoryMainDTO.getWarehouseIds(), inventoryMainDTO.getPartId());
        if(CollectionUtil.isNotEmpty(stockByInventoryList)){
            stockByInventoryList.stream().forEach(inventoryDetail ->{
                inventoryDetail.setInyNo(inventoryMainDTO.getInyNo());
                inventoryDetail.setInyDiffQty(inventoryDetail.getStockQuantity());
                inventoryDetail.setInventoryMainId(inventoryMainDTO.getId());
            });
            Map<String, List<InventoryDetail>> collect =
                    stockByInventoryList.stream().collect(Collectors.groupingBy(d -> d.getInventoryMainId() + "-" + d.getPartNo() + "-" + d.getSn() + "-" + d.getIfsBatchNo() + "-" + d.getLocNo()));
            List<InventoryDetail> resultList = new ArrayList<>();
            for (Map.Entry<String, List<InventoryDetail>> entry : collect.entrySet()) {
                BigDecimal quantity =
                        entry.getValue().stream().map(InventoryDetail::getStockQuantity).reduce(BigDecimal.ZERO,
                                BigDecimal::add);
                InventoryDetail inventoryDetail = entry.getValue().get(0);
                inventoryDetail.setStockQuantity(quantity);
                resultList.add(inventoryDetail);
            }
            inventoryDetailService.saveBatch(resultList);
 
        }
        return true;
    }
 
 
    @Override
    public boolean remove(Long id) {
        List<InventoryDetail> inventoryDetails = inventoryDetailMapper.selectList(Wrappers.<InventoryDetail>lambdaQuery()
                .eq(InventoryDetail::getInventoryMainId, id));
        if(CollectionUtil.isNotEmpty(inventoryDetails)){
            boolean inyQtyNotNull = inventoryDetails.stream().anyMatch(d -> d.getInyQty() != null);
            if (BooleanUtil.isTrue(inyQtyNotNull)) {
                throw new RuntimeException("明细表存在盘点数量,盘点表不能删除该条记录!");
            }
            inventoryDetailMapper.delete(Wrappers.<InventoryDetail>lambdaQuery().eq(InventoryDetail::getInventoryMainId, id));
        }
        baseMapper.deleteById(id);
        return true;
    }
 
    @Override
    public void export(HttpServletResponse response, List<Long> ids) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("盘点信息导出", "UTF-8").replaceAll("\\+", "%20");;
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        try {
            //新建ExcelWriter
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
            //获取sheet0对象
            WriteSheet mainSheet = EasyExcel.writerSheet(0, "导出").head(InventoryData.class).build();
            //向sheet0写入数据 传入空list这样只导出表头
            List<InventoryData> inventoryDataList = baseMapper.getExport(ids);
            excelWriter.write(inventoryDataList, mainSheet);
            //关闭流
            excelWriter.finish();
        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        }
    }
}