From a6cfd8a029d98e21aeb623e795b0ab45bd86f073 Mon Sep 17 00:00:00 2001 From: ah-max150 Date: Fri, 23 Oct 2026 17:54:49 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E8=90=BD=E5=9C=B0=E5=87=BA=E8=B4=A7?= =?UTF-8?q?=E4=B8=8E=20CI/PL=EF=BC=8C=E6=89=93=E9=80=9A=E6=8A=A5=E4=BB=B7?= =?UTF-8?q?=E6=8E=A5=E5=8F=97=E5=88=B0=E5=8D=95=E8=AF=81=E9=97=AD=E7=8E=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AgentCompanyLlmSettingsServiceImpl.java | 1 - .../document/service/CrmDocumentService.java | 80 +++ .../controller/CrmShipmentController.java | 84 +++ .../mapper/CrmShipmentItemMapper.java | 10 + .../shipment/mapper/CrmShipmentMapper.java | 10 + .../model/dto/ChangeCrmShipmentStatusDTO.java | 12 + .../model/dto/CreateCrmShipmentDTO.java | 51 ++ .../model/dto/CrmShipmentFilterDTO.java | 13 + .../model/dto/CrmShipmentItemDTO.java | 56 ++ .../model/dto/UpdateCrmShipmentDTO.java | 49 ++ .../shipment/model/po/CrmShipmentItemPO.java | 60 ++ .../crm/shipment/model/po/CrmShipmentPO.java | 70 ++ .../shipment/model/vo/CrmShipmentItemVO.java | 29 + .../crm/shipment/model/vo/CrmShipmentVO.java | 43 ++ .../shipment/service/CrmShipmentService.java | 32 + .../service/impl/CrmShipmentServiceImpl.java | 668 ++++++++++++++++++ .../crm/support/CrmDocPdfRenderer.java | 217 ++++++ .../migration/V5__crm_shipment_menu_seed.sql | 36 + .../src/main/resources/sql/init/sys_seed.sql | 39 + .../web-antd/src/api/crm/shipment/apis.ts | 60 ++ .../web-antd/src/api/crm/shipment/index.ts | 2 + .../src/api/crm/shipment/types/index.ts | 2 + .../src/api/crm/shipment/types/types.dto.ts | 51 ++ .../src/api/crm/shipment/types/types.vo.ts | 57 ++ .../web-antd/src/views/crm/quote/index.vue | 20 +- .../crm/shipment/components/ShipmentModal.vue | 429 +++++++++++ .../web-antd/src/views/crm/shipment/index.vue | 284 ++++++++ docs/外贸出口CRM雏形规划.md | 8 +- 28 files changed, 2468 insertions(+), 5 deletions(-) create mode 100644 apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/document/service/CrmDocumentService.java create mode 100644 apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/controller/CrmShipmentController.java create mode 100644 apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/mapper/CrmShipmentItemMapper.java create mode 100644 apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/mapper/CrmShipmentMapper.java create mode 100644 apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/ChangeCrmShipmentStatusDTO.java create mode 100644 apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/CreateCrmShipmentDTO.java create mode 100644 apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/CrmShipmentFilterDTO.java create mode 100644 apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/CrmShipmentItemDTO.java create mode 100644 apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/UpdateCrmShipmentDTO.java create mode 100644 apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/po/CrmShipmentItemPO.java create mode 100644 apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/po/CrmShipmentPO.java create mode 100644 apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/vo/CrmShipmentItemVO.java create mode 100644 apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/vo/CrmShipmentVO.java create mode 100644 apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/service/CrmShipmentService.java create mode 100644 apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/service/impl/CrmShipmentServiceImpl.java create mode 100644 apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/support/CrmDocPdfRenderer.java create mode 100644 apps/server/src/main/resources/db/migration/V5__crm_shipment_menu_seed.sql create mode 100644 apps/web/apps/web-antd/src/api/crm/shipment/apis.ts create mode 100644 apps/web/apps/web-antd/src/api/crm/shipment/index.ts create mode 100644 apps/web/apps/web-antd/src/api/crm/shipment/types/index.ts create mode 100644 apps/web/apps/web-antd/src/api/crm/shipment/types/types.dto.ts create mode 100644 apps/web/apps/web-antd/src/api/crm/shipment/types/types.vo.ts create mode 100644 apps/web/apps/web-antd/src/views/crm/shipment/components/ShipmentModal.vue create mode 100644 apps/web/apps/web-antd/src/views/crm/shipment/index.vue diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/service/impl/AgentCompanyLlmSettingsServiceImpl.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/service/impl/AgentCompanyLlmSettingsServiceImpl.java index 86f7b27..83ba832 100644 --- a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/service/impl/AgentCompanyLlmSettingsServiceImpl.java +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/service/impl/AgentCompanyLlmSettingsServiceImpl.java @@ -33,7 +33,6 @@ import top.xyquan.ecomdmbbackend.utils.CurrentUserContext; import java.time.format.DateTimeFormatter; import java.util.ArrayList; -import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/document/service/CrmDocumentService.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/document/service/CrmDocumentService.java new file mode 100644 index 0000000..841cbe3 --- /dev/null +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/document/service/CrmDocumentService.java @@ -0,0 +1,80 @@ +package top.xyquan.ecomdmbbackend.modules.crm.document.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import top.xyquan.ecomdmbbackend.modules.crm.document.mapper.CrmDocumentMapper; +import top.xyquan.ecomdmbbackend.modules.crm.document.model.po.CrmDocumentPO; +import top.xyquan.ecomdmbbackend.modules.crm.support.CrmGeneratedFileService; +import top.xyquan.ecomdmbbackend.modules.sys.file.model.po.SysFilePO; +import top.xyquan.ecomdmbbackend.utils.CurrentUserContext; + +/** + * 单证版本落库:标记旧版非最新,写入新 crm_document。 + */ +@Service +public class CrmDocumentService { + + private final CrmDocumentMapper documentMapper; + private final CrmGeneratedFileService generatedFileService; + private final CurrentUserContext currentUserContext; + + public CrmDocumentService(CrmDocumentMapper documentMapper, + CrmGeneratedFileService generatedFileService, + CurrentUserContext currentUserContext) { + this.documentMapper = documentMapper; + this.generatedFileService = generatedFileService; + this.currentUserContext = currentUserContext; + } + + @Transactional + public CrmDocumentPO savePdf(Long companyId, String docType, String docNo, + String refType, Long refId, + String filename, byte[] pdf) { + SysFilePO file = generatedFileService.saveBytes(companyId, filename, "application/pdf", pdf); + + documentMapper.update(null, new LambdaUpdateWrapper() + .eq(CrmDocumentPO::getCompanyId, companyId) + .eq(CrmDocumentPO::getRefType, refType) + .eq(CrmDocumentPO::getRefId, refId) + .eq(CrmDocumentPO::getDocType, docType) + .eq(CrmDocumentPO::getIsLatest, 1) + .set(CrmDocumentPO::getIsLatest, 0)); + + int nextVersion = 1; + CrmDocumentPO last = documentMapper.selectOne(new LambdaQueryWrapper() + .eq(CrmDocumentPO::getCompanyId, companyId) + .eq(CrmDocumentPO::getRefType, refType) + .eq(CrmDocumentPO::getRefId, refId) + .eq(CrmDocumentPO::getDocType, docType) + .orderByDesc(CrmDocumentPO::getVersionNo) + .last("LIMIT 1")); + if (last != null && last.getVersionNo() != null) { + nextVersion = last.getVersionNo() + 1; + } + + CrmDocumentPO doc = new CrmDocumentPO(); + doc.setCompanyId(companyId); + doc.setDocType(docType); + doc.setDocNo(docNo); + doc.setRefType(refType); + doc.setRefId(refId); + doc.setFileId(file.getId()); + doc.setIsLatest(1); + doc.setVersionNo(nextVersion); + doc.setCreateBy(currentUserContext.getCurrentUserId()); + documentMapper.insert(doc); + return doc; + } + + public CrmDocumentPO findLatest(Long companyId, String refType, Long refId, String docType) { + return documentMapper.selectOne(new LambdaQueryWrapper() + .eq(CrmDocumentPO::getCompanyId, companyId) + .eq(CrmDocumentPO::getRefType, refType) + .eq(CrmDocumentPO::getRefId, refId) + .eq(CrmDocumentPO::getDocType, docType) + .eq(CrmDocumentPO::getIsLatest, 1) + .last("LIMIT 1")); + } +} diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/controller/CrmShipmentController.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/controller/CrmShipmentController.java new file mode 100644 index 0000000..59ad14e --- /dev/null +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/controller/CrmShipmentController.java @@ -0,0 +1,84 @@ +package top.xyquan.ecomdmbbackend.modules.crm.shipment.controller; + +import jakarta.validation.Valid; +import org.springframework.web.bind.annotation.*; +import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission; +import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO; +import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO; +import top.xyquan.ecomdmbbackend.common.response.ApiResponse; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.ChangeCrmShipmentStatusDTO; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.CreateCrmShipmentDTO; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.CrmShipmentFilterDTO; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.UpdateCrmShipmentDTO; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.vo.CrmShipmentVO; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.service.CrmShipmentService; + +/** 出货管理。 */ +@RestController +@RequestMapping("/api/crm/shipment") +public class CrmShipmentController { + + private final CrmShipmentService crmShipmentService; + + public CrmShipmentController(CrmShipmentService crmShipmentService) { + this.crmShipmentService = crmShipmentService; + } + + @PostMapping("/create") + @RequirePermission(value = "crm:shipment:create", description = "创建出货") + public ApiResponse create(@Valid @RequestBody CreateCrmShipmentDTO dto) { + return ApiResponse.success("创建成功", crmShipmentService.create(dto)); + } + + @PostMapping("/from-quote/{quoteId}") + @RequirePermission(value = "crm:shipment:create", description = "从报价生成出货") + public ApiResponse createFromQuote(@PathVariable Long quoteId) { + return ApiResponse.success("已生成出货", crmShipmentService.createFromQuote(quoteId)); + } + + @PutMapping("/update/{id}") + @RequirePermission(value = "crm:shipment:update", description = "更新出货") + public ApiResponse update( + @PathVariable Long id, @Valid @RequestBody UpdateCrmShipmentDTO dto) { + return ApiResponse.success("更新成功", crmShipmentService.update(id, dto)); + } + + @DeleteMapping("/delete/{id}") + @RequirePermission(value = "crm:shipment:delete", description = "删除出货") + public ApiResponse delete(@PathVariable Long id) { + crmShipmentService.delete(id); + return ApiResponse.success("删除成功"); + } + + @GetMapping("/{id}") + @RequirePermission(value = "crm:shipment:read", description = "出货详情") + public ApiResponse get(@PathVariable Long id) { + return ApiResponse.success("获取成功", crmShipmentService.get(id)); + } + + @PostMapping("/list") + @RequirePermission(value = "crm:shipment:read", description = "出货列表") + public ApiResponse> list( + @Valid @RequestBody PageQueryDTO query) { + return ApiResponse.success("获取成功", crmShipmentService.page(query)); + } + + @PostMapping("/{id}/status") + @RequirePermission(value = "crm:shipment:status", description = "变更出货状态") + public ApiResponse changeStatus( + @PathVariable Long id, @Valid @RequestBody ChangeCrmShipmentStatusDTO dto) { + return ApiResponse.success("状态已更新", crmShipmentService.changeStatus(id, dto)); + } + + @PostMapping("/{id}/export-ci") + @RequirePermission(value = "crm:shipment:export", description = "导出商业发票 CI") + public ApiResponse exportCi(@PathVariable Long id) { + return ApiResponse.success("CI 已生成", crmShipmentService.exportCi(id)); + } + + @PostMapping("/{id}/export-pl") + @RequirePermission(value = "crm:shipment:export", description = "导出装箱单 PL") + public ApiResponse exportPl(@PathVariable Long id) { + return ApiResponse.success("PL 已生成", crmShipmentService.exportPl(id)); + } +} diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/mapper/CrmShipmentItemMapper.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/mapper/CrmShipmentItemMapper.java new file mode 100644 index 0000000..592432f --- /dev/null +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/mapper/CrmShipmentItemMapper.java @@ -0,0 +1,10 @@ +package top.xyquan.ecomdmbbackend.modules.crm.shipment.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.po.CrmShipmentItemPO; + +/** 出货行 Mapper。 */ +@Mapper +public interface CrmShipmentItemMapper extends BaseMapper { +} diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/mapper/CrmShipmentMapper.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/mapper/CrmShipmentMapper.java new file mode 100644 index 0000000..3d6941a --- /dev/null +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/mapper/CrmShipmentMapper.java @@ -0,0 +1,10 @@ +package top.xyquan.ecomdmbbackend.modules.crm.shipment.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.po.CrmShipmentPO; + +/** 出货单 Mapper。 */ +@Mapper +public interface CrmShipmentMapper extends BaseMapper { +} diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/ChangeCrmShipmentStatusDTO.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/ChangeCrmShipmentStatusDTO.java new file mode 100644 index 0000000..06ed1a8 --- /dev/null +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/ChangeCrmShipmentStatusDTO.java @@ -0,0 +1,12 @@ +package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto; + +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +/** 变更出货状态。 */ +@Data +public class ChangeCrmShipmentStatusDTO { + + @NotBlank(message = "目标状态不能为空") + private String status; +} diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/CreateCrmShipmentDTO.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/CreateCrmShipmentDTO.java new file mode 100644 index 0000000..bf88dee --- /dev/null +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/CreateCrmShipmentDTO.java @@ -0,0 +1,51 @@ +package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import lombok.Data; + +import java.time.LocalDate; +import java.util.List; + +/** 手动创建出货(可不关联报价)。 */ +@Data +public class CreateCrmShipmentDTO { + + private Long quoteId; + + @NotNull(message = "客户不能为空") + private Long customerId; + + private LocalDate planShipDate; + + private LocalDate actualShipDate; + + @Size(max = 100) + private String destinationPort; + + @Size(max = 32) + private String transportMode; + + @Size(max = 32) + private String containerType; + + @Size(max = 3) + private String currency; + + @Size(max = 16) + private String incoterm; + + @Size(max = 200) + private String paymentTerms; + + private Long ownerUserId; + + @Size(max = 1000) + private String remark; + + @NotEmpty(message = "至少一行明细") + @Valid + private List items; +} diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/CrmShipmentFilterDTO.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/CrmShipmentFilterDTO.java new file mode 100644 index 0000000..201f933 --- /dev/null +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/CrmShipmentFilterDTO.java @@ -0,0 +1,13 @@ +package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto; + +import lombok.Data; + +/** 出货列表筛选。 */ +@Data +public class CrmShipmentFilterDTO { + private String keyword; + private String status; + private Long customerId; + private Long quoteId; + private Boolean onlyMine; +} diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/CrmShipmentItemDTO.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/CrmShipmentItemDTO.java new file mode 100644 index 0000000..efc7300 --- /dev/null +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/CrmShipmentItemDTO.java @@ -0,0 +1,56 @@ +package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import lombok.Data; + +import java.math.BigDecimal; + +/** 出货行入参。 */ +@Data +public class CrmShipmentItemDTO { + + private Long productId; + + @Size(max = 64) + private String productCode; + + @NotBlank(message = "英文品名不能为空") + @Size(max = 200) + private String nameEn; + + @Size(max = 200) + private String nameZh; + + @Size(max = 500) + private String spec; + + @Size(max = 32) + private String hsCode; + + @Size(max = 32) + private String unit; + + @NotNull(message = "数量不能为空") + private BigDecimal qty; + + @NotNull(message = "单价不能为空") + private BigDecimal unitPrice; + + private Integer packages; + + private BigDecimal qtyPerPackage; + + private BigDecimal grossWeightKg; + + private BigDecimal netWeightKg; + + private BigDecimal volumeCbm; + + @Size(max = 64) + private String originCountry; + + @Size(max = 500) + private String remark; +} diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/UpdateCrmShipmentDTO.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/UpdateCrmShipmentDTO.java new file mode 100644 index 0000000..0c6f4b6 --- /dev/null +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/dto/UpdateCrmShipmentDTO.java @@ -0,0 +1,49 @@ +package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import lombok.Data; + +import java.time.LocalDate; +import java.util.List; + +/** 更新出货(草稿/待出货可改)。 */ +@Data +public class UpdateCrmShipmentDTO { + + @NotNull(message = "客户不能为空") + private Long customerId; + + private LocalDate planShipDate; + + private LocalDate actualShipDate; + + @Size(max = 100) + private String destinationPort; + + @Size(max = 32) + private String transportMode; + + @Size(max = 32) + private String containerType; + + @Size(max = 3) + private String currency; + + @Size(max = 16) + private String incoterm; + + @Size(max = 200) + private String paymentTerms; + + private Long ownerUserId; + + @Size(max = 1000) + private String remark; + + @NotEmpty(message = "至少一行明细") + @Valid + private List items; +} diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/po/CrmShipmentItemPO.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/po/CrmShipmentItemPO.java new file mode 100644 index 0000000..b8be826 --- /dev/null +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/po/CrmShipmentItemPO.java @@ -0,0 +1,60 @@ +package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.po; + +import com.baomidou.mybatisplus.annotation.*; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** 出货行(含箱规/重量/体积快照)。 */ +@Data +@TableName("crm_shipment_item") +public class CrmShipmentItemPO { + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + @TableField("company_id") + private Long companyId; + @TableField("shipment_id") + private Long shipmentId; + @TableField("line_no") + private Integer lineNo; + @TableField("product_id") + private Long productId; + @TableField("product_code") + private String productCode; + @TableField("name_en") + private String nameEn; + @TableField("name_zh") + private String nameZh; + @TableField("spec") + private String spec; + @TableField("hs_code") + private String hsCode; + @TableField("unit") + private String unit; + @TableField("qty") + private BigDecimal qty; + @TableField("unit_price") + private BigDecimal unitPrice; + @TableField("amount") + private BigDecimal amount; + @TableField("packages") + private Integer packages; + @TableField("qty_per_package") + private BigDecimal qtyPerPackage; + @TableField("gross_weight_kg") + private BigDecimal grossWeightKg; + @TableField("net_weight_kg") + private BigDecimal netWeightKg; + @TableField("volume_cbm") + private BigDecimal volumeCbm; + @TableField("origin_country") + private String originCountry; + @TableField("remark") + private String remark; + @TableField(value = "create_time", fill = FieldFill.INSERT) + private LocalDateTime createTime; + @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) + private LocalDateTime updateTime; +} diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/po/CrmShipmentPO.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/po/CrmShipmentPO.java new file mode 100644 index 0000000..d4060b2 --- /dev/null +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/po/CrmShipmentPO.java @@ -0,0 +1,70 @@ +package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.po; + +import com.baomidou.mybatisplus.annotation.*; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; + +/** 出货单头。 */ +@Data +@TableName("crm_shipment") +public class CrmShipmentPO { + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + @TableField("company_id") + private Long companyId; + @TableField("shipment_no") + private String shipmentNo; + @TableField("quote_id") + private Long quoteId; + @TableField("customer_id") + private Long customerId; + @TableField("plan_ship_date") + private LocalDate planShipDate; + @TableField("actual_ship_date") + private LocalDate actualShipDate; + @TableField("destination_port") + private String destinationPort; + @TableField("transport_mode") + private String transportMode; + @TableField("container_type") + private String containerType; + @TableField("currency") + private String currency; + @TableField("incoterm") + private String incoterm; + @TableField("payment_terms") + private String paymentTerms; + @TableField("status") + private String status; + @TableField("total_amount") + private BigDecimal totalAmount; + @TableField("total_packages") + private Integer totalPackages; + @TableField("total_gross_kg") + private BigDecimal totalGrossKg; + @TableField("total_net_kg") + private BigDecimal totalNetKg; + @TableField("total_cbm") + private BigDecimal totalCbm; + @TableField("owner_user_id") + private Long ownerUserId; + @TableField("remark") + private String remark; + @TableField(value = "create_time", fill = FieldFill.INSERT) + private LocalDateTime createTime; + @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) + private LocalDateTime updateTime; + @TableField("create_by") + private Long createBy; + @TableField("update_by") + private Long updateBy; + @TableLogic + @TableField("delete_time") + private LocalDateTime deleteTime; + @TableField("delete_by") + private Long deleteBy; +} diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/vo/CrmShipmentItemVO.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/vo/CrmShipmentItemVO.java new file mode 100644 index 0000000..39542b5 --- /dev/null +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/vo/CrmShipmentItemVO.java @@ -0,0 +1,29 @@ +package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +/** 出货行视图。 */ +@Data +public class CrmShipmentItemVO { + private Long id; + private Integer lineNo; + private Long productId; + private String productCode; + private String nameEn; + private String nameZh; + private String spec; + private String hsCode; + private String unit; + private BigDecimal qty; + private BigDecimal unitPrice; + private BigDecimal amount; + private Integer packages; + private BigDecimal qtyPerPackage; + private BigDecimal grossWeightKg; + private BigDecimal netWeightKg; + private BigDecimal volumeCbm; + private String originCountry; + private String remark; +} diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/vo/CrmShipmentVO.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/vo/CrmShipmentVO.java new file mode 100644 index 0000000..6bea2ae --- /dev/null +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/model/vo/CrmShipmentVO.java @@ -0,0 +1,43 @@ +package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + +/** 出货视图。 */ +@Data +public class CrmShipmentVO { + private Long id; + private Long companyId; + private String shipmentNo; + private Long quoteId; + private String quoteNo; + private Long customerId; + private String customerName; + private LocalDate planShipDate; + private LocalDate actualShipDate; + private String destinationPort; + private String transportMode; + private String containerType; + private String currency; + private String incoterm; + private String paymentTerms; + private String status; + private BigDecimal totalAmount; + private Integer totalPackages; + private BigDecimal totalGrossKg; + private BigDecimal totalNetKg; + private BigDecimal totalCbm; + private Long ownerUserId; + private String remark; + private LocalDateTime createTime; + private LocalDateTime updateTime; + private List items; + private Long latestCiFileId; + private String latestCiAccessUrl; + private Long latestPlFileId; + private String latestPlAccessUrl; +} diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/service/CrmShipmentService.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/service/CrmShipmentService.java new file mode 100644 index 0000000..b6db78b --- /dev/null +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/service/CrmShipmentService.java @@ -0,0 +1,32 @@ +package top.xyquan.ecomdmbbackend.modules.crm.shipment.service; + +import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO; +import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.ChangeCrmShipmentStatusDTO; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.CreateCrmShipmentDTO; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.CrmShipmentFilterDTO; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.UpdateCrmShipmentDTO; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.vo.CrmShipmentVO; + +/** 出货用例:CRUD、从报价生成、导出 CI/PL。 */ +public interface CrmShipmentService { + + CrmShipmentVO create(CreateCrmShipmentDTO dto); + + /** 从已接受报价生成出货草稿(带入客户与行项目)。 */ + CrmShipmentVO createFromQuote(Long quoteId); + + CrmShipmentVO update(Long id, UpdateCrmShipmentDTO dto); + + void delete(Long id); + + CrmShipmentVO get(Long id); + + PageResultVO page(PageQueryDTO query); + + CrmShipmentVO changeStatus(Long id, ChangeCrmShipmentStatusDTO dto); + + CrmShipmentVO exportCi(Long id); + + CrmShipmentVO exportPl(Long id); +} diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/service/impl/CrmShipmentServiceImpl.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/service/impl/CrmShipmentServiceImpl.java new file mode 100644 index 0000000..049d8bf --- /dev/null +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/shipment/service/impl/CrmShipmentServiceImpl.java @@ -0,0 +1,668 @@ +package top.xyquan.ecomdmbbackend.modules.crm.shipment.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; +import top.xyquan.ecomdmbbackend.common.exception.BusinessException; +import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO; +import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO; +import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils; +import top.xyquan.ecomdmbbackend.modules.crm.customer.mapper.CrmCustomerMapper; +import top.xyquan.ecomdmbbackend.modules.crm.customer.model.po.CrmCustomerPO; +import top.xyquan.ecomdmbbackend.modules.crm.document.model.po.CrmDocumentPO; +import top.xyquan.ecomdmbbackend.modules.crm.document.service.CrmDocumentService; +import top.xyquan.ecomdmbbackend.modules.crm.product.mapper.CrmProductMapper; +import top.xyquan.ecomdmbbackend.modules.crm.product.model.po.CrmProductPO; +import top.xyquan.ecomdmbbackend.modules.crm.profile.model.vo.CrmCompanyProfileVO; +import top.xyquan.ecomdmbbackend.modules.crm.profile.service.CrmCompanyProfileService; +import top.xyquan.ecomdmbbackend.modules.crm.quote.mapper.CrmQuoteItemMapper; +import top.xyquan.ecomdmbbackend.modules.crm.quote.mapper.CrmQuoteMapper; +import top.xyquan.ecomdmbbackend.modules.crm.quote.model.po.CrmQuoteItemPO; +import top.xyquan.ecomdmbbackend.modules.crm.quote.model.po.CrmQuotePO; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.mapper.CrmShipmentItemMapper; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.mapper.CrmShipmentMapper; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.*; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.po.CrmShipmentItemPO; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.po.CrmShipmentPO; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.vo.CrmShipmentItemVO; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.vo.CrmShipmentVO; +import top.xyquan.ecomdmbbackend.modules.crm.shipment.service.CrmShipmentService; +import top.xyquan.ecomdmbbackend.modules.crm.support.CrmDocPdfRenderer; +import top.xyquan.ecomdmbbackend.modules.crm.support.CrmSeqService; +import top.xyquan.ecomdmbbackend.modules.sys.file.service.SysFileService; +import top.xyquan.ecomdmbbackend.utils.CurrentUserContext; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.util.*; +import java.util.stream.Collectors; + +/** + * 出货:草稿可改删;从已接受报价生成;导出 CI/PL。 + */ +@Service +public class CrmShipmentServiceImpl extends ServiceImpl + implements CrmShipmentService { + + private static final Set STATUSES = Set.of("draft", "ready", "shipped", "closed"); + private static final Set EDITABLE = Set.of("draft", "ready"); + + private final CrmShipmentItemMapper shipmentItemMapper; + private final CrmCustomerMapper customerMapper; + private final CrmProductMapper productMapper; + private final CrmQuoteMapper quoteMapper; + private final CrmQuoteItemMapper quoteItemMapper; + private final CrmSeqService crmSeqService; + private final CrmCompanyProfileService profileService; + private final CrmDocPdfRenderer docPdfRenderer; + private final CrmDocumentService documentService; + private final SysFileService sysFileService; + private final CurrentUserContext currentUserContext; + + public CrmShipmentServiceImpl(CrmShipmentItemMapper shipmentItemMapper, + CrmCustomerMapper customerMapper, + CrmProductMapper productMapper, + CrmQuoteMapper quoteMapper, + CrmQuoteItemMapper quoteItemMapper, + CrmSeqService crmSeqService, + CrmCompanyProfileService profileService, + CrmDocPdfRenderer docPdfRenderer, + CrmDocumentService documentService, + SysFileService sysFileService, + CurrentUserContext currentUserContext) { + this.shipmentItemMapper = shipmentItemMapper; + this.customerMapper = customerMapper; + this.productMapper = productMapper; + this.quoteMapper = quoteMapper; + this.quoteItemMapper = quoteItemMapper; + this.crmSeqService = crmSeqService; + this.profileService = profileService; + this.docPdfRenderer = docPdfRenderer; + this.documentService = documentService; + this.sysFileService = sysFileService; + this.currentUserContext = currentUserContext; + } + + @Override + @Transactional + public CrmShipmentVO create(CreateCrmShipmentDTO dto) { + Long companyId = requireCompanyId(); + Long userId = currentUserContext.getCurrentUserId(); + requireCustomer(companyId, dto.getCustomerId()); + if (dto.getQuoteId() != null) { + requireQuote(companyId, dto.getQuoteId()); + } + + CrmShipmentPO ship = new CrmShipmentPO(); + ship.setCompanyId(companyId); + ship.setShipmentNo(crmSeqService.nextShipmentNo(companyId)); + ship.setQuoteId(dto.getQuoteId()); + applyHeader(ship, dto.getCustomerId(), dto.getPlanShipDate(), dto.getActualShipDate(), + dto.getDestinationPort(), dto.getTransportMode(), dto.getContainerType(), + dto.getCurrency(), dto.getIncoterm(), dto.getPaymentTerms(), + dto.getOwnerUserId() != null ? dto.getOwnerUserId() : userId, + dto.getRemark()); + ship.setStatus("draft"); + ship.setCreateBy(userId); + ship.setUpdateBy(userId); + + List items = buildItems(companyId, dto.getItems()); + applyTotals(ship, items); + this.save(ship); + persistItems(ship.getId(), companyId, items); + return get(ship.getId()); + } + + @Override + @Transactional + public CrmShipmentVO createFromQuote(Long quoteId) { + Long companyId = requireCompanyId(); + Long userId = currentUserContext.getCurrentUserId(); + CrmQuotePO quote = requireQuote(companyId, quoteId); + if (!"accepted".equals(quote.getStatus())) { + throw new BusinessException("仅已接受的报价可生成出货"); + } + List quoteItems = quoteItemMapper.selectList(new LambdaQueryWrapper() + .eq(CrmQuoteItemPO::getQuoteId, quoteId) + .orderByAsc(CrmQuoteItemPO::getLineNo)); + if (quoteItems.isEmpty()) { + throw new BusinessException("报价无明细,无法生成出货"); + } + + CrmShipmentPO ship = new CrmShipmentPO(); + ship.setCompanyId(companyId); + ship.setShipmentNo(crmSeqService.nextShipmentNo(companyId)); + ship.setQuoteId(quoteId); + ship.setCustomerId(quote.getCustomerId()); + ship.setPlanShipDate(LocalDate.now()); + ship.setCurrency(normalizeCurrency(quote.getCurrency())); + ship.setIncoterm(quote.getIncoterm()); + ship.setPaymentTerms(quote.getPaymentTerms()); + ship.setStatus("draft"); + ship.setOwnerUserId(quote.getOwnerUserId() != null ? quote.getOwnerUserId() : userId); + ship.setRemark(quote.getRemark()); + ship.setCreateBy(userId); + ship.setUpdateBy(userId); + + List items = new ArrayList<>(); + int lineNo = 1; + for (CrmQuoteItemPO qi : quoteItems) { + CrmShipmentItemPO item = new CrmShipmentItemPO(); + item.setCompanyId(companyId); + item.setLineNo(lineNo++); + item.setProductId(qi.getProductId()); + item.setProductCode(qi.getProductCode()); + item.setNameEn(qi.getNameEn()); + item.setNameZh(qi.getNameZh()); + item.setSpec(qi.getSpec()); + item.setUnit(qi.getUnit()); + item.setQty(qi.getQty()); + item.setUnitPrice(qi.getUnitPrice()); + item.setAmount(qi.getAmount()); + item.setRemark(qi.getRemark()); + enrichFromProduct(companyId, item); + items.add(item); + } + applyTotals(ship, items); + this.save(ship); + persistItems(ship.getId(), companyId, items); + return get(ship.getId()); + } + + @Override + @Transactional + public CrmShipmentVO update(Long id, UpdateCrmShipmentDTO dto) { + CrmShipmentPO ship = requireOwned(id); + if (!EDITABLE.contains(ship.getStatus())) { + throw new BusinessException("当前状态不可编辑"); + } + Long companyId = ship.getCompanyId(); + requireCustomer(companyId, dto.getCustomerId()); + + applyHeader(ship, dto.getCustomerId(), dto.getPlanShipDate(), dto.getActualShipDate(), + dto.getDestinationPort(), dto.getTransportMode(), dto.getContainerType(), + dto.getCurrency(), dto.getIncoterm(), dto.getPaymentTerms(), + dto.getOwnerUserId() != null ? dto.getOwnerUserId() : ship.getOwnerUserId(), + dto.getRemark()); + ship.setUpdateBy(currentUserContext.getCurrentUserId()); + + List items = buildItems(companyId, dto.getItems()); + applyTotals(ship, items); + this.updateById(ship); + + shipmentItemMapper.delete(new LambdaQueryWrapper() + .eq(CrmShipmentItemPO::getShipmentId, id)); + persistItems(id, companyId, items); + return get(id); + } + + @Override + @Transactional + public void delete(Long id) { + CrmShipmentPO ship = requireOwned(id); + if (!"draft".equals(ship.getStatus())) { + throw new BusinessException("仅草稿出货可删除"); + } + Long userId = currentUserContext.getCurrentUserId(); + this.lambdaUpdate() + .eq(CrmShipmentPO::getId, id) + .set(CrmShipmentPO::getDeleteBy, userId) + .update(); + this.removeById(id); + } + + @Override + public CrmShipmentVO get(Long id) { + return toDetailVo(requireOwned(id)); + } + + @Override + public PageResultVO page(PageQueryDTO query) { + Long companyId = requireCompanyId(); + CrmShipmentFilterDTO filters = query.getFilters() != null ? query.getFilters() : new CrmShipmentFilterDTO(); + LambdaQueryWrapper w = new LambdaQueryWrapper<>(); + w.eq(CrmShipmentPO::getCompanyId, companyId); + if (StringUtils.hasText(filters.getStatus())) { + w.eq(CrmShipmentPO::getStatus, filters.getStatus().trim()); + } + if (filters.getCustomerId() != null) { + w.eq(CrmShipmentPO::getCustomerId, filters.getCustomerId()); + } + if (filters.getQuoteId() != null) { + w.eq(CrmShipmentPO::getQuoteId, filters.getQuoteId()); + } + if (Boolean.TRUE.equals(filters.getOnlyMine())) { + w.eq(CrmShipmentPO::getOwnerUserId, currentUserContext.getCurrentUserId()); + } + if (StringUtils.hasText(filters.getKeyword())) { + String kw = filters.getKeyword().trim(); + w.and(x -> x.like(CrmShipmentPO::getShipmentNo, kw) + .or().like(CrmShipmentPO::getDestinationPort, kw) + .or().like(CrmShipmentPO::getRemark, kw)); + } + w.orderByDesc(CrmShipmentPO::getId); + IPage page = this.page(new Page<>(query.getPage(), query.getPageSize()), w); + + Set customerIds = page.getRecords().stream().map(CrmShipmentPO::getCustomerId).collect(Collectors.toSet()); + Set quoteIds = page.getRecords().stream() + .map(CrmShipmentPO::getQuoteId).filter(Objects::nonNull).collect(Collectors.toSet()); + Map customerNames = loadCustomerNames(companyId, customerIds); + Map quoteNos = loadQuoteNos(companyId, quoteIds); + + List records = page.getRecords().stream().map(s -> { + CrmShipmentVO vo = toBriefVo(s); + vo.setCustomerName(customerNames.get(s.getCustomerId())); + if (s.getQuoteId() != null) { + vo.setQuoteNo(quoteNos.get(s.getQuoteId())); + } + return vo; + }).toList(); + return PageResultVO.create(records, page.getTotal(), query.getPage(), query.getPageSize()); + } + + @Override + @Transactional + public CrmShipmentVO changeStatus(Long id, ChangeCrmShipmentStatusDTO dto) { + CrmShipmentPO ship = requireOwned(id); + String target = dto.getStatus().trim().toLowerCase(Locale.ROOT); + if (!STATUSES.contains(target)) { + throw new BusinessException("目标状态不合法"); + } + if (!isAllowedTransition(ship.getStatus(), target)) { + throw new BusinessException("不允许从 " + ship.getStatus() + " 变更为 " + target); + } + ship.setStatus(target); + if ("shipped".equals(target) && ship.getActualShipDate() == null) { + ship.setActualShipDate(LocalDate.now()); + } + ship.setUpdateBy(currentUserContext.getCurrentUserId()); + this.updateById(ship); + return get(id); + } + + @Override + @Transactional + public CrmShipmentVO exportCi(Long id) { + CrmShipmentPO ship = requireOwned(id); + List items = listItems(id); + if (items.isEmpty()) { + throw new BusinessException("出货无明细,无法导出 CI"); + } + Long companyId = ship.getCompanyId(); + CrmCustomerPO customer = requireCustomer(companyId, ship.getCustomerId()); + CrmCompanyProfileVO profile = profileService.getCurrent(); + LocalDate docDate = ship.getActualShipDate() != null + ? ship.getActualShipDate() + : (ship.getPlanShipDate() != null ? ship.getPlanShipDate() : LocalDate.now()); + + CrmDocPdfRenderer.Party seller = partyFromProfile(profile); + CrmDocPdfRenderer.Party buyer = partyFromCustomer(customer); + + List lines = new ArrayList<>(); + for (CrmShipmentItemPO item : items) { + lines.add(new CrmDocPdfRenderer.InvoiceLine( + item.getLineNo(), + item.getProductCode(), + item.getNameEn(), + item.getSpec(), + item.getHsCode(), + item.getUnit(), + item.getQty(), + item.getUnitPrice(), + item.getAmount())); + } + String docNo = ship.getShipmentNo() + "-CI"; + CrmDocPdfRenderer.InvoiceModel model = new CrmDocPdfRenderer.InvoiceModel( + "COMMERCIAL INVOICE", + docNo, + docDate.toString(), + ship.getCurrency(), + ship.getIncoterm(), + ship.getPaymentTerms(), + ship.getDestinationPort(), + ship.getTransportMode(), + ship.getContainerType(), + ship.getRemark(), + seller, + buyer, + lines, + ship.getTotalAmount()); + + byte[] pdf = docPdfRenderer.renderCommercialInvoice(model); + documentService.savePdf(companyId, "ci", docNo, "shipment", id, + "CI-" + ship.getShipmentNo() + ".pdf", pdf); + return get(id); + } + + @Override + @Transactional + public CrmShipmentVO exportPl(Long id) { + CrmShipmentPO ship = requireOwned(id); + List items = listItems(id); + if (items.isEmpty()) { + throw new BusinessException("出货无明细,无法导出 PL"); + } + Long companyId = ship.getCompanyId(); + CrmCustomerPO customer = requireCustomer(companyId, ship.getCustomerId()); + CrmCompanyProfileVO profile = profileService.getCurrent(); + LocalDate docDate = ship.getActualShipDate() != null + ? ship.getActualShipDate() + : (ship.getPlanShipDate() != null ? ship.getPlanShipDate() : LocalDate.now()); + + List lines = new ArrayList<>(); + for (CrmShipmentItemPO item : items) { + lines.add(new CrmDocPdfRenderer.PackLine( + item.getLineNo(), + item.getProductCode(), + item.getNameEn(), + item.getSpec(), + item.getUnit(), + item.getQty(), + item.getPackages(), + item.getQtyPerPackage(), + item.getGrossWeightKg(), + item.getNetWeightKg(), + item.getVolumeCbm(), + item.getOriginCountry())); + } + String docNo = ship.getShipmentNo() + "-PL"; + CrmDocPdfRenderer.PackingModel model = new CrmDocPdfRenderer.PackingModel( + "PACKING LIST", + docNo, + docDate.toString(), + ship.getDestinationPort(), + ship.getTransportMode(), + ship.getContainerType(), + ship.getRemark(), + partyFromProfile(profile), + partyFromCustomer(customer), + lines, + ship.getTotalPackages(), + ship.getTotalGrossKg(), + ship.getTotalNetKg(), + ship.getTotalCbm()); + + byte[] pdf = docPdfRenderer.renderPackingList(model); + documentService.savePdf(companyId, "pl", docNo, "shipment", id, + "PL-" + ship.getShipmentNo() + ".pdf", pdf); + return get(id); + } + + private void applyHeader(CrmShipmentPO ship, Long customerId, + LocalDate planShipDate, LocalDate actualShipDate, + String destinationPort, String transportMode, String containerType, + String currency, String incoterm, String paymentTerms, + Long ownerUserId, String remark) { + ship.setCustomerId(customerId); + ship.setPlanShipDate(planShipDate); + ship.setActualShipDate(actualShipDate); + ship.setDestinationPort(trimToNull(destinationPort)); + ship.setTransportMode(trimToNull(transportMode)); + ship.setContainerType(trimToNull(containerType)); + ship.setCurrency(normalizeCurrency(currency)); + ship.setIncoterm(trimToNull(incoterm)); + ship.setPaymentTerms(trimToNull(paymentTerms)); + ship.setOwnerUserId(ownerUserId); + ship.setRemark(trimToNull(remark)); + } + + private boolean isAllowedTransition(String from, String to) { + if (from.equals(to)) { + return true; + } + return switch (from) { + case "draft" -> Set.of("ready", "closed").contains(to); + case "ready" -> Set.of("shipped", "draft", "closed").contains(to); + case "shipped" -> "closed".equals(to); + case "closed" -> false; + default -> false; + }; + } + + private List buildItems(Long companyId, List dtos) { + List items = new ArrayList<>(); + int lineNo = 1; + for (CrmShipmentItemDTO dto : dtos) { + if (dto.getQty() == null || dto.getQty().compareTo(BigDecimal.ZERO) <= 0) { + throw new BusinessException("第 " + lineNo + " 行数量须大于 0"); + } + if (dto.getUnitPrice() == null || dto.getUnitPrice().compareTo(BigDecimal.ZERO) < 0) { + throw new BusinessException("第 " + lineNo + " 行单价不能为负"); + } + CrmShipmentItemPO item = new CrmShipmentItemPO(); + item.setCompanyId(companyId); + item.setLineNo(lineNo++); + item.setProductId(dto.getProductId()); + item.setProductCode(trimToNull(dto.getProductCode())); + item.setNameEn(dto.getNameEn().trim()); + item.setNameZh(trimToNull(dto.getNameZh())); + item.setSpec(trimToNull(dto.getSpec())); + item.setHsCode(trimToNull(dto.getHsCode())); + item.setUnit(StringUtils.hasText(dto.getUnit()) ? dto.getUnit().trim() : "PCS"); + item.setQty(dto.getQty()); + item.setUnitPrice(dto.getUnitPrice()); + item.setAmount(dto.getQty().multiply(dto.getUnitPrice()).setScale(2, RoundingMode.HALF_UP)); + item.setPackages(dto.getPackages()); + item.setQtyPerPackage(dto.getQtyPerPackage()); + item.setGrossWeightKg(dto.getGrossWeightKg()); + item.setNetWeightKg(dto.getNetWeightKg()); + item.setVolumeCbm(dto.getVolumeCbm()); + item.setOriginCountry(trimToNull(dto.getOriginCountry())); + item.setRemark(trimToNull(dto.getRemark())); + enrichFromProduct(companyId, item); + items.add(item); + } + return items; + } + + /** 缺省字段从产品补全(不覆盖已填值)。 */ + private void enrichFromProduct(Long companyId, CrmShipmentItemPO item) { + if (item.getProductId() == null) { + return; + } + CrmProductPO product = productMapper.selectById(item.getProductId()); + if (product == null || !companyId.equals(product.getCompanyId())) { + throw new BusinessException("产品不存在: " + item.getProductId()); + } + if (!StringUtils.hasText(item.getProductCode())) { + item.setProductCode(product.getCode()); + } + if (!StringUtils.hasText(item.getNameZh())) { + item.setNameZh(product.getNameZh()); + } + if (!StringUtils.hasText(item.getSpec())) { + item.setSpec(product.getSpec()); + } + if (!StringUtils.hasText(item.getHsCode())) { + item.setHsCode(product.getHsCode()); + } + if (item.getGrossWeightKg() == null && product.getGrossWeightKg() != null && item.getQty() != null) { + item.setGrossWeightKg(product.getGrossWeightKg().multiply(item.getQty()).setScale(3, RoundingMode.HALF_UP)); + } + if (item.getNetWeightKg() == null && product.getNetWeightKg() != null && item.getQty() != null) { + item.setNetWeightKg(product.getNetWeightKg().multiply(item.getQty()).setScale(3, RoundingMode.HALF_UP)); + } + if (item.getVolumeCbm() == null && product.getVolumeCbm() != null && item.getQty() != null) { + item.setVolumeCbm(product.getVolumeCbm().multiply(item.getQty()).setScale(4, RoundingMode.HALF_UP)); + } + } + + private void applyTotals(CrmShipmentPO ship, List items) { + ship.setTotalAmount(items.stream() + .map(CrmShipmentItemPO::getAmount) + .filter(Objects::nonNull) + .reduce(BigDecimal.ZERO, BigDecimal::add) + .setScale(2, RoundingMode.HALF_UP)); + int pkgs = items.stream() + .map(CrmShipmentItemPO::getPackages) + .filter(Objects::nonNull) + .mapToInt(Integer::intValue) + .sum(); + ship.setTotalPackages(pkgs > 0 ? pkgs : null); + ship.setTotalGrossKg(sumDecimal(items.stream().map(CrmShipmentItemPO::getGrossWeightKg), 3)); + ship.setTotalNetKg(sumDecimal(items.stream().map(CrmShipmentItemPO::getNetWeightKg), 3)); + ship.setTotalCbm(sumDecimal(items.stream().map(CrmShipmentItemPO::getVolumeCbm), 4)); + } + + private static BigDecimal sumDecimal(java.util.stream.Stream stream, int scale) { + BigDecimal sum = stream.filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add); + if (sum.compareTo(BigDecimal.ZERO) == 0) { + return null; + } + return sum.setScale(scale, RoundingMode.HALF_UP); + } + + private void persistItems(Long shipmentId, Long companyId, List items) { + for (CrmShipmentItemPO item : items) { + item.setId(null); + item.setShipmentId(shipmentId); + item.setCompanyId(companyId); + shipmentItemMapper.insert(item); + } + } + + private List listItems(Long shipmentId) { + return shipmentItemMapper.selectList(new LambdaQueryWrapper() + .eq(CrmShipmentItemPO::getShipmentId, shipmentId) + .orderByAsc(CrmShipmentItemPO::getLineNo)); + } + + private CrmShipmentVO toDetailVo(CrmShipmentPO ship) { + CrmShipmentVO vo = toBriefVo(ship); + CrmCustomerPO customer = customerMapper.selectById(ship.getCustomerId()); + if (customer != null) { + vo.setCustomerName(customer.getName()); + } + if (ship.getQuoteId() != null) { + CrmQuotePO quote = quoteMapper.selectById(ship.getQuoteId()); + if (quote != null) { + vo.setQuoteNo(quote.getQuoteNo()); + } + } + vo.setItems(listItems(ship.getId()).stream().map(item -> { + CrmShipmentItemVO iv = new CrmShipmentItemVO(); + BeanCopyUtils.copyProperties(item, iv); + return iv; + }).toList()); + + CrmDocumentPO ci = documentService.findLatest(ship.getCompanyId(), "shipment", ship.getId(), "ci"); + if (ci != null) { + vo.setLatestCiFileId(ci.getFileId()); + vo.setLatestCiAccessUrl(sysFileService.resolveAccessUrl(ci.getFileId())); + } + CrmDocumentPO pl = documentService.findLatest(ship.getCompanyId(), "shipment", ship.getId(), "pl"); + if (pl != null) { + vo.setLatestPlFileId(pl.getFileId()); + vo.setLatestPlAccessUrl(sysFileService.resolveAccessUrl(pl.getFileId())); + } + return vo; + } + + private CrmShipmentVO toBriefVo(CrmShipmentPO ship) { + CrmShipmentVO vo = new CrmShipmentVO(); + BeanCopyUtils.copyProperties(ship, vo); + return vo; + } + + private Map loadCustomerNames(Long companyId, Set ids) { + if (ids == null || ids.isEmpty()) { + return Map.of(); + } + return customerMapper.selectList(new LambdaQueryWrapper() + .eq(CrmCustomerPO::getCompanyId, companyId) + .in(CrmCustomerPO::getId, ids)) + .stream() + .collect(Collectors.toMap(CrmCustomerPO::getId, CrmCustomerPO::getName, (a, b) -> a)); + } + + private Map loadQuoteNos(Long companyId, Set ids) { + if (ids == null || ids.isEmpty()) { + return Map.of(); + } + return quoteMapper.selectList(new LambdaQueryWrapper() + .eq(CrmQuotePO::getCompanyId, companyId) + .in(CrmQuotePO::getId, ids)) + .stream() + .collect(Collectors.toMap(CrmQuotePO::getId, CrmQuotePO::getQuoteNo, (a, b) -> a)); + } + + private CrmDocPdfRenderer.Party partyFromProfile(CrmCompanyProfileVO profile) { + return new CrmDocPdfRenderer.Party( + firstNonBlank(profile.getLegalNameEn(), profile.getLegalNameZh()), + firstNonBlank(profile.getAddressEn(), profile.getAddressZh()), + profile.getCountry(), + profile.getPhone(), + profile.getEmail()); + } + + private CrmDocPdfRenderer.Party partyFromCustomer(CrmCustomerPO customer) { + return new CrmDocPdfRenderer.Party( + firstNonBlank(customer.getNameEn(), customer.getName()), + customer.getAddress(), + customer.getCountry(), + customer.getPhone(), + customer.getEmail()); + } + + private CrmCustomerPO requireCustomer(Long companyId, Long customerId) { + CrmCustomerPO customer = customerMapper.selectById(customerId); + if (customer == null || !companyId.equals(customer.getCompanyId())) { + throw new BusinessException("客户不存在"); + } + return customer; + } + + private CrmQuotePO requireQuote(Long companyId, Long quoteId) { + CrmQuotePO quote = quoteMapper.selectById(quoteId); + if (quote == null || !companyId.equals(quote.getCompanyId())) { + throw new BusinessException("报价不存在"); + } + return quote; + } + + private CrmShipmentPO requireOwned(Long id) { + Long companyId = requireCompanyId(); + CrmShipmentPO ship = this.getById(id); + if (ship == null || !companyId.equals(ship.getCompanyId())) { + throw new BusinessException("出货单不存在"); + } + return ship; + } + + private Long requireCompanyId() { + Long companyId = currentUserContext.getCurrentCompanyId(); + if (companyId == null) { + throw new BusinessException("请先选择公司"); + } + return companyId; + } + + private static String normalizeCurrency(String currency) { + if (!StringUtils.hasText(currency)) { + return "USD"; + } + return currency.trim().toUpperCase(Locale.ROOT); + } + + private static String trimToNull(String s) { + if (!StringUtils.hasText(s)) { + return null; + } + return s.trim(); + } + + private static String firstNonBlank(String a, String b) { + if (StringUtils.hasText(a)) { + return a.trim(); + } + if (StringUtils.hasText(b)) { + return b.trim(); + } + return ""; + } +} diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/support/CrmDocPdfRenderer.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/support/CrmDocPdfRenderer.java new file mode 100644 index 0000000..e761121 --- /dev/null +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/crm/support/CrmDocPdfRenderer.java @@ -0,0 +1,217 @@ +package top.xyquan.ecomdmbbackend.modules.crm.support; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import org.springframework.stereotype.Component; +import top.xyquan.ecomdmbbackend.common.exception.BusinessException; + +import java.io.ByteArrayOutputStream; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.List; + +/** + * 出货单证 CI / PL PDF(英文排版)。 + */ +@Component +public class CrmDocPdfRenderer { + + public record Party(String name, String address, String country, String phone, String email) { + } + + public record InvoiceLine(int lineNo, String code, String nameEn, String spec, String hsCode, + String unit, BigDecimal qty, BigDecimal unitPrice, BigDecimal amount) { + } + + public record PackLine(int lineNo, String code, String nameEn, String spec, + String unit, BigDecimal qty, Integer packages, BigDecimal qtyPerPackage, + BigDecimal grossKg, BigDecimal netKg, BigDecimal cbm, String origin) { + } + + public record InvoiceModel( + String title, + String docNo, + String docDate, + String currency, + String incoterm, + String paymentTerms, + String destinationPort, + String transportMode, + String containerType, + String remark, + Party seller, + Party buyer, + List lines, + BigDecimal totalAmount + ) { + } + + public record PackingModel( + String title, + String docNo, + String docDate, + String destinationPort, + String transportMode, + String containerType, + String remark, + Party seller, + Party buyer, + List lines, + Integer totalPackages, + BigDecimal totalGrossKg, + BigDecimal totalNetKg, + BigDecimal totalCbm + ) { + } + + public byte[] renderCommercialInvoice(InvoiceModel model) { + return toPdf(buildCiHtml(model)); + } + + public byte[] renderPackingList(PackingModel model) { + return toPdf(buildPlHtml(model)); + } + + private byte[] toPdf(String html) { + try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { + PdfRendererBuilder builder = new PdfRendererBuilder(); + builder.useFastMode(); + builder.withHtmlContent(html, null); + builder.toStream(out); + builder.run(); + return out.toByteArray(); + } catch (Exception e) { + throw new BusinessException("生成 PDF 失败: " + e.getMessage()); + } + } + + private String buildCiHtml(InvoiceModel m) { + StringBuilder rows = new StringBuilder(); + for (InvoiceLine line : m.lines()) { + rows.append("") + .append("").append(line.lineNo()).append("") + .append("").append(esc(line.code())).append("") + .append("").append(esc(line.nameEn())).append("") + .append("").append(esc(line.spec())).append("") + .append("").append(esc(line.hsCode())).append("") + .append("").append(esc(line.unit())).append("") + .append("").append(fmt(line.qty(), 3)).append("") + .append("").append(fmt(line.unitPrice(), 4)).append("") + .append("").append(fmt(line.amount(), 2)).append("") + .append(""); + } + Party s = nz(m.seller()); + Party b = nz(m.buyer()); + StringBuilder html = new StringBuilder(); + html.append(commonHead(m.title())) + .append(metaRow("No.", m.docNo(), "Date", m.docDate())) + .append(metaRow("Currency", m.currency(), "Incoterm", dash(m.incoterm()))) + .append(metaRow("Payment", dash(m.paymentTerms()), "Dest. Port", dash(m.destinationPort()))) + .append(metaRow("Transport", dash(m.transportMode()), "Container", dash(m.containerType()))) + .append("") + .append(partyBoxes(s, b)) + .append("") + .append("") + .append("") + .append("").append(rows).append("
#CodeDescriptionSpecHSUnitQtyUnit PriceAmount
") + .append("
Total ").append(esc(m.currency())).append(" ") + .append(fmt(m.totalAmount(), 2)).append("
") + .append("

Remark: ").append(esc(dash(m.remark()))).append("

") + .append(""); + return html.toString(); + } + + private String buildPlHtml(PackingModel m) { + StringBuilder rows = new StringBuilder(); + for (PackLine line : m.lines()) { + rows.append("") + .append("").append(line.lineNo()).append("") + .append("").append(esc(line.code())).append("") + .append("").append(esc(line.nameEn())).append("") + .append("").append(esc(line.spec())).append("") + .append("").append(esc(line.unit())).append("") + .append("").append(fmt(line.qty(), 3)).append("") + .append("").append(line.packages() == null ? "-" : line.packages()).append("") + .append("").append(fmt(line.qtyPerPackage(), 3)).append("") + .append("").append(fmt(line.grossKg(), 3)).append("") + .append("").append(fmt(line.netKg(), 3)).append("") + .append("").append(fmt(line.cbm(), 4)).append("") + .append("").append(esc(line.origin())).append("") + .append(""); + } + Party s = nz(m.seller()); + Party b = nz(m.buyer()); + StringBuilder html = new StringBuilder(); + html.append(commonHead(m.title())) + .append(metaRow("No.", m.docNo(), "Date", m.docDate())) + .append(metaRow("Dest. Port", dash(m.destinationPort()), "Transport", dash(m.transportMode()))) + .append(metaRow("Container", dash(m.containerType()), "", "")) + .append("") + .append(partyBoxes(s, b)) + .append("") + .append("") + .append("") + .append("").append(rows).append("
#CodeDescriptionSpecUnitQtyPkgsQty/PkgG.W.N.W.CBMOrigin
") + .append("
Pkgs: ").append(m.totalPackages() == null ? "-" : m.totalPackages()) + .append("   G.W.: ").append(fmt(m.totalGrossKg(), 3)) + .append(" kg   N.W.: ").append(fmt(m.totalNetKg(), 3)) + .append(" kg   CBM: ").append(fmt(m.totalCbm(), 4)).append("
") + .append("

Remark: ").append(esc(dash(m.remark()))).append("

") + .append(""); + return html.toString(); + } + + private static String commonHead(String title) { + return "

" + esc(title) + "

"; + } + + private static String metaRow(String k1, String v1, String k2, String v2) { + return "" + + ""; + } + + private static String partyBoxes(Party s, Party b) { + return "
" + esc(k1) + "" + esc(dash(v1)) + "" + esc(k2) + "" + esc(dash(v2)) + "
" + + "" + + "" + + "" + + "
Seller
" + esc(s.name()) + "
" + esc(s.address()) + + "
" + esc(s.country()) + "
" + esc(s.phone()) + " " + esc(s.email()) + "
Buyer
" + esc(b.name()) + "
" + esc(b.address()) + + "
" + esc(b.country()) + "
" + esc(b.phone()) + " " + esc(b.email()) + "
"; + } + + private static Party nz(Party p) { + return p != null ? p : new Party("", "", "", "", ""); + } + + private static String fmt(BigDecimal v, int scale) { + if (v == null) { + return "-"; + } + return v.setScale(scale, RoundingMode.HALF_UP).toPlainString(); + } + + private static String dash(String s) { + return s == null || s.isBlank() ? "-" : s; + } + + private static String esc(String s) { + if (s == null) { + return ""; + } + return s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """); + } +} diff --git a/apps/server/src/main/resources/db/migration/V5__crm_shipment_menu_seed.sql b/apps/server/src/main/resources/db/migration/V5__crm_shipment_menu_seed.sql new file mode 100644 index 0000000..4f712e1 --- /dev/null +++ b/apps/server/src/main/resources/db/migration/V5__crm_shipment_menu_seed.sql @@ -0,0 +1,36 @@ +-- CRM Phase2 出货菜单权限(幂等) + +INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`) +SELECT 6500, (SELECT id FROM `sys_permission` WHERE `code` = 'crm' LIMIT 1), 'crm:shipment', '出货', 'module', 1, '', 40 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6500 OR `code` = 'crm:shipment'); + +INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`) +SELECT 6501, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:read', '查看', 'api', 1, '', 1 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6501 OR `code` = 'crm:shipment:read'); + +INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`) +SELECT 6502, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:create', '创建', 'api', 1, '', 2 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6502 OR `code` = 'crm:shipment:create'); + +INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`) +SELECT 6503, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:update', '更新', 'api', 1, '', 3 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6503 OR `code` = 'crm:shipment:update'); + +INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`) +SELECT 6504, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:delete', '删除', 'api', 1, '', 4 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6504 OR `code` = 'crm:shipment:delete'); + +INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`) +SELECT 6505, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:status', '改状态', 'api', 1, '', 5 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6505 OR `code` = 'crm:shipment:status'); + +INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`) +SELECT 6506, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:export', '导出CI/PL', 'api', 1, '', 6 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6506 OR `code` = 'crm:shipment:export'); + +INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`) +SELECT 14105, (SELECT id FROM `sys_menu` WHERE `id` = 14100 OR `route_name` = 'CrmCatalog' LIMIT 1), 0, 'CrmShipment', '出货', '/crm/shipment', '/crm/shipment/index', '', 'lucide:ship', 'menu', 1, 1, 1, 4 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14105 OR `route_name` = 'CrmShipment'); + +INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`) +SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'crm:shipment:%' WHERE m.route_name = 'CrmShipment'; diff --git a/apps/server/src/main/resources/sql/init/sys_seed.sql b/apps/server/src/main/resources/sql/init/sys_seed.sql index 0dfa948..9b44594 100644 --- a/apps/server/src/main/resources/sql/init/sys_seed.sql +++ b/apps/server/src/main/resources/sql/init/sys_seed.sql @@ -621,3 +621,42 @@ SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'crm: INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`) SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'crm:profile:%' WHERE m.route_name = 'CrmProfile'; + +-- ------------------------------------------------ +-- CRM Phase2:出货 +-- ------------------------------------------------ + +INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`) +SELECT 6500, (SELECT id FROM `sys_permission` WHERE `code` = 'crm' LIMIT 1), 'crm:shipment', '出货', 'module', 1, '', 40 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6500 OR `code` = 'crm:shipment'); + +INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`) +SELECT 6501, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:read', '查看', 'api', 1, '', 1 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6501 OR `code` = 'crm:shipment:read'); + +INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`) +SELECT 6502, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:create', '创建', 'api', 1, '', 2 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6502 OR `code` = 'crm:shipment:create'); + +INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`) +SELECT 6503, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:update', '更新', 'api', 1, '', 3 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6503 OR `code` = 'crm:shipment:update'); + +INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`) +SELECT 6504, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:delete', '删除', 'api', 1, '', 4 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6504 OR `code` = 'crm:shipment:delete'); + +INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`) +SELECT 6505, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:status', '改状态', 'api', 1, '', 5 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6505 OR `code` = 'crm:shipment:status'); + +INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`) +SELECT 6506, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:export', '导出CI/PL', 'api', 1, '', 6 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6506 OR `code` = 'crm:shipment:export'); + +INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`) +SELECT 14105, (SELECT id FROM `sys_menu` WHERE `id` = 14100 OR `route_name` = 'CrmCatalog' LIMIT 1), 0, 'CrmShipment', '出货', '/crm/shipment', '/crm/shipment/index', '', 'lucide:ship', 'menu', 1, 1, 1, 4 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14105 OR `route_name` = 'CrmShipment'); + +INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`) +SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'crm:shipment:%' WHERE m.route_name = 'CrmShipment'; diff --git a/apps/web/apps/web-antd/src/api/crm/shipment/apis.ts b/apps/web/apps/web-antd/src/api/crm/shipment/apis.ts new file mode 100644 index 0000000..a05bcb5 --- /dev/null +++ b/apps/web/apps/web-antd/src/api/crm/shipment/apis.ts @@ -0,0 +1,60 @@ +import type { CrmShipmentDTO, CrmShipmentVO } from './types'; + +import type { PageQueryDTO, PageResultVO } from '#/types/common'; + +import { requestClient } from '#/api/request'; + +export async function getCrmShipmentPageApi( + params: PageQueryDTO, +) { + return requestClient.post>( + '/crm/shipment/list', + params, + ); +} + +export async function getCrmShipmentApi(id: number) { + return requestClient.get(`/crm/shipment/${id}`); +} + +export async function createCrmShipmentApi(data: CrmShipmentDTO.Create) { + return requestClient.post('/crm/shipment/create', data); +} + +export async function createCrmShipmentFromQuoteApi(quoteId: number) { + return requestClient.post( + `/crm/shipment/from-quote/${quoteId}`, + ); +} + +export async function updateCrmShipmentApi( + id: number, + data: CrmShipmentDTO.Update, +) { + return requestClient.put( + `/crm/shipment/update/${id}`, + data, + ); +} + +export async function deleteCrmShipmentApi(id: number) { + return requestClient.delete(`/crm/shipment/delete/${id}`); +} + +export async function changeCrmShipmentStatusApi( + id: number, + data: CrmShipmentDTO.ChangeStatus, +) { + return requestClient.post( + `/crm/shipment/${id}/status`, + data, + ); +} + +export async function exportCrmShipmentCiApi(id: number) { + return requestClient.post(`/crm/shipment/${id}/export-ci`); +} + +export async function exportCrmShipmentPlApi(id: number) { + return requestClient.post(`/crm/shipment/${id}/export-pl`); +} diff --git a/apps/web/apps/web-antd/src/api/crm/shipment/index.ts b/apps/web/apps/web-antd/src/api/crm/shipment/index.ts new file mode 100644 index 0000000..daf76d5 --- /dev/null +++ b/apps/web/apps/web-antd/src/api/crm/shipment/index.ts @@ -0,0 +1,2 @@ +export * from './apis'; +export * from './types'; diff --git a/apps/web/apps/web-antd/src/api/crm/shipment/types/index.ts b/apps/web/apps/web-antd/src/api/crm/shipment/types/index.ts new file mode 100644 index 0000000..dfd513c --- /dev/null +++ b/apps/web/apps/web-antd/src/api/crm/shipment/types/index.ts @@ -0,0 +1,2 @@ +export * from './types.dto'; +export * from './types.vo'; diff --git a/apps/web/apps/web-antd/src/api/crm/shipment/types/types.dto.ts b/apps/web/apps/web-antd/src/api/crm/shipment/types/types.dto.ts new file mode 100644 index 0000000..2332d3a --- /dev/null +++ b/apps/web/apps/web-antd/src/api/crm/shipment/types/types.dto.ts @@ -0,0 +1,51 @@ +/** 出货 DTO */ +export namespace CrmShipmentDTO { + export interface Item { + productId?: number; + productCode?: string; + nameEn: string; + nameZh?: string; + spec?: string; + hsCode?: string; + unit?: string; + qty: number; + unitPrice: number; + packages?: number; + qtyPerPackage?: number; + grossWeightKg?: number; + netWeightKg?: number; + volumeCbm?: number; + originCountry?: string; + remark?: string; + } + + export interface Create { + quoteId?: number; + customerId: number; + planShipDate?: string; + actualShipDate?: string; + destinationPort?: string; + transportMode?: string; + containerType?: string; + currency?: string; + incoterm?: string; + paymentTerms?: string; + ownerUserId?: number; + remark?: string; + items: Item[]; + } + + export type Update = Omit; + + export interface Filters { + keyword?: string; + status?: string; + customerId?: number; + quoteId?: number; + onlyMine?: boolean; + } + + export interface ChangeStatus { + status: string; + } +} diff --git a/apps/web/apps/web-antd/src/api/crm/shipment/types/types.vo.ts b/apps/web/apps/web-antd/src/api/crm/shipment/types/types.vo.ts new file mode 100644 index 0000000..047a2f5 --- /dev/null +++ b/apps/web/apps/web-antd/src/api/crm/shipment/types/types.vo.ts @@ -0,0 +1,57 @@ +/** 出货 VO */ +export namespace CrmShipmentVO { + export interface Item { + id?: number; + lineNo?: number; + productId?: number; + productCode?: string; + nameEn: string; + nameZh?: string; + spec?: string; + hsCode?: string; + unit?: string; + qty: number; + unitPrice: number; + amount?: number; + packages?: number; + qtyPerPackage?: number; + grossWeightKg?: number; + netWeightKg?: number; + volumeCbm?: number; + originCountry?: string; + remark?: string; + } + + export interface Info { + id: number; + companyId?: number; + shipmentNo: string; + quoteId?: number; + quoteNo?: string; + customerId: number; + customerName?: string; + planShipDate?: string; + actualShipDate?: string; + destinationPort?: string; + transportMode?: string; + containerType?: string; + currency?: string; + incoterm?: string; + paymentTerms?: string; + status: string; + totalAmount?: number; + totalPackages?: number; + totalGrossKg?: number; + totalNetKg?: number; + totalCbm?: number; + ownerUserId?: number; + remark?: string; + createTime?: string; + updateTime?: string; + items?: Item[]; + latestCiFileId?: number; + latestCiAccessUrl?: string; + latestPlFileId?: number; + latestPlAccessUrl?: string; + } +} diff --git a/apps/web/apps/web-antd/src/views/crm/quote/index.vue b/apps/web/apps/web-antd/src/views/crm/quote/index.vue index 8301ebe..ab5fc35 100644 --- a/apps/web/apps/web-antd/src/views/crm/quote/index.vue +++ b/apps/web/apps/web-antd/src/views/crm/quote/index.vue @@ -19,6 +19,7 @@ import { } from 'ant-design-vue'; import { useVbenVxeGrid } from '#/adapter/vxe-table'; +import { createCrmShipmentFromQuoteApi } from '#/api/crm/shipment'; import { changeCrmQuoteStatusApi, deleteCrmQuoteApi, @@ -57,6 +58,7 @@ const actionCodes = [ 'crm:quote:delete', 'crm:quote:status', 'crm:quote:export', + 'crm:shipment:create', ]; const showActionColumn = useActionColumnVisible(actionCodes); @@ -80,7 +82,7 @@ const actionColumn: NonNullable< VxeGridProps['columns'] >[number] = { title: '操作', - width: 280, + width: 340, fixed: 'right', slots: { default: 'action' }, }; @@ -177,6 +179,12 @@ async function handleExportPi(row: CrmQuoteVO.Info) { gridApi.reload(); } +async function handleCreateShipment(row: CrmQuoteVO.Info) { + const ship = await createCrmShipmentFromQuoteApi(row.id); + message.success(`已生成出货 ${ship.shipmentNo}`); + gridApi.reload(); +} + function statusActions(row: CrmQuoteVO.Info) { const s = row.status; const actions: Array<{ key: string; label: string }> = []; @@ -228,6 +236,16 @@ function statusActions(row: CrmQuoteVO.Info) { 导出PI + + + diff --git a/apps/web/apps/web-antd/src/views/crm/shipment/components/ShipmentModal.vue b/apps/web/apps/web-antd/src/views/crm/shipment/components/ShipmentModal.vue new file mode 100644 index 0000000..692d843 --- /dev/null +++ b/apps/web/apps/web-antd/src/views/crm/shipment/components/ShipmentModal.vue @@ -0,0 +1,429 @@ + + + diff --git a/apps/web/apps/web-antd/src/views/crm/shipment/index.vue b/apps/web/apps/web-antd/src/views/crm/shipment/index.vue new file mode 100644 index 0000000..f475a5f --- /dev/null +++ b/apps/web/apps/web-antd/src/views/crm/shipment/index.vue @@ -0,0 +1,284 @@ + + + diff --git a/docs/外贸出口CRM雏形规划.md b/docs/外贸出口CRM雏形规划.md index 5fa13eb..621a4b6 100644 --- a/docs/外贸出口CRM雏形规划.md +++ b/docs/外贸出口CRM雏形规划.md @@ -241,10 +241,11 @@ modules/crm/ ### Phase 2 — 出货与 CI/PL -- [ ] 从「已接受报价」生成出货;出货行可改箱规重量 -- [ ] 一键生成 CI、PL;下载;历史版本可查 +- [x] 从「已接受报价」生成出货;出货行可改箱规重量 +- [x] 一键生成 CI、PL;下载;历史版本经 `crm_document`(is_latest)可查 -**验收**:演示「报价接受 → 出货 → 下载 CI+PL」全程不重复手抄品名数量。 +**验收**:演示「报价接受 → 出货 → 下载 CI+PL」全程不重复手抄品名数量。 +**种子**:`V5__crm_shipment_menu_seed.sql`;公司菜单/权限需勾选「出货」。 ### Phase 3 — 邮件方案 A @@ -286,3 +287,4 @@ modules/crm/ | 2026-10-22 | 初稿:确认外贸出口、小团队、CI+PL+PI、邮件方案 A、Excel 导入 | | 2026-10-22 | 落地约定:表设计 `sql/design/crm/`;Flyway `db/migration/V2__crm_schema.sql`(`sql/migration` 已弃用)。软删 + 生成列唯一;单号 Q/SH+年+6 位;默认币种 USD;V2 一次建齐全部 crm_*,Phase0 只实现客户/产品 | | 2026-10-22 | Phase1:报价+状态+PI PDF+单证资料;菜单种子 V4 | +| 2026-10-23 | Phase2:出货 CRUD、从已接受报价生成、CI/PL PDF;菜单种子 V5 |