gaoluyang
2 天以前 8c65f898ed6e5b0c7a94c792c4562f6ec831dccd
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
package cn.iocoder.yudao.module.mes.controller.admin.wm.productsales;
 
import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.crm.api.customer.CrmCustomerApi;
import cn.iocoder.yudao.module.crm.api.customer.dto.CrmCustomerRespDTO;
import cn.iocoder.yudao.module.mes.controller.admin.wm.productsales.vo.MesWmProductSalesPageReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.wm.productsales.vo.MesWmProductSalesRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.wm.productsales.vo.MesWmProductSalesSaveReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.wm.productsales.vo.MesWmProductSalesShippingReqVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.wm.productsales.MesWmProductSalesDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.wm.productsales.MesWmProductSalesLineDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.wm.salesnotice.MesWmSalesNoticeDO;
import cn.iocoder.yudao.module.mes.service.wm.document.MesWmDocumentRenderer;
import cn.iocoder.yudao.module.mes.service.wm.productsales.MesWmProductSalesLineService;
import cn.iocoder.yudao.module.mes.service.wm.productsales.MesWmProductSalesService;
import cn.iocoder.yudao.module.mes.service.wm.salesnotice.MesWmSalesNoticeService;
import cn.iocoder.yudao.module.mdm.api.item.MdmItemApi;
import cn.iocoder.yudao.module.mdm.api.item.dto.MdmItemRespDTO;
import cn.iocoder.yudao.module.mdm.api.unit.MdmUnitMeasureApi;
import cn.iocoder.yudao.module.mdm.api.unit.dto.MdmUnitMeasureRespDTO;
import cn.iocoder.yudao.module.system.service.companyconfig.SystemCompanyConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
 
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.format.DateTimeFormatter;
import java.util.*;
 
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.module.mes.enums.ErrorCodeConstants.WM_PRODUCT_SALES_NOT_EXISTS;
 
@Tag(name = "管理后台 - MES 销售出库单")
@RestController
@RequestMapping("/mes/wm/product-sales")
@Validated
public class MesWmProductSalesController {
 
    @Resource
    private MesWmProductSalesService productSalesService;
    @Resource
    private MesWmProductSalesLineService productSalesLineService;
    @Resource
    private CrmCustomerApi crmCustomerApi;
    @Resource
    private MesWmSalesNoticeService salesNoticeService;
    @Resource
    private MdmItemApi mdmItemApi;
    @Resource
    private MdmUnitMeasureApi mdmUnitMeasureApi;
    @Resource
    private SystemCompanyConfigService companyConfigService;
 
    @PostMapping("/create")
    @Operation(summary = "创建销售出库单")
    @PreAuthorize("@ss.hasPermission('mes:wm-product-sales:create')")
    public CommonResult<Long> createProductSales(@Valid @RequestBody MesWmProductSalesSaveReqVO createReqVO) {
        return success(productSalesService.createProductSales(createReqVO));
    }
 
    @PutMapping("/update")
    @Operation(summary = "修改销售出库单")
    @PreAuthorize("@ss.hasPermission('mes:wm-product-sales:update')")
    public CommonResult<Boolean> updateProductSales(@Valid @RequestBody MesWmProductSalesSaveReqVO updateReqVO) {
        productSalesService.updateProductSales(updateReqVO);
        return success(true);
    }
 
    @DeleteMapping("/delete")
    @Operation(summary = "删除销售出库单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:wm-product-sales:delete')")
    public CommonResult<Boolean> deleteProductSales(@RequestParam("id") Long id) {
        productSalesService.deleteProductSales(id);
        return success(true);
    }
 
    @GetMapping("/get")
    @Operation(summary = "获得销售出库单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<MesWmProductSalesRespVO> getProductSales(@RequestParam("id") Long id) {
        MesWmProductSalesDO sales = productSalesService.getProductSales(id);
        if (sales == null) {
            return success(null);
        }
        return success(buildRespVOList(Collections.singletonList(sales)).get(0));
    }
 
