liding
4 天以前 c16a5f590db461391a4441e520f3264526c11905
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
package com.ruoyi.sales.controller;
 
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.basic.pojo.Customer;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.domain.R;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.sales.dto.*;
import com.ruoyi.sales.mapper.InvoiceLedgerMapper;
import com.ruoyi.sales.pojo.SalesLedger;
import com.ruoyi.sales.pojo.SalesLedgerProcessRoute;
import com.ruoyi.sales.service.ICommonFileService;
import com.ruoyi.sales.service.ISalesLedgerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 销售台账Controller
 *
 * @author ruoyi
 * @date 2025-05-08
 */
@RestController
@RequestMapping("/sales/ledger")
@AllArgsConstructor
@Api(tags = "销售台账")
@Slf4j
public class SalesLedgerController extends BaseController {
 
    private ISalesLedgerService salesLedgerService;
 
    private ICommonFileService commonFileService;
 
    @Autowired
    private InvoiceLedgerMapper invoiceLedgerMapper;
 
    /**
     * 导入销售台账
     */
    @Log(title = "导入销售台账", businessType = BusinessType.INSERT)
    @PostMapping("/import")
    @ApiOperation("导入销售台账")
    public AjaxResult importData(@RequestParam("file")
                                 @ApiParam(value = "Excel文件", required = true)
                                 MultipartFile file) {
        salesLedgerService.importData(file);
        return AjaxResult.success();
    }
 
