chenhj
2026-04-20 6604ae13d86b1f22c0a7a3af536526102d85b77d
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
package com.ruoyi.sales.service.impl;
 
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.approve.pojo.ApproveProcess;
import com.ruoyi.approve.service.impl.ApproveProcessServiceImpl;
import com.ruoyi.approve.vo.ApproveGetAndUpdateVo;
import com.ruoyi.approve.vo.ApproveProcessVO;
import com.ruoyi.basic.mapper.CustomerMapper;
import com.ruoyi.basic.mapper.ProductModelMapper;
import com.ruoyi.basic.pojo.Customer;
import com.ruoyi.basic.pojo.ProductModel;
import com.ruoyi.common.utils.OrderUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.sales.dto.QuotationRecordJSON;
import com.ruoyi.sales.dto.SalesQuotationDto;
import com.ruoyi.sales.mapper.QuotationRecordMapper;
import com.ruoyi.sales.mapper.SalesQuotationMapper;
import com.ruoyi.sales.mapper.SalesQuotationProductMapper;
import com.ruoyi.sales.pojo.SalesQuotation;
import com.ruoyi.sales.pojo.SalesQuotationProduct;
import com.ruoyi.sales.service.QuotationRecordService;
import com.ruoyi.sales.service.SalesQuotationProductService;
import com.ruoyi.sales.service.SalesQuotationService;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
 
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class SalesQuotationServiceImpl extends ServiceImpl<SalesQuotationMapper, SalesQuotation> implements SalesQuotationService {
    private final SalesQuotationMapper salesQuotationMapper;
    private final SalesQuotationProductMapper salesQuotationProductMapper;
    private final SalesQuotationProductService salesQuotationProductService;
    private final ApproveProcessServiceImpl approveProcessService;
    private final CustomerMapper customerMapper;
    private final SysUserMapper sysUserMapper;
    private final ProductModelMapper productModelMapper;
    private final QuotationRecordMapper quotationRecordMapper;
    private final QuotationRecordService quotationRecordsService;
 
    @Override
    public IPage<SalesQuotationDto> listPage(Page page, SalesQuotationDto salesQuotationDto) {
        IPage<SalesQuotationDto> salesQuotationDtoIPage = salesQuotationMapper.listPage(page, salesQuotationDto);
        if (CollectionUtils.isEmpty(salesQuotationDtoIPage.getRecords())) {
            return salesQuotationDtoIPage;
        }
        salesQuotationDtoIPage.getRecords().forEach(record -> {
            List<SalesQuotationProduct> products = salesQuotationProductMapper.selectBySalesQuotationId(record.getId());
            record.setProducts(products);
        });
        return salesQuotationDtoIPage;
    }
 
    @Override
    public boolean add(SalesQuotationDto salesQuotationDto) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SalesQuotation salesQuotation = new SalesQuotation();
        BeanUtils.copyProperties(salesQuotationDto, salesQuotation);
        String quotationNo = OrderUtils.countTodayByCreateTime(salesQuotationMapper, "QT", "quotation_no");
        salesQuotation.setQuotationNo(quotationNo);
        salesQuotation.setStatus("待审批");
        salesQuotationMapper.insert(salesQuotation);
        if (CollectionUtils.isEmpty(salesQuotationDto.getProducts())) {
            return true;
        }
        List<SalesQuotationProduct> products = salesQuotationDto.getProducts().stream().map(product -> {
            SalesQuotationProduct salesQuotationProduct = new SalesQuotationProduct();
            BeanUtils.copyProperties(product, salesQuotationProduct);
            salesQuotationProduct.setSalesQuotationId(salesQuotation.getId());
            return salesQuotationProduct;
        }).collect(Collectors.toList());
        salesQuotationProductService.saveBatch(products);
        // 报价审批
        ApproveProcessVO approveProcessVO = new ApproveProcessVO();
        approveProcessVO.setApproveType(6);
        approveProcessVO.setApproveDeptId(loginUser.getCurrentDeptId());
        approveProcessVO.setApproveReason(quotationNo);
        approveProcessVO.setApproveUserIds(salesQuotationDto.getApproveUserIds());
        approveProcessVO.setApproveUser(loginUser.getUserId());
        approveProcessVO.setApproveTime(LocalDate.now().toString());
        approveProcessVO.setPrice(salesQuotationDto.getTotalAmount());
        try {
            approveProcessService.addApprove(approveProcessVO);
        } catch (Exception e) {
            log.error("SalesQuotationServiceImpl error:{}", e);
            throw new RuntimeException("审批失败");
        }
        return true;
    }
 
    @Override
    public boolean edit(SalesQuotationDto salesQuotationDto) {
        SalesQuotation salesQuotation = new SalesQuotation();
        BeanUtils.copyProperties(salesQuotationDto, salesQuotation);
        ApproveGetAndUpdateVo vo = new ApproveGetAndUpdateVo();
        if ("拒绝".equals(salesQuotationDto.getStatus())) {
            vo.setApproveStatus(0);
            salesQuotation.setStatus("待审批");
        }
        if (salesQuotationMapper.updateById(salesQuotation) != 1) {
            return false;
        }
        salesQuotationProductMapper.delete(new LambdaQueryWrapper<SalesQuotationProduct>().eq(SalesQuotationProduct::getSalesQuotationId, salesQuotationDto.getId()));
        if (CollectionUtils.isEmpty(salesQuotationDto.getProducts())) {
            return true;
        }
        List<SalesQuotationProduct> products = salesQuotationDto.getProducts().stream().map(product -> {
            SalesQuotationProduct salesQuotationProduct = new SalesQuotationProduct();
            BeanUtils.copyProperties(product, salesQuotationProduct);
            salesQuotationProduct.setSalesQuotationId(salesQuotation.getId());
            return salesQuotationProduct;
        }).collect(Collectors.toList());
 
        salesQuotationProductService.saveBatch(products);
        // 修改报价审批
        vo.setApproveUserIds(salesQuotationDto.getApproveUserIds());
        vo.setApproveType(6);
        vo.setApproveReason(salesQuotationDto.getQuotationNo());
        approveProcessService.updateApproveUser(vo);
        return true;
    }
 
    @Override
    public boolean delete(Long id) {
        SalesQuotation salesQuotation = salesQuotationMapper.selectById(id);
        if (salesQuotation == null) return false;
        salesQuotationMapper.deleteById(id);
        salesQuotationProductMapper.delete(new LambdaQueryWrapper<SalesQuotationProduct>().eq(SalesQuotationProduct::getSalesQuotationId, id));
        // 删除报价审批
        ApproveProcess one = approveProcessService.getOne(new LambdaQueryWrapper<ApproveProcess>()
                .eq(ApproveProcess::getApproveType, 6)
                .eq(ApproveProcess::getApproveReason, salesQuotation.getQuotationNo()));
        if (one != null) {
            approveProcessService.delByIds(Collections.singletonList(one.getId()));
        }
        return true;
    }
 
    @Override
    public QuotationRecordJSON importData(MultipartFile file, String approveUserIdsJson) {
        try (InputStream inputStream = file.getInputStream();
             Workbook workbook = WorkbookFactory.create(inputStream)) {
            Sheet sheet = workbook.getNumberOfSheets() > 1 ? workbook.getSheetAt(1) : workbook.getSheetAt(0);
            DataFormatter dataFormatter = new DataFormatter();
 
            QuotationRecordJSON result = new QuotationRecordJSON();
            // 模板中客户信息固定在第2行(A2-F2),且只有一行
            Row customerRow = sheet.getRow(1);
            List<Customer> customers = customerMapper.selectList(new LambdaQueryWrapper<Customer>()
                    .eq(Customer::getCustomerName, getStringCell(customerRow, 0, dataFormatter)));
            if (CollectionUtils.isEmpty(customers)) {
                throw new RuntimeException("客户不存在");
            }
            List<SysUser> sysUsers = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getNickName, getStringCell(customerRow, 1, dataFormatter)));
            if (CollectionUtils.isEmpty(sysUsers)) {
                throw new RuntimeException("业务员不存在");
            }
 
            if (customerRow != null) {
                result.setCustomer(getStringCell(customerRow, 0, dataFormatter));
                result.setSalesperson(getStringCell(customerRow, 1, dataFormatter));
                result.setQuotationDate(getStringCell(customerRow, 2, dataFormatter));
                result.setValidDate(getStringCell(customerRow, 3, dataFormatter));
                result.setPaymentMethod(getStringCell(customerRow, 4, dataFormatter));
                result.setRemark(getStringCell(customerRow, 5, dataFormatter));
            }
 
            // 模板中产品表头在第7行,数据从第8行开始
            List<QuotationRecordJSON.ProductJSON> products = new ArrayList<>();
            int startRow = 7;
            for (int i = startRow; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                String product = getStringCell(row, 0, dataFormatter);
                String specification = getStringCell(row, 1, dataFormatter);
                List<ProductModel> productModels = productModelMapper.selectList(new LambdaQueryWrapper<ProductModel>()
                        .eq(ProductModel::getModel, specification));
                if (CollectionUtils.isEmpty(productModels)) {
                    throw new RuntimeException("产品不存在");
                }
                ProductModel productModel = productModels.get(0);
 
                BigDecimal unitPrice = getDecimalCell(row, 2, dataFormatter);
                if (isBlank(product) && isBlank(specification) && unitPrice == null) {
                    continue;
                }
                QuotationRecordJSON.ProductJSON item = new QuotationRecordJSON.ProductJSON();
                item.setProduct(product);
                item.setSpecification(specification);
                item.setUnit(productModel.getUnit());
                item.setUnitPrice(unitPrice);
                products.add(item);
            }
            result.setProducts(products);
            // 处理报价单
            SalesQuotation salesQuotation = addOrUpdateApproveProcess(result, approveUserIdsJson);
 
            Integer insertResult = quotationRecordsService.add(salesQuotation.getId(), result);
            if (insertResult <= 0) {
                throw new RuntimeException("报价记录新增失败");
            }
            return result;
        } catch (Exception e) {
            throw new RuntimeException("导入销售报价模板失败:" + e.getMessage(), e);
        }
    }
 
    private SalesQuotation addOrUpdateApproveProcess(QuotationRecordJSON quotationRecordJSON, String approveUserIdsJson) {
        List<SalesQuotation> salesQuotations = salesQuotationMapper.selectList(new LambdaQueryWrapper<SalesQuotation>()
                .eq(SalesQuotation::getCustomer, quotationRecordJSON.getCustomer())
                .eq(SalesQuotation::getStatus, "待审批"));
 
        if (CollectionUtils.isEmpty(salesQuotations)) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            SalesQuotation salesQuotation = new SalesQuotation();
            String quotationNo = OrderUtils.countTodayByCreateTime(salesQuotationMapper, "QT", "quotation_no");
            salesQuotation.setQuotationNo(quotationNo);
            salesQuotation.setCustomer(quotationRecordJSON.getCustomer());
            salesQuotation.setSalesperson(quotationRecordJSON.getSalesperson());
            salesQuotation.setQuotationDate(LocalDate.parse(quotationRecordJSON.getQuotationDate()));
            salesQuotation.setValidDate(LocalDate.parse(quotationRecordJSON.getValidDate()));
            salesQuotation.setPaymentMethod(quotationRecordJSON.getPaymentMethod());
            salesQuotation.setStatus("待审批");
            BigDecimal totalAmount = quotationRecordJSON.getProducts().stream()
                    .map(QuotationRecordJSON.ProductJSON::getUnitPrice)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            salesQuotation.setTotalAmount(totalAmount);
            salesQuotationMapper.insert(salesQuotation);
 
            List<SalesQuotationProduct> products = quotationRecordJSON.getProducts().stream().map(product -> {
                SalesQuotationProduct salesQuotationProduct = new SalesQuotationProduct();
                salesQuotationProduct.setProduct(product.getProduct());
                salesQuotationProduct.setSpecification(product.getSpecification());
                salesQuotationProduct.setUnit(product.getUnit());
                salesQuotationProduct.setUnitPrice(product.getUnitPrice().doubleValue());
                salesQuotationProduct.setSalesQuotationId(salesQuotation.getId());
                return salesQuotationProduct;
            }).collect(Collectors.toList());
            salesQuotationProductService.saveBatch(products);
            // 报价审批
            ApproveProcessVO approveProcessVO = new ApproveProcessVO();
            approveProcessVO.setApproveType(6);
            approveProcessVO.setApproveDeptId(loginUser.getCurrentDeptId());
            approveProcessVO.setApproveReason(quotationNo);
            approveProcessVO.setApproveUserIds(approveUserIdsJson);
            approveProcessVO.setApproveUser(loginUser.getUserId());
            approveProcessVO.setApproveTime(LocalDate.now().toString());
            approveProcessVO.setPrice(salesQuotation.getTotalAmount());
            try {
                approveProcessService.addApprove(approveProcessVO);
            } catch (Exception e) {
                log.error("SalesQuotationServiceImpl error:{}", e);
                throw new RuntimeException("审批失败");
            }
            return salesQuotation;
        } else {
            if (salesQuotations.size() > 1) {
                throw new RuntimeException("存在多个待审批的报价单");
            } else {
                SalesQuotation salesQuotation = salesQuotations.get(0);
                salesQuotation.setSalesperson(quotationRecordJSON.getSalesperson());
                salesQuotation.setQuotationDate(LocalDate.parse(quotationRecordJSON.getQuotationDate()));
                salesQuotation.setValidDate(LocalDate.parse(quotationRecordJSON.getValidDate()));
                salesQuotation.setPaymentMethod(quotationRecordJSON.getPaymentMethod());
                BigDecimal totalAmount = quotationRecordJSON.getProducts().stream()
                        .map(QuotationRecordJSON.ProductJSON::getUnitPrice)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                salesQuotation.setTotalAmount(totalAmount);
                salesQuotationMapper.updateById(salesQuotation);
 
                // 删除原来的报价产品
                salesQuotationProductMapper.delete(new LambdaQueryWrapper<SalesQuotationProduct>()
                        .eq(SalesQuotationProduct::getSalesQuotationId, salesQuotation.getId()));
 
                List<SalesQuotationProduct> products = quotationRecordJSON.getProducts().stream().map(product -> {
                    SalesQuotationProduct salesQuotationProduct = new SalesQuotationProduct();
                    salesQuotationProduct.setProduct(product.getProduct());
                    salesQuotationProduct.setSpecification(product.getSpecification());
                    salesQuotationProduct.setUnit(product.getUnit());
                    salesQuotationProduct.setUnitPrice(product.getUnitPrice().doubleValue());
                    salesQuotationProduct.setSalesQuotationId(salesQuotation.getId());
                    return salesQuotationProduct;
                }).collect(Collectors.toList());
                salesQuotationProductService.saveBatch(products);
                return salesQuotation;
            }
        }
    }
 
    private String getStringCell(Row row, int columnIndex, DataFormatter dataFormatter) {
        if (row == null) {
            return null;
        }
        Cell cell = row.getCell(columnIndex);
        if (cell == null) {
            return null;
        }
        if (cell.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)) {
            return cell.getLocalDateTimeCellValue().toLocalDate().format(DateTimeFormatter.ISO_LOCAL_DATE);
        }
        String value = dataFormatter.formatCellValue(cell);
        return isBlank(value) ? null : value.trim();
    }
 
    private BigDecimal getDecimalCell(Row row, int columnIndex, DataFormatter dataFormatter) {
        String value = getStringCell(row, columnIndex, dataFormatter);
        if (isBlank(value)) {
            return null;
        }
        try {
            return new BigDecimal(value.replace(",", ""));
        } catch (Exception e) {
            return null;
        }
    }
 
    private boolean isBlank(String value) {
        return value == null || value.trim().isEmpty();
    }
}