    @GetMapping("/page")
    @Operation(summary = "获得销售出库单分页")
    public CommonResult<PageResult<MesWmProductSalesRespVO>> getProductSalesPage(
            @Valid MesWmProductSalesPageReqVO pageReqVO) {
        PageResult<MesWmProductSalesDO> pageResult = productSalesService.getProductSalesPage(pageReqVO);
        return success(new PageResult<>(buildRespVOList(pageResult.getList()), pageResult.getTotal()));
    }
 
    @GetMapping("/export-excel")
    @Operation(summary = "导出销售出库单 Excel")
    @PreAuthorize("@ss.hasPermission('mes:wm-product-sales:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportProductSalesExcel(@Valid MesWmProductSalesPageReqVO pageReqVO,
                                        HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        PageResult<MesWmProductSalesDO> pageResult = productSalesService.getProductSalesPage(pageReqVO);
        ExcelUtils.write(response, "销售出库单.xls", "数据", MesWmProductSalesRespVO.class,
                buildRespVOList(pageResult.getList()));
    }
 
    @GetMapping("/export-word")
    @Operation(summary = "导出成品出库单 Word(带电子章,可手填签字后归档)")
    @Parameter(name = "id", description = "销售出库单编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:wm-product-sales:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportProductSalesWord(@RequestParam("id") Long id,
                                       HttpServletResponse response) throws IOException {
        MesWmProductSalesDO sales = productSalesService.getProductSales(id);
        if (sales == null) {
            throw exception(WM_PRODUCT_SALES_NOT_EXISTS);
        }
        List<MesWmProductSalesLineDO> lines = productSalesLineService.getProductSalesLineListBySalesId(id);
        Map<Long, MdmItemRespDTO> itemMap = mdmItemApi.getItemMap(
                convertSet(lines, MesWmProductSalesLineDO::getItemId));
        Map<Long, MdmUnitMeasureRespDTO> unitMap = mdmUnitMeasureApi
                .getUnitMeasureList(convertSet(itemMap.values(), MdmItemRespDTO::getUnitMeasureId))
                .getCheckedData().stream()
                .collect(java.util.stream.Collectors.toMap(MdmUnitMeasureRespDTO::getId, e -> e));
 
        Map<String, String> fields = new LinkedHashMap<>();
        fields.put("clientName", resolveClientName(sales.getClientId()));
        fields.put("code", sales.getCode());
        fields.put("salesDate", sales.getSalesDate() == null ? null
                : sales.getSalesDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        fields.put("saleOrderCode", sales.getSalesOrderCode());
        fields.put("noticeCode", resolveNoticeCode(sales.getNoticeId()));
        fields.put("contactName", sales.getContactName());
        fields.put("contactTelephone", sales.getContactTelephone());
        fields.put("contactAddress", sales.getContactAddress());
        fields.put("carrier", sales.getCarrier());
        fields.put("shippingNumber", sales.getShippingNumber());
        fields.put("remark", sales.getRemark());
 
        List<Map<String, String>> items = new ArrayList<>();
        for (MesWmProductSalesLineDO line : lines) {
            MdmItemRespDTO item = itemMap.get(line.getItemId());
            Map<String, String> row = new LinkedHashMap<>();
            row.put("itemName", item != null ? item.getName() : null);
            row.put("itemSpecification", item != null ? item.getSpecification() : null);
            MdmUnitMeasureRespDTO unit = item != null ? unitMap.get(item.getUnitMeasureId()) : null;
            row.put("unitName", unit != null ? unit.getName() : null);
            row.put("quantity", line.getQuantity() == null ? null : line.getQuantity().toPlainString());
            row.put("price", line.getPrice() == null ? null : line.getPrice().toPlainString());
            row.put("amount", line.getTotalPrice() == null ? null : line.getTotalPrice().toPlainString());
            row.put("batchCode", line.getBatchCode());
            items.add(row);
        }
 
        var companyConfig = companyConfigService.getCompanyConfig();
        byte[] content = MesWmDocumentRenderer.renderProductOutbound(fields, items,
                companyConfig != null ? companyConfig.getCompanyName() : null);
        writeWord(response, "成品出库单-" + sales.getCode() + ".docx", content);
    }
 
    private String resolveClientName(Long clientId) {
        if (clientId == null) {
            return null;
        }
        CrmCustomerRespDTO customer = crmCustomerApi.getCustomer(clientId);
        return customer != null ? customer.getName() : null;
    }
 
    private String resolveNoticeCode(Long noticeId) {
        if (noticeId == null) {
            return null;
        }
        MesWmSalesNoticeDO notice = salesNoticeService.getSalesNotice(noticeId);
        return notice != null ? notice.getCode() : null;
    }
 
    private static void writeWord(HttpServletResponse response, String filename, byte[] content) throws IOException {
        String encoded = URLEncoder.encode(filename, StandardCharsets.UTF_8).replace("+", "%20");
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + encoded);
        response.getOutputStream().write(content);
    }
 