    @ApiOperation("导出销售台账模板")
    @PostMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) {
        // 1. 模板文件在resources/static下的路径
        String templatePath = "static/销售台账导入模板.xlsx";
 
        // 2. 获取模板文件的输入流
        try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(templatePath)) {
            if (inputStream == null) {
                throw new FileNotFoundException("模板文件不存在:" + templatePath);
            }
 
            // 3. 设置响应头,触发浏览器下载
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("销售台账导入模板.xlsx", "utf-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
 
            // 4. 将模板文件写入响应输出流
            try (OutputStream outputStream = response.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, len);
                }
                outputStream.flush();
            }
        } catch (IOException e) {
            log.error("导出销售台账模板失败", e);
            // 若模板文件读取失败,返回错误提示
            try {
                response.getWriter().write("模板导出失败:" + e.getMessage());
            } catch (IOException ex) {
                log.error("响应输出错误", ex);
            }
        }
    }
 
    /**
     * 查询销售台账列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Page<?> page, SalesLedgerDto salesLedgerDto) {
        startPage();
        List<SalesLedger> list = salesLedgerService.selectSalesLedgerList(salesLedgerDto);
        // 计算已开票金额/未开票金额(已填写发票金额为准)
        if (CollectionUtils.isEmpty(list)) {
            return getDataTable(list);
        }
        List<Long> salesLedgerIds = list.stream().map(SalesLedger::getId).collect(Collectors.toList());
        List<InvoiceLedgerDto> invoiceLedgerDtoList = invoiceLedgerMapper.invoicedTotal(salesLedgerIds);
        if (CollectionUtils.isEmpty(invoiceLedgerDtoList)) {
            return getDataTable(list);
        }
        for (SalesLedger salesLedger : list) {
            for (InvoiceLedgerDto invoiceLedgerDto : invoiceLedgerDtoList) {
                if (salesLedger.getId().intValue() == invoiceLedgerDto.getSalesLedgerId()) {
                    BigDecimal noInvoiceAmountTotal = salesLedger.getContractAmount().subtract(invoiceLedgerDto.getInvoiceTotal());
                    salesLedger.setNoInvoiceAmountTotal(noInvoiceAmountTotal);
                }
            }
        }
 
        return getDataTable(list);
    }
 
    /**
     * 查询销售台账和产品父子列表
     */
    @GetMapping("/getSalesLedgerWithProducts")
    public SalesLedgerDto getSalesLedgerWithProducts(SalesLedgerDto salesLedgerDto) {
        return salesLedgerService.getSalesLedgerWithProducts(salesLedgerDto);
    }
 
    /**
     * 导出销售台账列表
     */
    @Log(title = "销售台账", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SalesLedgerDto salesLedgerDto) {
        Page<?> page = new Page<>(-1, -1);
        IPage<SalesLedger> salesLedgerIPage = listPage(page, salesLedgerDto);
        ExcelUtil<SalesLedger> util = new ExcelUtil<SalesLedger>(SalesLedger.class);
        if (salesLedgerIPage == null) {
            util.exportExcel(response, new ArrayList<>(), "销售台账数据");
            return;
        }
        List<SalesLedger> list = salesLedgerIPage.getRecords();
        util.exportExcel(response, list, "销售台账数据");
    }
 
    /**
     * 导出销售台账列表(包含产品明细,两个sheet页)
     */
    @Log(title = "销售台账", businessType = BusinessType.EXPORT)
    @PostMapping("/exportWithProducts")
    @ApiOperation("导出销售台账及产品明细(两个sheet页)")
    public void exportWithProducts(HttpServletResponse response, SalesLedgerDto salesLedgerDto) {
        salesLedgerService.exportWithProducts(response, salesLedgerDto);
    }
 
    /**
     * 导出售后台账工艺路线
     */
    @Log(title = "销售台账工艺路线", businessType = BusinessType.EXPORT)
    @PostMapping("/exportProcessRoute")
    @ApiOperation("导出售后台账工艺路线")
    public void exportProcessRoute(HttpServletResponse response,
                                   HttpServletRequest request,
                                   @RequestParam(value = "completedTimeStart", required = false) String completedTimeStart,
                                   @RequestParam(value = "completedTimeEnd", required = false) String completedTimeEnd) {
        List<Long> salesLedgerIds = parseSalesLedgerIds(request);
        salesLedgerService.exportProcessRoute(response, salesLedgerIds, completedTimeStart, completedTimeEnd);
    }
 
    /**
     * 导出开票登记列表
     */
    @Log(title = "导出开票登记列表", businessType = BusinessType.EXPORT)
    @PostMapping("/exportOne")
    public void exportOne(HttpServletResponse response, SalesLedgerDto salesLedgerDto) {
        Page<?> page = new Page<>();
        page.setCurrent(-1);
        page.setSize(-1);
        IPage<SalesLedger> salesLedgerIPage = listPage(page, salesLedgerDto);
        ExcelUtil<SalesLedger> util = new ExcelUtil<SalesLedger>(SalesLedger.class);
        util.exportExcel(response, salesLedgerIPage == null ? new ArrayList<>() : salesLedgerIPage.getRecords(), "导出开票登记列表");
    }
 
    /**
     * 新增修改销售台账
     */
    @Log(title = "销售台账", businessType = BusinessType.INSERT)
    @PostMapping("/addOrUpdateSalesLedger")
    public AjaxResult add(@RequestBody SalesLedgerDto salesLedgerDto) {
        return toAjax(salesLedgerService.addOrUpdateSalesLedger(salesLedgerDto));
    }
 
    /**
     * 销售订单绑定工艺路线
     */
    @PostMapping("/saleProcessBind")
    @ApiOperation("销售订单绑定工艺路线")
    public AjaxResult saleProcessBind(@RequestBody SalesLedgerProcessRouteDto salesLedgerProcessRouteDto) {
        salesLedgerService.saleProcessBind(salesLedgerProcessRouteDto);
        return AjaxResult.success();
    }
 
    /**
     * 反审核操作
     */
    @Log(title = "销售台账反审核", businessType = BusinessType.UPDATE)
    @PostMapping("/counterReview")
    @ApiOperation("反审核操作:作废或重新生成")
    public AjaxResult counterReview(@RequestBody CounterReviewDto dto) {
        List<Long> newLedgerIds = salesLedgerService.counterReview(dto);
        AjaxResult result = AjaxResult.success("反审核成功");
        if (newLedgerIds != null && !newLedgerIds.isEmpty()) {
            result.put("newLedgerIds", newLedgerIds);
        }
        return result;
    }
 
    /**
     * 标记订单完成
     */
    @Log(title = "销售台账标记完成", businessType = BusinessType.UPDATE)
    @PostMapping("/markOrderCompleted")
    @ApiOperation("标记订单完成(不可撤销)")
    public AjaxResult markOrderCompleted(@RequestBody Map<String, Object> params) {
        @SuppressWarnings("unchecked")
        List<Long> ids = ((List<Object>) params.get("ids")).stream()
            .map(obj -> Long.valueOf(obj.toString()))
            .collect(Collectors.toList());
        if (ids == null || ids.isEmpty()) {
            return AjaxResult.error("请选择要标记完成的订单");
        }
        salesLedgerService.markOrderCompleted(ids);
        return AjaxResult.success("标记完成成功");
    }
 
    /**
     * 递增打印次数
     */
    @PostMapping("/incrementPrintCount")
    @ApiOperation("递增打印次数")
    public AjaxResult incrementPrintCount(@RequestBody Map<String, Object> params) {
        Long id = params.get("id") != null ? Long.valueOf(params.get("id").toString()) : null;
        String printType = (String) params.get("printType");
        if (id == null) {
            return AjaxResult.error("销售台账ID不能为空");
        }
        if (printType == null || (!"label".equals(printType) && !"document".equals(printType))) {
            return AjaxResult.error("打印类型必须为 label 或 document");
        }
        salesLedgerService.incrementPrintCount(id, printType);
        return AjaxResult.success();
    }
 
    /**
     * 删除销售台账
     */
    @Log(title = "销售台账", businessType = BusinessType.DELETE)
    @DeleteMapping("/delLedger")
    public AjaxResult remove(@RequestBody Long[] ids) {
        if (ids == null || ids.length == 0) {
            return AjaxResult.error("请传入要删除的ID");
        }
        return toAjax(salesLedgerService.deleteSalesLedgerByIds(ids));
    }
 
    /**
     * 查询销售台账不分页
     *
     * @param salesLedgerDto
     * @return
     */
    @GetMapping("/listNoPage")
    public AjaxResult listNoPage(SalesLedgerDto salesLedgerDto) {
        List<SalesLedger> list = salesLedgerService.selectSalesLedgerList(salesLedgerDto);
        return AjaxResult.success(list);
    }
 
    /**
     * 销售台账附件删除
     */
    @Log(title = "销售台账附件删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/delLedgerFile")
    public AjaxResult delLedgerFile(@RequestBody Long[] ids) {
        if (ids == null || ids.length == 0) {
            return AjaxResult.error("请传入要删除的ID");
        }
        return toAjax(commonFileService.deleteSalesLedgerByIds(ids));
    }
 
    /**
     * 本月销售合同金额
     */
    @GetMapping("/getContractAmount")
    public AjaxResult getContractAmount() {
        try {
            BigDecimal contractAmount = salesLedgerService.getContractAmount();
            return AjaxResult.success(contractAmount != null ? contractAmount : BigDecimal.ZERO);
        } catch (Exception e) {
            return AjaxResult.error("获取合同金额失败:" + e.getMessage());
        }
    }
 
    /**
     * 客户合同金额TOP5统计
     */
    @GetMapping("/getTopFiveList")
    public AjaxResult getTopFiveList() {
        return AjaxResult.success(salesLedgerService.getTopFiveList());
    }
 
    /**
     * 近半年开票,回款金额
     */
    @GetMapping("/getAmountHalfYear")
    public AjaxResult getAmountHalfYear(@RequestParam(value = "type", defaultValue = "1") Integer type) {
        return AjaxResult.success(salesLedgerService.getAmountHalfYear(type));
    }
 
    /**
     * 查询销售台账列表
     */
    @GetMapping("/listPage")
    public IPage<SalesLedger> listPage(Page<?> page, SalesLedgerDto salesLedgerDto) {
        return salesLedgerService.selectSalesLedgerListPage(page, salesLedgerDto);
    }
 
    @ApiOperation("查询销售台账消耗物料信息")
    @GetMapping("/getSalesLedgerWithProductsLoss")
    public R getSalesLedgerWithProductsLoss(Long salesLedgerId) {
        return R.ok(salesLedgerService.getSalesLedgerWithProductsLoss(salesLedgerId));
    }
 
    @ApiOperation("获取销售订单绑定的工艺路线")
    @GetMapping("/salesProcess/{salesLedgerId}")
    public AjaxResult salesProcess(@PathVariable Long salesLedgerId) {
        SalesLedgerProcessRouteDto dto = salesLedgerService.salesProcess(salesLedgerId);
        return AjaxResult.success(dto);
    }
 
    @GetMapping("/processCard/{salesLedgerId}")
    @ApiOperation("打印生产流程卡")
    public AjaxResult processCard(@PathVariable Long salesLedgerId) {
        SalesProcessCardDto dto = salesLedgerService.processCard(salesLedgerId);
        return AjaxResult.success(dto);
    }
 
    @GetMapping("/salesOrders/{salesLedgerId}")
    @ApiOperation("打印销售订单")
    public AjaxResult salesOrders(@PathVariable Long salesLedgerId) {
        SalesOrdersDto salesOrdersDto = salesLedgerService.salesOrders(salesLedgerId);
        return AjaxResult.success(salesOrdersDto);
    }
 
    @PostMapping("/salesInvoices")
    @ApiOperation("打印销售发货单")
    public AjaxResult salesInvoices(@RequestBody List<Long> salesLedgerIds) {
        SalesInvoicesDto dto = salesLedgerService.salesInvoices(salesLedgerIds);
        return AjaxResult.success(dto);
    }
 
    @GetMapping("/salesLabel/{salesLedgerId}")
    @ApiOperation("打印订单标签")
    public AjaxResult salesLabel(@PathVariable Long salesLedgerId) {
        List<SalesLabelDto> list = salesLedgerService.salesLabel(salesLedgerId);
        return AjaxResult.success(list);
    }
 
    @PostMapping("/salesStock")
    @ApiOperation("销售台账产品入库")
    public AjaxResult salesStock(@RequestBody SalesProductStockDto dto) {
        salesLedgerService.salesStock(dto);
        return AjaxResult.success();
    }
 
    @GetMapping("/shippedCustomers")
    @ApiOperation("已发货客户名单")
    public AjaxResult shippedCustomers() {
        List<Customer> list = salesLedgerService.shippedCustomers();
        return AjaxResult.success(list);
    }
 
    @PostMapping("/scanInbound")
    @ApiOperation("销售订单扫码-合格入库")
    public AjaxResult scanInbound(@RequestBody SalesScanInboundDto dto) {
        salesLedgerService.scanInbound(dto);
        return AjaxResult.success();
    }
 
    @PostMapping("/scanInboundUnqualified")
    @ApiOperation("销售订单扫码-不合格入库")
    public AjaxResult scanInboundUnqualified(@RequestBody SalesScanInboundDto dto) {
        salesLedgerService.scanInboundUnqualified(dto);
        return AjaxResult.success();
    }
 
    @PostMapping("/scanOutbound")
    @ApiOperation("销售订单扫码-合格出库")
    public AjaxResult scanOutbound(@RequestBody SalesScanInboundDto dto) {
        salesLedgerService.scanOutbound(dto);
        return AjaxResult.success();
    }
 
    @PostMapping("/scanShipApply")
    @ApiOperation("销售订单扫码-发起发货审批(填写车牌/快递、审批人、附件;通过后自动扣库存并标记已发货)")
    public AjaxResult scanShipApply(@RequestBody SalesScanShipDto dto) {
        salesLedgerService.scanShipApply(dto);
        return AjaxResult.success("发货审批已发起");
    }
 
    @PostMapping("/scanOutboundUnqualified")
    @ApiOperation("销售订单扫码-不合格出库")
    public AjaxResult scanOutboundUnqualified(@RequestBody SalesScanInboundDto dto) {
        salesLedgerService.scanOutboundUnqualified(dto);
        return AjaxResult.success();
    }
 
    @PostMapping("/salesHistory/shippingImport")
    @ApiOperation("销售发货历史数据导入-已发货")
    public AjaxResult shippingImport(MultipartFile file) {
        salesLedgerService.shippingImport(file);
        return AjaxResult.success();
    }
 
    @PostMapping("/salesHistory/notShippingImport")
    @ApiOperation("销售发货历史数据导入-未发货")
    public AjaxResult notShippingImport(MultipartFile file) {
        salesLedgerService.notShippingImport(file);
        return AjaxResult.success();
    }
 
    @PostMapping("/salesHistory/shippingImportTemplate")
    @ApiOperation("销售发货历史数据导入-已发货导入模板下载")
    public void shippingImportTemplate(HttpServletResponse response) {
        ExcelUtil<SalesShippingImportDto> excelUtil = new ExcelUtil<>(SalesShippingImportDto.class);
        excelUtil.importTemplateExcel(response, "已出库导入模板下载");
    }
 
    @PostMapping("/salesHistory/notShippingImportTemplate")
    @ApiOperation("销售发货历史数据导入-未发货导入模板下载")
    public void notShippingImportTemplate(HttpServletResponse response) {
        ExcelUtil<SalesNotShippingImportDto> excelUtil = new ExcelUtil<>(SalesNotShippingImportDto.class);
        excelUtil.importTemplateExcel(response, "未出库导入模板下载");
    }
 
    private List<Long> parseSalesLedgerIds(HttpServletRequest request) {
        if (request == null) {
            return Collections.emptyList();
        }
 
        List<Long> ids = new ArrayList<>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        if (parameterMap == null || parameterMap.isEmpty()) {
            return ids;
        }
 
        String directValue = request.getParameter("salesLedgerIds");
        if (StringUtils.hasText(directValue)) {
            for (String value : directValue.split(",")) {
                addParsedLong(ids, value);
            }
        }
 
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey();
            if (!StringUtils.hasText(key)) {
                continue;
            }
            if (!"salesLedgerIds".equals(key) && !key.startsWith("salesLedgerIds[")) {
                continue;
            }
            String[] values = entry.getValue();
            if (values == null) {
                continue;
            }
            for (String value : values) {
                addParsedLong(ids, value);
            }
        }
 
        return ids.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
    }
 
    private void addParsedLong(List<Long> target, String value) {
        if (target == null || !StringUtils.hasText(value)) {
            return;
        }
        try {
            target.add(Long.valueOf(value.trim()));
        } catch (Exception ignored) {
            // ignore invalid id values
        }
    }
 
}