Compare commits

...
4 Commits
159 changed files with 11479 additions and 20 deletions
+11
View File
@@ -129,6 +129,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- CRM 动态 SMTP 发信(按公司账户建 Session,不用全局 MailSender) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- Spring AOP -->
<dependency>
<groupId>org.springframework.boot</groupId>
@@ -170,6 +175,12 @@
<artifactId>poi-ooxml</artifactId>
<version>5.2.5</version>
</dependency>
<!-- HTML → PDF(外贸单证 PI/CI/PL,正文以英文为主) -->
<dependency>
<groupId>com.openhtmltopdf</groupId>
<artifactId>openhtmltopdf-pdfbox</artifactId>
<version>1.0.10</version>
</dependency>
</dependencies>
<build>
+389
View File
@@ -0,0 +1,389 @@
-- ========================================
-- CRM 外贸出口域设计(雏形)
-- 规划文档:docs/外贸出口CRM雏形规划.md
-- 落地迁移:src/main/resources/db/migration/V2__crm_schema.sql
--
-- 已拍板约定(可改文档后再改表):
-- 1) 公司隔离 company_id;小团队默认同公司共享,owner_user_id 作负责人
-- 2) 软删:主业务表 delete_time / delete_by;列表默认排除已删
-- 3) 币种 ISO-4217 三字母,默认 USD
-- 4) 客户唯一:公司内 (name, country) 未删除;产品唯一:公司内 code 未删除
-- 5) 单号:Q{yyyy}{6位} / SH{yyyy}{6位},由 crm_seq 按公司+业务+年发号
-- 6) 金额:单价 decimal(18,4),行/头金额 decimal(18,2)
-- 7) 首版单证:PI/CI/PL;邮件方案 A(模板+手发)
-- ========================================
-- ----------------------------------------
-- 发号器
-- ----------------------------------------
DROP TABLE IF EXISTS `crm_seq`;
CREATE TABLE `crm_seq` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`biz_type` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '业务:quote/shipment/document',
`year` smallint UNSIGNED NOT NULL COMMENT '年份',
`next_val` int UNSIGNED NOT NULL DEFAULT 1 COMMENT '下一流水号',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_crm_seq_company_biz_year` (`company_id`, `biz_type`, `year`) USING BTREE,
CONSTRAINT `fk_crm_seq_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-单号发号器';
-- ----------------------------------------
-- 本公司出口抬头(卖方资料)
-- ----------------------------------------
DROP TABLE IF EXISTS `crm_company_profile`;
CREATE TABLE `crm_company_profile` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID(一公司一行)',
`legal_name_zh` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '中文法定名称',
`legal_name_en` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '英文名称(单证卖方)',
`address_zh` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '中文地址',
`address_en` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '英文地址',
`country` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '国家/地区',
`phone` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '电话',
`email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '邮箱',
`tax_no` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '税号/统一社会信用代码',
`bank_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '开户行',
`bank_account` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '银行账号',
`bank_swift` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'SWIFT/BIC',
`bank_address` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '银行地址',
`default_currency` char(3) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'USD' COMMENT '默认币种',
`default_incoterm` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '默认贸易术语 FOB/CIF…',
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人',
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_crm_company_profile_company` (`company_id`) USING BTREE,
CONSTRAINT `fk_crm_company_profile_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_company_profile_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_company_profile_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-本公司出口抬头';
-- ----------------------------------------
-- 客户
-- ----------------------------------------
DROP TABLE IF EXISTS `crm_customer`;
CREATE TABLE `crm_customer` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '客户ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '所属公司ID',
`name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '客户公司名',
`name_en` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '英文名(单证买方可覆盖)',
`country` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '国家/地区',
`address` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '地址',
`contact_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '联系人',
`email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '邮箱',
`phone` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '电话',
`currency` char(3) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'USD' COMMENT '偏好币种',
`payment_terms` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '付款条款备注',
`status` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'lead' COMMENT 'lead/following/won/paused',
`owner_user_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '负责人用户ID',
`remark` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人',
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人',
`delete_time` timestamp NULL DEFAULT NULL COMMENT '删除时间(软删)',
`delete_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '删除人',
-- 未删时 = name\\0country;已删为 NULL(唯一索引允许多 NULL,可复用同名)
`active_name_country` varchar(280) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci
GENERATED ALWAYS AS (IF(`delete_time` IS NULL, CONCAT(`name`, CHAR(31), IFNULL(`country`, '')), NULL)) STORED COMMENT '软删友好唯一键',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_crm_customer_company_active_name_country` (`company_id`, `active_name_country`) USING BTREE,
INDEX `idx_crm_customer_company_status` (`company_id`, `status`, `id`) USING BTREE,
INDEX `idx_crm_customer_company_owner` (`company_id`, `owner_user_id`) USING BTREE,
INDEX `idx_crm_customer_company_name` (`company_id`, `name`) USING BTREE,
INDEX `idx_crm_customer_delete_time` (`delete_time`) USING BTREE,
CONSTRAINT `fk_crm_customer_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_customer_owner` FOREIGN KEY (`owner_user_id`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_customer_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_customer_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_customer_deleter` FOREIGN KEY (`delete_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-客户';
-- ----------------------------------------
-- 产品
-- ----------------------------------------
DROP TABLE IF EXISTS `crm_product`;
CREATE TABLE `crm_product` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '产品ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '所属公司ID',
`code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'SKU/编码(公司内未删唯一)',
`name_zh` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '中文名',
`name_en` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '英文名(单证主用)',
`spec` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '规格',
`unit` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'PCS' COMMENT '单位',
`unit_price` decimal(18, 4) NULL DEFAULT NULL COMMENT '参考单价',
`currency` char(3) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'USD' COMMENT '币种',
`hs_code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'HS Code',
`gross_weight_kg` decimal(18, 3) NULL DEFAULT NULL COMMENT '参考毛重 kg/单位',
`net_weight_kg` decimal(18, 3) NULL DEFAULT NULL COMMENT '参考净重 kg/单位',
`volume_cbm` decimal(18, 4) NULL DEFAULT NULL COMMENT '参考体积 m³/单位',
`status` tinyint UNSIGNED NOT NULL DEFAULT 1 COMMENT '0禁用 1启用',
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人',
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人',
`delete_time` timestamp NULL DEFAULT NULL COMMENT '删除时间(软删)',
`delete_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '删除人',
`active_code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci
GENERATED ALWAYS AS (IF(`delete_time` IS NULL, `code`, NULL)) STORED COMMENT '软删友好唯一键',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_crm_product_company_active_code` (`company_id`, `active_code`) USING BTREE,
INDEX `idx_crm_product_company_status` (`company_id`, `status`, `id`) USING BTREE,
INDEX `idx_crm_product_delete_time` (`delete_time`) USING BTREE,
CONSTRAINT `fk_crm_product_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_product_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_product_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_product_deleter` FOREIGN KEY (`delete_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-产品';
-- ----------------------------------------
-- 报价
-- ----------------------------------------
DROP TABLE IF EXISTS `crm_quote_item`;
DROP TABLE IF EXISTS `crm_quote`;
CREATE TABLE `crm_quote` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '报价ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '所属公司ID',
`quote_no` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '报价号 Qyyyy######',
`customer_id` bigint UNSIGNED NOT NULL COMMENT '客户ID',
`quote_date` date NOT NULL COMMENT '报价日期',
`valid_until` date NULL DEFAULT NULL COMMENT '有效期至',
`currency` char(3) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'USD' COMMENT '币种',
`incoterm` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '贸易术语',
`payment_terms` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '付款条款',
`status` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'draft' COMMENT 'draft/sent/accepted/rejected/expired',
`total_amount` decimal(18, 2) NOT NULL DEFAULT 0.00 COMMENT '合计金额',
`owner_user_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '负责人',
`remark` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人',
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人',
`delete_time` timestamp NULL DEFAULT NULL COMMENT '删除时间',
`delete_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '删除人',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_crm_quote_company_no` (`company_id`, `quote_no`) USING BTREE,
INDEX `idx_crm_quote_company_status` (`company_id`, `status`, `id`) USING BTREE,
INDEX `idx_crm_quote_customer` (`customer_id`) USING BTREE,
INDEX `idx_crm_quote_delete_time` (`delete_time`) USING BTREE,
CONSTRAINT `fk_crm_quote_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_quote_customer` FOREIGN KEY (`customer_id`) REFERENCES `crm_customer` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT `fk_crm_quote_owner` FOREIGN KEY (`owner_user_id`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_quote_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_quote_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_quote_deleter` FOREIGN KEY (`delete_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-报价单';
CREATE TABLE `crm_quote_item` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '行ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID(冗余)',
`quote_id` bigint UNSIGNED NOT NULL COMMENT '报价ID',
`line_no` int UNSIGNED NOT NULL DEFAULT 1 COMMENT '行号',
`product_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '产品ID(可空,允许临时品名)',
`product_code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '编码快照',
`name_en` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '英文品名快照',
`name_zh` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '中文品名快照',
`spec` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '规格快照',
`unit` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'PCS' COMMENT '单位',
`qty` decimal(18, 3) NOT NULL DEFAULT 0 COMMENT '数量',
`unit_price` decimal(18, 4) NOT NULL DEFAULT 0 COMMENT '单价',
`amount` decimal(18, 2) NOT NULL DEFAULT 0.00 COMMENT '金额',
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '行备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_crm_quote_item_quote` (`quote_id`, `line_no`) USING BTREE,
INDEX `idx_crm_quote_item_product` (`product_id`) USING BTREE,
CONSTRAINT `fk_crm_quote_item_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_quote_item_quote` FOREIGN KEY (`quote_id`) REFERENCES `crm_quote` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_quote_item_product` FOREIGN KEY (`product_id`) REFERENCES `crm_product` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-报价行';
-- ----------------------------------------
-- 出货
-- ----------------------------------------
DROP TABLE IF EXISTS `crm_shipment_item`;
DROP TABLE IF EXISTS `crm_shipment`;
CREATE TABLE `crm_shipment` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '出货ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '所属公司ID',
`shipment_no` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '出货号 SHyyyy######',
`quote_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '来源报价(可空)',
`customer_id` bigint UNSIGNED NOT NULL COMMENT '客户ID',
`plan_ship_date` date NULL DEFAULT NULL COMMENT '计划出货日',
`actual_ship_date` date NULL DEFAULT NULL COMMENT '实际出货日',
`destination_port` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '目的港',
`transport_mode` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '运输方式 sea/air/express…',
`container_type` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '柜型 20GP/40HQ…',
`currency` char(3) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'USD' COMMENT '币种(CI)',
`incoterm` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '贸易术语',
`payment_terms` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '付款条款',
`status` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'draft' COMMENT 'draft/ready/shipped/closed',
`total_amount` decimal(18, 2) NOT NULL DEFAULT 0.00 COMMENT '发票合计',
`total_packages` int UNSIGNED NULL DEFAULT NULL COMMENT '总箱数',
`total_gross_kg` decimal(18, 3) NULL DEFAULT NULL COMMENT '总毛重',
`total_net_kg` decimal(18, 3) NULL DEFAULT NULL COMMENT '总净重',
`total_cbm` decimal(18, 4) NULL DEFAULT NULL COMMENT '总体积',
`owner_user_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '负责人',
`remark` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人',
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人',
`delete_time` timestamp NULL DEFAULT NULL COMMENT '删除时间',
`delete_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '删除人',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_crm_shipment_company_no` (`company_id`, `shipment_no`) USING BTREE,
INDEX `idx_crm_shipment_company_status` (`company_id`, `status`, `id`) USING BTREE,
INDEX `idx_crm_shipment_quote` (`quote_id`) USING BTREE,
INDEX `idx_crm_shipment_customer` (`customer_id`) USING BTREE,
INDEX `idx_crm_shipment_delete_time` (`delete_time`) USING BTREE,
CONSTRAINT `fk_crm_shipment_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_shipment_quote` FOREIGN KEY (`quote_id`) REFERENCES `crm_quote` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_shipment_customer` FOREIGN KEY (`customer_id`) REFERENCES `crm_customer` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT `fk_crm_shipment_owner` FOREIGN KEY (`owner_user_id`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_shipment_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_shipment_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_shipment_deleter` FOREIGN KEY (`delete_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-出货单';
CREATE TABLE `crm_shipment_item` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '行ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID(冗余)',
`shipment_id` bigint UNSIGNED NOT NULL COMMENT '出货ID',
`line_no` int UNSIGNED NOT NULL DEFAULT 1 COMMENT '行号',
`product_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '产品ID',
`product_code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '编码快照',
`name_en` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '英文品名',
`name_zh` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '中文品名',
`spec` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '规格',
`hs_code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'HS Code',
`unit` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'PCS' COMMENT '单位',
`qty` decimal(18, 3) NOT NULL DEFAULT 0 COMMENT '数量',
`unit_price` decimal(18, 4) NOT NULL DEFAULT 0 COMMENT '单价',
`amount` decimal(18, 2) NOT NULL DEFAULT 0.00 COMMENT '金额',
`packages` int UNSIGNED NULL DEFAULT NULL COMMENT '箱数',
`qty_per_package` decimal(18, 3) NULL DEFAULT NULL COMMENT '每箱数量',
`gross_weight_kg` decimal(18, 3) NULL DEFAULT NULL COMMENT '毛重 kg',
`net_weight_kg` decimal(18, 3) NULL DEFAULT NULL COMMENT '净重 kg',
`volume_cbm` decimal(18, 4) NULL DEFAULT NULL COMMENT '体积 m³',
`origin_country` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '原产地',
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '行备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_crm_shipment_item_shipment` (`shipment_id`, `line_no`) USING BTREE,
INDEX `idx_crm_shipment_item_product` (`product_id`) USING BTREE,
CONSTRAINT `fk_crm_shipment_item_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_shipment_item_shipment` FOREIGN KEY (`shipment_id`) REFERENCES `crm_shipment` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_shipment_item_product` FOREIGN KEY (`product_id`) REFERENCES `crm_product` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-出货行';
-- ----------------------------------------
-- 单证元数据(文件落 sys_file)
-- ----------------------------------------
DROP TABLE IF EXISTS `crm_document`;
CREATE TABLE `crm_document` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '单证ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`doc_type` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'pi/ci/pl',
`doc_no` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '单证号(可空,默认同业务单号)',
`ref_type` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'quote/shipment',
`ref_id` bigint UNSIGNED NOT NULL COMMENT '业务单ID',
`file_id` bigint UNSIGNED NOT NULL COMMENT 'sys_file.id',
`is_latest` tinyint UNSIGNED NOT NULL DEFAULT 1 COMMENT '是否最新版本 1是 0否',
`version_no` int UNSIGNED NOT NULL DEFAULT 1 COMMENT '版本号',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_crm_document_ref` (`company_id`, `ref_type`, `ref_id`, `doc_type`, `is_latest`) USING BTREE,
INDEX `idx_crm_document_file` (`file_id`) USING BTREE,
CONSTRAINT `fk_crm_document_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_document_file` FOREIGN KEY (`file_id`) REFERENCES `sys_file` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT `fk_crm_document_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-单证记录';
-- ----------------------------------------
-- 邮件(方案 A)
-- ----------------------------------------
DROP TABLE IF EXISTS `crm_mail_log`;
DROP TABLE IF EXISTS `crm_mail_template`;
DROP TABLE IF EXISTS `crm_mail_account`;
CREATE TABLE `crm_mail_account` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '显示名',
`from_email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '发件邮箱',
`smtp_host` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'SMTP 主机',
`smtp_port` int UNSIGNED NOT NULL DEFAULT 465 COMMENT 'SMTP 端口',
`smtp_ssl` tinyint UNSIGNED NOT NULL DEFAULT 1 COMMENT '是否 SSL/TLS',
`username` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '登录用户名',
`password_cipher` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '密码密文',
`enabled` tinyint UNSIGNED NOT NULL DEFAULT 1 COMMENT '是否启用',
`is_default` tinyint UNSIGNED NOT NULL DEFAULT 0 COMMENT '是否默认发件',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人',
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_crm_mail_account_company` (`company_id`, `enabled`) USING BTREE,
CONSTRAINT `fk_crm_mail_account_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_account_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_account_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-发件账户';
CREATE TABLE `crm_mail_template` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '模板ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '模板名称',
`scene` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'outreach' COMMENT 'outreach/quote_followup/shipment_notice',
`subject` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '主题(支持变量)',
`body_html` mediumtext CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '正文 HTML(支持变量)',
`enabled` tinyint UNSIGNED NOT NULL DEFAULT 1 COMMENT '是否启用',
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人',
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人',
`delete_time` timestamp NULL DEFAULT NULL COMMENT '删除时间',
`delete_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '删除人',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_crm_mail_template_company_scene` (`company_id`, `scene`, `enabled`) USING BTREE,
CONSTRAINT `fk_crm_mail_template_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_template_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_template_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_template_deleter` FOREIGN KEY (`delete_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-邮件模板';
CREATE TABLE `crm_mail_log` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '日志ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`account_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '发件账户',
`template_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '模板ID',
`customer_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '关联客户',
`ref_type` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'quote/shipment 等',
`ref_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '业务单ID',
`to_email` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '收件人',
`cc_email` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '抄送',
`subject` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '实际主题',
`body_html` mediumtext CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT '实际正文',
`status` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'pending' COMMENT 'pending/success/failed',
`error_message` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '失败原因',
`sent_at` timestamp NULL DEFAULT NULL COMMENT '发送时间',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '操作人',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_crm_mail_log_company_time` (`company_id`, `create_time` DESC) USING BTREE,
INDEX `idx_crm_mail_log_customer` (`customer_id`) USING BTREE,
CONSTRAINT `fk_crm_mail_log_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_log_account` FOREIGN KEY (`account_id`) REFERENCES `crm_mail_account` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_log_template` FOREIGN KEY (`template_id`) REFERENCES `crm_mail_template` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_log_customer` FOREIGN KEY (`customer_id`) REFERENCES `crm_customer` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_log_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-邮件发送记录';
@@ -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;
@@ -0,0 +1,81 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.controller;
import jakarta.validation.Valid;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
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.customer.model.dto.CreateCrmCustomerDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto.CrmCustomerFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto.UpdateCrmCustomerDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.vo.CrmCustomerVO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.service.CrmCustomerService;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmImportResultVO;
/**
* 客户管理接口。
*/
@RestController
@RequestMapping("/api/crm/customer")
public class CrmCustomerController {
private final CrmCustomerService crmCustomerService;
public CrmCustomerController(CrmCustomerService crmCustomerService) {
this.crmCustomerService = crmCustomerService;
}
@PostMapping("/create")
@RequirePermission(value = "crm:customer:create", description = "创建客户")
public ApiResponse<CrmCustomerVO> create(@Valid @RequestBody CreateCrmCustomerDTO dto) {
return ApiResponse.success("创建成功", crmCustomerService.create(dto));
}
@PutMapping("/update/{id}")
@RequirePermission(value = "crm:customer:update", description = "更新客户")
public ApiResponse<CrmCustomerVO> update(@PathVariable Long id, @Valid @RequestBody UpdateCrmCustomerDTO dto) {
return ApiResponse.success("更新成功", crmCustomerService.update(id, dto));
}
@DeleteMapping("/delete/{id}")
@RequirePermission(value = "crm:customer:delete", description = "删除客户")
public ApiResponse<Void> delete(@PathVariable Long id) {
crmCustomerService.delete(id);
return ApiResponse.success("删除成功");
}
@GetMapping("/{id}")
@RequirePermission(value = "crm:customer:read", description = "客户详情")
public ApiResponse<CrmCustomerVO> get(@PathVariable Long id) {
return ApiResponse.success("获取成功", crmCustomerService.get(id));
}
@PostMapping("/list")
@RequirePermission(value = "crm:customer:read", description = "客户列表")
public ApiResponse<PageResultVO<CrmCustomerVO>> list(
@Valid @RequestBody PageQueryDTO<CrmCustomerFilterDTO> query) {
return ApiResponse.success("获取成功", crmCustomerService.page(query));
}
@GetMapping("/import/template")
@RequirePermission(value = "crm:customer:import", description = "下载客户导入模板")
public ResponseEntity<byte[]> importTemplate() {
byte[] bytes = crmCustomerService.importTemplate();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=crm-customer-import.xlsx")
.contentType(MediaType.parseMediaType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.body(bytes);
}
@PostMapping("/import")
@RequirePermission(value = "crm:customer:import", description = "导入客户")
public ApiResponse<CrmImportResultVO> importExcel(@RequestParam("file") MultipartFile file) {
return ApiResponse.success("导入完成", crmCustomerService.importExcel(file));
}
}
@@ -0,0 +1,12 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.po.CrmCustomerPO;
/**
* 客户 Mapper。
*/
@Mapper
public interface CrmCustomerMapper extends BaseMapper<CrmCustomerPO> {
}
@@ -0,0 +1,49 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
/**
* 创建客户。
*/
@Data
public class CreateCrmCustomerDTO {
@NotBlank(message = "客户名称不能为空")
@Size(max = 200)
private String name;
@Size(max = 200)
private String nameEn;
@Size(max = 64)
private String country;
@Size(max = 500)
private String address;
@Size(max = 100)
private String contactName;
@Size(max = 100)
private String email;
@Size(max = 50)
private String phone;
@Size(max = 3)
private String currency;
@Size(max = 200)
private String paymentTerms;
/** lead/following/won/paused */
@Size(max = 32)
private String status;
private Long ownerUserId;
@Size(max = 1000)
private String remark;
}
@@ -0,0 +1,16 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto;
import lombok.Data;
/**
* 客户列表筛选。
*/
@Data
public class CrmCustomerFilterDTO {
private String keyword;
private String status;
private String country;
private Long ownerUserId;
/** true 时仅看我负责的 */
private Boolean onlyMine;
}
@@ -0,0 +1,48 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
/**
* 更新客户。
*/
@Data
public class UpdateCrmCustomerDTO {
@NotBlank(message = "客户名称不能为空")
@Size(max = 200)
private String name;
@Size(max = 200)
private String nameEn;
@Size(max = 64)
private String country;
@Size(max = 500)
private String address;
@Size(max = 100)
private String contactName;
@Size(max = 100)
private String email;
@Size(max = 50)
private String phone;
@Size(max = 3)
private String currency;
@Size(max = 200)
private String paymentTerms;
@Size(max = 32)
private String status;
private Long ownerUserId;
@Size(max = 1000)
private String remark;
}
@@ -0,0 +1,76 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 客户实体。
*/
@Data
@TableName("crm_customer")
public class CrmCustomerPO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("name")
private String name;
@TableField("name_en")
private String nameEn;
@TableField("country")
private String country;
@TableField("address")
private String address;
@TableField("contact_name")
private String contactName;
@TableField("email")
private String email;
@TableField("phone")
private String phone;
@TableField("currency")
private String currency;
@TableField("payment_terms")
private String paymentTerms;
/** lead / following / won / paused */
@TableField("status")
private String status;
@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;
}
@@ -0,0 +1,28 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.model.vo;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 客户视图。
*/
@Data
public class CrmCustomerVO {
private Long id;
private Long companyId;
private String name;
private String nameEn;
private String country;
private String address;
private String contactName;
private String email;
private String phone;
private String currency;
private String paymentTerms;
private String status;
private Long ownerUserId;
private String remark;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,30 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.service;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto.CreateCrmCustomerDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto.CrmCustomerFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto.UpdateCrmCustomerDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.vo.CrmCustomerVO;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmImportResultVO;
/**
* 客户用例。
*/
public interface CrmCustomerService {
CrmCustomerVO create(CreateCrmCustomerDTO dto);
CrmCustomerVO update(Long id, UpdateCrmCustomerDTO dto);
void delete(Long id);
CrmCustomerVO get(Long id);
PageResultVO<CrmCustomerVO> page(PageQueryDTO<CrmCustomerFilterDTO> query);
byte[] importTemplate();
CrmImportResultVO importExcel(MultipartFile file);
}
@@ -0,0 +1,237 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.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.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
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.dto.CreateCrmCustomerDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto.CrmCustomerFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto.UpdateCrmCustomerDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.po.CrmCustomerPO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.vo.CrmCustomerVO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.service.CrmCustomerService;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmExcelSupport;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmImportResultVO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.util.List;
import java.util.Locale;
import java.util.Set;
/**
* 客户用例实现:公司隔离、软删、Excel 导入。
*/
@Service
public class CrmCustomerServiceImpl extends ServiceImpl<CrmCustomerMapper, CrmCustomerPO>
implements CrmCustomerService {
private static final Set<String> STATUSES = Set.of("lead", "following", "won", "paused");
private static final String[] IMPORT_HEADERS = {
"公司名*", "国家", "联系人", "邮箱", "电话", "币种", "备注"
};
private final CurrentUserContext currentUserContext;
private final CrmExcelSupport crmExcelSupport;
public CrmCustomerServiceImpl(CurrentUserContext currentUserContext, CrmExcelSupport crmExcelSupport) {
this.currentUserContext = currentUserContext;
this.crmExcelSupport = crmExcelSupport;
}
@Override
@Transactional
public CrmCustomerVO create(CreateCrmCustomerDTO dto) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
CrmCustomerPO po = new CrmCustomerPO();
BeanCopyUtils.copyProperties(dto, po);
normalize(po);
po.setCompanyId(companyId);
po.setCreateBy(userId);
po.setUpdateBy(userId);
if (po.getOwnerUserId() == null) {
po.setOwnerUserId(userId);
}
try {
this.save(po);
} catch (DuplicateKeyException e) {
throw new BusinessException("同国家下客户名称已存在");
}
return toVo(po);
}
@Override
@Transactional
public CrmCustomerVO update(Long id, UpdateCrmCustomerDTO dto) {
CrmCustomerPO existing = requireOwned(id);
BeanCopyUtils.copyProperties(dto, existing);
normalize(existing);
existing.setUpdateBy(currentUserContext.getCurrentUserId());
try {
this.updateById(existing);
} catch (DuplicateKeyException e) {
throw new BusinessException("同国家下客户名称已存在");
}
return toVo(this.getById(id));
}
@Override
@Transactional
public void delete(Long id) {
requireOwned(id);
Long userId = currentUserContext.getCurrentUserId();
this.lambdaUpdate()
.eq(CrmCustomerPO::getId, id)
.set(CrmCustomerPO::getDeleteBy, userId)
.update();
this.removeById(id);
}
@Override
public CrmCustomerVO get(Long id) {
return toVo(requireOwned(id));
}
@Override
public PageResultVO<CrmCustomerVO> page(PageQueryDTO<CrmCustomerFilterDTO> query) {
Long companyId = requireCompanyId();
CrmCustomerFilterDTO filters = query.getFilters() != null ? query.getFilters() : new CrmCustomerFilterDTO();
LambdaQueryWrapper<CrmCustomerPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(CrmCustomerPO::getCompanyId, companyId);
if (StringUtils.hasText(filters.getKeyword())) {
String kw = filters.getKeyword().trim();
wrapper.and(w -> w.like(CrmCustomerPO::getName, kw)
.or().like(CrmCustomerPO::getNameEn, kw)
.or().like(CrmCustomerPO::getContactName, kw)
.or().like(CrmCustomerPO::getEmail, kw));
}
if (StringUtils.hasText(filters.getStatus())) {
wrapper.eq(CrmCustomerPO::getStatus, filters.getStatus().trim());
}
if (StringUtils.hasText(filters.getCountry())) {
wrapper.eq(CrmCustomerPO::getCountry, filters.getCountry().trim());
}
if (Boolean.TRUE.equals(filters.getOnlyMine())) {
wrapper.eq(CrmCustomerPO::getOwnerUserId, currentUserContext.getCurrentUserId());
} else if (filters.getOwnerUserId() != null) {
wrapper.eq(CrmCustomerPO::getOwnerUserId, filters.getOwnerUserId());
}
wrapper.orderByDesc(CrmCustomerPO::getId);
IPage<CrmCustomerPO> page = this.page(new Page<>(query.getPage(), query.getPageSize()), wrapper);
List<CrmCustomerVO> records = page.getRecords().stream().map(this::toVo).toList();
return PageResultVO.create(records, page.getTotal(), query.getPage(), query.getPageSize());
}
@Override
public byte[] importTemplate() {
return crmExcelSupport.buildTemplate("客户导入", IMPORT_HEADERS);
}
@Override
@Transactional
public CrmImportResultVO importExcel(MultipartFile file) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
CrmImportResultVO result = new CrmImportResultVO();
List<CrmExcelSupport.RowContext> rows = crmExcelSupport.parseRows(file, IMPORT_HEADERS.length, r -> r);
for (CrmExcelSupport.RowContext row : rows) {
try {
String name = row.str(0);
if (!StringUtils.hasText(name)) {
throw new BusinessException("公司名不能为空");
}
CrmCustomerPO po = new CrmCustomerPO();
po.setCompanyId(companyId);
po.setName(name.trim());
po.setCountry(row.str(1));
po.setContactName(row.str(2));
po.setEmail(row.str(3));
po.setPhone(row.str(4));
po.setCurrency(row.str(5));
po.setRemark(row.str(6));
po.setOwnerUserId(userId);
po.setCreateBy(userId);
po.setUpdateBy(userId);
normalize(po);
// 同名同国:更新
LambdaQueryWrapper<CrmCustomerPO> exists = new LambdaQueryWrapper<>();
exists.eq(CrmCustomerPO::getCompanyId, companyId)
.eq(CrmCustomerPO::getName, po.getName())
.eq(po.getCountry() != null, CrmCustomerPO::getCountry, po.getCountry())
.isNull(po.getCountry() == null, CrmCustomerPO::getCountry);
CrmCustomerPO old = this.getOne(exists, false);
if (old != null) {
po.setId(old.getId());
this.updateById(po);
} else {
this.save(po);
}
result.setSuccessCount(result.getSuccessCount() + 1);
} catch (Exception e) {
result.setFailCount(result.getFailCount() + 1);
String msg = e instanceof BusinessException be ? be.getMessage() : e.getMessage();
result.getErrors().add(new CrmImportResultVO.RowError(row.rowNum(), msg));
}
}
return result;
}
private void normalize(CrmCustomerPO po) {
if (!StringUtils.hasText(po.getCurrency())) {
po.setCurrency("USD");
} else {
po.setCurrency(po.getCurrency().trim().toUpperCase(Locale.ROOT));
}
if (!StringUtils.hasText(po.getStatus())) {
po.setStatus("lead");
} else {
String s = po.getStatus().trim().toLowerCase(Locale.ROOT);
if (!STATUSES.contains(s)) {
throw new BusinessException("客户状态不合法");
}
po.setStatus(s);
}
if (po.getName() != null) {
po.setName(po.getName().trim());
}
if (po.getCountry() != null) {
po.setCountry(po.getCountry().trim());
if (po.getCountry().isEmpty()) {
po.setCountry(null);
}
}
}
private CrmCustomerPO requireOwned(Long id) {
Long companyId = requireCompanyId();
CrmCustomerPO po = this.getById(id);
if (po == null || !companyId.equals(po.getCompanyId())) {
throw new BusinessException("客户不存在");
}
return po;
}
private Long requireCompanyId() {
Long companyId = currentUserContext.getCurrentCompanyId();
if (companyId == null) {
throw new BusinessException("请先选择公司");
}
return companyId;
}
private CrmCustomerVO toVo(CrmCustomerPO po) {
CrmCustomerVO vo = new CrmCustomerVO();
BeanCopyUtils.copyProperties(po, vo);
return vo;
}
}
@@ -0,0 +1,9 @@
package top.xyquan.ecomdmbbackend.modules.crm.document.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.crm.document.model.po.CrmDocumentPO;
@Mapper
public interface CrmDocumentMapper extends BaseMapper<CrmDocumentPO> {
}
@@ -0,0 +1,35 @@
package top.xyquan.ecomdmbbackend.modules.crm.document.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.time.LocalDateTime;
/** 单证记录。 */
@Data
@TableName("crm_document")
public class CrmDocumentPO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("doc_type")
private String docType;
@TableField("doc_no")
private String docNo;
@TableField("ref_type")
private String refType;
@TableField("ref_id")
private Long refId;
@TableField("file_id")
private Long fileId;
@TableField("is_latest")
private Integer isLatest;
@TableField("version_no")
private Integer versionNo;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField("create_by")
private Long createBy;
}
@@ -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<CrmDocumentPO>()
.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<CrmDocumentPO>()
.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<CrmDocumentPO>()
.eq(CrmDocumentPO::getCompanyId, companyId)
.eq(CrmDocumentPO::getRefType, refType)
.eq(CrmDocumentPO::getRefId, refId)
.eq(CrmDocumentPO::getDocType, docType)
.eq(CrmDocumentPO::getIsLatest, 1)
.last("LIMIT 1"));
}
}
@@ -0,0 +1,62 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.account.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.dto.CreateCrmMailAccountDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.dto.UpdateCrmMailAccountDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.vo.CrmMailAccountVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.service.CrmMailAccountService;
import java.util.List;
/** 发件账户管理。 */
@RestController
@RequestMapping("/api/crm/mail-account")
public class CrmMailAccountController {
private final CrmMailAccountService mailAccountService;
public CrmMailAccountController(CrmMailAccountService mailAccountService) {
this.mailAccountService = mailAccountService;
}
@PostMapping("/create")
@RequirePermission(value = "crm:mail-account:create", description = "创建发件账户")
public ApiResponse<CrmMailAccountVO> create(@Valid @RequestBody CreateCrmMailAccountDTO dto) {
return ApiResponse.success("创建成功", mailAccountService.create(dto));
}
@PutMapping("/update/{id}")
@RequirePermission(value = "crm:mail-account:update", description = "更新发件账户")
public ApiResponse<CrmMailAccountVO> update(
@PathVariable Long id, @Valid @RequestBody UpdateCrmMailAccountDTO dto) {
return ApiResponse.success("更新成功", mailAccountService.update(id, dto));
}
@DeleteMapping("/delete/{id}")
@RequirePermission(value = "crm:mail-account:delete", description = "删除发件账户")
public ApiResponse<Void> delete(@PathVariable Long id) {
mailAccountService.delete(id);
return ApiResponse.success("删除成功");
}
@GetMapping("/{id}")
@RequirePermission(value = "crm:mail-account:read", description = "发件账户详情")
public ApiResponse<CrmMailAccountVO> get(@PathVariable Long id) {
return ApiResponse.success("获取成功", mailAccountService.get(id));
}
@GetMapping("/list")
@RequirePermission(value = "crm:mail-account:read", description = "发件账户列表")
public ApiResponse<List<CrmMailAccountVO>> list() {
return ApiResponse.success("获取成功", mailAccountService.listAll());
}
@GetMapping("/options")
@RequirePermission(value = "crm:mail:send", description = "启用发件账户选项")
public ApiResponse<List<CrmMailAccountVO>> options() {
return ApiResponse.success("获取成功", mailAccountService.listEnabled());
}
}
@@ -0,0 +1,10 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.account.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.po.CrmMailAccountPO;
/** 发件账户 Mapper。 */
@Mapper
public interface CrmMailAccountMapper extends BaseMapper<CrmMailAccountPO> {
}
@@ -0,0 +1,43 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.dto;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
/** 创建发件账户。 */
@Data
public class CreateCrmMailAccountDTO {
@NotBlank
@Size(max = 100)
private String name;
@NotBlank
@Email
@Size(max = 100)
private String fromEmail;
@NotBlank
@Size(max = 200)
private String smtpHost;
@NotNull
private Integer smtpPort;
/** 1=SSL/TLS,0=STARTTLS */
private Integer smtpSsl;
@NotBlank
@Size(max = 200)
private String username;
@NotBlank
@Size(max = 200)
private String password;
private Integer enabled;
private Integer isDefault;
}
@@ -0,0 +1,42 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.dto;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
/** 更新发件账户;password 空则保留原密文。 */
@Data
public class UpdateCrmMailAccountDTO {
@NotBlank
@Size(max = 100)
private String name;
@NotBlank
@Email
@Size(max = 100)
private String fromEmail;
@NotBlank
@Size(max = 200)
private String smtpHost;
@NotNull
private Integer smtpPort;
private Integer smtpSsl;
@NotBlank
@Size(max = 200)
private String username;
/** 留空表示不改密码 */
@Size(max = 200)
private String password;
private Integer enabled;
private Integer isDefault;
}
@@ -0,0 +1,43 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.time.LocalDateTime;
/** 公司 SMTP 发件账户。 */
@Data
@TableName("crm_mail_account")
public class CrmMailAccountPO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("name")
private String name;
@TableField("from_email")
private String fromEmail;
@TableField("smtp_host")
private String smtpHost;
@TableField("smtp_port")
private Integer smtpPort;
@TableField("smtp_ssl")
private Integer smtpSsl;
@TableField("username")
private String username;
@TableField("password_cipher")
private String passwordCipher;
@TableField("enabled")
private Integer enabled;
@TableField("is_default")
private Integer isDefault;
@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;
}
@@ -0,0 +1,23 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.vo;
import lombok.Data;
import java.time.LocalDateTime;
/** 发件账户视图(不含密码)。 */
@Data
public class CrmMailAccountVO {
private Long id;
private Long companyId;
private String name;
private String fromEmail;
private String smtpHost;
private Integer smtpPort;
private Integer smtpSsl;
private String username;
private Integer enabled;
private Integer isDefault;
private Boolean passwordSet;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,30 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.account.service;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.dto.CreateCrmMailAccountDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.dto.UpdateCrmMailAccountDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.po.CrmMailAccountPO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.vo.CrmMailAccountVO;
import java.util.List;
/** 发件账户用例。 */
public interface CrmMailAccountService {
CrmMailAccountVO create(CreateCrmMailAccountDTO dto);
CrmMailAccountVO update(Long id, UpdateCrmMailAccountDTO dto);
void delete(Long id);
CrmMailAccountVO get(Long id);
List<CrmMailAccountVO> listAll();
/** 启用账户下拉(发信用)。 */
List<CrmMailAccountVO> listEnabled();
/** 解析发件账户:指定 id,否则取默认启用账户。 */
CrmMailAccountPO requireForSend(Long companyId, Long accountId);
String decryptPassword(CrmMailAccountPO account);
}
@@ -0,0 +1,196 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.account.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.modules.crm.mail.account.mapper.CrmMailAccountMapper;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.dto.CreateCrmMailAccountDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.dto.UpdateCrmMailAccountDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.po.CrmMailAccountPO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.vo.CrmMailAccountVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.service.CrmMailAccountService;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmSecretCrypto;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.util.List;
/**
* 发件账户:密码入库加密;VO 不回传明文。
*/
@Service
public class CrmMailAccountServiceImpl extends ServiceImpl<CrmMailAccountMapper, CrmMailAccountPO>
implements CrmMailAccountService {
private final CrmSecretCrypto secretCrypto;
private final CurrentUserContext currentUserContext;
public CrmMailAccountServiceImpl(CrmSecretCrypto secretCrypto,
CurrentUserContext currentUserContext) {
this.secretCrypto = secretCrypto;
this.currentUserContext = currentUserContext;
}
@Override
@Transactional
public CrmMailAccountVO create(CreateCrmMailAccountDTO dto) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
CrmMailAccountPO po = new CrmMailAccountPO();
po.setCompanyId(companyId);
applyFields(po, dto.getName(), dto.getFromEmail(), dto.getSmtpHost(), dto.getSmtpPort(),
dto.getSmtpSsl(), dto.getUsername(), dto.getEnabled(), dto.getIsDefault());
po.setPasswordCipher(secretCrypto.encrypt(dto.getPassword()));
po.setCreateBy(userId);
po.setUpdateBy(userId);
this.save(po);
if (Integer.valueOf(1).equals(po.getIsDefault())) {
clearOtherDefaults(companyId, po.getId());
}
return toVo(po);
}
@Override
@Transactional
public CrmMailAccountVO update(Long id, UpdateCrmMailAccountDTO dto) {
CrmMailAccountPO po = requireOwned(id);
applyFields(po, dto.getName(), dto.getFromEmail(), dto.getSmtpHost(), dto.getSmtpPort(),
dto.getSmtpSsl(), dto.getUsername(), dto.getEnabled(), dto.getIsDefault());
if (StringUtils.hasText(dto.getPassword())) {
po.setPasswordCipher(secretCrypto.encrypt(dto.getPassword().trim()));
}
po.setUpdateBy(currentUserContext.getCurrentUserId());
this.updateById(po);
if (Integer.valueOf(1).equals(po.getIsDefault())) {
clearOtherDefaults(po.getCompanyId(), po.getId());
}
return toVo(po);
}
@Override
@Transactional
public void delete(Long id) {
requireOwned(id);
this.removeById(id);
}
@Override
public CrmMailAccountVO get(Long id) {
return toVo(requireOwned(id));
}
@Override
public List<CrmMailAccountVO> listAll() {
Long companyId = requireCompanyId();
return this.list(new LambdaQueryWrapper<CrmMailAccountPO>()
.eq(CrmMailAccountPO::getCompanyId, companyId)
.orderByDesc(CrmMailAccountPO::getIsDefault)
.orderByDesc(CrmMailAccountPO::getId))
.stream().map(this::toVo).toList();
}
@Override
public List<CrmMailAccountVO> listEnabled() {
Long companyId = requireCompanyId();
return this.list(new LambdaQueryWrapper<CrmMailAccountPO>()
.eq(CrmMailAccountPO::getCompanyId, companyId)
.eq(CrmMailAccountPO::getEnabled, 1)
.orderByDesc(CrmMailAccountPO::getIsDefault)
.orderByDesc(CrmMailAccountPO::getId))
.stream().map(this::toVo).toList();
}
@Override
public CrmMailAccountPO requireForSend(Long companyId, Long accountId) {
CrmMailAccountPO account;
if (accountId != null) {
account = this.getById(accountId);
if (account == null || !companyId.equals(account.getCompanyId())) {
throw new BusinessException("发件账户不存在");
}
} else {
account = this.getOne(new LambdaQueryWrapper<CrmMailAccountPO>()
.eq(CrmMailAccountPO::getCompanyId, companyId)
.eq(CrmMailAccountPO::getEnabled, 1)
.eq(CrmMailAccountPO::getIsDefault, 1)
.last("LIMIT 1"));
if (account == null) {
account = this.getOne(new LambdaQueryWrapper<CrmMailAccountPO>()
.eq(CrmMailAccountPO::getCompanyId, companyId)
.eq(CrmMailAccountPO::getEnabled, 1)
.orderByDesc(CrmMailAccountPO::getId)
.last("LIMIT 1"));
}
}
if (account == null) {
throw new BusinessException("请先配置启用的发件账户");
}
if (!Integer.valueOf(1).equals(account.getEnabled())) {
throw new BusinessException("发件账户未启用");
}
return account;
}
@Override
public String decryptPassword(CrmMailAccountPO account) {
return secretCrypto.decrypt(account.getPasswordCipher());
}
private void clearOtherDefaults(Long companyId, Long keepId) {
this.update(null, new LambdaUpdateWrapper<CrmMailAccountPO>()
.eq(CrmMailAccountPO::getCompanyId, companyId)
.ne(CrmMailAccountPO::getId, keepId)
.eq(CrmMailAccountPO::getIsDefault, 1)
.set(CrmMailAccountPO::getIsDefault, 0));
}
private void applyFields(CrmMailAccountPO po, String name, String fromEmail, String host,
Integer port, Integer ssl, String username, Integer enabled, Integer isDefault) {
po.setName(name.trim());
po.setFromEmail(fromEmail.trim());
po.setSmtpHost(host.trim());
po.setSmtpPort(port != null && port > 0 ? port : 465);
po.setSmtpSsl(ssl == null || ssl == 1 ? 1 : 0);
po.setUsername(username.trim());
po.setEnabled(enabled == null || enabled == 1 ? 1 : 0);
po.setIsDefault(isDefault != null && isDefault == 1 ? 1 : 0);
}
private CrmMailAccountVO toVo(CrmMailAccountPO po) {
CrmMailAccountVO vo = new CrmMailAccountVO();
vo.setId(po.getId());
vo.setCompanyId(po.getCompanyId());
vo.setName(po.getName());
vo.setFromEmail(po.getFromEmail());
vo.setSmtpHost(po.getSmtpHost());
vo.setSmtpPort(po.getSmtpPort());
vo.setSmtpSsl(po.getSmtpSsl());
vo.setUsername(po.getUsername());
vo.setEnabled(po.getEnabled());
vo.setIsDefault(po.getIsDefault());
vo.setPasswordSet(StringUtils.hasText(po.getPasswordCipher()));
vo.setCreateTime(po.getCreateTime());
vo.setUpdateTime(po.getUpdateTime());
return vo;
}
private CrmMailAccountPO requireOwned(Long id) {
Long companyId = requireCompanyId();
CrmMailAccountPO po = this.getById(id);
if (po == null || !companyId.equals(po.getCompanyId())) {
throw new BusinessException("发件账户不存在");
}
return po;
}
private Long requireCompanyId() {
Long companyId = currentUserContext.getCurrentCompanyId();
if (companyId == null) {
throw new BusinessException("请先选择公司");
}
return companyId;
}
}
@@ -0,0 +1,36 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.log.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.mail.log.model.dto.CrmMailLogFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.vo.CrmMailLogVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.service.CrmMailLogService;
/** 邮件发送记录。 */
@RestController
@RequestMapping("/api/crm/mail-log")
public class CrmMailLogController {
private final CrmMailLogService mailLogService;
public CrmMailLogController(CrmMailLogService mailLogService) {
this.mailLogService = mailLogService;
}
@PostMapping("/list")
@RequirePermission(value = "crm:mail-log:read", description = "发送记录列表")
public ApiResponse<PageResultVO<CrmMailLogVO>> list(
@Valid @RequestBody PageQueryDTO<CrmMailLogFilterDTO> query) {
return ApiResponse.success("获取成功", mailLogService.page(query));
}
@GetMapping("/{id}")
@RequirePermission(value = "crm:mail-log:read", description = "发送记录详情")
public ApiResponse<CrmMailLogVO> get(@PathVariable Long id) {
return ApiResponse.success("获取成功", mailLogService.get(id));
}
}
@@ -0,0 +1,10 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.log.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.po.CrmMailLogPO;
/** 发送记录 Mapper。 */
@Mapper
public interface CrmMailLogMapper extends BaseMapper<CrmMailLogPO> {
}
@@ -0,0 +1,13 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.dto;
import lombok.Data;
/** 发送记录筛选。 */
@Data
public class CrmMailLogFilterDTO {
private String keyword;
private String status;
private Long customerId;
private String refType;
private Long refId;
}
@@ -0,0 +1,45 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.time.LocalDateTime;
/** 邮件发送记录。 */
@Data
@TableName("crm_mail_log")
public class CrmMailLogPO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("account_id")
private Long accountId;
@TableField("template_id")
private Long templateId;
@TableField("customer_id")
private Long customerId;
@TableField("ref_type")
private String refType;
@TableField("ref_id")
private Long refId;
@TableField("to_email")
private String toEmail;
@TableField("cc_email")
private String ccEmail;
@TableField("subject")
private String subject;
@TableField("body_html")
private String bodyHtml;
@TableField("status")
private String status;
@TableField("error_message")
private String errorMessage;
@TableField("sent_at")
private LocalDateTime sentAt;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField("create_by")
private Long createBy;
}
@@ -0,0 +1,29 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.vo;
import lombok.Data;
import java.time.LocalDateTime;
/** 发送记录视图。 */
@Data
public class CrmMailLogVO {
private Long id;
private Long companyId;
private Long accountId;
private String accountName;
private Long templateId;
private String templateName;
private Long customerId;
private String customerName;
private String refType;
private Long refId;
private String toEmail;
private String ccEmail;
private String subject;
private String bodyHtml;
private String status;
private String errorMessage;
private LocalDateTime sentAt;
private LocalDateTime createTime;
private Long createBy;
}
@@ -0,0 +1,17 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.log.service;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.dto.CrmMailLogFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.po.CrmMailLogPO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.vo.CrmMailLogVO;
/** 发送记录查询与落库。 */
public interface CrmMailLogService {
PageResultVO<CrmMailLogVO> page(PageQueryDTO<CrmMailLogFilterDTO> query);
CrmMailLogVO get(Long id);
void insertLog(CrmMailLogPO log);
}
@@ -0,0 +1,183 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.log.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.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.mail.account.mapper.CrmMailAccountMapper;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.po.CrmMailAccountPO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.mapper.CrmMailLogMapper;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.dto.CrmMailLogFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.po.CrmMailLogPO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.vo.CrmMailLogVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.service.CrmMailLogService;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.mapper.CrmMailTemplateMapper;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.po.CrmMailTemplatePO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.util.*;
import java.util.stream.Collectors;
/** 发送记录:只读列表 + 写入。 */
@Service
public class CrmMailLogServiceImpl extends ServiceImpl<CrmMailLogMapper, CrmMailLogPO>
implements CrmMailLogService {
private final CrmCustomerMapper customerMapper;
private final CrmMailAccountMapper accountMapper;
private final CrmMailTemplateMapper templateMapper;
private final CurrentUserContext currentUserContext;
public CrmMailLogServiceImpl(CrmCustomerMapper customerMapper,
CrmMailAccountMapper accountMapper,
CrmMailTemplateMapper templateMapper,
CurrentUserContext currentUserContext) {
this.customerMapper = customerMapper;
this.accountMapper = accountMapper;
this.templateMapper = templateMapper;
this.currentUserContext = currentUserContext;
}
@Override
public PageResultVO<CrmMailLogVO> page(PageQueryDTO<CrmMailLogFilterDTO> query) {
Long companyId = requireCompanyId();
CrmMailLogFilterDTO filters =
query.getFilters() != null ? query.getFilters() : new CrmMailLogFilterDTO();
LambdaQueryWrapper<CrmMailLogPO> w = new LambdaQueryWrapper<>();
w.eq(CrmMailLogPO::getCompanyId, companyId);
if (StringUtils.hasText(filters.getStatus())) {
w.eq(CrmMailLogPO::getStatus, filters.getStatus().trim());
}
if (filters.getCustomerId() != null) {
w.eq(CrmMailLogPO::getCustomerId, filters.getCustomerId());
}
if (StringUtils.hasText(filters.getRefType())) {
w.eq(CrmMailLogPO::getRefType, filters.getRefType().trim());
}
if (filters.getRefId() != null) {
w.eq(CrmMailLogPO::getRefId, filters.getRefId());
}
if (StringUtils.hasText(filters.getKeyword())) {
String kw = filters.getKeyword().trim();
w.and(x -> x.like(CrmMailLogPO::getToEmail, kw)
.or().like(CrmMailLogPO::getSubject, kw));
}
w.orderByDesc(CrmMailLogPO::getId);
IPage<CrmMailLogPO> page = this.page(new Page<>(query.getPage(), query.getPageSize()), w);
Set<Long> customerIds = page.getRecords().stream()
.map(CrmMailLogPO::getCustomerId).filter(Objects::nonNull).collect(Collectors.toSet());
Set<Long> accountIds = page.getRecords().stream()
.map(CrmMailLogPO::getAccountId).filter(Objects::nonNull).collect(Collectors.toSet());
Set<Long> templateIds = page.getRecords().stream()
.map(CrmMailLogPO::getTemplateId).filter(Objects::nonNull).collect(Collectors.toSet());
Map<Long, String> customers = loadCustomerNames(companyId, customerIds);
Map<Long, String> accounts = loadAccountNames(companyId, accountIds);
Map<Long, String> templates = loadTemplateNames(companyId, templateIds);
List<CrmMailLogVO> records = page.getRecords().stream().map(log -> {
CrmMailLogVO vo = toVo(log);
if (log.getCustomerId() != null) {
vo.setCustomerName(customers.get(log.getCustomerId()));
}
if (log.getAccountId() != null) {
vo.setAccountName(accounts.get(log.getAccountId()));
}
if (log.getTemplateId() != null) {
vo.setTemplateName(templates.get(log.getTemplateId()));
}
return vo;
}).toList();
return PageResultVO.create(records, page.getTotal(), query.getPage(), query.getPageSize());
}
@Override
public CrmMailLogVO get(Long id) {
Long companyId = requireCompanyId();
CrmMailLogPO log = this.getById(id);
if (log == null || !companyId.equals(log.getCompanyId())) {
throw new BusinessException("发送记录不存在");
}
CrmMailLogVO vo = toVo(log);
if (log.getCustomerId() != null) {
CrmCustomerPO c = customerMapper.selectById(log.getCustomerId());
if (c != null) {
vo.setCustomerName(c.getName());
}
}
if (log.getAccountId() != null) {
CrmMailAccountPO a = accountMapper.selectById(log.getAccountId());
if (a != null) {
vo.setAccountName(a.getName());
}
}
if (log.getTemplateId() != null) {
CrmMailTemplatePO t = templateMapper.selectById(log.getTemplateId());
if (t != null) {
vo.setTemplateName(t.getName());
}
}
return vo;
}
@Override
public void insertLog(CrmMailLogPO log) {
this.baseMapper.insert(log);
}
private CrmMailLogVO toVo(CrmMailLogPO po) {
CrmMailLogVO vo = new CrmMailLogVO();
BeanCopyUtils.copyProperties(po, vo);
return vo;
}
private Map<Long, String> loadCustomerNames(Long companyId, Set<Long> ids) {
if (ids.isEmpty()) {
return Map.of();
}
return customerMapper.selectList(new LambdaQueryWrapper<CrmCustomerPO>()
.eq(CrmCustomerPO::getCompanyId, companyId)
.in(CrmCustomerPO::getId, ids))
.stream()
.collect(Collectors.toMap(CrmCustomerPO::getId, CrmCustomerPO::getName, (a, b) -> a));
}
private Map<Long, String> loadAccountNames(Long companyId, Set<Long> ids) {
if (ids.isEmpty()) {
return Map.of();
}
return accountMapper.selectList(new LambdaQueryWrapper<CrmMailAccountPO>()
.eq(CrmMailAccountPO::getCompanyId, companyId)
.in(CrmMailAccountPO::getId, ids))
.stream()
.collect(Collectors.toMap(CrmMailAccountPO::getId, CrmMailAccountPO::getName, (a, b) -> a));
}
private Map<Long, String> loadTemplateNames(Long companyId, Set<Long> ids) {
if (ids.isEmpty()) {
return Map.of();
}
return templateMapper.selectList(new LambdaQueryWrapper<CrmMailTemplatePO>()
.eq(CrmMailTemplatePO::getCompanyId, companyId)
.in(CrmMailTemplatePO::getId, ids))
.stream()
.collect(Collectors.toMap(CrmMailTemplatePO::getId, CrmMailTemplatePO::getName, (a, b) -> a));
}
private Long requireCompanyId() {
Long companyId = currentUserContext.getCurrentCompanyId();
if (companyId == null) {
throw new BusinessException("请先选择公司");
}
return companyId;
}
}
@@ -0,0 +1,35 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.send.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.vo.CrmMailLogVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.dto.CrmMailPreviewDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.dto.CrmMailSendDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.vo.CrmMailPreviewVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.service.CrmMailSendService;
/** 手发邮件:预览与确认发送。 */
@RestController
@RequestMapping("/api/crm/mail")
public class CrmMailSendController {
private final CrmMailSendService mailSendService;
public CrmMailSendController(CrmMailSendService mailSendService) {
this.mailSendService = mailSendService;
}
@PostMapping("/preview")
@RequirePermission(value = "crm:mail:send", description = "预览邮件")
public ApiResponse<CrmMailPreviewVO> preview(@Valid @RequestBody CrmMailPreviewDTO dto) {
return ApiResponse.success("预览成功", mailSendService.preview(dto));
}
@PostMapping("/send")
@RequirePermission(value = "crm:mail:send", description = "发送邮件")
public ApiResponse<CrmMailLogVO> send(@Valid @RequestBody CrmMailSendDTO dto) {
return ApiResponse.success("发送成功", mailSendService.send(dto));
}
}
@@ -0,0 +1,20 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.dto;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
/** 预览:模板 + 客户/业务单上下文。 */
@Data
public class CrmMailPreviewDTO {
@NotNull(message = "模板不能为空")
private Long templateId;
@NotNull(message = "客户不能为空")
private Long customerId;
/** quote / shipment,可空 */
private String refType;
private Long refId;
}
@@ -0,0 +1,39 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.dto;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
/** 确认发送:用户可改主题/正文后再发。 */
@Data
public class CrmMailSendDTO {
/** 空则用默认发件账户 */
private Long accountId;
private Long templateId;
@NotNull(message = "客户不能为空")
private Long customerId;
private String refType;
private Long refId;
@NotBlank
@Email
@Size(max = 200)
private String toEmail;
@Size(max = 500)
private String ccEmail;
@NotBlank
@Size(max = 500)
private String subject;
@NotBlank
private String bodyHtml;
}
@@ -0,0 +1,18 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.vo;
import lombok.Data;
import java.util.Map;
/** 预览结果(已替换变量)。 */
@Data
public class CrmMailPreviewVO {
private Long templateId;
private String templateName;
private String scene;
private Long customerId;
private String toEmail;
private String subject;
private String bodyHtml;
private Map<String, String> variables;
}
@@ -0,0 +1,14 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.send.service;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.vo.CrmMailLogVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.dto.CrmMailPreviewDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.dto.CrmMailSendDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.vo.CrmMailPreviewVO;
/** 手发邮件:预览变量 → 确认发送 → 写日志。 */
public interface CrmMailSendService {
CrmMailPreviewVO preview(CrmMailPreviewDTO dto);
CrmMailLogVO send(CrmMailSendDTO dto);
}
@@ -0,0 +1,276 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.send.service.impl;
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.modules.crm.customer.mapper.CrmCustomerMapper;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.po.CrmCustomerPO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.po.CrmMailAccountPO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.service.CrmMailAccountService;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.po.CrmMailLogPO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.vo.CrmMailLogVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.service.CrmMailLogService;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.dto.CrmMailPreviewDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.dto.CrmMailSendDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.vo.CrmMailPreviewVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.service.CrmMailSendService;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.po.CrmMailTemplatePO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.service.CrmMailTemplateService;
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.CrmQuoteMapper;
import top.xyquan.ecomdmbbackend.modules.crm.quote.model.po.CrmQuotePO;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.mapper.CrmShipmentMapper;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.po.CrmShipmentPO;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmMailVariableRenderer;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmSmtpClient;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
/**
* 邮件发送编排:拼变量 → SMTP → 落 crm_mail_log(成功/失败均记)。
*/
@Service
public class CrmMailSendServiceImpl implements CrmMailSendService {
private final CrmMailTemplateService templateService;
private final CrmMailAccountService accountService;
private final CrmMailLogService mailLogService;
private final CrmCustomerMapper customerMapper;
private final CrmQuoteMapper quoteMapper;
private final CrmShipmentMapper shipmentMapper;
private final CrmCompanyProfileService profileService;
private final CrmMailVariableRenderer variableRenderer;
private final CrmSmtpClient smtpClient;
private final CurrentUserContext currentUserContext;
public CrmMailSendServiceImpl(CrmMailTemplateService templateService,
CrmMailAccountService accountService,
CrmMailLogService mailLogService,
CrmCustomerMapper customerMapper,
CrmQuoteMapper quoteMapper,
CrmShipmentMapper shipmentMapper,
CrmCompanyProfileService profileService,
CrmMailVariableRenderer variableRenderer,
CrmSmtpClient smtpClient,
CurrentUserContext currentUserContext) {
this.templateService = templateService;
this.accountService = accountService;
this.mailLogService = mailLogService;
this.customerMapper = customerMapper;
this.quoteMapper = quoteMapper;
this.shipmentMapper = shipmentMapper;
this.profileService = profileService;
this.variableRenderer = variableRenderer;
this.smtpClient = smtpClient;
this.currentUserContext = currentUserContext;
}
@Override
public CrmMailPreviewVO preview(CrmMailPreviewDTO dto) {
Long companyId = requireCompanyId();
CrmMailTemplatePO template = templateService.requireOwned(companyId, dto.getTemplateId());
CrmCustomerPO customer = requireCustomer(companyId, dto.getCustomerId());
Map<String, String> vars = buildVariables(companyId, customer, dto.getRefType(), dto.getRefId());
CrmMailPreviewVO vo = new CrmMailPreviewVO();
vo.setTemplateId(template.getId());
vo.setTemplateName(template.getName());
vo.setScene(template.getScene());
vo.setCustomerId(customer.getId());
vo.setToEmail(customer.getEmail());
vo.setSubject(variableRenderer.render(template.getSubject(), vars));
vo.setBodyHtml(variableRenderer.render(template.getBodyHtml(), vars));
vo.setVariables(vars);
return vo;
}
@Override
@Transactional
public CrmMailLogVO send(CrmMailSendDTO dto) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
requireCustomer(companyId, dto.getCustomerId());
if (dto.getTemplateId() != null) {
templateService.requireOwned(companyId, dto.getTemplateId());
}
validateRef(companyId, dto.getCustomerId(), dto.getRefType(), dto.getRefId());
CrmMailAccountPO account = accountService.requireForSend(companyId, dto.getAccountId());
String password = accountService.decryptPassword(account);
CrmMailLogPO log = new CrmMailLogPO();
log.setCompanyId(companyId);
log.setAccountId(account.getId());
log.setTemplateId(dto.getTemplateId());
log.setCustomerId(dto.getCustomerId());
log.setRefType(trimToNull(dto.getRefType()));
log.setRefId(dto.getRefId());
log.setToEmail(dto.getToEmail().trim());
log.setCcEmail(trimToNull(dto.getCcEmail()));
log.setSubject(dto.getSubject().trim());
log.setBodyHtml(dto.getBodyHtml());
log.setCreateBy(userId);
try {
smtpClient.send(
new CrmSmtpClient.SmtpAccount(
account.getName(),
account.getFromEmail(),
account.getSmtpHost(),
account.getSmtpPort(),
Integer.valueOf(1).equals(account.getSmtpSsl()),
account.getUsername(),
password),
log.getToEmail(),
log.getCcEmail(),
log.getSubject(),
log.getBodyHtml());
log.setStatus("success");
log.setSentAt(LocalDateTime.now());
} catch (Exception e) {
log.setStatus("failed");
String msg = e.getMessage();
if (msg != null && msg.length() > 1000) {
msg = msg.substring(0, 1000);
}
log.setErrorMessage(msg);
mailLogService.insertLog(log);
throw new BusinessException("发送失败: " + e.getMessage());
}
mailLogService.insertLog(log);
return mailLogService.get(log.getId());
}
private Map<String, String> buildVariables(Long companyId, CrmCustomerPO customer,
String refType, Long refId) {
Map<String, String> vars = new LinkedHashMap<>();
vars.put("customerName", nz(firstNonBlank(customer.getNameEn(), customer.getName())));
vars.put("contactName", nz(customer.getContactName()));
vars.put("customerEmail", nz(customer.getEmail()));
vars.put("customerCountry", nz(customer.getCountry()));
vars.put("customerPhone", nz(customer.getPhone()));
CrmCompanyProfileVO profile = profileService.getCurrent();
vars.put("companyName", nz(firstNonBlank(profile.getLegalNameEn(), profile.getLegalNameZh())));
vars.put("companyEmail", nz(profile.getEmail()));
vars.put("companyPhone", nz(profile.getPhone()));
vars.put("quoteNo", "");
vars.put("quoteDate", "");
vars.put("totalAmount", "");
vars.put("currency", nz(customer.getCurrency()));
vars.put("incoterm", "");
vars.put("shipmentNo", "");
vars.put("destinationPort", "");
vars.put("planShipDate", "");
if (!StringUtils.hasText(refType) || refId == null) {
return vars;
}
String type = refType.trim().toLowerCase(Locale.ROOT);
if ("quote".equals(type)) {
CrmQuotePO quote = quoteMapper.selectById(refId);
if (quote == null || !companyId.equals(quote.getCompanyId())) {
throw new BusinessException("报价不存在");
}
if (!customer.getId().equals(quote.getCustomerId())) {
throw new BusinessException("报价与客户不匹配");
}
vars.put("quoteNo", nz(quote.getQuoteNo()));
vars.put("quoteDate", quote.getQuoteDate() != null ? quote.getQuoteDate().toString() : "");
vars.put("totalAmount", quote.getTotalAmount() != null ? quote.getTotalAmount().toPlainString() : "");
vars.put("currency", nz(quote.getCurrency()));
vars.put("incoterm", nz(quote.getIncoterm()));
} else if ("shipment".equals(type)) {
CrmShipmentPO ship = shipmentMapper.selectById(refId);
if (ship == null || !companyId.equals(ship.getCompanyId())) {
throw new BusinessException("出货单不存在");
}
if (!customer.getId().equals(ship.getCustomerId())) {
throw new BusinessException("出货与客户不匹配");
}
vars.put("shipmentNo", nz(ship.getShipmentNo()));
vars.put("destinationPort", nz(ship.getDestinationPort()));
vars.put("planShipDate",
ship.getPlanShipDate() != null ? ship.getPlanShipDate().toString() : "");
vars.put("totalAmount", ship.getTotalAmount() != null ? ship.getTotalAmount().toPlainString() : "");
vars.put("currency", nz(ship.getCurrency()));
vars.put("incoterm", nz(ship.getIncoterm()));
if (ship.getQuoteId() != null) {
CrmQuotePO quote = quoteMapper.selectById(ship.getQuoteId());
if (quote != null) {
vars.put("quoteNo", nz(quote.getQuoteNo()));
}
}
}
return vars;
}
private void validateRef(Long companyId, Long customerId, String refType, Long refId) {
if (!StringUtils.hasText(refType) && refId == null) {
return;
}
if (!StringUtils.hasText(refType) || refId == null) {
throw new BusinessException("关联业务单类型与 ID 需同时提供");
}
String type = refType.trim().toLowerCase(Locale.ROOT);
if ("quote".equals(type)) {
CrmQuotePO quote = quoteMapper.selectById(refId);
if (quote == null || !companyId.equals(quote.getCompanyId())
|| !customerId.equals(quote.getCustomerId())) {
throw new BusinessException("关联报价无效");
}
} else if ("shipment".equals(type)) {
CrmShipmentPO ship = shipmentMapper.selectById(refId);
if (ship == null || !companyId.equals(ship.getCompanyId())
|| !customerId.equals(ship.getCustomerId())) {
throw new BusinessException("关联出货无效");
}
} else {
throw new BusinessException("不支持的关联类型: " + refType);
}
}
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 Long requireCompanyId() {
Long companyId = currentUserContext.getCurrentCompanyId();
if (companyId == null) {
throw new BusinessException("请先选择公司");
}
return companyId;
}
private static String nz(String s) {
return s == null ? "" : s;
}
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 "";
}
}
@@ -0,0 +1,67 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.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.mail.template.model.dto.CreateCrmMailTemplateDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto.CrmMailTemplateFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto.UpdateCrmMailTemplateDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.vo.CrmMailTemplateVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.service.CrmMailTemplateService;
import java.util.List;
/** 邮件模板管理。 */
@RestController
@RequestMapping("/api/crm/mail-template")
public class CrmMailTemplateController {
private final CrmMailTemplateService mailTemplateService;
public CrmMailTemplateController(CrmMailTemplateService mailTemplateService) {
this.mailTemplateService = mailTemplateService;
}
@PostMapping("/create")
@RequirePermission(value = "crm:mail-template:create", description = "创建邮件模板")
public ApiResponse<CrmMailTemplateVO> create(@Valid @RequestBody CreateCrmMailTemplateDTO dto) {
return ApiResponse.success("创建成功", mailTemplateService.create(dto));
}
@PutMapping("/update/{id}")
@RequirePermission(value = "crm:mail-template:update", description = "更新邮件模板")
public ApiResponse<CrmMailTemplateVO> update(
@PathVariable Long id, @Valid @RequestBody UpdateCrmMailTemplateDTO dto) {
return ApiResponse.success("更新成功", mailTemplateService.update(id, dto));
}
@DeleteMapping("/delete/{id}")
@RequirePermission(value = "crm:mail-template:delete", description = "删除邮件模板")
public ApiResponse<Void> delete(@PathVariable Long id) {
mailTemplateService.delete(id);
return ApiResponse.success("删除成功");
}
@GetMapping("/{id}")
@RequirePermission(value = "crm:mail-template:read", description = "邮件模板详情")
public ApiResponse<CrmMailTemplateVO> get(@PathVariable Long id) {
return ApiResponse.success("获取成功", mailTemplateService.get(id));
}
@PostMapping("/list")
@RequirePermission(value = "crm:mail-template:read", description = "邮件模板列表")
public ApiResponse<PageResultVO<CrmMailTemplateVO>> list(
@Valid @RequestBody PageQueryDTO<CrmMailTemplateFilterDTO> query) {
return ApiResponse.success("获取成功", mailTemplateService.page(query));
}
@GetMapping("/options")
@RequirePermission(value = "crm:mail:send", description = "启用模板选项")
public ApiResponse<List<CrmMailTemplateVO>> options(
@RequestParam(required = false) String scene) {
return ApiResponse.success("获取成功", mailTemplateService.listEnabled(scene));
}
}
@@ -0,0 +1,10 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.po.CrmMailTemplatePO;
/** 邮件模板 Mapper。 */
@Mapper
public interface CrmMailTemplateMapper extends BaseMapper<CrmMailTemplatePO> {
}
@@ -0,0 +1,30 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
/** 创建邮件模板。 */
@Data
public class CreateCrmMailTemplateDTO {
@NotBlank
@Size(max = 100)
private String name;
@NotBlank
@Size(max = 32)
private String scene;
@NotBlank
@Size(max = 500)
private String subject;
@NotBlank
private String bodyHtml;
private Integer enabled;
@Size(max = 500)
private String remark;
}
@@ -0,0 +1,11 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto;
import lombok.Data;
/** 模板列表筛选。 */
@Data
public class CrmMailTemplateFilterDTO {
private String keyword;
private String scene;
private Integer enabled;
}
@@ -0,0 +1,30 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
/** 更新邮件模板。 */
@Data
public class UpdateCrmMailTemplateDTO {
@NotBlank
@Size(max = 100)
private String name;
@NotBlank
@Size(max = 32)
private String scene;
@NotBlank
@Size(max = 500)
private String subject;
@NotBlank
private String bodyHtml;
private Integer enabled;
@Size(max = 500)
private String remark;
}
@@ -0,0 +1,42 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.time.LocalDateTime;
/** 邮件模板。 */
@Data
@TableName("crm_mail_template")
public class CrmMailTemplatePO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("name")
private String name;
@TableField("scene")
private String scene;
@TableField("subject")
private String subject;
@TableField("body_html")
private String bodyHtml;
@TableField("enabled")
private Integer enabled;
@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;
}
@@ -0,0 +1,20 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.vo;
import lombok.Data;
import java.time.LocalDateTime;
/** 邮件模板视图。 */
@Data
public class CrmMailTemplateVO {
private Long id;
private Long companyId;
private String name;
private String scene;
private String subject;
private String bodyHtml;
private Integer enabled;
private String remark;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,30 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.service;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto.CreateCrmMailTemplateDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto.CrmMailTemplateFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto.UpdateCrmMailTemplateDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.po.CrmMailTemplatePO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.vo.CrmMailTemplateVO;
import java.util.List;
/** 邮件模板用例。 */
public interface CrmMailTemplateService {
CrmMailTemplateVO create(CreateCrmMailTemplateDTO dto);
CrmMailTemplateVO update(Long id, UpdateCrmMailTemplateDTO dto);
void delete(Long id);
CrmMailTemplateVO get(Long id);
PageResultVO<CrmMailTemplateVO> page(PageQueryDTO<CrmMailTemplateFilterDTO> query);
/** 启用模板下拉(发信用)。 */
List<CrmMailTemplateVO> listEnabled(String scene);
CrmMailTemplatePO requireOwned(Long companyId, Long id);
}
@@ -0,0 +1,157 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.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.mail.template.mapper.CrmMailTemplateMapper;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto.CreateCrmMailTemplateDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto.CrmMailTemplateFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto.UpdateCrmMailTemplateDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.po.CrmMailTemplatePO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.vo.CrmMailTemplateVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.service.CrmMailTemplateService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.util.List;
import java.util.Locale;
import java.util.Set;
/** 邮件模板 CRUD。 */
@Service
public class CrmMailTemplateServiceImpl extends ServiceImpl<CrmMailTemplateMapper, CrmMailTemplatePO>
implements CrmMailTemplateService {
private static final Set<String> SCENES = Set.of("outreach", "quote_followup", "shipment_notice");
private final CurrentUserContext currentUserContext;
public CrmMailTemplateServiceImpl(CurrentUserContext currentUserContext) {
this.currentUserContext = currentUserContext;
}
@Override
@Transactional
public CrmMailTemplateVO create(CreateCrmMailTemplateDTO dto) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
CrmMailTemplatePO po = new CrmMailTemplatePO();
po.setCompanyId(companyId);
apply(po, dto.getName(), dto.getScene(), dto.getSubject(), dto.getBodyHtml(),
dto.getEnabled(), dto.getRemark());
po.setCreateBy(userId);
po.setUpdateBy(userId);
this.save(po);
return toVo(po);
}
@Override
@Transactional
public CrmMailTemplateVO update(Long id, UpdateCrmMailTemplateDTO dto) {
CrmMailTemplatePO po = requireOwnedLocal(id);
apply(po, dto.getName(), dto.getScene(), dto.getSubject(), dto.getBodyHtml(),
dto.getEnabled(), dto.getRemark());
po.setUpdateBy(currentUserContext.getCurrentUserId());
this.updateById(po);
return toVo(po);
}
@Override
@Transactional
public void delete(Long id) {
CrmMailTemplatePO po = requireOwnedLocal(id);
po.setDeleteBy(currentUserContext.getCurrentUserId());
this.updateById(po);
this.removeById(id);
}
@Override
public CrmMailTemplateVO get(Long id) {
return toVo(requireOwnedLocal(id));
}
@Override
public PageResultVO<CrmMailTemplateVO> page(PageQueryDTO<CrmMailTemplateFilterDTO> query) {
Long companyId = requireCompanyId();
CrmMailTemplateFilterDTO filters =
query.getFilters() != null ? query.getFilters() : new CrmMailTemplateFilterDTO();
LambdaQueryWrapper<CrmMailTemplatePO> w = new LambdaQueryWrapper<>();
w.eq(CrmMailTemplatePO::getCompanyId, companyId);
if (StringUtils.hasText(filters.getScene())) {
w.eq(CrmMailTemplatePO::getScene, filters.getScene().trim());
}
if (filters.getEnabled() != null) {
w.eq(CrmMailTemplatePO::getEnabled, filters.getEnabled());
}
if (StringUtils.hasText(filters.getKeyword())) {
String kw = filters.getKeyword().trim();
w.and(x -> x.like(CrmMailTemplatePO::getName, kw)
.or().like(CrmMailTemplatePO::getSubject, kw));
}
w.orderByDesc(CrmMailTemplatePO::getId);
IPage<CrmMailTemplatePO> page = this.page(new Page<>(query.getPage(), query.getPageSize()), w);
List<CrmMailTemplateVO> records = page.getRecords().stream().map(this::toVo).toList();
return PageResultVO.create(records, page.getTotal(), query.getPage(), query.getPageSize());
}
@Override
public List<CrmMailTemplateVO> listEnabled(String scene) {
Long companyId = requireCompanyId();
LambdaQueryWrapper<CrmMailTemplatePO> w = new LambdaQueryWrapper<>();
w.eq(CrmMailTemplatePO::getCompanyId, companyId)
.eq(CrmMailTemplatePO::getEnabled, 1);
if (StringUtils.hasText(scene)) {
w.eq(CrmMailTemplatePO::getScene, scene.trim());
}
w.orderByDesc(CrmMailTemplatePO::getId);
return this.list(w).stream().map(this::toVo).toList();
}
@Override
public CrmMailTemplatePO requireOwned(Long companyId, Long id) {
CrmMailTemplatePO po = this.getById(id);
if (po == null || !companyId.equals(po.getCompanyId())) {
throw new BusinessException("邮件模板不存在");
}
return po;
}
private void apply(CrmMailTemplatePO po, String name, String scene, String subject,
String bodyHtml, Integer enabled, String remark) {
String sceneNorm = scene.trim().toLowerCase(Locale.ROOT);
if (!SCENES.contains(sceneNorm)) {
throw new BusinessException("场景不合法,可用: outreach / quote_followup / shipment_notice");
}
po.setName(name.trim());
po.setScene(sceneNorm);
po.setSubject(subject.trim());
po.setBodyHtml(bodyHtml);
po.setEnabled(enabled == null || enabled == 1 ? 1 : 0);
po.setRemark(StringUtils.hasText(remark) ? remark.trim() : null);
}
private CrmMailTemplateVO toVo(CrmMailTemplatePO po) {
CrmMailTemplateVO vo = new CrmMailTemplateVO();
BeanCopyUtils.copyProperties(po, vo);
return vo;
}
private CrmMailTemplatePO requireOwnedLocal(Long id) {
return requireOwned(requireCompanyId(), id);
}
private Long requireCompanyId() {
Long companyId = currentUserContext.getCurrentCompanyId();
if (companyId == null) {
throw new BusinessException("请先选择公司");
}
return companyId;
}
}
@@ -0,0 +1,81 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.controller;
import jakarta.validation.Valid;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
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.product.model.dto.CreateCrmProductDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.dto.CrmProductFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.dto.UpdateCrmProductDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.vo.CrmProductVO;
import top.xyquan.ecomdmbbackend.modules.crm.product.service.CrmProductService;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmImportResultVO;
/**
* 产品管理接口。
*/
@RestController
@RequestMapping("/api/crm/product")
public class CrmProductController {
private final CrmProductService crmProductService;
public CrmProductController(CrmProductService crmProductService) {
this.crmProductService = crmProductService;
}
@PostMapping("/create")
@RequirePermission(value = "crm:product:create", description = "创建产品")
public ApiResponse<CrmProductVO> create(@Valid @RequestBody CreateCrmProductDTO dto) {
return ApiResponse.success("创建成功", crmProductService.create(dto));
}
@PutMapping("/update/{id}")
@RequirePermission(value = "crm:product:update", description = "更新产品")
public ApiResponse<CrmProductVO> update(@PathVariable Long id, @Valid @RequestBody UpdateCrmProductDTO dto) {
return ApiResponse.success("更新成功", crmProductService.update(id, dto));
}
@DeleteMapping("/delete/{id}")
@RequirePermission(value = "crm:product:delete", description = "删除产品")
public ApiResponse<Void> delete(@PathVariable Long id) {
crmProductService.delete(id);
return ApiResponse.success("删除成功");
}
@GetMapping("/{id}")
@RequirePermission(value = "crm:product:read", description = "产品详情")
public ApiResponse<CrmProductVO> get(@PathVariable Long id) {
return ApiResponse.success("获取成功", crmProductService.get(id));
}
@PostMapping("/list")
@RequirePermission(value = "crm:product:read", description = "产品列表")
public ApiResponse<PageResultVO<CrmProductVO>> list(
@Valid @RequestBody PageQueryDTO<CrmProductFilterDTO> query) {
return ApiResponse.success("获取成功", crmProductService.page(query));
}
@GetMapping("/import/template")
@RequirePermission(value = "crm:product:import", description = "下载产品导入模板")
public ResponseEntity<byte[]> importTemplate() {
byte[] bytes = crmProductService.importTemplate();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=crm-product-import.xlsx")
.contentType(MediaType.parseMediaType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.body(bytes);
}
@PostMapping("/import")
@RequirePermission(value = "crm:product:import", description = "导入产品")
public ApiResponse<CrmImportResultVO> importExcel(@RequestParam("file") MultipartFile file) {
return ApiResponse.success("导入完成", crmProductService.importExcel(file));
}
}
@@ -0,0 +1,12 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.po.CrmProductPO;
/**
* 产品 Mapper。
*/
@Mapper
public interface CrmProductMapper extends BaseMapper<CrmProductPO> {
}
@@ -0,0 +1,48 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.model.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.math.BigDecimal;
/**
* 创建产品。
*/
@Data
public class CreateCrmProductDTO {
@NotBlank(message = "产品编码不能为空")
@Size(max = 64)
private String code;
@Size(max = 200)
private String nameZh;
@NotBlank(message = "英文名不能为空")
@Size(max = 200)
private String nameEn;
@Size(max = 500)
private String spec;
@Size(max = 32)
private String unit;
private BigDecimal unitPrice;
@Size(max = 3)
private String currency;
@Size(max = 32)
private String hsCode;
private BigDecimal grossWeightKg;
private BigDecimal netWeightKg;
private BigDecimal volumeCbm;
private Integer status;
@Size(max = 500)
private String remark;
}
@@ -0,0 +1,12 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.model.dto;
import lombok.Data;
/**
* 产品列表筛选。
*/
@Data
public class CrmProductFilterDTO {
private String keyword;
private Integer status;
}
@@ -0,0 +1,48 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.model.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.math.BigDecimal;
/**
* 更新产品。
*/
@Data
public class UpdateCrmProductDTO {
@NotBlank(message = "产品编码不能为空")
@Size(max = 64)
private String code;
@Size(max = 200)
private String nameZh;
@NotBlank(message = "英文名不能为空")
@Size(max = 200)
private String nameEn;
@Size(max = 500)
private String spec;
@Size(max = 32)
private String unit;
private BigDecimal unitPrice;
@Size(max = 3)
private String currency;
@Size(max = 32)
private String hsCode;
private BigDecimal grossWeightKg;
private BigDecimal netWeightKg;
private BigDecimal volumeCbm;
private Integer status;
@Size(max = 500)
private String remark;
}
@@ -0,0 +1,79 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 产品实体。
*/
@Data
@TableName("crm_product")
public class CrmProductPO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("code")
private String code;
@TableField("name_zh")
private String nameZh;
@TableField("name_en")
private String nameEn;
@TableField("spec")
private String spec;
@TableField("unit")
private String unit;
@TableField("unit_price")
private BigDecimal unitPrice;
@TableField("currency")
private String currency;
@TableField("hs_code")
private String hsCode;
@TableField("gross_weight_kg")
private BigDecimal grossWeightKg;
@TableField("net_weight_kg")
private BigDecimal netWeightKg;
@TableField("volume_cbm")
private BigDecimal volumeCbm;
@TableField("status")
private Integer status;
@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;
}
@@ -0,0 +1,30 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.model.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 产品视图。
*/
@Data
public class CrmProductVO {
private Long id;
private Long companyId;
private String code;
private String nameZh;
private String nameEn;
private String spec;
private String unit;
private BigDecimal unitPrice;
private String currency;
private String hsCode;
private BigDecimal grossWeightKg;
private BigDecimal netWeightKg;
private BigDecimal volumeCbm;
private Integer status;
private String remark;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,30 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.service;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.dto.CreateCrmProductDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.dto.CrmProductFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.dto.UpdateCrmProductDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.vo.CrmProductVO;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmImportResultVO;
/**
* 产品用例。
*/
public interface CrmProductService {
CrmProductVO create(CreateCrmProductDTO dto);
CrmProductVO update(Long id, UpdateCrmProductDTO dto);
void delete(Long id);
CrmProductVO get(Long id);
PageResultVO<CrmProductVO> page(PageQueryDTO<CrmProductFilterDTO> query);
byte[] importTemplate();
CrmImportResultVO importExcel(MultipartFile file);
}
@@ -0,0 +1,214 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.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.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
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.product.mapper.CrmProductMapper;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.dto.CreateCrmProductDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.dto.CrmProductFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.dto.UpdateCrmProductDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.po.CrmProductPO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.vo.CrmProductVO;
import top.xyquan.ecomdmbbackend.modules.crm.product.service.CrmProductService;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmExcelSupport;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmImportResultVO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.util.List;
import java.util.Locale;
/**
* 产品用例实现:编码 upsert、Excel 导入。
*/
@Service
public class CrmProductServiceImpl extends ServiceImpl<CrmProductMapper, CrmProductPO>
implements CrmProductService {
private static final String[] IMPORT_HEADERS = {
"编码*", "中文名", "英文名*", "单位", "单价", "币种", "HS"
};
private final CurrentUserContext currentUserContext;
private final CrmExcelSupport crmExcelSupport;
public CrmProductServiceImpl(CurrentUserContext currentUserContext, CrmExcelSupport crmExcelSupport) {
this.currentUserContext = currentUserContext;
this.crmExcelSupport = crmExcelSupport;
}
@Override
@Transactional
public CrmProductVO create(CreateCrmProductDTO dto) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
CrmProductPO po = new CrmProductPO();
BeanCopyUtils.copyProperties(dto, po);
normalize(po);
po.setCompanyId(companyId);
po.setCreateBy(userId);
po.setUpdateBy(userId);
try {
this.save(po);
} catch (DuplicateKeyException e) {
throw new BusinessException("产品编码已存在");
}
return toVo(po);
}
@Override
@Transactional
public CrmProductVO update(Long id, UpdateCrmProductDTO dto) {
CrmProductPO existing = requireOwned(id);
BeanCopyUtils.copyProperties(dto, existing);
normalize(existing);
existing.setUpdateBy(currentUserContext.getCurrentUserId());
try {
this.updateById(existing);
} catch (DuplicateKeyException e) {
throw new BusinessException("产品编码已存在");
}
return toVo(this.getById(id));
}
@Override
@Transactional
public void delete(Long id) {
requireOwned(id);
Long userId = currentUserContext.getCurrentUserId();
this.lambdaUpdate()
.eq(CrmProductPO::getId, id)
.set(CrmProductPO::getDeleteBy, userId)
.update();
this.removeById(id);
}
@Override
public CrmProductVO get(Long id) {
return toVo(requireOwned(id));
}
@Override
public PageResultVO<CrmProductVO> page(PageQueryDTO<CrmProductFilterDTO> query) {
Long companyId = requireCompanyId();
CrmProductFilterDTO filters = query.getFilters() != null ? query.getFilters() : new CrmProductFilterDTO();
LambdaQueryWrapper<CrmProductPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(CrmProductPO::getCompanyId, companyId);
if (StringUtils.hasText(filters.getKeyword())) {
String kw = filters.getKeyword().trim();
wrapper.and(w -> w.like(CrmProductPO::getCode, kw)
.or().like(CrmProductPO::getNameZh, kw)
.or().like(CrmProductPO::getNameEn, kw)
.or().like(CrmProductPO::getHsCode, kw));
}
if (filters.getStatus() != null) {
wrapper.eq(CrmProductPO::getStatus, filters.getStatus());
}
wrapper.orderByDesc(CrmProductPO::getId);
IPage<CrmProductPO> page = this.page(new Page<>(query.getPage(), query.getPageSize()), wrapper);
List<CrmProductVO> records = page.getRecords().stream().map(this::toVo).toList();
return PageResultVO.create(records, page.getTotal(), query.getPage(), query.getPageSize());
}
@Override
public byte[] importTemplate() {
return crmExcelSupport.buildTemplate("产品导入", IMPORT_HEADERS);
}
@Override
@Transactional
public CrmImportResultVO importExcel(MultipartFile file) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
CrmImportResultVO result = new CrmImportResultVO();
List<CrmExcelSupport.RowContext> rows = crmExcelSupport.parseRows(file, IMPORT_HEADERS.length, r -> r);
for (CrmExcelSupport.RowContext row : rows) {
try {
String code = row.str(0);
String nameEn = row.str(2);
if (!StringUtils.hasText(code)) {
throw new BusinessException("编码不能为空");
}
if (!StringUtils.hasText(nameEn)) {
throw new BusinessException("英文名不能为空");
}
CrmProductPO po = new CrmProductPO();
po.setCompanyId(companyId);
po.setCode(code.trim());
po.setNameZh(row.str(1));
po.setNameEn(nameEn.trim());
po.setUnit(row.str(3));
po.setUnitPrice(row.decimal(4));
po.setCurrency(row.str(5));
po.setHsCode(row.str(6));
po.setCreateBy(userId);
po.setUpdateBy(userId);
normalize(po);
LambdaQueryWrapper<CrmProductPO> exists = new LambdaQueryWrapper<>();
exists.eq(CrmProductPO::getCompanyId, companyId).eq(CrmProductPO::getCode, po.getCode());
CrmProductPO old = this.getOne(exists, false);
if (old != null) {
po.setId(old.getId());
this.updateById(po);
} else {
this.save(po);
}
result.setSuccessCount(result.getSuccessCount() + 1);
} catch (Exception e) {
result.setFailCount(result.getFailCount() + 1);
String msg = e instanceof BusinessException be ? be.getMessage() : e.getMessage();
result.getErrors().add(new CrmImportResultVO.RowError(row.rowNum(), msg));
}
}
return result;
}
private void normalize(CrmProductPO po) {
if (po.getCode() != null) {
po.setCode(po.getCode().trim());
}
if (!StringUtils.hasText(po.getUnit())) {
po.setUnit("PCS");
}
if (!StringUtils.hasText(po.getCurrency())) {
po.setCurrency("USD");
} else {
po.setCurrency(po.getCurrency().trim().toUpperCase(Locale.ROOT));
}
if (po.getStatus() == null) {
po.setStatus(1);
}
}
private CrmProductPO requireOwned(Long id) {
Long companyId = requireCompanyId();
CrmProductPO po = this.getById(id);
if (po == null || !companyId.equals(po.getCompanyId())) {
throw new BusinessException("产品不存在");
}
return po;
}
private Long requireCompanyId() {
Long companyId = currentUserContext.getCurrentCompanyId();
if (companyId == null) {
throw new BusinessException("请先选择公司");
}
return companyId;
}
private CrmProductVO toVo(CrmProductPO po) {
CrmProductVO vo = new CrmProductVO();
BeanCopyUtils.copyProperties(po, vo);
return vo;
}
}
@@ -0,0 +1,33 @@
package top.xyquan.ecomdmbbackend.modules.crm.profile.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.crm.profile.model.dto.UpdateCrmCompanyProfileDTO;
import top.xyquan.ecomdmbbackend.modules.crm.profile.model.vo.CrmCompanyProfileVO;
import top.xyquan.ecomdmbbackend.modules.crm.profile.service.CrmCompanyProfileService;
/** 本公司出口抬头。 */
@RestController
@RequestMapping("/api/crm/profile")
public class CrmCompanyProfileController {
private final CrmCompanyProfileService crmCompanyProfileService;
public CrmCompanyProfileController(CrmCompanyProfileService crmCompanyProfileService) {
this.crmCompanyProfileService = crmCompanyProfileService;
}
@GetMapping
@RequirePermission(value = "crm:profile:read", description = "查看单证资料")
public ApiResponse<CrmCompanyProfileVO> get() {
return ApiResponse.success("获取成功", crmCompanyProfileService.getCurrent());
}
@PutMapping
@RequirePermission(value = "crm:profile:update", description = "更新单证资料")
public ApiResponse<CrmCompanyProfileVO> save(@Valid @RequestBody UpdateCrmCompanyProfileDTO dto) {
return ApiResponse.success("保存成功", crmCompanyProfileService.save(dto));
}
}
@@ -0,0 +1,9 @@
package top.xyquan.ecomdmbbackend.modules.crm.profile.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.crm.profile.model.po.CrmCompanyProfilePO;
@Mapper
public interface CrmCompanyProfileMapper extends BaseMapper<CrmCompanyProfilePO> {
}
@@ -0,0 +1,40 @@
package top.xyquan.ecomdmbbackend.modules.crm.profile.model.dto;
import jakarta.validation.constraints.Size;
import lombok.Data;
/** 更新本公司出口抬头。 */
@Data
public class UpdateCrmCompanyProfileDTO {
@Size(max = 200)
private String legalNameZh;
@Size(max = 200)
private String legalNameEn;
@Size(max = 500)
private String addressZh;
@Size(max = 500)
private String addressEn;
@Size(max = 64)
private String country;
@Size(max = 50)
private String phone;
@Size(max = 100)
private String email;
@Size(max = 64)
private String taxNo;
@Size(max = 200)
private String bankName;
@Size(max = 100)
private String bankAccount;
@Size(max = 32)
private String bankSwift;
@Size(max = 500)
private String bankAddress;
@Size(max = 3)
private String defaultCurrency;
@Size(max = 16)
private String defaultIncoterm;
@Size(max = 500)
private String remark;
}
@@ -0,0 +1,55 @@
package top.xyquan.ecomdmbbackend.modules.crm.profile.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.time.LocalDateTime;
/** 本公司出口抬头。 */
@Data
@TableName("crm_company_profile")
public class CrmCompanyProfilePO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("legal_name_zh")
private String legalNameZh;
@TableField("legal_name_en")
private String legalNameEn;
@TableField("address_zh")
private String addressZh;
@TableField("address_en")
private String addressEn;
@TableField("country")
private String country;
@TableField("phone")
private String phone;
@TableField("email")
private String email;
@TableField("tax_no")
private String taxNo;
@TableField("bank_name")
private String bankName;
@TableField("bank_account")
private String bankAccount;
@TableField("bank_swift")
private String bankSwift;
@TableField("bank_address")
private String bankAddress;
@TableField("default_currency")
private String defaultCurrency;
@TableField("default_incoterm")
private String defaultIncoterm;
@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;
}
@@ -0,0 +1,28 @@
package top.xyquan.ecomdmbbackend.modules.crm.profile.model.vo;
import lombok.Data;
import java.time.LocalDateTime;
/** 本公司出口抬头视图。 */
@Data
public class CrmCompanyProfileVO {
private Long id;
private Long companyId;
private String legalNameZh;
private String legalNameEn;
private String addressZh;
private String addressEn;
private String country;
private String phone;
private String email;
private String taxNo;
private String bankName;
private String bankAccount;
private String bankSwift;
private String bankAddress;
private String defaultCurrency;
private String defaultIncoterm;
private String remark;
private LocalDateTime updateTime;
}
@@ -0,0 +1,12 @@
package top.xyquan.ecomdmbbackend.modules.crm.profile.service;
import top.xyquan.ecomdmbbackend.modules.crm.profile.model.dto.UpdateCrmCompanyProfileDTO;
import top.xyquan.ecomdmbbackend.modules.crm.profile.model.vo.CrmCompanyProfileVO;
/** 本公司出口抬头。 */
public interface CrmCompanyProfileService {
CrmCompanyProfileVO getCurrent();
CrmCompanyProfileVO save(UpdateCrmCompanyProfileDTO dto);
}
@@ -0,0 +1,91 @@
package top.xyquan.ecomdmbbackend.modules.crm.profile.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.utils.BeanCopyUtils;
import top.xyquan.ecomdmbbackend.modules.crm.profile.mapper.CrmCompanyProfileMapper;
import top.xyquan.ecomdmbbackend.modules.crm.profile.model.dto.UpdateCrmCompanyProfileDTO;
import top.xyquan.ecomdmbbackend.modules.crm.profile.model.po.CrmCompanyProfilePO;
import top.xyquan.ecomdmbbackend.modules.crm.profile.model.vo.CrmCompanyProfileVO;
import top.xyquan.ecomdmbbackend.modules.crm.profile.service.CrmCompanyProfileService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.util.Locale;
/**
* 一公司一行出口抬头;不存在时返回空壳。
*/
@Service
public class CrmCompanyProfileServiceImpl
extends ServiceImpl<CrmCompanyProfileMapper, CrmCompanyProfilePO>
implements CrmCompanyProfileService {
private final CurrentUserContext currentUserContext;
public CrmCompanyProfileServiceImpl(CurrentUserContext currentUserContext) {
this.currentUserContext = currentUserContext;
}
@Override
public CrmCompanyProfileVO getCurrent() {
Long companyId = requireCompanyId();
CrmCompanyProfilePO po = findByCompany(companyId);
if (po == null) {
CrmCompanyProfileVO empty = new CrmCompanyProfileVO();
empty.setCompanyId(companyId);
empty.setDefaultCurrency("USD");
return empty;
}
return toVo(po);
}
@Override
@Transactional
public CrmCompanyProfileVO save(UpdateCrmCompanyProfileDTO dto) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
CrmCompanyProfilePO po = findByCompany(companyId);
if (po == null) {
po = new CrmCompanyProfilePO();
po.setCompanyId(companyId);
po.setCreateBy(userId);
}
BeanCopyUtils.copyProperties(dto, po);
if (!StringUtils.hasText(po.getDefaultCurrency())) {
po.setDefaultCurrency("USD");
} else {
po.setDefaultCurrency(po.getDefaultCurrency().trim().toUpperCase(Locale.ROOT));
}
po.setUpdateBy(userId);
if (po.getId() == null) {
this.save(po);
} else {
this.updateById(po);
}
return toVo(this.getById(po.getId()));
}
private CrmCompanyProfilePO findByCompany(Long companyId) {
return this.getOne(new LambdaQueryWrapper<CrmCompanyProfilePO>()
.eq(CrmCompanyProfilePO::getCompanyId, companyId)
.last("LIMIT 1"), false);
}
private Long requireCompanyId() {
Long companyId = currentUserContext.getCurrentCompanyId();
if (companyId == null) {
throw new BusinessException("请先选择公司");
}
return companyId;
}
private CrmCompanyProfileVO toVo(CrmCompanyProfilePO po) {
CrmCompanyProfileVO vo = new CrmCompanyProfileVO();
BeanCopyUtils.copyProperties(po, vo);
return vo;
}
}
@@ -0,0 +1,71 @@
package top.xyquan.ecomdmbbackend.modules.crm.quote.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.quote.model.dto.ChangeCrmQuoteStatusDTO;
import top.xyquan.ecomdmbbackend.modules.crm.quote.model.dto.CreateCrmQuoteDTO;
import top.xyquan.ecomdmbbackend.modules.crm.quote.model.dto.CrmQuoteFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.quote.model.dto.UpdateCrmQuoteDTO;
import top.xyquan.ecomdmbbackend.modules.crm.quote.model.vo.CrmQuoteVO;
import top.xyquan.ecomdmbbackend.modules.crm.quote.service.CrmQuoteService;
/** 报价管理。 */
@RestController
@RequestMapping("/api/crm/quote")
public class CrmQuoteController {
private final CrmQuoteService crmQuoteService;
public CrmQuoteController(CrmQuoteService crmQuoteService) {
this.crmQuoteService = crmQuoteService;
}
@PostMapping("/create")
@RequirePermission(value = "crm:quote:create", description = "创建报价")
public ApiResponse<CrmQuoteVO> create(@Valid @RequestBody CreateCrmQuoteDTO dto) {
return ApiResponse.success("创建成功", crmQuoteService.create(dto));
}
@PutMapping("/update/{id}")
@RequirePermission(value = "crm:quote:update", description = "更新报价")
public ApiResponse<CrmQuoteVO> update(@PathVariable Long id, @Valid @RequestBody UpdateCrmQuoteDTO dto) {
return ApiResponse.success("更新成功", crmQuoteService.update(id, dto));
}
@DeleteMapping("/delete/{id}")
@RequirePermission(value = "crm:quote:delete", description = "删除报价")
public ApiResponse<Void> delete(@PathVariable Long id) {
crmQuoteService.delete(id);
return ApiResponse.success("删除成功");
}
@GetMapping("/{id}")
@RequirePermission(value = "crm:quote:read", description = "报价详情")
public ApiResponse<CrmQuoteVO> get(@PathVariable Long id) {
return ApiResponse.success("获取成功", crmQuoteService.get(id));
}
@PostMapping("/list")
@RequirePermission(value = "crm:quote:read", description = "报价列表")
public ApiResponse<PageResultVO<CrmQuoteVO>> list(
@Valid @RequestBody PageQueryDTO<CrmQuoteFilterDTO> query) {
return ApiResponse.success("获取成功", crmQuoteService.page(query));
}
@PostMapping("/{id}/status")
@RequirePermission(value = "crm:quote:status", description = "变更报价状态")
public ApiResponse<CrmQuoteVO> changeStatus(
@PathVariable Long id, @Valid @RequestBody ChangeCrmQuoteStatusDTO dto) {
return ApiResponse.success("状态已更新", crmQuoteService.changeStatus(id, dto));
}
@PostMapping("/{id}/export-pi")
@RequirePermission(value = "crm:quote:export", description = "导出形式发票 PI")
public ApiResponse<CrmQuoteVO> exportPi(@PathVariable Long id) {
return ApiResponse.success("PI 已生成", crmQuoteService.exportPi(id));
}
}
@@ -0,0 +1,9 @@
package top.xyquan.ecomdmbbackend.modules.crm.quote.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.crm.quote.model.po.CrmQuoteItemPO;
@Mapper
public interface CrmQuoteItemMapper extends BaseMapper<CrmQuoteItemPO> {
}
@@ -0,0 +1,9 @@
package top.xyquan.ecomdmbbackend.modules.crm.quote.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.crm.quote.model.po.CrmQuotePO;
@Mapper
public interface CrmQuoteMapper extends BaseMapper<CrmQuotePO> {
}
@@ -0,0 +1,13 @@
package top.xyquan.ecomdmbbackend.modules.crm.quote.model.dto;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/** 变更报价状态。 */
@Data
public class ChangeCrmQuoteStatusDTO {
/** sent / accepted / rejected / expired / draft */
@NotBlank(message = "目标状态不能为空")
private String status;
}
@@ -0,0 +1,40 @@
package top.xyquan.ecomdmbbackend.modules.crm.quote.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 CreateCrmQuoteDTO {
@NotNull(message = "客户不能为空")
private Long customerId;
private LocalDate quoteDate;
private LocalDate validUntil;
@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<CrmQuoteItemDTO> items;
}
@@ -0,0 +1,12 @@
package top.xyquan.ecomdmbbackend.modules.crm.quote.model.dto;
import lombok.Data;
/** 报价列表筛选。 */
@Data
public class CrmQuoteFilterDTO {
private String keyword;
private String status;
private Long customerId;
private Boolean onlyMine;
}
@@ -0,0 +1,40 @@
package top.xyquan.ecomdmbbackend.modules.crm.quote.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 CrmQuoteItemDTO {
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 unit;
@NotNull(message = "数量不能为空")
private BigDecimal qty;
@NotNull(message = "单价不能为空")
private BigDecimal unitPrice;
@Size(max = 500)
private String remark;
}
@@ -0,0 +1,40 @@
package top.xyquan.ecomdmbbackend.modules.crm.quote.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;
/** 更新报价(仅 draft)。 */
@Data
public class UpdateCrmQuoteDTO {
@NotNull(message = "客户不能为空")
private Long customerId;
private LocalDate quoteDate;
private LocalDate validUntil;
@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<CrmQuoteItemDTO> items;
}
@@ -0,0 +1,46 @@
package top.xyquan.ecomdmbbackend.modules.crm.quote.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/** 报价行。 */
@Data
@TableName("crm_quote_item")
public class CrmQuoteItemPO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("quote_id")
private Long quoteId;
@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("unit")
private String unit;
@TableField("qty")
private BigDecimal qty;
@TableField("unit_price")
private BigDecimal unitPrice;
@TableField("amount")
private BigDecimal amount;
@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;
}
@@ -0,0 +1,54 @@
package top.xyquan.ecomdmbbackend.modules.crm.quote.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_quote")
public class CrmQuotePO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("quote_no")
private String quoteNo;
@TableField("customer_id")
private Long customerId;
@TableField("quote_date")
private LocalDate quoteDate;
@TableField("valid_until")
private LocalDate validUntil;
@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("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;
}
@@ -0,0 +1,22 @@
package top.xyquan.ecomdmbbackend.modules.crm.quote.model.vo;
import lombok.Data;
import java.math.BigDecimal;
/** 报价行视图。 */
@Data
public class CrmQuoteItemVO {
private Long id;
private Integer lineNo;
private Long productId;
private String productCode;
private String nameEn;
private String nameZh;
private String spec;
private String unit;
private BigDecimal qty;
private BigDecimal unitPrice;
private BigDecimal amount;
private String remark;
}
@@ -0,0 +1,33 @@
package top.xyquan.ecomdmbbackend.modules.crm.quote.model.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
/** 报价视图。 */
@Data
public class CrmQuoteVO {
private Long id;
private Long companyId;
private String quoteNo;
private Long customerId;
private String customerName;
private LocalDate quoteDate;
private LocalDate validUntil;
private String currency;
private String incoterm;
private String paymentTerms;
private String status;
private BigDecimal totalAmount;
private Long ownerUserId;
private String remark;
private LocalDateTime createTime;
private LocalDateTime updateTime;
private List<CrmQuoteItemVO> items;
/** 最新 PI 文件 ID */
private Long latestPiFileId;
private String latestPiAccessUrl;
}
@@ -0,0 +1,28 @@
package top.xyquan.ecomdmbbackend.modules.crm.quote.service;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.crm.quote.model.dto.ChangeCrmQuoteStatusDTO;
import top.xyquan.ecomdmbbackend.modules.crm.quote.model.dto.CreateCrmQuoteDTO;
import top.xyquan.ecomdmbbackend.modules.crm.quote.model.dto.CrmQuoteFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.quote.model.dto.UpdateCrmQuoteDTO;
import top.xyquan.ecomdmbbackend.modules.crm.quote.model.vo.CrmQuoteVO;
/** 报价用例。 */
public interface CrmQuoteService {
CrmQuoteVO create(CreateCrmQuoteDTO dto);
CrmQuoteVO update(Long id, UpdateCrmQuoteDTO dto);
void delete(Long id);
CrmQuoteVO get(Long id);
PageResultVO<CrmQuoteVO> page(PageQueryDTO<CrmQuoteFilterDTO> query);
CrmQuoteVO changeStatus(Long id, ChangeCrmQuoteStatusDTO dto);
/** 生成 PI PDF,返回含最新文件信息的报价详情。 */
CrmQuoteVO exportPi(Long id);
}
@@ -0,0 +1,481 @@
package top.xyquan.ecomdmbbackend.modules.crm.quote.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.mapper.CrmDocumentMapper;
import top.xyquan.ecomdmbbackend.modules.crm.document.model.po.CrmDocumentPO;
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.dto.*;
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.quote.model.vo.CrmQuoteItemVO;
import top.xyquan.ecomdmbbackend.modules.crm.quote.model.vo.CrmQuoteVO;
import top.xyquan.ecomdmbbackend.modules.crm.quote.service.CrmQuoteService;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmGeneratedFileService;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmPiPdfRenderer;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmSeqService;
import top.xyquan.ecomdmbbackend.modules.sys.file.model.po.SysFilePO;
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;
/**
* 报价:草稿可改删;状态流转;导出 PI 挂 crm_document。
*/
@Service
public class CrmQuoteServiceImpl extends ServiceImpl<CrmQuoteMapper, CrmQuotePO> implements CrmQuoteService {
private static final Set<String> STATUSES =
Set.of("draft", "sent", "accepted", "rejected", "expired");
private final CrmQuoteItemMapper quoteItemMapper;
private final CrmCustomerMapper customerMapper;
private final CrmProductMapper productMapper;
private final CrmDocumentMapper documentMapper;
private final CrmSeqService crmSeqService;
private final CrmCompanyProfileService profileService;
private final CrmPiPdfRenderer piPdfRenderer;
private final CrmGeneratedFileService generatedFileService;
private final SysFileService sysFileService;
private final CurrentUserContext currentUserContext;
public CrmQuoteServiceImpl(CrmQuoteItemMapper quoteItemMapper,
CrmCustomerMapper customerMapper,
CrmProductMapper productMapper,
CrmDocumentMapper documentMapper,
CrmSeqService crmSeqService,
CrmCompanyProfileService profileService,
CrmPiPdfRenderer piPdfRenderer,
CrmGeneratedFileService generatedFileService,
SysFileService sysFileService,
CurrentUserContext currentUserContext) {
this.quoteItemMapper = quoteItemMapper;
this.customerMapper = customerMapper;
this.productMapper = productMapper;
this.documentMapper = documentMapper;
this.crmSeqService = crmSeqService;
this.profileService = profileService;
this.piPdfRenderer = piPdfRenderer;
this.generatedFileService = generatedFileService;
this.sysFileService = sysFileService;
this.currentUserContext = currentUserContext;
}
@Override
@Transactional
public CrmQuoteVO create(CreateCrmQuoteDTO dto) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
requireCustomer(companyId, dto.getCustomerId());
CrmQuotePO quote = new CrmQuotePO();
quote.setCompanyId(companyId);
quote.setQuoteNo(crmSeqService.nextQuoteNo(companyId));
quote.setCustomerId(dto.getCustomerId());
quote.setQuoteDate(dto.getQuoteDate() != null ? dto.getQuoteDate() : LocalDate.now());
quote.setValidUntil(dto.getValidUntil());
quote.setCurrency(normalizeCurrency(dto.getCurrency()));
quote.setIncoterm(trimToNull(dto.getIncoterm()));
quote.setPaymentTerms(trimToNull(dto.getPaymentTerms()));
quote.setStatus("draft");
quote.setOwnerUserId(dto.getOwnerUserId() != null ? dto.getOwnerUserId() : userId);
quote.setRemark(trimToNull(dto.getRemark()));
quote.setCreateBy(userId);
quote.setUpdateBy(userId);
List<CrmQuoteItemPO> items = buildItems(companyId, dto.getItems());
quote.setTotalAmount(sumAmount(items));
this.save(quote);
persistItems(quote.getId(), companyId, items);
return get(quote.getId());
}
@Override
@Transactional
public CrmQuoteVO update(Long id, UpdateCrmQuoteDTO dto) {
CrmQuotePO quote = requireOwned(id);
if (!"draft".equals(quote.getStatus())) {
throw new BusinessException("仅草稿状态可编辑");
}
Long companyId = quote.getCompanyId();
requireCustomer(companyId, dto.getCustomerId());
quote.setCustomerId(dto.getCustomerId());
if (dto.getQuoteDate() != null) {
quote.setQuoteDate(dto.getQuoteDate());
}
quote.setValidUntil(dto.getValidUntil());
quote.setCurrency(normalizeCurrency(dto.getCurrency()));
quote.setIncoterm(trimToNull(dto.getIncoterm()));
quote.setPaymentTerms(trimToNull(dto.getPaymentTerms()));
if (dto.getOwnerUserId() != null) {
quote.setOwnerUserId(dto.getOwnerUserId());
}
quote.setRemark(trimToNull(dto.getRemark()));
quote.setUpdateBy(currentUserContext.getCurrentUserId());
List<CrmQuoteItemPO> items = buildItems(companyId, dto.getItems());
quote.setTotalAmount(sumAmount(items));
this.updateById(quote);
quoteItemMapper.delete(new LambdaQueryWrapper<CrmQuoteItemPO>()
.eq(CrmQuoteItemPO::getQuoteId, id));
persistItems(id, companyId, items);
return get(id);
}
@Override
@Transactional
public void delete(Long id) {
CrmQuotePO quote = requireOwned(id);
if (!Set.of("draft", "rejected").contains(quote.getStatus())) {
throw new BusinessException("仅草稿或已拒绝的报价可删除");
}
Long userId = currentUserContext.getCurrentUserId();
this.lambdaUpdate()
.eq(CrmQuotePO::getId, id)
.set(CrmQuotePO::getDeleteBy, userId)
.update();
this.removeById(id);
}
@Override
public CrmQuoteVO get(Long id) {
CrmQuotePO quote = requireOwned(id);
return toDetailVo(quote);
}
@Override
public PageResultVO<CrmQuoteVO> page(PageQueryDTO<CrmQuoteFilterDTO> query) {
Long companyId = requireCompanyId();
CrmQuoteFilterDTO filters = query.getFilters() != null ? query.getFilters() : new CrmQuoteFilterDTO();
LambdaQueryWrapper<CrmQuotePO> w = new LambdaQueryWrapper<>();
w.eq(CrmQuotePO::getCompanyId, companyId);
if (StringUtils.hasText(filters.getStatus())) {
w.eq(CrmQuotePO::getStatus, filters.getStatus().trim());
}
if (filters.getCustomerId() != null) {
w.eq(CrmQuotePO::getCustomerId, filters.getCustomerId());
}
if (Boolean.TRUE.equals(filters.getOnlyMine())) {
w.eq(CrmQuotePO::getOwnerUserId, currentUserContext.getCurrentUserId());
}
if (StringUtils.hasText(filters.getKeyword())) {
String kw = filters.getKeyword().trim();
w.and(x -> x.like(CrmQuotePO::getQuoteNo, kw).or().like(CrmQuotePO::getRemark, kw));
}
w.orderByDesc(CrmQuotePO::getId);
IPage<CrmQuotePO> page = this.page(new Page<>(query.getPage(), query.getPageSize()), w);
Map<Long, String> customerNames = loadCustomerNames(
companyId, page.getRecords().stream().map(CrmQuotePO::getCustomerId).collect(Collectors.toSet()));
List<CrmQuoteVO> records = page.getRecords().stream().map(q -> {
CrmQuoteVO vo = toBriefVo(q);
vo.setCustomerName(customerNames.get(q.getCustomerId()));
return vo;
}).toList();
return PageResultVO.create(records, page.getTotal(), query.getPage(), query.getPageSize());
}
@Override
@Transactional
public CrmQuoteVO changeStatus(Long id, ChangeCrmQuoteStatusDTO dto) {
CrmQuotePO quote = requireOwned(id);
String target = dto.getStatus().trim().toLowerCase(Locale.ROOT);
if (!STATUSES.contains(target)) {
throw new BusinessException("目标状态不合法");
}
String from = quote.getStatus();
if (!isAllowedTransition(from, target)) {
throw new BusinessException("不允许从 " + from + " 变更为 " + target);
}
quote.setStatus(target);
quote.setUpdateBy(currentUserContext.getCurrentUserId());
this.updateById(quote);
return get(id);
}
@Override
@Transactional
public CrmQuoteVO exportPi(Long id) {
CrmQuotePO quote = requireOwned(id);
Long companyId = quote.getCompanyId();
List<CrmQuoteItemPO> items = listItems(id);
if (items.isEmpty()) {
throw new BusinessException("报价无明细,无法导出 PI");
}
CrmCustomerPO customer = requireCustomer(companyId, quote.getCustomerId());
CrmCompanyProfileVO profile = profileService.getCurrent();
CrmPiPdfRenderer.Party seller = new CrmPiPdfRenderer.Party(
firstNonBlank(profile.getLegalNameEn(), profile.getLegalNameZh()),
firstNonBlank(profile.getAddressEn(), profile.getAddressZh()),
profile.getCountry(),
profile.getPhone(),
profile.getEmail());
CrmPiPdfRenderer.Party buyer = new CrmPiPdfRenderer.Party(
firstNonBlank(customer.getNameEn(), customer.getName()),
customer.getAddress(),
customer.getCountry(),
customer.getPhone(),
customer.getEmail());
List<CrmPiPdfRenderer.Line> lines = new ArrayList<>();
for (CrmQuoteItemPO item : items) {
lines.add(new CrmPiPdfRenderer.Line(
item.getLineNo(),
item.getProductCode(),
item.getNameEn(),
item.getSpec(),
item.getUnit(),
item.getQty(),
item.getUnitPrice(),
item.getAmount()));
}
CrmPiPdfRenderer.PiModel model = new CrmPiPdfRenderer.PiModel(
"PROFORMA INVOICE",
quote.getQuoteNo(),
quote.getQuoteDate() != null ? quote.getQuoteDate().toString() : "",
quote.getValidUntil() != null ? quote.getValidUntil().toString() : null,
quote.getCurrency(),
quote.getIncoterm(),
quote.getPaymentTerms(),
quote.getRemark(),
seller,
buyer,
lines,
quote.getTotalAmount());
byte[] pdf = piPdfRenderer.render(model);
String filename = "PI-" + quote.getQuoteNo() + ".pdf";
SysFilePO file = generatedFileService.saveBytes(
companyId, filename, "application/pdf", pdf);
// 旧版本取消 latest
documentMapper.update(null, new com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<CrmDocumentPO>()
.eq(CrmDocumentPO::getCompanyId, companyId)
.eq(CrmDocumentPO::getRefType, "quote")
.eq(CrmDocumentPO::getRefId, id)
.eq(CrmDocumentPO::getDocType, "pi")
.eq(CrmDocumentPO::getIsLatest, 1)
.set(CrmDocumentPO::getIsLatest, 0));
int nextVersion = 1;
CrmDocumentPO last = documentMapper.selectOne(new LambdaQueryWrapper<CrmDocumentPO>()
.eq(CrmDocumentPO::getCompanyId, companyId)
.eq(CrmDocumentPO::getRefType, "quote")
.eq(CrmDocumentPO::getRefId, id)
.eq(CrmDocumentPO::getDocType, "pi")
.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("pi");
doc.setDocNo(quote.getQuoteNo());
doc.setRefType("quote");
doc.setRefId(id);
doc.setFileId(file.getId());
doc.setIsLatest(1);
doc.setVersionNo(nextVersion);
doc.setCreateBy(currentUserContext.getCurrentUserId());
documentMapper.insert(doc);
return get(id);
}
private boolean isAllowedTransition(String from, String to) {
if (from.equals(to)) {
return true;
}
return switch (from) {
case "draft" -> Set.of("sent", "rejected").contains(to);
case "sent" -> Set.of("accepted", "rejected", "expired", "draft").contains(to);
case "rejected", "expired" -> "draft".equals(to);
case "accepted" -> false;
default -> false;
};
}
private List<CrmQuoteItemPO> buildItems(Long companyId, List<CrmQuoteItemDTO> dtos) {
List<CrmQuoteItemPO> items = new ArrayList<>();
int lineNo = 1;
for (CrmQuoteItemDTO 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 + " 行单价不能为负");
}
CrmQuoteItemPO item = new CrmQuoteItemPO();
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.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.setRemark(trimToNull(dto.getRemark()));
if (dto.getProductId() != null) {
CrmProductPO product = productMapper.selectById(dto.getProductId());
if (product == null || !companyId.equals(product.getCompanyId())) {
throw new BusinessException("产品不存在: " + dto.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());
}
}
items.add(item);
}
return items;
}
private void persistItems(Long quoteId, Long companyId, List<CrmQuoteItemPO> items) {
for (CrmQuoteItemPO item : items) {
item.setId(null);
item.setQuoteId(quoteId);
item.setCompanyId(companyId);
quoteItemMapper.insert(item);
}
}
private BigDecimal sumAmount(List<CrmQuoteItemPO> items) {
return items.stream()
.map(CrmQuoteItemPO::getAmount)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add)
.setScale(2, RoundingMode.HALF_UP);
}
private List<CrmQuoteItemPO> listItems(Long quoteId) {
return quoteItemMapper.selectList(new LambdaQueryWrapper<CrmQuoteItemPO>()
.eq(CrmQuoteItemPO::getQuoteId, quoteId)
.orderByAsc(CrmQuoteItemPO::getLineNo));
}
private CrmQuoteVO toDetailVo(CrmQuotePO quote) {
CrmQuoteVO vo = toBriefVo(quote);
CrmCustomerPO customer = customerMapper.selectById(quote.getCustomerId());
if (customer != null) {
vo.setCustomerName(customer.getName());
}
vo.setItems(listItems(quote.getId()).stream().map(item -> {
CrmQuoteItemVO iv = new CrmQuoteItemVO();
BeanCopyUtils.copyProperties(item, iv);
return iv;
}).toList());
CrmDocumentPO latestPi = documentMapper.selectOne(new LambdaQueryWrapper<CrmDocumentPO>()
.eq(CrmDocumentPO::getCompanyId, quote.getCompanyId())
.eq(CrmDocumentPO::getRefType, "quote")
.eq(CrmDocumentPO::getRefId, quote.getId())
.eq(CrmDocumentPO::getDocType, "pi")
.eq(CrmDocumentPO::getIsLatest, 1)
.last("LIMIT 1"));
if (latestPi != null) {
vo.setLatestPiFileId(latestPi.getFileId());
vo.setLatestPiAccessUrl(sysFileService.resolveAccessUrl(latestPi.getFileId()));
}
return vo;
}
private CrmQuoteVO toBriefVo(CrmQuotePO quote) {
CrmQuoteVO vo = new CrmQuoteVO();
BeanCopyUtils.copyProperties(quote, vo);
return vo;
}
private Map<Long, String> loadCustomerNames(Long companyId, Set<Long> ids) {
if (ids == null || ids.isEmpty()) {
return Map.of();
}
return customerMapper.selectList(new LambdaQueryWrapper<CrmCustomerPO>()
.eq(CrmCustomerPO::getCompanyId, companyId)
.in(CrmCustomerPO::getId, ids))
.stream()
.collect(Collectors.toMap(CrmCustomerPO::getId, CrmCustomerPO::getName, (a, b) -> a));
}
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 requireOwned(Long id) {
Long companyId = requireCompanyId();
CrmQuotePO quote = this.getById(id);
if (quote == null || !companyId.equals(quote.getCompanyId())) {
throw new BusinessException("报价不存在");
}
return quote;
}
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 "";
}
}
@@ -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<CrmShipmentVO> create(@Valid @RequestBody CreateCrmShipmentDTO dto) {
return ApiResponse.success("创建成功", crmShipmentService.create(dto));
}
@PostMapping("/from-quote/{quoteId}")
@RequirePermission(value = "crm:shipment:create", description = "从报价生成出货")
public ApiResponse<CrmShipmentVO> createFromQuote(@PathVariable Long quoteId) {
return ApiResponse.success("已生成出货", crmShipmentService.createFromQuote(quoteId));
}
@PutMapping("/update/{id}")
@RequirePermission(value = "crm:shipment:update", description = "更新出货")
public ApiResponse<CrmShipmentVO> 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<Void> delete(@PathVariable Long id) {
crmShipmentService.delete(id);
return ApiResponse.success("删除成功");
}
@GetMapping("/{id}")
@RequirePermission(value = "crm:shipment:read", description = "出货详情")
public ApiResponse<CrmShipmentVO> get(@PathVariable Long id) {
return ApiResponse.success("获取成功", crmShipmentService.get(id));
}
@PostMapping("/list")
@RequirePermission(value = "crm:shipment:read", description = "出货列表")
public ApiResponse<PageResultVO<CrmShipmentVO>> list(
@Valid @RequestBody PageQueryDTO<CrmShipmentFilterDTO> query) {
return ApiResponse.success("获取成功", crmShipmentService.page(query));
}
@PostMapping("/{id}/status")
@RequirePermission(value = "crm:shipment:status", description = "变更出货状态")
public ApiResponse<CrmShipmentVO> 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<CrmShipmentVO> exportCi(@PathVariable Long id) {
return ApiResponse.success("CI 已生成", crmShipmentService.exportCi(id));
}
@PostMapping("/{id}/export-pl")
@RequirePermission(value = "crm:shipment:export", description = "导出装箱单 PL")
public ApiResponse<CrmShipmentVO> exportPl(@PathVariable Long id) {
return ApiResponse.success("PL 已生成", crmShipmentService.exportPl(id));
}
}
@@ -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<CrmShipmentItemPO> {
}
@@ -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<CrmShipmentPO> {
}
@@ -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;
}
@@ -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<CrmShipmentItemDTO> items;
}
@@ -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;
}
@@ -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;
}
@@ -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<CrmShipmentItemDTO> items;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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<CrmShipmentItemVO> items;
private Long latestCiFileId;
private String latestCiAccessUrl;
private Long latestPlFileId;
private String latestPlAccessUrl;
}
@@ -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<CrmShipmentVO> page(PageQueryDTO<CrmShipmentFilterDTO> query);
CrmShipmentVO changeStatus(Long id, ChangeCrmShipmentStatusDTO dto);
CrmShipmentVO exportCi(Long id);
CrmShipmentVO exportPl(Long id);
}
@@ -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<CrmShipmentMapper, CrmShipmentPO>
implements CrmShipmentService {
private static final Set<String> STATUSES = Set.of("draft", "ready", "shipped", "closed");
private static final Set<String> 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<CrmShipmentItemPO> 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<CrmQuoteItemPO> quoteItems = quoteItemMapper.selectList(new LambdaQueryWrapper<CrmQuoteItemPO>()
.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<CrmShipmentItemPO> 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<CrmShipmentItemPO> items = buildItems(companyId, dto.getItems());
applyTotals(ship, items);
this.updateById(ship);
shipmentItemMapper.delete(new LambdaQueryWrapper<CrmShipmentItemPO>()
.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<CrmShipmentVO> page(PageQueryDTO<CrmShipmentFilterDTO> query) {
Long companyId = requireCompanyId();
CrmShipmentFilterDTO filters = query.getFilters() != null ? query.getFilters() : new CrmShipmentFilterDTO();
LambdaQueryWrapper<CrmShipmentPO> 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<CrmShipmentPO> page = this.page(new Page<>(query.getPage(), query.getPageSize()), w);
Set<Long> customerIds = page.getRecords().stream().map(CrmShipmentPO::getCustomerId).collect(Collectors.toSet());
Set<Long> quoteIds = page.getRecords().stream()
.map(CrmShipmentPO::getQuoteId).filter(Objects::nonNull).collect(Collectors.toSet());
Map<Long, String> customerNames = loadCustomerNames(companyId, customerIds);
Map<Long, String> quoteNos = loadQuoteNos(companyId, quoteIds);
List<CrmShipmentVO> 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<CrmShipmentItemPO> 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<CrmDocPdfRenderer.InvoiceLine> 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<CrmShipmentItemPO> 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<CrmDocPdfRenderer.PackLine> 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<CrmShipmentItemPO> buildItems(Long companyId, List<CrmShipmentItemDTO> dtos) {
List<CrmShipmentItemPO> 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<CrmShipmentItemPO> 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<BigDecimal> 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<CrmShipmentItemPO> items) {
for (CrmShipmentItemPO item : items) {
item.setId(null);
item.setShipmentId(shipmentId);
item.setCompanyId(companyId);
shipmentItemMapper.insert(item);
}
}
private List<CrmShipmentItemPO> listItems(Long shipmentId) {
return shipmentItemMapper.selectList(new LambdaQueryWrapper<CrmShipmentItemPO>()
.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<Long, String> loadCustomerNames(Long companyId, Set<Long> ids) {
if (ids == null || ids.isEmpty()) {
return Map.of();
}
return customerMapper.selectList(new LambdaQueryWrapper<CrmCustomerPO>()
.eq(CrmCustomerPO::getCompanyId, companyId)
.in(CrmCustomerPO::getId, ids))
.stream()
.collect(Collectors.toMap(CrmCustomerPO::getId, CrmCustomerPO::getName, (a, b) -> a));
}
private Map<Long, String> loadQuoteNos(Long companyId, Set<Long> ids) {
if (ids == null || ids.isEmpty()) {
return Map.of();
}
return quoteMapper.selectList(new LambdaQueryWrapper<CrmQuotePO>()
.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 "";
}
}
@@ -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<InvoiceLine> 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<PackLine> 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("<tr>")
.append("<td>").append(line.lineNo()).append("</td>")
.append("<td>").append(esc(line.code())).append("</td>")
.append("<td>").append(esc(line.nameEn())).append("</td>")
.append("<td>").append(esc(line.spec())).append("</td>")
.append("<td>").append(esc(line.hsCode())).append("</td>")
.append("<td>").append(esc(line.unit())).append("</td>")
.append("<td class='num'>").append(fmt(line.qty(), 3)).append("</td>")
.append("<td class='num'>").append(fmt(line.unitPrice(), 4)).append("</td>")
.append("<td class='num'>").append(fmt(line.amount(), 2)).append("</td>")
.append("</tr>");
}
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("</table>")
.append(partyBoxes(s, b))
.append("<table class=\"items\"><thead><tr>")
.append("<th>#</th><th>Code</th><th>Description</th><th>Spec</th><th>HS</th>")
.append("<th>Unit</th><th>Qty</th><th>Unit Price</th><th>Amount</th>")
.append("</tr></thead><tbody>").append(rows).append("</tbody></table>")
.append("<div class=\"total\">Total ").append(esc(m.currency())).append(" ")
.append(fmt(m.totalAmount(), 2)).append("</div>")
.append("<p class=\"muted\">Remark: ").append(esc(dash(m.remark()))).append("</p>")
.append("</body></html>");
return html.toString();
}
private String buildPlHtml(PackingModel m) {
StringBuilder rows = new StringBuilder();
for (PackLine line : m.lines()) {
rows.append("<tr>")
.append("<td>").append(line.lineNo()).append("</td>")
.append("<td>").append(esc(line.code())).append("</td>")
.append("<td>").append(esc(line.nameEn())).append("</td>")
.append("<td>").append(esc(line.spec())).append("</td>")
.append("<td>").append(esc(line.unit())).append("</td>")
.append("<td class='num'>").append(fmt(line.qty(), 3)).append("</td>")
.append("<td class='num'>").append(line.packages() == null ? "-" : line.packages()).append("</td>")
.append("<td class='num'>").append(fmt(line.qtyPerPackage(), 3)).append("</td>")
.append("<td class='num'>").append(fmt(line.grossKg(), 3)).append("</td>")
.append("<td class='num'>").append(fmt(line.netKg(), 3)).append("</td>")
.append("<td class='num'>").append(fmt(line.cbm(), 4)).append("</td>")
.append("<td>").append(esc(line.origin())).append("</td>")
.append("</tr>");
}
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("</table>")
.append(partyBoxes(s, b))
.append("<table class=\"items\"><thead><tr>")
.append("<th>#</th><th>Code</th><th>Description</th><th>Spec</th><th>Unit</th>")
.append("<th>Qty</th><th>Pkgs</th><th>Qty/Pkg</th><th>G.W.</th><th>N.W.</th><th>CBM</th><th>Origin</th>")
.append("</tr></thead><tbody>").append(rows).append("</tbody></table>")
.append("<div class=\"total\">Pkgs: ").append(m.totalPackages() == null ? "-" : m.totalPackages())
.append(" &nbsp; G.W.: ").append(fmt(m.totalGrossKg(), 3))
.append(" kg &nbsp; N.W.: ").append(fmt(m.totalNetKg(), 3))
.append(" kg &nbsp; CBM: ").append(fmt(m.totalCbm(), 4)).append("</div>")
.append("<p class=\"muted\">Remark: ").append(esc(dash(m.remark()))).append("</p>")
.append("</body></html>");
return html.toString();
}
private static String commonHead(String title) {
return "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"/><style>"
+ "@page { size: A4; margin: 16mm; }"
+ "body { font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #222; }"
+ "h1 { font-size: 16px; margin: 0 0 8px 0; }"
+ ".meta td { padding: 2px 8px 2px 0; vertical-align: top; }"
+ ".box { border: 1px solid #ccc; padding: 8px; width: 48%; }"
+ ".row { width: 100%; margin-bottom: 10px; }"
+ ".row td { vertical-align: top; }"
+ "table.items { width: 100%; border-collapse: collapse; margin-top: 8px; }"
+ "table.items th, table.items td { border: 1px solid #999; padding: 4px 5px; }"
+ "table.items th { background: #f2f2f2; text-align: left; }"
+ ".num { text-align: right; white-space: nowrap; }"
+ ".total { margin-top: 10px; text-align: right; font-size: 12px; font-weight: bold; }"
+ ".muted { color: #666; font-size: 9px; }"
+ "</style></head><body><h1>" + esc(title) + "</h1><table class=\"meta\">";
}
private static String metaRow(String k1, String v1, String k2, String v2) {
return "<tr><td><b>" + esc(k1) + "</b></td><td>" + esc(dash(v1)) + "</td>"
+ "<td><b>" + esc(k2) + "</b></td><td>" + esc(dash(v2)) + "</td></tr>";
}
private static String partyBoxes(Party s, Party b) {
return "<table class=\"row\"><tr>"
+ "<td class=\"box\"><b>Seller</b><br/>" + esc(s.name()) + "<br/>" + esc(s.address())
+ "<br/>" + esc(s.country()) + "<br/>" + esc(s.phone()) + " " + esc(s.email()) + "</td>"
+ "<td style=\"width:4%\"></td>"
+ "<td class=\"box\"><b>Buyer</b><br/>" + esc(b.name()) + "<br/>" + esc(b.address())
+ "<br/>" + esc(b.country()) + "<br/>" + esc(b.phone()) + " " + esc(b.email()) + "</td>"
+ "</tr></table>";
}
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("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;");
}
}
@@ -0,0 +1,168 @@
package top.xyquan.ecomdmbbackend.modules.crm.support;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
/**
* CRM Excel 模板生成与行解析(POI)。
*/
@Component
public class CrmExcelSupport {
public static final int MAX_IMPORT_ROWS = 2000;
public byte[] buildTemplate(String sheetName, String[] headers) {
try (Workbook wb = new XSSFWorkbook(); ByteArrayOutputStream out = new ByteArrayOutputStream()) {
Sheet sheet = wb.createSheet(sheetName);
Row header = sheet.createRow(0);
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setBold(true);
style.setFont(font);
for (int i = 0; i < headers.length; i++) {
Cell cell = header.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(style);
sheet.setColumnWidth(i, 18 * 256);
}
wb.write(out);
return out.toByteArray();
} catch (Exception e) {
throw new BusinessException("生成导入模板失败");
}
}
public <T> List<T> parseRows(MultipartFile file, int expectedCols, Function<RowContext, T> mapper) {
if (file == null || file.isEmpty()) {
throw new BusinessException("请上传 Excel 文件");
}
String name = file.getOriginalFilename();
if (name == null || !(name.endsWith(".xlsx") || name.endsWith(".xls"))) {
throw new BusinessException("仅支持 .xlsx / .xls 文件");
}
try (InputStream in = file.getInputStream(); Workbook wb = WorkbookFactory.create(in)) {
Sheet sheet = wb.getSheetAt(0);
if (sheet == null) {
throw new BusinessException("Excel 无工作表");
}
Iterator<Row> it = sheet.iterator();
if (!it.hasNext()) {
throw new BusinessException("Excel 为空");
}
it.next(); // skip header
List<T> rows = new ArrayList<>();
int dataCount = 0;
while (it.hasNext()) {
Row row = it.next();
if (isBlankRow(row, expectedCols)) {
continue;
}
dataCount++;
if (dataCount > MAX_IMPORT_ROWS) {
throw new BusinessException("单次最多导入 " + MAX_IMPORT_ROWS + " 行");
}
rows.add(mapper.apply(new RowContext(row)));
}
if (rows.isEmpty()) {
throw new BusinessException("没有可导入的数据行");
}
return rows;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException("解析 Excel 失败:" + e.getMessage());
}
}
private boolean isBlankRow(Row row, int cols) {
for (int i = 0; i < cols; i++) {
if (StringUtils.hasText(cellString(row, i))) {
return false;
}
}
return true;
}
public static String cellString(Row row, int idx) {
Cell cell = row.getCell(idx, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
if (cell == null) {
return null;
}
return switch (cell.getCellType()) {
case STRING -> trimToNull(cell.getStringCellValue());
case NUMERIC -> {
if (DateUtil.isCellDateFormatted(cell)) {
yield cell.getLocalDateTimeCellValue() != null
? cell.getLocalDateTimeCellValue().toLocalDate().toString()
: null;
}
double n = cell.getNumericCellValue();
if (n == Math.rint(n) && Math.abs(n) < 1e15) {
yield String.valueOf((long) n);
}
yield BigDecimal.valueOf(n).stripTrailingZeros().toPlainString();
}
case BOOLEAN -> String.valueOf(cell.getBooleanCellValue());
case FORMULA -> {
try {
yield trimToNull(cell.getStringCellValue());
} catch (Exception ex) {
yield BigDecimal.valueOf(cell.getNumericCellValue()).stripTrailingZeros().toPlainString();
}
}
default -> null;
};
}
public static BigDecimal cellDecimal(Row row, int idx) {
String s = cellString(row, idx);
if (!StringUtils.hasText(s)) {
return null;
}
try {
return new BigDecimal(s.trim());
} catch (Exception e) {
throw new BusinessException("第 " + (row.getRowNum() + 1) + " 行数字格式错误");
}
}
private static String trimToNull(String s) {
if (s == null) {
return null;
}
String t = s.trim();
return t.isEmpty() ? null : t;
}
public static final class RowContext {
private final Row row;
public RowContext(Row row) {
this.row = row;
}
public int rowNum() {
return row.getRowNum() + 1;
}
public String str(int idx) {
return cellString(row, idx);
}
public BigDecimal decimal(int idx) {
return cellDecimal(row, idx);
}
}
}
@@ -0,0 +1,72 @@
package top.xyquan.ecomdmbbackend.modules.crm.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.xyquan.ecomdmbbackend.modules.sys.file.mapper.SysFileMapper;
import top.xyquan.ecomdmbbackend.modules.sys.file.model.FileCategory;
import top.xyquan.ecomdmbbackend.modules.sys.file.model.po.SysFilePO;
import top.xyquan.ecomdmbbackend.modules.sys.file.support.FileStorageSupport;
import top.xyquan.ecomdmbbackend.modules.sys.file.support.StoragePathBuilder;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import top.xyquan.ecomdmbbackend.utils.FileHashUtils;
import java.io.ByteArrayInputStream;
import java.time.LocalDateTime;
/**
* 业务生成文件写入 sys_file(复用存储路径规则)。
*/
@Service
public class CrmGeneratedFileService {
private final SysFileMapper sysFileMapper;
private final FileStorageSupport fileStorageSupport;
private final StoragePathBuilder storagePathBuilder;
private final CurrentUserContext currentUserContext;
public CrmGeneratedFileService(SysFileMapper sysFileMapper,
FileStorageSupport fileStorageSupport,
StoragePathBuilder storagePathBuilder,
CurrentUserContext currentUserContext) {
this.sysFileMapper = sysFileMapper;
this.fileStorageSupport = fileStorageSupport;
this.storagePathBuilder = storagePathBuilder;
this.currentUserContext = currentUserContext;
}
@Transactional
public SysFilePO saveBytes(Long companyId, String filename, String mimeType, byte[] content) {
String hash = FileHashUtils.calculateFileHash(content);
LambdaQueryWrapper<SysFilePO> w = new LambdaQueryWrapper<>();
w.eq(SysFilePO::getCompanyId, companyId)
.eq(SysFilePO::getFileHash, hash)
.isNull(SysFilePO::getDeleteTime)
.last("LIMIT 1");
SysFilePO existing = sysFileMapper.selectOne(w);
if (existing != null) {
return existing;
}
String relative = storagePathBuilder.build(filename, hash, FileCategory.FILE);
String storagePath = fileStorageSupport.persist(relative, new ByteArrayInputStream(content));
String ext = "";
int dot = filename.lastIndexOf('.');
if (dot >= 0) {
ext = filename.substring(dot + 1).toLowerCase();
}
SysFilePO po = new SysFilePO();
po.setCompanyId(companyId);
po.setStorageType(fileStorageSupport.storageType());
po.setStoragePath(storagePath);
po.setFilename(filename);
po.setFileFormat(ext);
po.setMimeType(mimeType);
po.setFileSize((long) content.length);
po.setFileHash(hash);
po.setCategory(FileCategory.FILE);
po.setUploadBy(currentUserContext.getCurrentUserId());
po.setUploadTime(LocalDateTime.now());
sysFileMapper.insert(po);
return po;
}
}
@@ -0,0 +1,29 @@
package top.xyquan.ecomdmbbackend.modules.crm.support;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* Excel 导入结果。
*/
@Data
public class CrmImportResultVO {
private int successCount;
private int failCount;
private List<RowError> errors = new ArrayList<>();
@Data
public static class RowError {
private int rowNum;
private String message;
public RowError() {}
public RowError(int rowNum, String message) {
this.rowNum = rowNum;
this.message = message;
}
}
}
@@ -0,0 +1,32 @@
package top.xyquan.ecomdmbbackend.modules.crm.support;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 邮件模板变量替换:{{key}} → 上下文值。
*/
@Component
public class CrmMailVariableRenderer {
private static final Pattern VAR = Pattern.compile("\\{\\{\\s*([a-zA-Z0-9_]+)\\s*}}");
public String render(String template, Map<String, String> vars) {
if (!StringUtils.hasText(template)) {
return "";
}
Matcher m = VAR.matcher(template);
StringBuilder sb = new StringBuilder();
while (m.find()) {
String key = m.group(1);
String value = vars.getOrDefault(key, "");
m.appendReplacement(sb, Matcher.quoteReplacement(value == null ? "" : value));
}
m.appendTail(sb);
return sb.toString();
}
}
@@ -0,0 +1,139 @@
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;
/**
* 形式发票 PI → PDF(英文排版,避免中文字体依赖)。
*/
@Component
public class CrmPiPdfRenderer {
public record Party(String name, String address, String country, String phone, String email) {
}
public record Line(int lineNo, String code, String nameEn, String spec, String unit,
BigDecimal qty, BigDecimal unitPrice, BigDecimal amount) {
}
public record PiModel(
String docTitle,
String quoteNo,
String quoteDate,
String validUntil,
String currency,
String incoterm,
String paymentTerms,
String remark,
Party seller,
Party buyer,
List<Line> lines,
BigDecimal totalAmount
) {
}
public byte[] render(PiModel model) {
String html = buildHtml(model);
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("生成 PI PDF 失败: " + e.getMessage());
}
}
private String buildHtml(PiModel m) {
StringBuilder rows = new StringBuilder();
for (Line line : m.lines()) {
rows.append("<tr>")
.append("<td>").append(line.lineNo()).append("</td>")
.append("<td>").append(esc(line.code())).append("</td>")
.append("<td>").append(esc(line.nameEn())).append("</td>")
.append("<td>").append(esc(line.spec())).append("</td>")
.append("<td>").append(esc(line.unit())).append("</td>")
.append("<td class='num'>").append(fmt(line.qty(), 3)).append("</td>")
.append("<td class='num'>").append(fmt(line.unitPrice(), 4)).append("</td>")
.append("<td class='num'>").append(fmt(line.amount(), 2)).append("</td>")
.append("</tr>");
}
Party s = m.seller() != null ? m.seller() : new Party("", "", "", "", "");
Party b = m.buyer() != null ? m.buyer() : new Party("", "", "", "", "");
StringBuilder html = new StringBuilder();
html.append("<!DOCTYPE html><html><head><meta charset=\"UTF-8\"/>")
.append("<style>")
.append("@page { size: A4; margin: 18mm; }")
.append("body { font-family: Helvetica, Arial, sans-serif; font-size: 11px; color: #222; }")
.append("h1 { font-size: 18px; margin: 0 0 8px 0; letter-spacing: 1px; }")
.append(".meta td { padding: 2px 8px 2px 0; vertical-align: top; }")
.append(".box { border: 1px solid #ccc; padding: 8px; width: 48%; }")
.append(".row { width: 100%; margin-bottom: 12px; }")
.append(".row td { vertical-align: top; }")
.append("table.items { width: 100%; border-collapse: collapse; margin-top: 10px; }")
.append("table.items th, table.items td { border: 1px solid #999; padding: 5px 6px; }")
.append("table.items th { background: #f2f2f2; text-align: left; }")
.append(".num { text-align: right; white-space: nowrap; }")
.append(".total { margin-top: 10px; text-align: right; font-size: 13px; font-weight: bold; }")
.append(".muted { color: #666; font-size: 10px; }")
.append("</style></head><body>")
.append("<h1>").append(esc(m.docTitle())).append("</h1>")
.append("<table class=\"meta\">")
.append("<tr><td><b>No.</b></td><td>").append(esc(m.quoteNo())).append("</td>")
.append("<td><b>Date</b></td><td>").append(esc(m.quoteDate())).append("</td></tr>")
.append("<tr><td><b>Valid Until</b></td><td>").append(esc(dash(m.validUntil()))).append("</td>")
.append("<td><b>Currency</b></td><td>").append(esc(m.currency())).append("</td></tr>")
.append("<tr><td><b>Incoterm</b></td><td>").append(esc(dash(m.incoterm()))).append("</td>")
.append("<td><b>Payment</b></td><td>").append(esc(dash(m.paymentTerms()))).append("</td></tr>")
.append("</table>")
.append("<table class=\"row\"><tr>")
.append("<td class=\"box\"><b>Seller</b><br/>").append(esc(s.name())).append("<br/>")
.append(esc(s.address())).append("<br/>").append(esc(s.country())).append("<br/>")
.append(esc(s.phone())).append(" ").append(esc(s.email())).append("</td>")
.append("<td style=\"width:4%\"></td>")
.append("<td class=\"box\"><b>Buyer</b><br/>").append(esc(b.name())).append("<br/>")
.append(esc(b.address())).append("<br/>").append(esc(b.country())).append("<br/>")
.append(esc(b.phone())).append(" ").append(esc(b.email())).append("</td>")
.append("</tr></table>")
.append("<table class=\"items\"><thead><tr>")
.append("<th>#</th><th>Code</th><th>Description</th><th>Spec</th>")
.append("<th>Unit</th><th>Qty</th><th>Unit Price</th><th>Amount</th>")
.append("</tr></thead><tbody>")
.append(rows)
.append("</tbody></table>")
.append("<div class=\"total\">Total ").append(esc(m.currency())).append(" ")
.append(fmt(m.totalAmount(), 2)).append("</div>")
.append("<p class=\"muted\">Remark: ").append(esc(dash(m.remark()))).append("</p>")
.append("</body></html>");
return html.toString();
}
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("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;");
}
}
@@ -0,0 +1,70 @@
package top.xyquan.ecomdmbbackend.modules.crm.support;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
/**
* CRM 敏感字段 AES-GCM(SMTP 密码等);密钥由 jwt.secret 派生。
*/
@Component
public class CrmSecretCrypto {
private static final String TRANSFORMATION = "AES/GCM/NoPadding";
private static final int GCM_IV_LENGTH = 12;
private static final int GCM_TAG_LENGTH = 128;
private final String jwtSecret;
public CrmSecretCrypto(@Value("${jwt.secret}") String jwtSecret) {
this.jwtSecret = jwtSecret;
}
public String encrypt(String plain) {
try {
byte[] iv = new byte[GCM_IV_LENGTH];
new SecureRandom().nextBytes(iv);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKey(), new GCMParameterSpec(GCM_TAG_LENGTH, iv));
byte[] cipherBytes = cipher.doFinal(plain.getBytes(StandardCharsets.UTF_8));
ByteBuffer buffer = ByteBuffer.allocate(iv.length + cipherBytes.length);
buffer.put(iv);
buffer.put(cipherBytes);
return Base64.getEncoder().encodeToString(buffer.array());
} catch (Exception e) {
throw new BusinessException("加密失败");
}
}
public String decrypt(String token) {
try {
byte[] all = Base64.getDecoder().decode(token);
ByteBuffer buffer = ByteBuffer.wrap(all);
byte[] iv = new byte[GCM_IV_LENGTH];
buffer.get(iv);
byte[] cipherBytes = new byte[buffer.remaining()];
buffer.get(cipherBytes);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKey(), new GCMParameterSpec(GCM_TAG_LENGTH, iv));
return new String(cipher.doFinal(cipherBytes), StandardCharsets.UTF_8);
} catch (Exception e) {
throw new BusinessException("解密失败,请检查 jwt.secret 是否变更");
}
}
private SecretKey secretKey() throws Exception {
byte[] digest = MessageDigest.getInstance("SHA-256")
.digest(jwtSecret.getBytes(StandardCharsets.UTF_8));
return new SecretKeySpec(digest, "AES");
}
}
@@ -0,0 +1,8 @@
package top.xyquan.ecomdmbbackend.modules.crm.support;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface CrmSeqMapper extends BaseMapper<CrmSeqPO> {
}
@@ -0,0 +1,33 @@
package top.xyquan.ecomdmbbackend.modules.crm.support;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
/** 单号发号器实体。 */
@Data
@TableName("crm_seq")
public class CrmSeqPO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("biz_type")
private String bizType;
@TableField("year")
private Integer year;
@TableField("next_val")
private Integer nextVal;
@TableField("update_time")
private LocalDateTime updateTime;
}
@@ -0,0 +1,58 @@
package top.xyquan.ecomdmbbackend.modules.crm.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Year;
/**
* 公司+年维度发号:Qyyyy###### / SHyyyy######。
*/
@Service
public class CrmSeqService {
public static final String BIZ_QUOTE = "quote";
public static final String BIZ_SHIPMENT = "shipment";
private final CrmSeqMapper crmSeqMapper;
public CrmSeqService(CrmSeqMapper crmSeqMapper) {
this.crmSeqMapper = crmSeqMapper;
}
@Transactional
public String nextQuoteNo(Long companyId) {
int seq = nextVal(companyId, BIZ_QUOTE);
return String.format("Q%d%06d", Year.now().getValue(), seq);
}
@Transactional
public String nextShipmentNo(Long companyId) {
int seq = nextVal(companyId, BIZ_SHIPMENT);
return String.format("SH%d%06d", Year.now().getValue(), seq);
}
private int nextVal(Long companyId, String bizType) {
int year = Year.now().getValue();
LambdaQueryWrapper<CrmSeqPO> q = new LambdaQueryWrapper<>();
q.eq(CrmSeqPO::getCompanyId, companyId)
.eq(CrmSeqPO::getBizType, bizType)
.eq(CrmSeqPO::getYear, year)
.last("FOR UPDATE");
CrmSeqPO row = crmSeqMapper.selectOne(q);
if (row == null) {
row = new CrmSeqPO();
row.setCompanyId(companyId);
row.setBizType(bizType);
row.setYear(year);
row.setNextVal(2);
crmSeqMapper.insert(row);
return 1;
}
int current = row.getNextVal() == null ? 1 : row.getNextVal();
row.setNextVal(current + 1);
crmSeqMapper.updateById(row);
return current;
}
}
@@ -0,0 +1,72 @@
package top.xyquan.ecomdmbbackend.modules.crm.support;
import jakarta.mail.Authenticator;
import jakarta.mail.Message;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import java.util.Properties;
/**
* 按账户动态建 SMTP Session 发送;不持有全局 MailSender。
*/
@Component
public class CrmSmtpClient {
public void send(SmtpAccount account, String to, String cc, String subject, String bodyHtml) {
try {
Properties props = new Properties();
props.put("mail.smtp.host", account.host());
props.put("mail.smtp.port", String.valueOf(account.port()));
props.put("mail.smtp.auth", "true");
if (account.ssl()) {
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.port", String.valueOf(account.port()));
} else {
props.put("mail.smtp.starttls.enable", "true");
}
props.put("mail.smtp.connectiontimeout", "15000");
props.put("mail.smtp.timeout", "30000");
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(account.username(), account.password());
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(account.fromEmail(), account.fromName()));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
if (StringUtils.hasText(cc)) {
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
}
message.setSubject(subject, "UTF-8");
message.setContent(bodyHtml, "text/html; charset=UTF-8");
Transport.send(message);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException("邮件发送失败: " + e.getMessage());
}
}
/** SMTP 发件参数(明文密码仅在内存短暂使用)。 */
public record SmtpAccount(
String fromName,
String fromEmail,
String host,
int port,
boolean ssl,
String username,
String password
) {
}
}

Some files were not shown because too many files have changed in this diff Show More