    @PutMapping("/submit")
    @Operation(summary = "提交销售出库单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:wm-product-sales:submit')")
    public CommonResult<Boolean> submitProductSales(@RequestParam("id") Long id) {
        productSalesService.submitProductSales(id);
        return success(true);
    }
 
    @GetMapping("/check-quantity")
    @Operation(summary = "校验销售出库单数量")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> checkProductSalesQuantity(@RequestParam("id") Long id) {
        return success(productSalesService.checkProductSalesQuantity(id));
    }
 
    @PutMapping("/stock")
    @Operation(summary = "执行拣货")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:wm-product-sales:stock')")
    public CommonResult<Boolean> stockProductSales(@RequestParam("id") Long id) {
        productSalesService.stockProductSales(id);
        return success(true);
    }
 
    @PutMapping("/shipping")
    @Operation(summary = "填写运单")
    @PreAuthorize("@ss.hasPermission('mes:wm-product-sales:shipping')")
    public CommonResult<Boolean> shippingProductSales(@Valid @RequestBody MesWmProductSalesShippingReqVO reqVO) {
        productSalesService.shippingProductSales(reqVO);
        return success(true);
    }
 
    @PutMapping("/finish")
    @Operation(summary = "执行出库")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:wm-product-sales:finish')")
    public CommonResult<Boolean> finishProductSales(@RequestParam("id") Long id) {
        productSalesService.finishProductSales(id);
        return success(true);
    }
 
    @PutMapping("/cancel")
    @Operation(summary = "取消销售出库单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:wm-product-sales:cancel')")
    public CommonResult<Boolean> cancelProductSales(@RequestParam("id") Long id) {
        productSalesService.cancelProductSales(id);
        return success(true);
    }
 
    // ==================== 拼接 VO ====================
 
    private List<MesWmProductSalesRespVO> buildRespVOList(List<MesWmProductSalesDO> list) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        // 1. 获得关联数据
        Map<Long, CrmCustomerRespDTO> customerMap = crmCustomerApi.getCustomerMap(
                convertSet(list, MesWmProductSalesDO::getClientId));
        Map<Long, MesWmSalesNoticeDO> noticeMap = salesNoticeService.getSalesNoticeMap(
                convertSet(list, MesWmProductSalesDO::getNoticeId));
        // 2. 构建结果
        return BeanUtils.toBean(list, MesWmProductSalesRespVO.class, vo -> {
            MapUtils.findAndThen(customerMap, vo.getClientId(), customer ->
                    vo.setClientName(customer.getName()));
            MapUtils.findAndThen(noticeMap, vo.getNoticeId(),
                    notice -> vo.setNoticeCode(notice.getCode()));
        });
    }
 
}