mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
feat: 加入规格体系
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -40,7 +40,7 @@ CREATE TABLE `ec_product` (
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`category_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '类目ID',
|
||||
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '商品名称',
|
||||
`product_code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '商品编码(公司内唯一;未填为空)',
|
||||
`product_code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '商品编码(公司内唯一,必填)',
|
||||
`main_image_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '主图图片ID(系统文件)',
|
||||
`main_image_url` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '主图外链URL(渠道自动建品等;查询时有 id 则覆盖)',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
@@ -77,7 +77,8 @@ CREATE TABLE `ec_product_sku` (
|
||||
`name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'SKU 名称(如颜色/尺码组合展示名)',
|
||||
`sku_code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'SKU 编码(公司内唯一,对应商家外部编码)',
|
||||
`barcode` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '条码(可选)',
|
||||
`attrs` json NULL COMMENT '规格属性 JSON,如 [{"name":"颜色","value":"红"}]',
|
||||
`attrs` json NULL COMMENT '规格属性 JSON,如 [{"name":"颜色","value":"红"}](冗余/过渡;结构化见 ec_product_spec*)',
|
||||
`spec_combination_key` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '规格组合键(value_id 升序拼接;空=未结构化遗留)',
|
||||
`image_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT 'SKU 图文件ID(系统文件,可选)',
|
||||
`image_url` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'SKU 图外链URL(渠道自动建品等;查询时有 id 则覆盖)',
|
||||
`status` tinyint NOT NULL DEFAULT 1 COMMENT '状态:0停用 1启用',
|
||||
@@ -89,6 +90,7 @@ CREATE TABLE `ec_product_sku` (
|
||||
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uk_ec_product_sku_company_code`(`company_id` ASC, `sku_code` ASC) USING BTREE,
|
||||
UNIQUE INDEX `uk_ec_product_sku_product_combination`(`product_id` ASC, `spec_combination_key` ASC) USING BTREE,
|
||||
INDEX `idx_ec_product_sku_company`(`company_id` ASC) USING BTREE,
|
||||
INDEX `idx_ec_product_sku_product`(`product_id` ASC) USING BTREE,
|
||||
INDEX `idx_ec_product_sku_status`(`status` ASC) USING BTREE,
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
-- 商品规格维设计(与 migration V20260910b 对齐)
|
||||
-- ec_product_spec / ec_product_spec_value / ec_product_sku_spec_value
|
||||
-- SKU.spec_combination_key:空=遗留无结构多 SKU;非空=结构化组合唯一
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `ec_product_spec` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '规格维ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`product_id` bigint UNSIGNED NOT NULL COMMENT '商品ID',
|
||||
`name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '规格名称,如颜色、尺码',
|
||||
`sort_order` int NOT NULL DEFAULT 0 COMMENT '排序(越小越靠前,影响 SKU 编码拼接顺序)',
|
||||
`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 '创建人ID',
|
||||
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uk_ec_product_spec_product_name` (`product_id` ASC, `name` ASC) USING BTREE,
|
||||
INDEX `idx_ec_product_spec_company_product` (`company_id` ASC, `product_id` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_product_spec_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_product_spec_product` FOREIGN KEY (`product_id`) REFERENCES `ec_product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-商品规格维' ROW_FORMAT = Dynamic;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `ec_product_spec_value` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '规格值ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`product_id` bigint UNSIGNED NOT NULL COMMENT '商品ID(冗余,便于校验归属)',
|
||||
`spec_id` bigint UNSIGNED NOT NULL COMMENT '规格维ID',
|
||||
`value_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '规格值展示名',
|
||||
`value_code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '规格值编码(拼 SKU 编码)',
|
||||
`sort_order` int 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 '创建人ID',
|
||||
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uk_ec_product_spec_value_name` (`spec_id` ASC, `value_name` ASC) USING BTREE,
|
||||
UNIQUE INDEX `uk_ec_product_spec_value_code` (`spec_id` ASC, `value_code` ASC) USING BTREE,
|
||||
INDEX `idx_ec_product_spec_value_product` (`product_id` ASC) USING BTREE,
|
||||
INDEX `idx_ec_product_spec_value_company` (`company_id` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_product_spec_value_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_product_spec_value_product` FOREIGN KEY (`product_id`) REFERENCES `ec_product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_product_spec_value_spec` FOREIGN KEY (`spec_id`) REFERENCES `ec_product_spec` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-商品规格值' ROW_FORMAT = Dynamic;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `ec_product_sku_spec_value` (
|
||||
`sku_id` bigint UNSIGNED NOT NULL COMMENT 'SKU ID',
|
||||
`spec_value_id` bigint UNSIGNED NOT NULL COMMENT '规格值ID',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
PRIMARY KEY (`sku_id`, `spec_value_id`) USING BTREE,
|
||||
INDEX `idx_ec_product_sku_spec_value_sv` (`spec_value_id` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_product_sku_spec_value_sku` FOREIGN KEY (`sku_id`) REFERENCES `ec_product_sku` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_product_sku_spec_value_sv` FOREIGN KEY (`spec_value_id`) REFERENCES `ec_product_spec_value` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-SKU与规格值关系' ROW_FORMAT = Dynamic;
|
||||
@@ -0,0 +1,34 @@
|
||||
-- 规格模板设计(与 migration V20260910c 对齐)
|
||||
-- ec_spec_template / ec_spec_template_value
|
||||
-- 模型:一个模板 = 一个规格维(公司级);建公司时种子 款式/颜色/尺码/容量
|
||||
-- 商品规格实例见 ec_product_spec_design.sql
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `ec_spec_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 '规格维名称,如颜色、尺码',
|
||||
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '备注',
|
||||
`sort_order` int 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 '创建人ID',
|
||||
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uk_ec_spec_template_company_name` (`company_id` ASC, `name` ASC) USING BTREE,
|
||||
INDEX `idx_ec_spec_template_company` (`company_id` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_spec_template_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 = '电商-规格模板(单维)' ROW_FORMAT = Dynamic;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `ec_spec_template_value` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '模板规格值ID',
|
||||
`template_id` bigint UNSIGNED NOT NULL COMMENT '模板ID',
|
||||
`value_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '规格值名称',
|
||||
`value_code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '规格值编码',
|
||||
`sort_order` int 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 '更新时间',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uk_ec_spec_template_value_name` (`template_id` ASC, `value_name` ASC) USING BTREE,
|
||||
UNIQUE INDEX `uk_ec_spec_template_value_code` (`template_id` ASC, `value_code` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_spec_template_value_template` FOREIGN KEY (`template_id`) REFERENCES `ec_spec_template` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-规格模板值' ROW_FORMAT = Dynamic;
|
||||
@@ -0,0 +1,23 @@
|
||||
-- 存量空商品编码补齐后加非空约束(公司内仍唯一)
|
||||
-- 优先 P{id};若同公司已被占用则用 P{id}_{id} 兜底
|
||||
|
||||
UPDATE `ec_product` p
|
||||
SET p.`product_code` = CONCAT('P', p.`id`)
|
||||
WHERE (p.`product_code` IS NULL OR TRIM(p.`product_code`) = '')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM (
|
||||
SELECT `id`, `company_id`, `product_code`
|
||||
FROM `ec_product`
|
||||
) x
|
||||
WHERE x.`company_id` = p.`company_id`
|
||||
AND x.`product_code` = CONCAT('P', p.`id`)
|
||||
AND x.`id` <> p.`id`
|
||||
);
|
||||
|
||||
UPDATE `ec_product`
|
||||
SET `product_code` = CONCAT('P', `id`, '_', `id`)
|
||||
WHERE `product_code` IS NULL OR TRIM(`product_code`) = '';
|
||||
|
||||
ALTER TABLE `ec_product`
|
||||
MODIFY COLUMN `product_code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '商品编码(公司内唯一,必填)';
|
||||
@@ -0,0 +1,55 @@
|
||||
-- 商品规格维:规格 / 规格值 / SKU-规格值关系;SKU 增加组合键(空=遗留无结构)
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `ec_product_spec` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '规格维ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`product_id` bigint UNSIGNED NOT NULL COMMENT '商品ID',
|
||||
`name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '规格名称,如颜色、尺码',
|
||||
`sort_order` int NOT NULL DEFAULT 0 COMMENT '排序(越小越靠前,影响 SKU 编码拼接顺序)',
|
||||
`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 '创建人ID',
|
||||
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uk_ec_product_spec_product_name` (`product_id` ASC, `name` ASC) USING BTREE,
|
||||
INDEX `idx_ec_product_spec_company_product` (`company_id` ASC, `product_id` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_product_spec_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_product_spec_product` FOREIGN KEY (`product_id`) REFERENCES `ec_product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-商品规格维' ROW_FORMAT = Dynamic;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `ec_product_spec_value` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '规格值ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`product_id` bigint UNSIGNED NOT NULL COMMENT '商品ID(冗余,便于校验归属)',
|
||||
`spec_id` bigint UNSIGNED NOT NULL COMMENT '规格维ID',
|
||||
`value_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '规格值展示名',
|
||||
`value_code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '规格值编码(拼 SKU 编码)',
|
||||
`sort_order` int 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 '创建人ID',
|
||||
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uk_ec_product_spec_value_name` (`spec_id` ASC, `value_name` ASC) USING BTREE,
|
||||
UNIQUE INDEX `uk_ec_product_spec_value_code` (`spec_id` ASC, `value_code` ASC) USING BTREE,
|
||||
INDEX `idx_ec_product_spec_value_product` (`product_id` ASC) USING BTREE,
|
||||
INDEX `idx_ec_product_spec_value_company` (`company_id` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_product_spec_value_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_product_spec_value_product` FOREIGN KEY (`product_id`) REFERENCES `ec_product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_product_spec_value_spec` FOREIGN KEY (`spec_id`) REFERENCES `ec_product_spec` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-商品规格值' ROW_FORMAT = Dynamic;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `ec_product_sku_spec_value` (
|
||||
`sku_id` bigint UNSIGNED NOT NULL COMMENT 'SKU ID',
|
||||
`spec_value_id` bigint UNSIGNED NOT NULL COMMENT '规格值ID',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
PRIMARY KEY (`sku_id`, `spec_value_id`) USING BTREE,
|
||||
INDEX `idx_ec_product_sku_spec_value_sv` (`spec_value_id` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_product_sku_spec_value_sku` FOREIGN KEY (`sku_id`) REFERENCES `ec_product_sku` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_product_sku_spec_value_sv` FOREIGN KEY (`spec_value_id`) REFERENCES `ec_product_spec_value` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-SKU与规格值关系' ROW_FORMAT = Dynamic;
|
||||
|
||||
-- NULL = 遗留无结构多 SKU;非空时同商品内组合唯一
|
||||
ALTER TABLE `ec_product_sku`
|
||||
ADD COLUMN `spec_combination_key` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '规格组合键(value_id 升序拼接;空=未结构化)' AFTER `attrs`,
|
||||
ADD UNIQUE INDEX `uk_ec_product_sku_product_combination` (`product_id` ASC, `spec_combination_key` ASC) USING BTREE;
|
||||
@@ -0,0 +1,67 @@
|
||||
-- 规格模板两表模型:模板=单个规格维;建公司时种子 款式/颜色/尺码/容量
|
||||
-- 若曾执行过三表版本,先删后建
|
||||
|
||||
DROP TABLE IF EXISTS `ec_spec_template_value`;
|
||||
DROP TABLE IF EXISTS `ec_spec_template_spec`;
|
||||
DROP TABLE IF EXISTS `ec_spec_template`;
|
||||
|
||||
CREATE TABLE `ec_spec_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 '规格维名称,如颜色、尺码',
|
||||
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '备注',
|
||||
`sort_order` int 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 '创建人ID',
|
||||
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uk_ec_spec_template_company_name` (`company_id` ASC, `name` ASC) USING BTREE,
|
||||
INDEX `idx_ec_spec_template_company` (`company_id` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_spec_template_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 = '电商-规格模板(单维)' ROW_FORMAT = Dynamic;
|
||||
|
||||
CREATE TABLE `ec_spec_template_value` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '模板规格值ID',
|
||||
`template_id` bigint UNSIGNED NOT NULL COMMENT '模板ID',
|
||||
`value_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '规格值名称',
|
||||
`value_code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '规格值编码',
|
||||
`sort_order` int 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 '更新时间',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uk_ec_spec_template_value_name` (`template_id` ASC, `value_name` ASC) USING BTREE,
|
||||
UNIQUE INDEX `uk_ec_spec_template_value_code` (`template_id` ASC, `value_code` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_spec_template_value_template` FOREIGN KEY (`template_id`) REFERENCES `ec_spec_template` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-规格模板值' ROW_FORMAT = Dynamic;
|
||||
|
||||
-- 权限:ec:product:spec-template:*
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 3160, (SELECT id FROM `sys_permission` WHERE `code` = 'ec:product' LIMIT 1), 'ec:product:spec-template', '规格模板', 'module', 1, '', 30
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3160 OR `code` = 'ec:product:spec-template');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 3161, (SELECT id FROM `sys_permission` WHERE `code` = 'ec:product:spec-template' LIMIT 1), 'ec:product:spec-template:read', '查看', 'api', 1, '', 1
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3161 OR `code` = 'ec:product:spec-template:read');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 3162, (SELECT id FROM `sys_permission` WHERE `code` = 'ec:product:spec-template' LIMIT 1), 'ec:product:spec-template:create', '创建', 'api', 1, '', 2
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3162 OR `code` = 'ec:product:spec-template:create');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 3163, (SELECT id FROM `sys_permission` WHERE `code` = 'ec:product:spec-template' LIMIT 1), 'ec:product:spec-template:update', '更新', 'api', 1, '', 3
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3163 OR `code` = 'ec:product:spec-template:update');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 3164, (SELECT id FROM `sys_permission` WHERE `code` = 'ec:product:spec-template' LIMIT 1), 'ec:product:spec-template:delete', '删除', 'api', 1, '', 4
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3164 OR `code` = 'ec:product:spec-template:delete');
|
||||
|
||||
-- 菜单:经营商品下
|
||||
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
|
||||
SELECT 56, (SELECT id FROM `sys_menu` WHERE `id` = 14006 OR `name` = '经营商品' LIMIT 1), 0, '规格模板', 'SpecTemplate', '规格模板', '/ec/product/spec-template', '/ec/product/spec-template/index', '', 'lucide:layout-template', 'menu', 1, 1, 1, 3
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 56 OR `name` = '规格模板' OR `route_name` = 'SpecTemplate');
|
||||
|
||||
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||
SELECT m.id, p.id FROM `sys_menu` m
|
||||
JOIN `sys_permission` p ON p.code LIKE 'ec:product:spec-template:%'
|
||||
WHERE m.name = '规格模板';
|
||||
@@ -0,0 +1,47 @@
|
||||
-- 为所有已有公司补齐默认规格模板与规格值(与 seedDefaultTemplates 一致,可重复执行)
|
||||
-- 依赖:V20260910c 已建 ec_spec_template / ec_spec_template_value
|
||||
|
||||
-- 1) 缺省的规格维模板
|
||||
INSERT INTO `ec_spec_template` (`company_id`, `name`, `sort_order`)
|
||||
SELECT c.`id`, d.`name`, d.`sort_order`
|
||||
FROM `org_company` c
|
||||
CROSS JOIN (
|
||||
SELECT '款式' AS `name`, 0 AS `sort_order`
|
||||
UNION ALL SELECT '颜色', 1
|
||||
UNION ALL SELECT '尺码', 2
|
||||
UNION ALL SELECT '容量', 3
|
||||
) d
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM `ec_spec_template` t
|
||||
WHERE t.`company_id` = c.`id`
|
||||
AND t.`name` = d.`name`
|
||||
);
|
||||
|
||||
-- 2) 缺省的规格值(按维名匹配;已存在同名或同编码则跳过)
|
||||
INSERT INTO `ec_spec_template_value` (`template_id`, `value_name`, `value_code`, `sort_order`)
|
||||
SELECT t.`id`, v.`value_name`, v.`value_code`, v.`sort_order`
|
||||
FROM `ec_spec_template` t
|
||||
INNER JOIN (
|
||||
SELECT '款式' AS `template_name`, '标准款' AS `value_name`, 'STD' AS `value_code`, 0 AS `sort_order`
|
||||
UNION ALL SELECT '颜色', '黑色', 'BLK', 0
|
||||
UNION ALL SELECT '颜色', '白色', 'WHT', 1
|
||||
UNION ALL SELECT '颜色', '灰色', 'GRY', 2
|
||||
UNION ALL SELECT '颜色', '红色', 'RED', 3
|
||||
UNION ALL SELECT '颜色', '蓝色', 'BLU', 4
|
||||
UNION ALL SELECT '尺码', 'S', 'S', 0
|
||||
UNION ALL SELECT '尺码', 'M', 'M', 1
|
||||
UNION ALL SELECT '尺码', 'L', 'L', 2
|
||||
UNION ALL SELECT '尺码', 'XL', 'XL', 3
|
||||
UNION ALL SELECT '容量', '100ML', '100ML', 0
|
||||
UNION ALL SELECT '容量', '250ML', '250ML', 1
|
||||
UNION ALL SELECT '容量', '500ML', '500ML', 2
|
||||
UNION ALL SELECT '容量', '1L', '1L', 3
|
||||
) v ON v.`template_name` = t.`name`
|
||||
WHERE t.`name` IN ('款式', '颜色', '尺码', '容量')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM `ec_spec_template_value` x
|
||||
WHERE x.`template_id` = t.`id`
|
||||
AND (x.`value_name` = v.`value_name` OR x.`value_code` = v.`value_code`)
|
||||
);
|
||||
+6
@@ -4,6 +4,7 @@ import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.ReplaceProductSpecsDTO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
@@ -17,6 +18,7 @@ public class CreateProductDTO {
|
||||
@NotBlank(message = "商品名称不能为空")
|
||||
private String name;
|
||||
|
||||
@NotBlank(message = "商品编码不能为空")
|
||||
private String productCode;
|
||||
|
||||
private Long categoryId;
|
||||
@@ -26,6 +28,10 @@ public class CreateProductDTO {
|
||||
@Valid
|
||||
private List<ProductSkuDTO> skus;
|
||||
|
||||
/** 可选;与商品同事务写入规格维(id 空=新增)。 */
|
||||
@Valid
|
||||
private List<ReplaceProductSpecsDTO.SpecItem> specs;
|
||||
|
||||
@Data
|
||||
public static class ProductSkuDTO {
|
||||
|
||||
|
||||
+9
-1
@@ -4,6 +4,7 @@ import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.ReplaceProductSpecsDTO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
@@ -17,6 +18,7 @@ public class UpdateProductDTO {
|
||||
@NotBlank(message = "商品名称不能为空")
|
||||
private String name;
|
||||
|
||||
@NotBlank(message = "商品编码不能为空")
|
||||
private String productCode;
|
||||
|
||||
private Long categoryId;
|
||||
@@ -24,11 +26,17 @@ public class UpdateProductDTO {
|
||||
private Long mainImageId;
|
||||
|
||||
/**
|
||||
* 传入则按全量同步:id>0 更新,id 为 null/0 新增,库中有但未出现的删除。
|
||||
* 传入则按全量同步:id>0 更新,id 为 null/0 新增,库中有但未出现的删除。
|
||||
*/
|
||||
@Valid
|
||||
private List<ProductSkuUpdateDTO> skus;
|
||||
|
||||
/**
|
||||
* 传入则全量同步规格维(有 id 更新,无 id 新增,未出现的删除)。
|
||||
*/
|
||||
@Valid
|
||||
private List<ReplaceProductSpecsDTO.SpecItem> specs;
|
||||
|
||||
@Data
|
||||
public static class ProductSkuUpdateDTO {
|
||||
|
||||
|
||||
+5
@@ -67,6 +67,11 @@ public class ProductVO {
|
||||
*/
|
||||
private Long updateBy;
|
||||
|
||||
/**
|
||||
* 商品规格维(结构化)
|
||||
*/
|
||||
private List<top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecVO> specs;
|
||||
|
||||
/**
|
||||
* 商品 SKU 列表
|
||||
*/
|
||||
|
||||
+32
-8
@@ -30,6 +30,8 @@ import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.service.OrderService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.service.ProductSkuService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.ReplaceProductSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.service.ProductSpecService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.adfee.mapper.AdFeeMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.adfee.model.po.AdFeePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.fakeordersfee.mapper.FakeOrdersFeeMapper;
|
||||
@@ -64,6 +66,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final SysFileMapper sysFileMapper;
|
||||
private final ProductSkuService productSkuService;
|
||||
private final ProductSpecService productSpecService;
|
||||
private final CategoryService categoryService;
|
||||
private final OrderService orderService;
|
||||
private final BiOrderStatDirtyDayService biOrderStatDirtyDayService;
|
||||
@@ -72,7 +75,9 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
private final FakeOrdersFeeMapper fakeOrdersFeeMapper;
|
||||
|
||||
public ProductServiceImpl(CurrentUserContext currentUserContext, SysFileMapper sysFileMapper,
|
||||
@Lazy ProductSkuService productSkuService, @Lazy CategoryService categoryService,
|
||||
@Lazy ProductSkuService productSkuService,
|
||||
@Lazy ProductSpecService productSpecService,
|
||||
@Lazy CategoryService categoryService,
|
||||
@Lazy OrderService orderService,
|
||||
BiOrderStatDirtyDayService biOrderStatDirtyDayService,
|
||||
OrderItemMapper orderItemMapper,
|
||||
@@ -81,6 +86,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.sysFileMapper = sysFileMapper;
|
||||
this.productSkuService = productSkuService;
|
||||
this.productSpecService = productSpecService;
|
||||
this.categoryService = categoryService;
|
||||
this.orderService = orderService;
|
||||
this.biOrderStatDirtyDayService = biOrderStatDirtyDayService;
|
||||
@@ -144,8 +150,14 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
}
|
||||
}
|
||||
|
||||
if (createProductDTO.getSpecs() != null) {
|
||||
ReplaceProductSpecsDTO specsDto = new ReplaceProductSpecsDTO();
|
||||
specsDto.setSpecs(createProductDTO.getSpecs());
|
||||
productSpecService.replaceSpecs(product.getId(), specsDto);
|
||||
}
|
||||
|
||||
CreateProductResultDTO result = new CreateProductResultDTO();
|
||||
result.setProduct(convertToVO(product));
|
||||
result.setProduct(convertToVO(this.getById(product.getId())));
|
||||
result.setSkuIdsCostChangedWithLinkedOrders(new ArrayList<>(syncSkuIds));
|
||||
return result;
|
||||
}
|
||||
@@ -464,6 +476,12 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
rawCostChangedSkuIds, newSkuIdsFromCodeWithOrders);
|
||||
}
|
||||
|
||||
if (updateProductDTO.getSpecs() != null) {
|
||||
ReplaceProductSpecsDTO specsDto = new ReplaceProductSpecsDTO();
|
||||
specsDto.setSpecs(updateProductDTO.getSpecs());
|
||||
productSpecService.replaceSpecs(id, specsDto);
|
||||
}
|
||||
|
||||
// 返回结果:成本变更且有关联订单的规格 ∪ 新增规格(编码非空)且有关联订单的规格
|
||||
UpdateProductResultDTO result = new UpdateProductResultDTO();
|
||||
LinkedHashSet<Long> syncUnion = new LinkedHashSet<>();
|
||||
@@ -720,6 +738,15 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
.collect(Collectors.toList());
|
||||
|
||||
productVO.setSkus(skuVOs);
|
||||
productVO.setSpecs(productSpecService.listByProductId(product.getId()));
|
||||
if (!skuVOs.isEmpty()) {
|
||||
Map<Long, List<top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecValueVO>> bySku =
|
||||
productSpecService.listSkuSpecValues(
|
||||
skuVOs.stream().map(ProductSkuVO::getId).collect(Collectors.toList()));
|
||||
for (ProductSkuVO skuVo : skuVOs) {
|
||||
skuVo.setSpecValues(bySku.getOrDefault(skuVo.getId(), List.of()));
|
||||
}
|
||||
}
|
||||
return productVO;
|
||||
}
|
||||
|
||||
@@ -727,12 +754,9 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
return productSkuService.toVo(productSku);
|
||||
}
|
||||
|
||||
/** 公司内商品编码唯一;未填不校验。 */
|
||||
/** 公司内商品编码唯一;必填。 */
|
||||
private void assertProductCodeUnique(Long companyId, String productCode, Long excludeId) {
|
||||
String code = normalizeProductCode(productCode);
|
||||
if (code == null) {
|
||||
return;
|
||||
}
|
||||
LambdaQueryWrapper<ProductPO> uniqueWrapper = new LambdaQueryWrapper<>();
|
||||
uniqueWrapper.eq(ProductPO::getCompanyId, companyId)
|
||||
.eq(ProductPO::getProductCode, code);
|
||||
@@ -744,10 +768,10 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
}
|
||||
}
|
||||
|
||||
/** 空白编码规范为 null,不参与唯一约束。 */
|
||||
/** 商品编码必填并 trim。 */
|
||||
private static String normalizeProductCode(String productCode) {
|
||||
if (productCode == null || productCode.isBlank()) {
|
||||
return null;
|
||||
throw new BusinessException("商品编码不能为空");
|
||||
}
|
||||
return productCode.trim();
|
||||
}
|
||||
|
||||
+4
@@ -35,6 +35,10 @@ public class ProductSkuPO {
|
||||
@TableField("attrs")
|
||||
private String attrs;
|
||||
|
||||
/** 空=遗留无结构;非空=结构化组合唯一键 */
|
||||
@TableField("spec_combination_key")
|
||||
private String specCombinationKey;
|
||||
|
||||
@TableField("image_id")
|
||||
private Long imageId;
|
||||
|
||||
|
||||
+7
@@ -5,6 +5,7 @@ import lombok.Data;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 商品 SKU VO(含当前生效成本扁平字段)
|
||||
@@ -24,6 +25,12 @@ public class ProductSkuVO {
|
||||
|
||||
private String skuCode;
|
||||
|
||||
/** 空=遗留无结构 SKU */
|
||||
private String specCombinationKey;
|
||||
|
||||
/** 结构化规格值(未结构化则为空) */
|
||||
private List<top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecValueVO> specValues;
|
||||
|
||||
private String imageUrl;
|
||||
|
||||
private BigDecimal productCost;
|
||||
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.vo.ProductSkuVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.BindSkuSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.CreateSkuFromSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.GenerateProductSkusDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.ReplaceProductSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.service.ProductSpecService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.ApplySpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.SaveProductAsTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.vo.SpecTemplateVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.service.SpecTemplateService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 商品规格维 API(属商品;生成 SKU 可选)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/ec/product/{productId}/specs")
|
||||
public class ProductSpecController {
|
||||
|
||||
private final ProductSpecService productSpecService;
|
||||
private final SpecTemplateService specTemplateService;
|
||||
|
||||
public ProductSpecController(ProductSpecService productSpecService,
|
||||
SpecTemplateService specTemplateService) {
|
||||
this.productSpecService = productSpecService;
|
||||
this.specTemplateService = specTemplateService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@RequirePermission(value = "ec:product:read", description = "查询商品规格", allowSuper = true)
|
||||
public ApiResponse<List<ProductSpecVO>> list(@PathVariable Long productId) {
|
||||
return ApiResponse.success("获取成功", productSpecService.listByProductId(productId));
|
||||
}
|
||||
|
||||
@PutMapping
|
||||
@RequirePermission(value = "ec:product:update", description = "保存商品规格", allowSuper = true)
|
||||
public ApiResponse<List<ProductSpecVO>> replace(@PathVariable Long productId,
|
||||
@Valid @RequestBody ReplaceProductSpecsDTO dto) {
|
||||
return ApiResponse.success("保存成功", productSpecService.replaceSpecs(productId, dto));
|
||||
}
|
||||
|
||||
@PostMapping("/generate-skus")
|
||||
@RequirePermission(value = "ec:product:update", description = "按规格生成SKU", allowSuper = true)
|
||||
public ApiResponse<List<ProductSkuVO>> generateSkus(@PathVariable Long productId,
|
||||
@RequestBody(required = false) GenerateProductSkusDTO dto) {
|
||||
List<ProductSkuVO> created = productSpecService.generateSkus(productId,
|
||||
dto != null ? dto : new GenerateProductSkusDTO());
|
||||
return ApiResponse.success("已生成 " + created.size() + " 个 SKU", created);
|
||||
}
|
||||
|
||||
@PostMapping("/skus")
|
||||
@RequirePermission(value = "ec:product:update", description = "按规格值创建SKU", allowSuper = true)
|
||||
public ApiResponse<ProductSkuVO> createSkuFromSpecs(@PathVariable Long productId,
|
||||
@Valid @RequestBody CreateSkuFromSpecsDTO dto) {
|
||||
return ApiResponse.success("创建成功", productSpecService.createSkuFromSpecs(productId, dto));
|
||||
}
|
||||
|
||||
/**
|
||||
* 为已有 SKU 绑定规格值(不改 sku_code);body.specValueIds 空则解绑。
|
||||
*/
|
||||
@PutMapping("/skus/{skuId}")
|
||||
@RequirePermission(value = "ec:product:update", description = "SKU绑定规格", allowSuper = true)
|
||||
public ApiResponse<ProductSkuVO> bindSkuSpecs(@PathVariable Long productId,
|
||||
@PathVariable Long skuId,
|
||||
@RequestBody(required = false) BindSkuSpecsDTO dto) {
|
||||
return ApiResponse.success("绑定成功",
|
||||
productSpecService.bindSkuSpecs(productId, skuId, dto != null ? dto : new BindSkuSpecsDTO()));
|
||||
}
|
||||
|
||||
/** 套用规格模板到商品(合并维值,不生成 SKU)。 */
|
||||
@PostMapping("/apply-template")
|
||||
@RequirePermission(value = "ec:product:update", description = "套用规格模板", allowSuper = true)
|
||||
public ApiResponse<List<ProductSpecVO>> applyTemplate(@PathVariable Long productId,
|
||||
@Valid @RequestBody ApplySpecTemplateDTO dto) {
|
||||
return ApiResponse.success("套用成功", specTemplateService.applyToProduct(productId, dto));
|
||||
}
|
||||
|
||||
/** 将商品现有规格另存为公司模板。 */
|
||||
@PostMapping("/save-as-template")
|
||||
@RequirePermission(value = "ec:product:spec-template:create", description = "商品规格另存为模板", allowSuper = true)
|
||||
public ApiResponse<SpecTemplateVO> saveAsTemplate(@PathVariable Long productId,
|
||||
@Valid @RequestBody SaveProductAsTemplateDTO dto) {
|
||||
return ApiResponse.success("保存成功", specTemplateService.saveProductAsTemplate(productId, dto));
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.domain;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po.ProductSpecPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po.ProductSpecValuePO;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 规格组合键与 SKU 编码生成(纯函数,无 IO)。
|
||||
* combination_key 按 value_id 升序;sku_code 按规格 sort 拼接 value_code。
|
||||
*/
|
||||
public final class ProductSpecCodes {
|
||||
|
||||
public static final int MAX_GENERATED_SKUS = 200;
|
||||
|
||||
private ProductSpecCodes() {
|
||||
}
|
||||
|
||||
/** 组合唯一键:规格值 ID 升序,下划线拼接。 */
|
||||
public static String combinationKey(List<Long> specValueIds) {
|
||||
if (specValueIds == null || specValueIds.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return specValueIds.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.sorted()
|
||||
.map(String::valueOf)
|
||||
.collect(Collectors.joining("_"));
|
||||
}
|
||||
|
||||
/**
|
||||
* sku_code = productCode-valueCode…(规格 sort 升序,同 sort 再按 specId)。
|
||||
*/
|
||||
public static String buildSkuCode(String productCode,
|
||||
List<ProductSpecValuePO> values,
|
||||
Map<Long, ProductSpecPO> specById) {
|
||||
String pc = productCode == null ? "" : productCode.trim();
|
||||
if (pc.isEmpty()) {
|
||||
throw new IllegalArgumentException("商品编码不能为空");
|
||||
}
|
||||
if (values == null || values.isEmpty()) {
|
||||
return pc;
|
||||
}
|
||||
List<ProductSpecValuePO> ordered = new ArrayList<>(values);
|
||||
ordered.sort(Comparator
|
||||
.comparing((ProductSpecValuePO v) -> {
|
||||
ProductSpecPO s = specById.get(v.getSpecId());
|
||||
return s != null && s.getSortOrder() != null ? s.getSortOrder() : 0;
|
||||
})
|
||||
.thenComparing(v -> v.getSpecId() != null ? v.getSpecId() : 0L)
|
||||
.thenComparing(v -> v.getSortOrder() != null ? v.getSortOrder() : 0)
|
||||
.thenComparing(v -> v.getId() != null ? v.getId() : 0L));
|
||||
StringBuilder sb = new StringBuilder(pc);
|
||||
for (ProductSpecValuePO v : ordered) {
|
||||
String code = v.getValueCode() == null ? "" : v.getValueCode().trim();
|
||||
if (code.isEmpty()) {
|
||||
throw new IllegalArgumentException("规格值编码不能为空");
|
||||
}
|
||||
sb.append('-').append(code);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/** 展示名:valueName 按规格 sort 用「/」拼接。 */
|
||||
public static String buildSkuDisplayName(List<ProductSpecValuePO> values,
|
||||
Map<Long, ProductSpecPO> specById) {
|
||||
if (values == null || values.isEmpty()) {
|
||||
return "默认";
|
||||
}
|
||||
List<ProductSpecValuePO> ordered = new ArrayList<>(values);
|
||||
ordered.sort(Comparator
|
||||
.comparing((ProductSpecValuePO v) -> {
|
||||
ProductSpecPO s = specById.get(v.getSpecId());
|
||||
return s != null && s.getSortOrder() != null ? s.getSortOrder() : 0;
|
||||
})
|
||||
.thenComparing(v -> v.getSpecId() != null ? v.getSpecId() : 0L));
|
||||
return ordered.stream()
|
||||
.map(v -> v.getValueName() != null ? v.getValueName() : "")
|
||||
.filter(s -> !s.isBlank())
|
||||
.collect(Collectors.joining("/"));
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po.ProductSkuSpecValuePO;
|
||||
|
||||
@Mapper
|
||||
public interface ProductSkuSpecValueMapper extends BaseMapper<ProductSkuSpecValuePO> {
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po.ProductSpecPO;
|
||||
|
||||
@Mapper
|
||||
public interface ProductSpecMapper extends BaseMapper<ProductSpecPO> {
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po.ProductSpecValuePO;
|
||||
|
||||
@Mapper
|
||||
public interface ProductSpecValueMapper extends BaseMapper<ProductSpecValuePO> {
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 为已有 SKU 绑定(或解绑)规格值。
|
||||
* 不修改 sku_code;specValueIds 空或 null 表示解绑回 legacy。
|
||||
*/
|
||||
@Data
|
||||
public class BindSkuSpecsDTO {
|
||||
|
||||
/** 规格值 ID;同一规格维最多一个;空=解绑 */
|
||||
private List<Long> specValueIds;
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 按所选规格值创建 SKU(允许缺维;编码可空则按商品编码+value_code 生成)。
|
||||
*/
|
||||
@Data
|
||||
public class CreateSkuFromSpecsDTO {
|
||||
|
||||
/** 规格值 ID 列表;同一规格维最多一个 */
|
||||
@NotEmpty(message = "请至少选择一个规格值")
|
||||
private List<Long> specValueIds;
|
||||
|
||||
/** 可选;空则自动生成 */
|
||||
private String skuCode;
|
||||
|
||||
/** 可选;空则用规格值名拼接 */
|
||||
private String name;
|
||||
|
||||
@NotNull(message = "商品成本不能为空")
|
||||
private BigDecimal productCost;
|
||||
|
||||
private BigDecimal shippingCost;
|
||||
|
||||
private BigDecimal otherCost;
|
||||
|
||||
private String remark;
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 按当前规格维笛卡尔积生成缺失 SKU。
|
||||
* 成本缺省为 0,可随后在 SKU 成本中调整。
|
||||
*/
|
||||
@Data
|
||||
public class GenerateProductSkusDTO {
|
||||
|
||||
private BigDecimal productCost;
|
||||
|
||||
private BigDecimal shippingCost;
|
||||
|
||||
private BigDecimal otherCost;
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 全量覆盖保存商品规格维。specs 可空列表表示清空未引用规格。 */
|
||||
@Data
|
||||
public class ReplaceProductSpecsDTO {
|
||||
|
||||
@Valid
|
||||
private List<SpecItem> specs;
|
||||
|
||||
@Data
|
||||
public static class SpecItem {
|
||||
/** 已有规格维 ID;空表示新增 */
|
||||
private Long id;
|
||||
|
||||
@NotBlank(message = "规格名称不能为空")
|
||||
private String name;
|
||||
|
||||
private Integer sortOrder;
|
||||
|
||||
@Valid
|
||||
private List<ValueItem> values;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class ValueItem {
|
||||
/** 已有规格值 ID;空表示新增 */
|
||||
private Long id;
|
||||
|
||||
@NotBlank(message = "规格值名称不能为空")
|
||||
private String valueName;
|
||||
|
||||
@NotBlank(message = "规格值编码不能为空")
|
||||
@Pattern(regexp = "^[A-Za-z0-9_-]+$", message = "规格值编码仅允许字母、数字、下划线、中划线")
|
||||
private String valueCode;
|
||||
|
||||
private Integer sortOrder;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** SKU 与规格值多对多关系。 */
|
||||
@Data
|
||||
@TableName("ec_product_sku_spec_value")
|
||||
public class ProductSkuSpecValuePO {
|
||||
|
||||
@TableField("sku_id")
|
||||
private Long skuId;
|
||||
|
||||
@TableField("spec_value_id")
|
||||
private Long specValueId;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
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("ec_product_spec")
|
||||
public class ProductSpecPO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("product_id")
|
||||
private Long productId;
|
||||
|
||||
@TableField("name")
|
||||
private String name;
|
||||
|
||||
@TableField("sort_order")
|
||||
private Integer sortOrder;
|
||||
|
||||
@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;
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
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;
|
||||
|
||||
/** 商品规格值(含 value_code,用于拼 SKU 编码)。 */
|
||||
@Data
|
||||
@TableName("ec_product_spec_value")
|
||||
public class ProductSpecValuePO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("product_id")
|
||||
private Long productId;
|
||||
|
||||
@TableField("spec_id")
|
||||
private Long specId;
|
||||
|
||||
@TableField("value_name")
|
||||
private String valueName;
|
||||
|
||||
@TableField("value_code")
|
||||
private String valueCode;
|
||||
|
||||
@TableField("sort_order")
|
||||
private Integer sortOrder;
|
||||
|
||||
@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;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 商品规格维视图。 */
|
||||
@Data
|
||||
public class ProductSpecVO {
|
||||
|
||||
private Long id;
|
||||
private String name;
|
||||
private Integer sortOrder;
|
||||
private List<ProductSpecValueVO> values;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/** 商品规格值视图。 */
|
||||
@Data
|
||||
public class ProductSpecValueVO {
|
||||
|
||||
private Long id;
|
||||
private Long specId;
|
||||
private String valueName;
|
||||
private String valueCode;
|
||||
private Integer sortOrder;
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.vo.ProductSkuVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.BindSkuSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.CreateSkuFromSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.GenerateProductSkusDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.ReplaceProductSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecValueVO;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** 商品规格维:查询、覆盖保存、按规格生成/绑定 SKU。 */
|
||||
public interface ProductSpecService {
|
||||
|
||||
List<ProductSpecVO> listByProductId(Long productId);
|
||||
|
||||
List<ProductSpecVO> replaceSpecs(Long productId, ReplaceProductSpecsDTO dto);
|
||||
|
||||
/** 笛卡尔积生成缺失结构化 SKU;sku_code 冲突则整批失败。 */
|
||||
List<ProductSkuVO> generateSkus(Long productId, GenerateProductSkusDTO dto);
|
||||
|
||||
/** 按所选规格值创建 SKU(允许缺维)。 */
|
||||
ProductSkuVO createSkuFromSpecs(Long productId, CreateSkuFromSpecsDTO dto);
|
||||
|
||||
/**
|
||||
* 为已有 SKU 绑定规格(可缺维);不改 sku_code。
|
||||
* specValueIds 空则解绑,回到 legacy(combination_key 空)。
|
||||
*/
|
||||
ProductSkuVO bindSkuSpecs(Long productId, Long skuId, BindSkuSpecsDTO dto);
|
||||
|
||||
/** 批量查询 SKU 已绑规格值(skuId → values)。 */
|
||||
Map<Long, List<ProductSpecValueVO>> listSkuSpecValues(Collection<Long> skuIds);
|
||||
}
|
||||
+604
@@ -0,0 +1,604 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.service.impl;
|
||||
|
||||
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 org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.cost.service.ProductSkuCostService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.mapper.ProductSkuMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.vo.ProductSkuVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.service.ProductSkuService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.domain.ProductSpecCodes;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.mapper.ProductSkuSpecValueMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.mapper.ProductSpecMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.mapper.ProductSpecValueMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.BindSkuSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.CreateSkuFromSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.GenerateProductSkusDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.ReplaceProductSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po.ProductSkuSpecValuePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po.ProductSpecPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po.ProductSpecValuePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecValueVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.service.ProductSpecService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 商品规格维服务:覆盖保存规格树、按维笛卡尔生成结构化 SKU。
|
||||
*/
|
||||
@Service
|
||||
public class ProductSpecServiceImpl implements ProductSpecService {
|
||||
|
||||
private final ProductMapper productMapper;
|
||||
private final ProductSpecMapper specMapper;
|
||||
private final ProductSpecValueMapper valueMapper;
|
||||
private final ProductSkuSpecValueMapper skuSpecValueMapper;
|
||||
private final ProductSkuMapper skuMapper;
|
||||
private final ProductSkuService productSkuService;
|
||||
private final ProductSkuCostService productSkuCostService;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public ProductSpecServiceImpl(ProductMapper productMapper,
|
||||
ProductSpecMapper specMapper,
|
||||
ProductSpecValueMapper valueMapper,
|
||||
ProductSkuSpecValueMapper skuSpecValueMapper,
|
||||
ProductSkuMapper skuMapper,
|
||||
ProductSkuService productSkuService,
|
||||
ProductSkuCostService productSkuCostService,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.productMapper = productMapper;
|
||||
this.specMapper = specMapper;
|
||||
this.valueMapper = valueMapper;
|
||||
this.skuSpecValueMapper = skuSpecValueMapper;
|
||||
this.skuMapper = skuMapper;
|
||||
this.productSkuService = productSkuService;
|
||||
this.productSkuCostService = productSkuCostService;
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ProductSpecVO> listByProductId(Long productId) {
|
||||
ProductPO product = requireProduct(productId);
|
||||
return loadSpecTree(product.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public List<ProductSpecVO> replaceSpecs(Long productId, ReplaceProductSpecsDTO dto) {
|
||||
ProductPO product = requireProduct(productId);
|
||||
Long companyId = product.getCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
List<ReplaceProductSpecsDTO.SpecItem> items =
|
||||
dto.getSpecs() == null ? List.of() : dto.getSpecs();
|
||||
|
||||
Set<Long> keepSpecIds = new HashSet<>();
|
||||
Set<Long> keepValueIds = new HashSet<>();
|
||||
int specOrder = 0;
|
||||
for (ReplaceProductSpecsDTO.SpecItem item : items) {
|
||||
if (item == null || !StringUtils.hasText(item.getName())) {
|
||||
throw new BusinessException("规格名称不能为空");
|
||||
}
|
||||
String specName = item.getName().trim();
|
||||
ProductSpecPO spec = resolveOrCreateSpec(product, item.getId(), specName,
|
||||
item.getSortOrder() != null ? item.getSortOrder() : specOrder++, userId);
|
||||
keepSpecIds.add(spec.getId());
|
||||
|
||||
List<ReplaceProductSpecsDTO.ValueItem> values =
|
||||
item.getValues() == null ? List.of() : item.getValues();
|
||||
Set<String> nameSeen = new HashSet<>();
|
||||
Set<String> codeSeen = new HashSet<>();
|
||||
int valueOrder = 0;
|
||||
for (ReplaceProductSpecsDTO.ValueItem vi : values) {
|
||||
if (vi == null) {
|
||||
continue;
|
||||
}
|
||||
String vn = requireText(vi.getValueName(), "规格值名称不能为空");
|
||||
String vc = requireText(vi.getValueCode(), "规格值编码不能为空").toUpperCase();
|
||||
validateValueCode(vc);
|
||||
if (!nameSeen.add(vn)) {
|
||||
throw new BusinessException("同一规格下规格值名称重复: " + vn);
|
||||
}
|
||||
if (!codeSeen.add(vc)) {
|
||||
throw new BusinessException("同一规格下规格值编码重复: " + vc);
|
||||
}
|
||||
ProductSpecValuePO value = resolveOrCreateValue(product, spec, vi.getId(), vn, vc,
|
||||
vi.getSortOrder() != null ? vi.getSortOrder() : valueOrder++, userId);
|
||||
keepValueIds.add(value.getId());
|
||||
}
|
||||
}
|
||||
|
||||
// 删除未保留且未被 SKU 引用的规格值 / 规格维
|
||||
List<ProductSpecValuePO> existingValues = valueMapper.selectList(new LambdaQueryWrapper<ProductSpecValuePO>()
|
||||
.eq(ProductSpecValuePO::getProductId, productId));
|
||||
for (ProductSpecValuePO v : existingValues) {
|
||||
if (keepValueIds.contains(v.getId())) {
|
||||
continue;
|
||||
}
|
||||
if (isValueReferenced(v.getId())) {
|
||||
throw new BusinessException("规格值「" + v.getValueName() + "」已被 SKU 使用,无法删除");
|
||||
}
|
||||
valueMapper.deleteById(v.getId());
|
||||
}
|
||||
List<ProductSpecPO> existingSpecs = specMapper.selectList(new LambdaQueryWrapper<ProductSpecPO>()
|
||||
.eq(ProductSpecPO::getProductId, productId));
|
||||
for (ProductSpecPO s : existingSpecs) {
|
||||
if (keepSpecIds.contains(s.getId())) {
|
||||
continue;
|
||||
}
|
||||
long remain = valueMapper.selectCount(new LambdaQueryWrapper<ProductSpecValuePO>()
|
||||
.eq(ProductSpecValuePO::getSpecId, s.getId()));
|
||||
if (remain > 0) {
|
||||
throw new BusinessException("规格「" + s.getName() + "」下仍有规格值,无法删除");
|
||||
}
|
||||
specMapper.deleteById(s.getId());
|
||||
}
|
||||
return loadSpecTree(productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public List<ProductSkuVO> generateSkus(Long productId, GenerateProductSkusDTO dto) {
|
||||
ProductPO product = requireProduct(productId);
|
||||
if (!StringUtils.hasText(product.getProductCode())) {
|
||||
throw new BusinessException("请先填写商品编码后再生成 SKU");
|
||||
}
|
||||
String productCode = product.getProductCode().trim();
|
||||
Long companyId = product.getCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
|
||||
List<ProductSpecPO> specs = specMapper.selectList(new LambdaQueryWrapper<ProductSpecPO>()
|
||||
.eq(ProductSpecPO::getProductId, productId)
|
||||
.orderByAsc(ProductSpecPO::getSortOrder)
|
||||
.orderByAsc(ProductSpecPO::getId));
|
||||
if (specs.isEmpty()) {
|
||||
throw new BusinessException("请先配置商品规格后再生成 SKU");
|
||||
}
|
||||
Map<Long, ProductSpecPO> specById = specs.stream()
|
||||
.collect(Collectors.toMap(ProductSpecPO::getId, s -> s, (a, b) -> a));
|
||||
|
||||
List<List<ProductSpecValuePO>> dimValues = new ArrayList<>();
|
||||
for (ProductSpecPO spec : specs) {
|
||||
List<ProductSpecValuePO> vals = valueMapper.selectList(new LambdaQueryWrapper<ProductSpecValuePO>()
|
||||
.eq(ProductSpecValuePO::getSpecId, spec.getId())
|
||||
.orderByAsc(ProductSpecValuePO::getSortOrder)
|
||||
.orderByAsc(ProductSpecValuePO::getId));
|
||||
if (vals.isEmpty()) {
|
||||
throw new BusinessException("规格「" + spec.getName() + "」下没有规格值");
|
||||
}
|
||||
dimValues.add(vals);
|
||||
}
|
||||
|
||||
List<List<ProductSpecValuePO>> combos = cartesian(dimValues);
|
||||
if (combos.size() > ProductSpecCodes.MAX_GENERATED_SKUS) {
|
||||
throw new BusinessException("生成 SKU 数量超过上限 " + ProductSpecCodes.MAX_GENERATED_SKUS
|
||||
+ "(当前 " + combos.size() + "),请减少规格值");
|
||||
}
|
||||
|
||||
// 预检:组合键 / sku_code 冲突则整批失败
|
||||
Set<String> existingKeys = skuMapper.selectList(new LambdaQueryWrapper<ProductSkuPO>()
|
||||
.eq(ProductSkuPO::getProductId, productId)
|
||||
.isNotNull(ProductSkuPO::getSpecCombinationKey))
|
||||
.stream()
|
||||
.map(ProductSkuPO::getSpecCombinationKey)
|
||||
.filter(StringUtils::hasText)
|
||||
.collect(Collectors.toSet());
|
||||
Set<String> existingCodes = skuMapper.selectList(new LambdaQueryWrapper<ProductSkuPO>()
|
||||
.eq(ProductSkuPO::getCompanyId, companyId))
|
||||
.stream()
|
||||
.map(ProductSkuPO::getSkuCode)
|
||||
.filter(StringUtils::hasText)
|
||||
.map(String::trim)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
List<PendingSku> toCreate = new ArrayList<>();
|
||||
for (List<ProductSpecValuePO> combo : combos) {
|
||||
List<Long> ids = combo.stream().map(ProductSpecValuePO::getId).toList();
|
||||
String key = ProductSpecCodes.combinationKey(ids);
|
||||
if (existingKeys.contains(key)) {
|
||||
continue;
|
||||
}
|
||||
String skuCode = ProductSpecCodes.buildSkuCode(productCode, combo, specById);
|
||||
if (existingCodes.contains(skuCode)) {
|
||||
throw new BusinessException("SKU 编码冲突,整批未生成: " + skuCode);
|
||||
}
|
||||
if (toCreate.stream().anyMatch(p -> p.skuCode.equals(skuCode) || p.combinationKey.equals(key))) {
|
||||
throw new BusinessException("生成结果内部出现重复 SKU 编码或组合: " + skuCode);
|
||||
}
|
||||
toCreate.add(new PendingSku(key, skuCode,
|
||||
ProductSpecCodes.buildSkuDisplayName(combo, specById), combo));
|
||||
existingCodes.add(skuCode);
|
||||
existingKeys.add(key);
|
||||
}
|
||||
|
||||
BigDecimal productCost = dto != null && dto.getProductCost() != null
|
||||
? dto.getProductCost() : BigDecimal.ZERO;
|
||||
BigDecimal shippingCost = dto != null && dto.getShippingCost() != null
|
||||
? dto.getShippingCost() : BigDecimal.ZERO;
|
||||
BigDecimal otherCost = dto != null && dto.getOtherCost() != null
|
||||
? dto.getOtherCost() : BigDecimal.ZERO;
|
||||
|
||||
List<ProductSkuVO> created = new ArrayList<>();
|
||||
for (PendingSku pending : toCreate) {
|
||||
ProductSkuPO sku = new ProductSkuPO();
|
||||
sku.setCompanyId(companyId);
|
||||
sku.setProductId(productId);
|
||||
sku.setName(pending.displayName);
|
||||
sku.setSkuCode(pending.skuCode);
|
||||
sku.setSpecCombinationKey(pending.combinationKey);
|
||||
sku.setStatus(1);
|
||||
sku.setSortOrder(0);
|
||||
sku.setCreateBy(userId);
|
||||
sku.setUpdateBy(userId);
|
||||
if (!productSkuService.save(sku)) {
|
||||
throw new BusinessException("创建 SKU 失败: " + pending.skuCode);
|
||||
}
|
||||
productSkuCostService.writeInitialCostIfPresent(sku.getId(), companyId,
|
||||
productCost, shippingCost, otherCost, userId);
|
||||
for (ProductSpecValuePO v : pending.values) {
|
||||
ProductSkuSpecValuePO rel = new ProductSkuSpecValuePO();
|
||||
rel.setSkuId(sku.getId());
|
||||
rel.setSpecValueId(v.getId());
|
||||
skuSpecValueMapper.insert(rel);
|
||||
}
|
||||
created.add(productSkuService.toVo(sku));
|
||||
}
|
||||
return created;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ProductSkuVO createSkuFromSpecs(Long productId, CreateSkuFromSpecsDTO dto) {
|
||||
ProductPO product = requireProduct(productId);
|
||||
if (dto == null || dto.getSpecValueIds() == null || dto.getSpecValueIds().isEmpty()) {
|
||||
throw new BusinessException("请至少选择一个规格值");
|
||||
}
|
||||
if (!StringUtils.hasText(product.getProductCode())) {
|
||||
throw new BusinessException("请先填写商品编码");
|
||||
}
|
||||
Long companyId = product.getCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
|
||||
ResolvedSpecValues resolved = resolveSpecValues(productId, dto.getSpecValueIds());
|
||||
String key = ProductSpecCodes.combinationKey(
|
||||
resolved.values().stream().map(ProductSpecValuePO::getId).toList());
|
||||
assertCombinationAvailable(productId, key, null);
|
||||
|
||||
String skuCode = StringUtils.hasText(dto.getSkuCode())
|
||||
? dto.getSkuCode().trim()
|
||||
: ProductSpecCodes.buildSkuCode(product.getProductCode(), resolved.values(), resolved.specById());
|
||||
if (skuMapper.selectCount(new LambdaQueryWrapper<ProductSkuPO>()
|
||||
.eq(ProductSkuPO::getCompanyId, companyId)
|
||||
.eq(ProductSkuPO::getSkuCode, skuCode)) > 0) {
|
||||
throw new BusinessException("SKU 编码已存在: " + skuCode);
|
||||
}
|
||||
|
||||
String name = StringUtils.hasText(dto.getName())
|
||||
? dto.getName().trim()
|
||||
: ProductSpecCodes.buildSkuDisplayName(resolved.values(), resolved.specById());
|
||||
|
||||
ProductSkuPO sku = new ProductSkuPO();
|
||||
sku.setCompanyId(companyId);
|
||||
sku.setProductId(productId);
|
||||
sku.setName(name);
|
||||
sku.setSkuCode(skuCode);
|
||||
sku.setSpecCombinationKey(key);
|
||||
sku.setRemark(dto.getRemark());
|
||||
sku.setStatus(1);
|
||||
sku.setSortOrder(0);
|
||||
sku.setCreateBy(userId);
|
||||
sku.setUpdateBy(userId);
|
||||
if (!productSkuService.save(sku)) {
|
||||
throw new BusinessException("创建 SKU 失败");
|
||||
}
|
||||
productSkuCostService.writeInitialCostIfPresent(sku.getId(), companyId,
|
||||
dto.getProductCost(),
|
||||
dto.getShippingCost() != null ? dto.getShippingCost() : BigDecimal.ZERO,
|
||||
dto.getOtherCost() != null ? dto.getOtherCost() : BigDecimal.ZERO,
|
||||
userId);
|
||||
replaceSkuSpecRels(sku.getId(), resolved.values());
|
||||
ProductSkuVO vo = productSkuService.toVo(sku);
|
||||
vo.setSpecValues(resolved.values().stream().map(this::toValueVo).toList());
|
||||
return vo;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ProductSkuVO bindSkuSpecs(Long productId, Long skuId, BindSkuSpecsDTO dto) {
|
||||
ProductPO product = requireProduct(productId);
|
||||
ProductSkuPO sku = skuMapper.selectById(skuId);
|
||||
if (sku == null || !Objects.equals(sku.getProductId(), productId)
|
||||
|| !Objects.equals(sku.getCompanyId(), product.getCompanyId())) {
|
||||
throw new BusinessException("SKU 不存在或不属于当前商品");
|
||||
}
|
||||
|
||||
List<Long> rawIds = dto != null && dto.getSpecValueIds() != null
|
||||
? dto.getSpecValueIds() : List.of();
|
||||
List<Long> valueIds = rawIds.stream().filter(Objects::nonNull).distinct().toList();
|
||||
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
if (valueIds.isEmpty()) {
|
||||
// 解绑:回到 legacy,保留原 sku_code / name(须显式 set null,updateById 会忽略 null)
|
||||
skuSpecValueMapper.delete(new LambdaQueryWrapper<ProductSkuSpecValuePO>()
|
||||
.eq(ProductSkuSpecValuePO::getSkuId, skuId));
|
||||
skuMapper.update(null, new LambdaUpdateWrapper<ProductSkuPO>()
|
||||
.eq(ProductSkuPO::getId, skuId)
|
||||
.set(ProductSkuPO::getSpecCombinationKey, null)
|
||||
.set(ProductSkuPO::getUpdateBy, userId));
|
||||
ProductSkuVO vo = productSkuService.toVo(skuMapper.selectById(skuId));
|
||||
vo.setSpecValues(List.of());
|
||||
return vo;
|
||||
}
|
||||
|
||||
ResolvedSpecValues resolved = resolveSpecValues(productId, valueIds);
|
||||
String key = ProductSpecCodes.combinationKey(
|
||||
resolved.values().stream().map(ProductSpecValuePO::getId).toList());
|
||||
assertCombinationAvailable(productId, key, skuId);
|
||||
|
||||
replaceSkuSpecRels(skuId, resolved.values());
|
||||
sku.setSpecCombinationKey(key);
|
||||
sku.setUpdateBy(userId);
|
||||
// 刻意不改 sku_code / name:外部同步编码可保留
|
||||
skuMapper.updateById(sku);
|
||||
|
||||
ProductSkuVO vo = productSkuService.toVo(skuMapper.selectById(skuId));
|
||||
vo.setSpecValues(resolved.values().stream().map(this::toValueVo).toList());
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 校验规格值归属与同维唯一,返回有序解析结果。 */
|
||||
private ResolvedSpecValues resolveSpecValues(Long productId, List<Long> rawValueIds) {
|
||||
List<Long> valueIds = rawValueIds.stream().filter(Objects::nonNull).distinct().toList();
|
||||
if (valueIds.isEmpty()) {
|
||||
throw new BusinessException("请至少选择一个规格值");
|
||||
}
|
||||
List<ProductSpecValuePO> values = valueMapper.selectBatchIds(valueIds);
|
||||
if (values.size() != valueIds.size()) {
|
||||
throw new BusinessException("存在无效的规格值");
|
||||
}
|
||||
for (ProductSpecValuePO v : values) {
|
||||
if (!Objects.equals(v.getProductId(), productId)) {
|
||||
throw new BusinessException("规格值不属于当前商品");
|
||||
}
|
||||
}
|
||||
Set<Long> specIds = new HashSet<>();
|
||||
for (ProductSpecValuePO v : values) {
|
||||
if (!specIds.add(v.getSpecId())) {
|
||||
throw new BusinessException("同一规格维只能选择一个规格值");
|
||||
}
|
||||
}
|
||||
Map<Long, ProductSpecPO> specById = specMapper.selectBatchIds(specIds).stream()
|
||||
.collect(Collectors.toMap(ProductSpecPO::getId, s -> s, (a, b) -> a));
|
||||
return new ResolvedSpecValues(values, specById);
|
||||
}
|
||||
|
||||
/** 同商品下组合键唯一(excludeSkuId 为当前绑定 SKU 时可排除自身)。 */
|
||||
private void assertCombinationAvailable(Long productId, String key, Long excludeSkuId) {
|
||||
if (!StringUtils.hasText(key)) {
|
||||
return;
|
||||
}
|
||||
LambdaQueryWrapper<ProductSkuPO> w = new LambdaQueryWrapper<ProductSkuPO>()
|
||||
.eq(ProductSkuPO::getProductId, productId)
|
||||
.eq(ProductSkuPO::getSpecCombinationKey, key);
|
||||
if (excludeSkuId != null) {
|
||||
w.ne(ProductSkuPO::getId, excludeSkuId);
|
||||
}
|
||||
if (skuMapper.selectCount(w) > 0) {
|
||||
throw new BusinessException("该规格组合已被其他 SKU 占用");
|
||||
}
|
||||
}
|
||||
|
||||
/** 覆盖写 SKU-规格值关系。 */
|
||||
private void replaceSkuSpecRels(Long skuId, List<ProductSpecValuePO> values) {
|
||||
skuSpecValueMapper.delete(new LambdaQueryWrapper<ProductSkuSpecValuePO>()
|
||||
.eq(ProductSkuSpecValuePO::getSkuId, skuId));
|
||||
for (ProductSpecValuePO v : values) {
|
||||
ProductSkuSpecValuePO rel = new ProductSkuSpecValuePO();
|
||||
rel.setSkuId(skuId);
|
||||
rel.setSpecValueId(v.getId());
|
||||
skuSpecValueMapper.insert(rel);
|
||||
}
|
||||
}
|
||||
|
||||
private record ResolvedSpecValues(List<ProductSpecValuePO> values,
|
||||
Map<Long, ProductSpecPO> specById) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<Long, List<ProductSpecValueVO>> listSkuSpecValues(Collection<Long> skuIds) {
|
||||
if (skuIds == null || skuIds.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
List<ProductSkuSpecValuePO> rels = skuSpecValueMapper.selectList(
|
||||
new LambdaQueryWrapper<ProductSkuSpecValuePO>()
|
||||
.in(ProductSkuSpecValuePO::getSkuId, skuIds));
|
||||
if (rels.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Set<Long> valueIds = rels.stream().map(ProductSkuSpecValuePO::getSpecValueId).collect(Collectors.toSet());
|
||||
Map<Long, ProductSpecValuePO> valueMap = valueMapper.selectBatchIds(valueIds).stream()
|
||||
.collect(Collectors.toMap(ProductSpecValuePO::getId, v -> v, (a, b) -> a));
|
||||
Map<Long, List<ProductSpecValueVO>> result = new HashMap<>();
|
||||
for (ProductSkuSpecValuePO rel : rels) {
|
||||
ProductSpecValuePO po = valueMap.get(rel.getSpecValueId());
|
||||
if (po == null) {
|
||||
continue;
|
||||
}
|
||||
result.computeIfAbsent(rel.getSkuId(), k -> new ArrayList<>()).add(toValueVo(po));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private ProductSpecValueVO toValueVo(ProductSpecValuePO v) {
|
||||
ProductSpecValueVO vv = new ProductSpecValueVO();
|
||||
vv.setId(v.getId());
|
||||
vv.setSpecId(v.getSpecId());
|
||||
vv.setValueName(v.getValueName());
|
||||
vv.setValueCode(v.getValueCode());
|
||||
vv.setSortOrder(v.getSortOrder());
|
||||
return vv;
|
||||
}
|
||||
|
||||
private ProductSpecPO resolveOrCreateSpec(ProductPO product, Long id, String name,
|
||||
int sortOrder, Long userId) {
|
||||
if (id != null && id > 0) {
|
||||
ProductSpecPO existing = specMapper.selectById(id);
|
||||
if (existing == null || !Objects.equals(existing.getProductId(), product.getId())) {
|
||||
throw new BusinessException("规格不存在或不属于当前商品");
|
||||
}
|
||||
existing.setName(name);
|
||||
existing.setSortOrder(sortOrder);
|
||||
existing.setUpdateBy(userId);
|
||||
specMapper.updateById(existing);
|
||||
return existing;
|
||||
}
|
||||
ProductSpecPO po = new ProductSpecPO();
|
||||
po.setCompanyId(product.getCompanyId());
|
||||
po.setProductId(product.getId());
|
||||
po.setName(name);
|
||||
po.setSortOrder(sortOrder);
|
||||
po.setCreateBy(userId);
|
||||
po.setUpdateBy(userId);
|
||||
specMapper.insert(po);
|
||||
return po;
|
||||
}
|
||||
|
||||
private ProductSpecValuePO resolveOrCreateValue(ProductPO product, ProductSpecPO spec, Long id,
|
||||
String valueName, String valueCode,
|
||||
int sortOrder, Long userId) {
|
||||
if (id != null && id > 0) {
|
||||
ProductSpecValuePO existing = valueMapper.selectById(id);
|
||||
if (existing == null || !Objects.equals(existing.getProductId(), product.getId())
|
||||
|| !Objects.equals(existing.getSpecId(), spec.getId())) {
|
||||
throw new BusinessException("规格值不存在或不属于当前规格");
|
||||
}
|
||||
if (isValueReferenced(existing.getId())) {
|
||||
if (!Objects.equals(existing.getValueName(), valueName)
|
||||
|| !Objects.equals(existing.getValueCode(), valueCode)) {
|
||||
throw new BusinessException("规格值「" + existing.getValueName()
|
||||
+ "」已被 SKU 使用,禁止修改名称或编码");
|
||||
}
|
||||
} else {
|
||||
existing.setValueName(valueName);
|
||||
existing.setValueCode(valueCode);
|
||||
}
|
||||
existing.setSortOrder(sortOrder);
|
||||
existing.setUpdateBy(userId);
|
||||
valueMapper.updateById(existing);
|
||||
return existing;
|
||||
}
|
||||
ProductSpecValuePO po = new ProductSpecValuePO();
|
||||
po.setCompanyId(product.getCompanyId());
|
||||
po.setProductId(product.getId());
|
||||
po.setSpecId(spec.getId());
|
||||
po.setValueName(valueName);
|
||||
po.setValueCode(valueCode);
|
||||
po.setSortOrder(sortOrder);
|
||||
po.setCreateBy(userId);
|
||||
po.setUpdateBy(userId);
|
||||
valueMapper.insert(po);
|
||||
return po;
|
||||
}
|
||||
|
||||
private boolean isValueReferenced(Long specValueId) {
|
||||
return skuSpecValueMapper.selectCount(new LambdaQueryWrapper<ProductSkuSpecValuePO>()
|
||||
.eq(ProductSkuSpecValuePO::getSpecValueId, specValueId)) > 0;
|
||||
}
|
||||
|
||||
private List<ProductSpecVO> loadSpecTree(Long productId) {
|
||||
List<ProductSpecPO> specs = specMapper.selectList(new LambdaQueryWrapper<ProductSpecPO>()
|
||||
.eq(ProductSpecPO::getProductId, productId)
|
||||
.orderByAsc(ProductSpecPO::getSortOrder)
|
||||
.orderByAsc(ProductSpecPO::getId));
|
||||
if (specs.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<Long> specIds = specs.stream().map(ProductSpecPO::getId).toList();
|
||||
Map<Long, List<ProductSpecValuePO>> valuesBySpec = valueMapper.selectList(
|
||||
new LambdaQueryWrapper<ProductSpecValuePO>()
|
||||
.in(ProductSpecValuePO::getSpecId, specIds)
|
||||
.orderByAsc(ProductSpecValuePO::getSortOrder)
|
||||
.orderByAsc(ProductSpecValuePO::getId))
|
||||
.stream()
|
||||
.collect(Collectors.groupingBy(ProductSpecValuePO::getSpecId));
|
||||
List<ProductSpecVO> result = new ArrayList<>();
|
||||
for (ProductSpecPO s : specs) {
|
||||
ProductSpecVO vo = new ProductSpecVO();
|
||||
vo.setId(s.getId());
|
||||
vo.setName(s.getName());
|
||||
vo.setSortOrder(s.getSortOrder());
|
||||
List<ProductSpecValueVO> vals = new ArrayList<>();
|
||||
for (ProductSpecValuePO v : valuesBySpec.getOrDefault(s.getId(), List.of())) {
|
||||
ProductSpecValueVO vv = new ProductSpecValueVO();
|
||||
vv.setId(v.getId());
|
||||
vv.setSpecId(v.getSpecId());
|
||||
vv.setValueName(v.getValueName());
|
||||
vv.setValueCode(v.getValueCode());
|
||||
vv.setSortOrder(v.getSortOrder());
|
||||
vals.add(vv);
|
||||
}
|
||||
vo.setValues(vals);
|
||||
result.add(vo);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private ProductPO requireProduct(Long productId) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
ProductPO product = productMapper.selectById(productId);
|
||||
if (product == null || !Objects.equals(product.getCompanyId(), companyId)) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
return product;
|
||||
}
|
||||
|
||||
private static String requireText(String s, String message) {
|
||||
if (!StringUtils.hasText(s)) {
|
||||
throw new BusinessException(message);
|
||||
}
|
||||
return s.trim();
|
||||
}
|
||||
|
||||
private static void validateValueCode(String code) {
|
||||
if (!code.matches("^[A-Za-z0-9_-]+$")) {
|
||||
throw new BusinessException("规格值编码仅允许字母、数字、下划线、中划线: " + code);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<List<ProductSpecValuePO>> cartesian(List<List<ProductSpecValuePO>> dims) {
|
||||
List<List<ProductSpecValuePO>> result = new ArrayList<>();
|
||||
result.add(new ArrayList<>());
|
||||
for (List<ProductSpecValuePO> dim : dims) {
|
||||
List<List<ProductSpecValuePO>> next = new ArrayList<>();
|
||||
for (List<ProductSpecValuePO> prefix : result) {
|
||||
for (ProductSpecValuePO v : dim) {
|
||||
List<ProductSpecValuePO> row = new ArrayList<>(prefix);
|
||||
row.add(v);
|
||||
next.add(row);
|
||||
}
|
||||
}
|
||||
result = next;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private record PendingSku(String combinationKey, String skuCode, String displayName,
|
||||
List<ProductSpecValuePO> values) {
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.CreateSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.ReplaceSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.UpdateSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.vo.SpecTemplateVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.service.SpecTemplateService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 规格模板 API:公司级单维 CRUD。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/ec/product/spec-templates")
|
||||
public class SpecTemplateController {
|
||||
|
||||
private final SpecTemplateService specTemplateService;
|
||||
|
||||
public SpecTemplateController(SpecTemplateService specTemplateService) {
|
||||
this.specTemplateService = specTemplateService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@RequirePermission(value = "ec:product:spec-template:read", description = "查询规格模板列表", allowSuper = true)
|
||||
public ApiResponse<List<SpecTemplateVO>> list() {
|
||||
return ApiResponse.success("获取成功", specTemplateService.listForCompany());
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
@RequirePermission(value = "ec:product:spec-template:read", description = "查询规格模板详情", allowSuper = true)
|
||||
public ApiResponse<SpecTemplateVO> get(@PathVariable Long id) {
|
||||
return ApiResponse.success("获取成功", specTemplateService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@RequirePermission(value = "ec:product:spec-template:create", description = "创建规格模板", allowSuper = true)
|
||||
public ApiResponse<SpecTemplateVO> create(@Valid @RequestBody CreateSpecTemplateDTO dto) {
|
||||
return ApiResponse.success("创建成功", specTemplateService.create(dto));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@RequirePermission(value = "ec:product:spec-template:update", description = "更新规格模板", allowSuper = true)
|
||||
public ApiResponse<SpecTemplateVO> update(@PathVariable Long id,
|
||||
@Valid @RequestBody UpdateSpecTemplateDTO dto) {
|
||||
return ApiResponse.success("更新成功", specTemplateService.update(id, dto));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}/content")
|
||||
@RequirePermission(value = "ec:product:spec-template:update", description = "覆盖规格模板值", allowSuper = true)
|
||||
public ApiResponse<SpecTemplateVO> replaceContent(@PathVariable Long id,
|
||||
@Valid @RequestBody ReplaceSpecTemplateDTO dto) {
|
||||
return ApiResponse.success("保存成功", specTemplateService.replaceContent(id, dto));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@RequirePermission(value = "ec:product:spec-template:delete", description = "删除规格模板", allowSuper = true)
|
||||
public ApiResponse<Void> delete(@PathVariable Long id) {
|
||||
specTemplateService.delete(id);
|
||||
return ApiResponse.<Void>success("删除成功", null);
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.po.SpecTemplatePO;
|
||||
|
||||
@Mapper
|
||||
public interface SpecTemplateMapper extends BaseMapper<SpecTemplatePO> {
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.po.SpecTemplateValuePO;
|
||||
|
||||
@Mapper
|
||||
public interface SpecTemplateValueMapper extends BaseMapper<SpecTemplateValuePO> {
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 将模板维值套用到商品规格(合并,不生成 SKU)。 */
|
||||
@Data
|
||||
public class ApplySpecTemplateDTO {
|
||||
|
||||
@NotNull(message = "模板ID不能为空")
|
||||
private Long templateId;
|
||||
|
||||
/** 可选;空表示模板下全部值 */
|
||||
private List<Long> templateValueIds;
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 创建公司级规格模板(单维)。 */
|
||||
@Data
|
||||
public class CreateSpecTemplateDTO {
|
||||
|
||||
@NotBlank(message = "模板名称不能为空")
|
||||
private String name;
|
||||
|
||||
private String remark;
|
||||
|
||||
private Integer sortOrder;
|
||||
|
||||
@Valid
|
||||
private List<ReplaceSpecTemplateDTO.ValueItem> values;
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 全量覆盖模板规格值。 */
|
||||
@Data
|
||||
public class ReplaceSpecTemplateDTO {
|
||||
|
||||
@Valid
|
||||
private List<ValueItem> values;
|
||||
|
||||
@Data
|
||||
public static class ValueItem {
|
||||
|
||||
/** 已有值 ID;空表示新增 */
|
||||
private Long id;
|
||||
|
||||
@NotBlank(message = "规格值名称不能为空")
|
||||
private String valueName;
|
||||
|
||||
@NotBlank(message = "规格值编码不能为空")
|
||||
@Pattern(regexp = "^[A-Za-z0-9_-]+$", message = "规格值编码仅允许字母、数字、下划线、中划线")
|
||||
private String valueCode;
|
||||
|
||||
private Integer sortOrder;
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
/** 将商品某一规格维另存为公司模板。 */
|
||||
@Data
|
||||
public class SaveProductAsTemplateDTO {
|
||||
|
||||
@NotNull(message = "商品规格ID不能为空")
|
||||
private Long productSpecId;
|
||||
|
||||
/** 可选;覆盖模板名,默认取规格维名称 */
|
||||
private String name;
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 更新公司级模板;values 非空时全量覆盖规格值。 */
|
||||
@Data
|
||||
public class UpdateSpecTemplateDTO {
|
||||
|
||||
private String name;
|
||||
|
||||
private String remark;
|
||||
|
||||
private Integer sortOrder;
|
||||
|
||||
@Valid
|
||||
private List<ReplaceSpecTemplateDTO.ValueItem> values;
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
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;
|
||||
|
||||
/** 规格模板(单维);name 即规格维名称。 */
|
||||
@Data
|
||||
@TableName("ec_spec_template")
|
||||
public class SpecTemplatePO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("name")
|
||||
private String name;
|
||||
|
||||
@TableField("remark")
|
||||
private String remark;
|
||||
|
||||
@TableField("sort_order")
|
||||
private Integer sortOrder;
|
||||
|
||||
@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;
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
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("ec_spec_template_value")
|
||||
public class SpecTemplateValuePO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("template_id")
|
||||
private Long templateId;
|
||||
|
||||
@TableField("value_name")
|
||||
private String valueName;
|
||||
|
||||
@TableField("value_code")
|
||||
private String valueCode;
|
||||
|
||||
@TableField("sort_order")
|
||||
private Integer sortOrder;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/** 规格模板视图(单维 + 值列表)。 */
|
||||
@Data
|
||||
public class SpecTemplateVO {
|
||||
|
||||
private Long id;
|
||||
private Long companyId;
|
||||
/** 规格维名称,如颜色、尺码 */
|
||||
private String name;
|
||||
private String remark;
|
||||
private Integer sortOrder;
|
||||
private LocalDateTime createTime;
|
||||
private LocalDateTime updateTime;
|
||||
private List<SpecTemplateValueVO> values;
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/** 规格模板值视图。 */
|
||||
@Data
|
||||
public class SpecTemplateValueVO {
|
||||
|
||||
private Long id;
|
||||
private String valueName;
|
||||
private String valueCode;
|
||||
private Integer sortOrder;
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.ApplySpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.CreateSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.ReplaceSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.SaveProductAsTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.UpdateSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.vo.SpecTemplateVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 规格模板:公司级单维维护、套用与另存。 */
|
||||
public interface SpecTemplateService {
|
||||
|
||||
/** 本公司模板列表;无模板时先种子默认维。 */
|
||||
List<SpecTemplateVO> listForCompany();
|
||||
|
||||
/** 读取本公司模板详情。 */
|
||||
SpecTemplateVO get(Long id);
|
||||
|
||||
/** 创建本公司模板。 */
|
||||
SpecTemplateVO create(CreateSpecTemplateDTO dto);
|
||||
|
||||
/** 更新本公司模板;values 非空时全量覆盖规格值。 */
|
||||
SpecTemplateVO update(Long id, UpdateSpecTemplateDTO dto);
|
||||
|
||||
/** 删除本公司模板。 */
|
||||
void delete(Long id);
|
||||
|
||||
/** 全量覆盖模板规格值。 */
|
||||
SpecTemplateVO replaceContent(Long id, ReplaceSpecTemplateDTO dto);
|
||||
|
||||
/** 按勾选值合并到商品规格,不生成 SKU。 */
|
||||
List<ProductSpecVO> applyToProduct(Long productId, ApplySpecTemplateDTO dto);
|
||||
|
||||
/** 从商品某一规格维拷贝创建本公司模板。 */
|
||||
SpecTemplateVO saveProductAsTemplate(Long productId, SaveProductAsTemplateDTO dto);
|
||||
|
||||
/** 为公司种子默认规格维(款式/颜色/尺码/容量),已存在则跳过。 */
|
||||
void seedDefaultTemplates(Long companyId, Long userId);
|
||||
}
|
||||
+551
@@ -0,0 +1,551 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
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.ec.product.spec.model.dto.ReplaceProductSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecValueVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.service.ProductSpecService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.mapper.SpecTemplateMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.mapper.SpecTemplateValueMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.ApplySpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.CreateSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.ReplaceSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.SaveProductAsTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.UpdateSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.po.SpecTemplatePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.po.SpecTemplateValuePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.vo.SpecTemplateVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.vo.SpecTemplateValueVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.service.SpecTemplateService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 规格模板服务:公司级单维 CRUD、默认种子、套用与另存。
|
||||
*/
|
||||
@Service
|
||||
public class SpecTemplateServiceImpl implements SpecTemplateService {
|
||||
|
||||
private final SpecTemplateMapper templateMapper;
|
||||
private final SpecTemplateValueMapper valueMapper;
|
||||
private final ProductSpecService productSpecService;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public SpecTemplateServiceImpl(SpecTemplateMapper templateMapper,
|
||||
SpecTemplateValueMapper valueMapper,
|
||||
ProductSpecService productSpecService,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.templateMapper = templateMapper;
|
||||
this.valueMapper = valueMapper;
|
||||
this.productSpecService = productSpecService;
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SpecTemplateVO> listForCompany() {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
if (countByCompany(companyId) == 0) {
|
||||
seedDefaultTemplates(companyId, currentUserContext.getCurrentUserId());
|
||||
}
|
||||
List<SpecTemplatePO> templates = templateMapper.selectList(new LambdaQueryWrapper<SpecTemplatePO>()
|
||||
.eq(SpecTemplatePO::getCompanyId, companyId)
|
||||
.orderByAsc(SpecTemplatePO::getSortOrder)
|
||||
.orderByAsc(SpecTemplatePO::getId));
|
||||
return toVoList(templates);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SpecTemplateVO get(Long id) {
|
||||
SpecTemplatePO po = requireCompanyTemplate(id);
|
||||
return toVoWithValues(po);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public SpecTemplateVO create(CreateSpecTemplateDTO dto) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
String name = requireText(dto.getName(), "模板名称不能为空");
|
||||
assertCompanyNameAvailable(companyId, name, null);
|
||||
|
||||
SpecTemplatePO po = new SpecTemplatePO();
|
||||
po.setCompanyId(companyId);
|
||||
po.setName(name);
|
||||
po.setRemark(trimToNull(dto.getRemark()));
|
||||
po.setSortOrder(dto.getSortOrder() != null ? dto.getSortOrder() : 0);
|
||||
po.setCreateBy(userId);
|
||||
po.setUpdateBy(userId);
|
||||
templateMapper.insert(po);
|
||||
|
||||
if (dto.getValues() != null && !dto.getValues().isEmpty()) {
|
||||
doReplaceContent(po.getId(), dto.getValues());
|
||||
}
|
||||
return get(po.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public SpecTemplateVO update(Long id, UpdateSpecTemplateDTO dto) {
|
||||
SpecTemplatePO po = requireCompanyTemplate(id);
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
|
||||
if (StringUtils.hasText(dto.getName())) {
|
||||
String name = dto.getName().trim();
|
||||
if (!Objects.equals(name, po.getName())) {
|
||||
assertCompanyNameAvailable(po.getCompanyId(), name, po.getId());
|
||||
}
|
||||
po.setName(name);
|
||||
}
|
||||
if (dto.getRemark() != null) {
|
||||
po.setRemark(trimToNull(dto.getRemark()));
|
||||
}
|
||||
if (dto.getSortOrder() != null) {
|
||||
po.setSortOrder(dto.getSortOrder());
|
||||
}
|
||||
po.setUpdateBy(userId);
|
||||
templateMapper.updateById(po);
|
||||
|
||||
if (dto.getValues() != null && !dto.getValues().isEmpty()) {
|
||||
doReplaceContent(id, dto.getValues());
|
||||
}
|
||||
return get(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void delete(Long id) {
|
||||
requireCompanyTemplate(id);
|
||||
templateMapper.deleteById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public SpecTemplateVO replaceContent(Long id, ReplaceSpecTemplateDTO dto) {
|
||||
requireCompanyTemplate(id);
|
||||
List<ReplaceSpecTemplateDTO.ValueItem> items =
|
||||
dto.getValues() == null ? List.of() : dto.getValues();
|
||||
doReplaceContent(id, items);
|
||||
return get(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public List<ProductSpecVO> applyToProduct(Long productId, ApplySpecTemplateDTO dto) {
|
||||
SpecTemplatePO template = requireCompanyTemplate(dto.getTemplateId());
|
||||
List<SpecTemplateValueVO> selected = filterTemplateValues(template.getId(), dto);
|
||||
if (selected.isEmpty()) {
|
||||
throw new BusinessException("未选中任何模板规格值");
|
||||
}
|
||||
|
||||
List<ProductSpecVO> existing = productSpecService.listByProductId(productId);
|
||||
ReplaceProductSpecsDTO replaceDto = buildMergedReplaceDto(existing, template, selected);
|
||||
return productSpecService.replaceSpecs(productId, replaceDto);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public SpecTemplateVO saveProductAsTemplate(Long productId, SaveProductAsTemplateDTO dto) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
|
||||
ProductSpecVO sourceSpec = productSpecService.listByProductId(productId).stream()
|
||||
.filter(s -> Objects.equals(s.getId(), dto.getProductSpecId()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new BusinessException("商品规格不存在"));
|
||||
|
||||
String name = StringUtils.hasText(dto.getName())
|
||||
? dto.getName().trim() : sourceSpec.getName();
|
||||
assertCompanyNameAvailable(companyId, name, null);
|
||||
|
||||
SpecTemplatePO po = new SpecTemplatePO();
|
||||
po.setCompanyId(companyId);
|
||||
po.setName(name);
|
||||
po.setSortOrder(sourceSpec.getSortOrder() != null ? sourceSpec.getSortOrder() : 0);
|
||||
po.setCreateBy(userId);
|
||||
po.setUpdateBy(userId);
|
||||
templateMapper.insert(po);
|
||||
|
||||
copyProductSpecValuesToTemplate(po.getId(), sourceSpec);
|
||||
return get(po.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void seedDefaultTemplates(Long companyId, Long userId) {
|
||||
seedOneIfAbsent(companyId, userId, "款式", 0,
|
||||
List.of(value("标准款", "STD", 0)));
|
||||
seedOneIfAbsent(companyId, userId, "颜色", 1,
|
||||
List.of(
|
||||
value("黑色", "BLK", 0),
|
||||
value("白色", "WHT", 1),
|
||||
value("灰色", "GRY", 2),
|
||||
value("红色", "RED", 3),
|
||||
value("蓝色", "BLU", 4)));
|
||||
seedOneIfAbsent(companyId, userId, "尺码", 2,
|
||||
List.of(
|
||||
value("S", "S", 0),
|
||||
value("M", "M", 1),
|
||||
value("L", "L", 2),
|
||||
value("XL", "XL", 3)));
|
||||
seedOneIfAbsent(companyId, userId, "容量", 3,
|
||||
List.of(
|
||||
value("100ML", "100ML", 0),
|
||||
value("250ML", "250ML", 1),
|
||||
value("500ML", "500ML", 2),
|
||||
value("1L", "1L", 3)));
|
||||
}
|
||||
|
||||
/** 全量覆盖模板规格值。 */
|
||||
private void doReplaceContent(Long templateId, List<ReplaceSpecTemplateDTO.ValueItem> items) {
|
||||
Set<Long> keepValueIds = new HashSet<>();
|
||||
Set<String> nameSeen = new HashSet<>();
|
||||
Set<String> codeSeen = new HashSet<>();
|
||||
int valueOrder = 0;
|
||||
|
||||
for (ReplaceSpecTemplateDTO.ValueItem vi : items) {
|
||||
if (vi == null) {
|
||||
continue;
|
||||
}
|
||||
String vn = requireText(vi.getValueName(), "规格值名称不能为空");
|
||||
String vc = requireText(vi.getValueCode(), "规格值编码不能为空").toUpperCase();
|
||||
validateValueCode(vc);
|
||||
if (!nameSeen.add(vn)) {
|
||||
throw new BusinessException("同一模板下规格值名称重复: " + vn);
|
||||
}
|
||||
if (!codeSeen.add(vc)) {
|
||||
throw new BusinessException("同一模板下规格值编码重复: " + vc);
|
||||
}
|
||||
SpecTemplateValuePO value = resolveOrCreateValue(templateId, vi.getId(), vn, vc,
|
||||
vi.getSortOrder() != null ? vi.getSortOrder() : valueOrder++);
|
||||
keepValueIds.add(value.getId());
|
||||
}
|
||||
|
||||
List<SpecTemplateValuePO> existing = valueMapper.selectList(new LambdaQueryWrapper<SpecTemplateValuePO>()
|
||||
.eq(SpecTemplateValuePO::getTemplateId, templateId));
|
||||
for (SpecTemplateValuePO v : existing) {
|
||||
if (!keepValueIds.contains(v.getId())) {
|
||||
valueMapper.deleteById(v.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 按勾选过滤模板值;空表示全部值。 */
|
||||
private List<SpecTemplateValueVO> filterTemplateValues(Long templateId, ApplySpecTemplateDTO dto) {
|
||||
List<SpecTemplateValueVO> all = toValueVos(loadValues(templateId));
|
||||
if (dto.getTemplateValueIds() == null || dto.getTemplateValueIds().isEmpty()) {
|
||||
return all;
|
||||
}
|
||||
Set<Long> filter = dto.getTemplateValueIds().stream()
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toSet());
|
||||
return all.stream()
|
||||
.filter(v -> filter.contains(v.getId()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/** 合并模板维名与值到商品 ReplaceProductSpecsDTO。 */
|
||||
private ReplaceProductSpecsDTO buildMergedReplaceDto(List<ProductSpecVO> existing,
|
||||
SpecTemplatePO template,
|
||||
List<SpecTemplateValueVO> templateValues) {
|
||||
List<ReplaceProductSpecsDTO.SpecItem> items = new ArrayList<>();
|
||||
Map<String, ReplaceProductSpecsDTO.SpecItem> itemByName = new LinkedHashMap<>();
|
||||
|
||||
for (ProductSpecVO spec : existing) {
|
||||
ReplaceProductSpecsDTO.SpecItem item = toReplaceSpecItem(spec);
|
||||
items.add(item);
|
||||
itemByName.put(spec.getName(), item);
|
||||
}
|
||||
|
||||
ReplaceProductSpecsDTO.SpecItem target = itemByName.get(template.getName());
|
||||
if (target != null) {
|
||||
mergeTemplateValuesIntoSpec(target, template.getName(), templateValues);
|
||||
} else {
|
||||
ReplaceProductSpecsDTO.SpecItem newItem = new ReplaceProductSpecsDTO.SpecItem();
|
||||
newItem.setName(template.getName());
|
||||
newItem.setSortOrder(template.getSortOrder() != null ? template.getSortOrder() : items.size());
|
||||
List<ReplaceProductSpecsDTO.ValueItem> values = new ArrayList<>();
|
||||
for (SpecTemplateValueVO tv : templateValues) {
|
||||
ReplaceProductSpecsDTO.ValueItem vi = new ReplaceProductSpecsDTO.ValueItem();
|
||||
vi.setValueName(tv.getValueName());
|
||||
vi.setValueCode(tv.getValueCode().toUpperCase());
|
||||
vi.setSortOrder(tv.getSortOrder());
|
||||
values.add(vi);
|
||||
}
|
||||
newItem.setValues(values);
|
||||
items.add(newItem);
|
||||
}
|
||||
|
||||
ReplaceProductSpecsDTO dto = new ReplaceProductSpecsDTO();
|
||||
dto.setSpecs(items);
|
||||
return dto;
|
||||
}
|
||||
|
||||
/** 同名维合并:只追加不存在的值,名称/编码冲突则整次失败。 */
|
||||
private void mergeTemplateValuesIntoSpec(ReplaceProductSpecsDTO.SpecItem item,
|
||||
String specName,
|
||||
List<SpecTemplateValueVO> templateValues) {
|
||||
List<ReplaceProductSpecsDTO.ValueItem> values =
|
||||
item.getValues() == null ? new ArrayList<>() : new ArrayList<>(item.getValues());
|
||||
item.setValues(values);
|
||||
|
||||
Map<String, ReplaceProductSpecsDTO.ValueItem> byName = values.stream()
|
||||
.collect(Collectors.toMap(ReplaceProductSpecsDTO.ValueItem::getValueName, v -> v, (a, b) -> a));
|
||||
Map<String, ReplaceProductSpecsDTO.ValueItem> byCode = values.stream()
|
||||
.collect(Collectors.toMap(v -> v.getValueCode().toUpperCase(), v -> v, (a, b) -> a));
|
||||
|
||||
int nextOrder = values.stream()
|
||||
.map(ReplaceProductSpecsDTO.ValueItem::getSortOrder)
|
||||
.filter(Objects::nonNull)
|
||||
.mapToInt(Integer::intValue)
|
||||
.max().orElse(-1) + 1;
|
||||
|
||||
for (SpecTemplateValueVO tv : templateValues) {
|
||||
String name = tv.getValueName();
|
||||
String code = tv.getValueCode().toUpperCase();
|
||||
validateValueCode(code);
|
||||
|
||||
ReplaceProductSpecsDTO.ValueItem byNameMatch = byName.get(name);
|
||||
ReplaceProductSpecsDTO.ValueItem byCodeMatch = byCode.get(code);
|
||||
|
||||
if (byNameMatch != null && byCodeMatch != null) {
|
||||
if (!Objects.equals(byNameMatch.getId(), byCodeMatch.getId())) {
|
||||
throw new BusinessException("规格「" + specName + "」下名称与编码指向不同已有值,冲突");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (byNameMatch != null) {
|
||||
if (!Objects.equals(byNameMatch.getValueCode().toUpperCase(), code)) {
|
||||
throw new BusinessException("规格「" + specName + "」下规格值名称「"
|
||||
+ name + "」已存在但编码冲突");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (byCodeMatch != null) {
|
||||
if (!Objects.equals(byCodeMatch.getValueName(), name)) {
|
||||
throw new BusinessException("规格「" + specName + "」下规格值编码「"
|
||||
+ code + "」已存在但名称冲突");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
ReplaceProductSpecsDTO.ValueItem vi = new ReplaceProductSpecsDTO.ValueItem();
|
||||
vi.setValueName(name);
|
||||
vi.setValueCode(code);
|
||||
vi.setSortOrder(tv.getSortOrder() != null ? tv.getSortOrder() : nextOrder++);
|
||||
values.add(vi);
|
||||
byName.put(name, vi);
|
||||
byCode.put(code, vi);
|
||||
}
|
||||
}
|
||||
|
||||
private SpecTemplateValuePO resolveOrCreateValue(Long templateId, Long id,
|
||||
String valueName, String valueCode, int sortOrder) {
|
||||
if (id != null && id > 0) {
|
||||
SpecTemplateValuePO existing = valueMapper.selectById(id);
|
||||
if (existing == null || !Objects.equals(existing.getTemplateId(), templateId)) {
|
||||
throw new BusinessException("模板规格值不存在或不属于当前模板");
|
||||
}
|
||||
existing.setValueName(valueName);
|
||||
existing.setValueCode(valueCode);
|
||||
existing.setSortOrder(sortOrder);
|
||||
valueMapper.updateById(existing);
|
||||
return existing;
|
||||
}
|
||||
SpecTemplateValuePO po = new SpecTemplateValuePO();
|
||||
po.setTemplateId(templateId);
|
||||
po.setValueName(valueName);
|
||||
po.setValueCode(valueCode);
|
||||
po.setSortOrder(sortOrder);
|
||||
valueMapper.insert(po);
|
||||
return po;
|
||||
}
|
||||
|
||||
/** 从商品规格维拷贝值到新模板。 */
|
||||
private void copyProductSpecValuesToTemplate(Long templateId, ProductSpecVO spec) {
|
||||
List<ProductSpecValueVO> values = spec.getValues() == null ? List.of() : spec.getValues();
|
||||
int valueOrder = 0;
|
||||
for (ProductSpecValueVO val : values) {
|
||||
SpecTemplateValuePO valPo = new SpecTemplateValuePO();
|
||||
valPo.setTemplateId(templateId);
|
||||
valPo.setValueName(val.getValueName());
|
||||
valPo.setValueCode(val.getValueCode());
|
||||
valPo.setSortOrder(val.getSortOrder() != null ? val.getSortOrder() : valueOrder++);
|
||||
valueMapper.insert(valPo);
|
||||
}
|
||||
}
|
||||
|
||||
private void seedOneIfAbsent(Long companyId, Long userId, String name, int sortOrder,
|
||||
List<SeedValue> values) {
|
||||
if (existsByCompanyAndName(companyId, name)) {
|
||||
return;
|
||||
}
|
||||
SpecTemplatePO po = new SpecTemplatePO();
|
||||
po.setCompanyId(companyId);
|
||||
po.setName(name);
|
||||
po.setSortOrder(sortOrder);
|
||||
po.setCreateBy(userId);
|
||||
po.setUpdateBy(userId);
|
||||
templateMapper.insert(po);
|
||||
|
||||
int order = 0;
|
||||
for (SeedValue sv : values) {
|
||||
SpecTemplateValuePO valPo = new SpecTemplateValuePO();
|
||||
valPo.setTemplateId(po.getId());
|
||||
valPo.setValueName(sv.name());
|
||||
valPo.setValueCode(sv.code());
|
||||
valPo.setSortOrder(sv.sortOrder() != null ? sv.sortOrder() : order++);
|
||||
valueMapper.insert(valPo);
|
||||
}
|
||||
}
|
||||
|
||||
private List<SpecTemplateVO> toVoList(List<SpecTemplatePO> templates) {
|
||||
if (templates.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<Long> templateIds = templates.stream().map(SpecTemplatePO::getId).toList();
|
||||
Map<Long, List<SpecTemplateValuePO>> valuesByTemplate = valueMapper.selectList(
|
||||
new LambdaQueryWrapper<SpecTemplateValuePO>()
|
||||
.in(SpecTemplateValuePO::getTemplateId, templateIds)
|
||||
.orderByAsc(SpecTemplateValuePO::getSortOrder)
|
||||
.orderByAsc(SpecTemplateValuePO::getId))
|
||||
.stream()
|
||||
.collect(Collectors.groupingBy(SpecTemplateValuePO::getTemplateId));
|
||||
|
||||
List<SpecTemplateVO> result = new ArrayList<>();
|
||||
for (SpecTemplatePO po : templates) {
|
||||
result.add(toVo(po, valuesByTemplate.getOrDefault(po.getId(), List.of())));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private SpecTemplateVO toVoWithValues(SpecTemplatePO po) {
|
||||
return toVo(po, loadValues(po.getId()));
|
||||
}
|
||||
|
||||
private SpecTemplateVO toVo(SpecTemplatePO po, List<SpecTemplateValuePO> values) {
|
||||
SpecTemplateVO vo = new SpecTemplateVO();
|
||||
vo.setId(po.getId());
|
||||
vo.setCompanyId(po.getCompanyId());
|
||||
vo.setName(po.getName());
|
||||
vo.setRemark(po.getRemark());
|
||||
vo.setSortOrder(po.getSortOrder());
|
||||
vo.setCreateTime(po.getCreateTime());
|
||||
vo.setUpdateTime(po.getUpdateTime());
|
||||
vo.setValues(toValueVos(values));
|
||||
return vo;
|
||||
}
|
||||
|
||||
private List<SpecTemplateValuePO> loadValues(Long templateId) {
|
||||
return valueMapper.selectList(new LambdaQueryWrapper<SpecTemplateValuePO>()
|
||||
.eq(SpecTemplateValuePO::getTemplateId, templateId)
|
||||
.orderByAsc(SpecTemplateValuePO::getSortOrder)
|
||||
.orderByAsc(SpecTemplateValuePO::getId));
|
||||
}
|
||||
|
||||
private List<SpecTemplateValueVO> toValueVos(List<SpecTemplateValuePO> values) {
|
||||
List<SpecTemplateValueVO> result = new ArrayList<>();
|
||||
for (SpecTemplateValuePO v : values) {
|
||||
SpecTemplateValueVO vv = new SpecTemplateValueVO();
|
||||
vv.setId(v.getId());
|
||||
vv.setValueName(v.getValueName());
|
||||
vv.setValueCode(v.getValueCode());
|
||||
vv.setSortOrder(v.getSortOrder());
|
||||
result.add(vv);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private ReplaceProductSpecsDTO.SpecItem toReplaceSpecItem(ProductSpecVO spec) {
|
||||
ReplaceProductSpecsDTO.SpecItem item = new ReplaceProductSpecsDTO.SpecItem();
|
||||
item.setId(spec.getId());
|
||||
item.setName(spec.getName());
|
||||
item.setSortOrder(spec.getSortOrder());
|
||||
List<ReplaceProductSpecsDTO.ValueItem> values = new ArrayList<>();
|
||||
if (spec.getValues() != null) {
|
||||
for (ProductSpecValueVO v : spec.getValues()) {
|
||||
ReplaceProductSpecsDTO.ValueItem vi = new ReplaceProductSpecsDTO.ValueItem();
|
||||
vi.setId(v.getId());
|
||||
vi.setValueName(v.getValueName());
|
||||
vi.setValueCode(v.getValueCode());
|
||||
vi.setSortOrder(v.getSortOrder());
|
||||
values.add(vi);
|
||||
}
|
||||
}
|
||||
item.setValues(values);
|
||||
return item;
|
||||
}
|
||||
|
||||
/** 可读写:仅本公司模板。 */
|
||||
private SpecTemplatePO requireCompanyTemplate(Long id) {
|
||||
SpecTemplatePO po = templateMapper.selectById(id);
|
||||
if (po == null) {
|
||||
throw new BusinessException("规格模板不存在");
|
||||
}
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
if (!Objects.equals(po.getCompanyId(), companyId)) {
|
||||
throw new BusinessException("规格模板不存在");
|
||||
}
|
||||
return po;
|
||||
}
|
||||
|
||||
private long countByCompany(Long companyId) {
|
||||
return templateMapper.selectCount(new LambdaQueryWrapper<SpecTemplatePO>()
|
||||
.eq(SpecTemplatePO::getCompanyId, companyId));
|
||||
}
|
||||
|
||||
private boolean existsByCompanyAndName(Long companyId, String name) {
|
||||
return templateMapper.selectCount(new LambdaQueryWrapper<SpecTemplatePO>()
|
||||
.eq(SpecTemplatePO::getCompanyId, companyId)
|
||||
.eq(SpecTemplatePO::getName, name)) > 0;
|
||||
}
|
||||
|
||||
private void assertCompanyNameAvailable(Long companyId, String name, Long excludeId) {
|
||||
LambdaQueryWrapper<SpecTemplatePO> w = new LambdaQueryWrapper<SpecTemplatePO>()
|
||||
.eq(SpecTemplatePO::getCompanyId, companyId)
|
||||
.eq(SpecTemplatePO::getName, name);
|
||||
if (excludeId != null) {
|
||||
w.ne(SpecTemplatePO::getId, excludeId);
|
||||
}
|
||||
if (templateMapper.selectCount(w) > 0) {
|
||||
throw new BusinessException("模板名称已存在: " + name);
|
||||
}
|
||||
}
|
||||
|
||||
private static SeedValue value(String name, String code, int sortOrder) {
|
||||
return new SeedValue(name, code, sortOrder);
|
||||
}
|
||||
|
||||
private record SeedValue(String name, String code, Integer sortOrder) {}
|
||||
|
||||
private static String requireText(String s, String message) {
|
||||
if (!StringUtils.hasText(s)) {
|
||||
throw new BusinessException(message);
|
||||
}
|
||||
return s.trim();
|
||||
}
|
||||
|
||||
private static String trimToNull(String s) {
|
||||
if (!StringUtils.hasText(s)) {
|
||||
return null;
|
||||
}
|
||||
return s.trim();
|
||||
}
|
||||
|
||||
private static void validateValueCode(String code) {
|
||||
if (!code.matches("^[A-Za-z0-9_-]+$")) {
|
||||
throw new BusinessException("规格值编码仅允许字母、数字、下划线、中划线: " + code);
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -34,6 +34,7 @@ import top.xyquan.ecomdmbbackend.modules.org.company.member.enums.CompanyMemberR
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseEnforcement;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseInfo;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseValidator;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.service.SpecTemplateService;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -59,12 +60,14 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
|
||||
private final CompanyMemberService companyMemberService;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final LicenseValidator licenseValidator;
|
||||
private final SpecTemplateService specTemplateService;
|
||||
|
||||
public CompanyServiceImpl(@Lazy CurrentUserContext currentUserContext, SysFileService sysFileService,
|
||||
CompanyMenuService companyMenuService, DepartmentService departmentService,
|
||||
PositionService positionService, MenuService menuService,
|
||||
@Lazy UserService userService, @Lazy CompanyMemberService companyMemberService,
|
||||
PasswordEncoder passwordEncoder, LicenseValidator licenseValidator) {
|
||||
PasswordEncoder passwordEncoder, LicenseValidator licenseValidator,
|
||||
@Lazy SpecTemplateService specTemplateService) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.sysFileService = sysFileService;
|
||||
this.companyMenuService = companyMenuService;
|
||||
@@ -75,6 +78,7 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
|
||||
this.companyMemberService = companyMemberService;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.licenseValidator = licenseValidator;
|
||||
this.specTemplateService = specTemplateService;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -166,6 +170,9 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
|
||||
// 初始化公司岗位
|
||||
initCompanyPositions(company.getId(), creatorId);
|
||||
|
||||
// 初始化默认规格模板
|
||||
specTemplateService.seedDefaultTemplates(company.getId(), creatorId);
|
||||
|
||||
// 转换为VO并返回
|
||||
return convertToVO(company);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,10 @@ export namespace ProductSkuVO {
|
||||
name: string;
|
||||
/** SKU 编码 */
|
||||
skuCode?: string;
|
||||
/** 规格组合键;空=未结构化 */
|
||||
specCombinationKey?: string;
|
||||
/** 已绑规格值 */
|
||||
specValues?: import('#/api/ec/product/spec').ProductSpecVO.SpecValue[];
|
||||
/** 商品成本 */
|
||||
productCost: number;
|
||||
/** 运费成本 */
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* 规格模板 API(单维:一个模板=一个规格维 + 若干值)
|
||||
*/
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
import type { ProductSpecVO } from '#/api/ec/product/spec';
|
||||
|
||||
export namespace SpecTemplateVO {
|
||||
export interface Info {
|
||||
id: number;
|
||||
companyId: number;
|
||||
name: string;
|
||||
remark?: string;
|
||||
sortOrder?: number;
|
||||
values?: Value[];
|
||||
createTime?: string;
|
||||
updateTime?: string;
|
||||
}
|
||||
|
||||
export interface Value {
|
||||
id?: number;
|
||||
valueName: string;
|
||||
valueCode: string;
|
||||
sortOrder?: number;
|
||||
}
|
||||
}
|
||||
|
||||
export namespace SpecTemplateDTO {
|
||||
export interface Create {
|
||||
name: string;
|
||||
remark?: string;
|
||||
sortOrder?: number;
|
||||
values?: ValueItem[];
|
||||
}
|
||||
|
||||
export interface Update {
|
||||
name?: string;
|
||||
remark?: string;
|
||||
sortOrder?: number;
|
||||
values?: ValueItem[];
|
||||
}
|
||||
|
||||
export interface ReplaceContent {
|
||||
values?: ValueItem[];
|
||||
}
|
||||
|
||||
export interface ValueItem {
|
||||
id?: number;
|
||||
valueName: string;
|
||||
valueCode: string;
|
||||
sortOrder?: number;
|
||||
}
|
||||
|
||||
export interface Apply {
|
||||
templateId: number;
|
||||
/** 空=该维全部值 */
|
||||
templateValueIds?: number[];
|
||||
}
|
||||
|
||||
export interface SaveAs {
|
||||
productSpecId: number;
|
||||
name?: string;
|
||||
}
|
||||
}
|
||||
|
||||
export async function listSpecTemplatesApi() {
|
||||
return requestClient.get<SpecTemplateVO.Info[]>(
|
||||
'/ec/product/spec-templates',
|
||||
);
|
||||
}
|
||||
|
||||
export async function getSpecTemplateApi(id: number) {
|
||||
return requestClient.get<SpecTemplateVO.Info>(
|
||||
`/ec/product/spec-templates/${id}`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function createSpecTemplateApi(data: SpecTemplateDTO.Create) {
|
||||
return requestClient.post<SpecTemplateVO.Info>(
|
||||
'/ec/product/spec-templates',
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateSpecTemplateApi(
|
||||
id: number,
|
||||
data: SpecTemplateDTO.Update,
|
||||
) {
|
||||
return requestClient.put<SpecTemplateVO.Info>(
|
||||
`/ec/product/spec-templates/${id}`,
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
export async function replaceSpecTemplateContentApi(
|
||||
id: number,
|
||||
data: SpecTemplateDTO.ReplaceContent,
|
||||
) {
|
||||
return requestClient.put<SpecTemplateVO.Info>(
|
||||
`/ec/product/spec-templates/${id}/content`,
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
export async function deleteSpecTemplateApi(id: number) {
|
||||
return requestClient.delete(`/ec/product/spec-templates/${id}`);
|
||||
}
|
||||
|
||||
export async function applySpecTemplateApi(
|
||||
productId: number,
|
||||
data: SpecTemplateDTO.Apply,
|
||||
) {
|
||||
return requestClient.post<ProductSpecVO.Spec[]>(
|
||||
`/ec/product/${productId}/specs/apply-template`,
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
export async function saveProductAsSpecTemplateApi(
|
||||
productId: number,
|
||||
data: SpecTemplateDTO.SaveAs,
|
||||
) {
|
||||
return requestClient.post<SpecTemplateVO.Info>(
|
||||
`/ec/product/${productId}/specs/save-as-template`,
|
||||
data,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* 商品规格维 API / 类型
|
||||
*/
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
import type { ProductSkuVO } from '#/api/ec/product/sku/types';
|
||||
|
||||
export namespace ProductSpecVO {
|
||||
export interface Spec {
|
||||
id?: number;
|
||||
name?: string;
|
||||
sortOrder?: number;
|
||||
values?: SpecValue[];
|
||||
}
|
||||
|
||||
export interface SpecValue {
|
||||
id?: number;
|
||||
specId?: number;
|
||||
valueName?: string;
|
||||
valueCode?: string;
|
||||
sortOrder?: number;
|
||||
}
|
||||
}
|
||||
|
||||
export namespace ProductSpecDTO {
|
||||
export interface Replace {
|
||||
specs?: SpecItem[];
|
||||
}
|
||||
|
||||
export interface SpecItem {
|
||||
id?: number;
|
||||
name: string;
|
||||
sortOrder?: number;
|
||||
values?: ValueItem[];
|
||||
}
|
||||
|
||||
export interface ValueItem {
|
||||
id?: number;
|
||||
valueName: string;
|
||||
valueCode: string;
|
||||
sortOrder?: number;
|
||||
}
|
||||
|
||||
export interface GenerateSkus {
|
||||
productCost?: number;
|
||||
shippingCost?: number;
|
||||
otherCost?: number;
|
||||
}
|
||||
|
||||
export interface CreateSkuFromSpecs {
|
||||
specValueIds: number[];
|
||||
skuCode?: string;
|
||||
name?: string;
|
||||
productCost: number;
|
||||
shippingCost?: number;
|
||||
otherCost?: number;
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
/** 已有 SKU 绑定规格;空数组=解绑 */
|
||||
export interface BindSkuSpecs {
|
||||
specValueIds?: number[];
|
||||
}
|
||||
}
|
||||
|
||||
/** 查询商品规格维 */
|
||||
export async function listProductSpecsApi(productId: number) {
|
||||
return requestClient.get<ProductSpecVO.Spec[]>(
|
||||
`/ec/product/${productId}/specs`,
|
||||
);
|
||||
}
|
||||
|
||||
/** 覆盖保存商品规格维 */
|
||||
export async function replaceProductSpecsApi(
|
||||
productId: number,
|
||||
data: ProductSpecDTO.Replace,
|
||||
) {
|
||||
return requestClient.put<ProductSpecVO.Spec[]>(
|
||||
`/ec/product/${productId}/specs`,
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
/** 按规格笛卡尔积生成缺失 SKU */
|
||||
export async function generateProductSkusApi(
|
||||
productId: number,
|
||||
data?: ProductSpecDTO.GenerateSkus,
|
||||
) {
|
||||
return requestClient.post<ProductSkuVO.Info[]>(
|
||||
`/ec/product/${productId}/specs/generate-skus`,
|
||||
data ?? {},
|
||||
);
|
||||
}
|
||||
|
||||
/** 按所选规格值创建 SKU(可缺维;skuCode 可自定义) */
|
||||
export async function createSkuFromSpecsApi(
|
||||
productId: number,
|
||||
data: ProductSpecDTO.CreateSkuFromSpecs,
|
||||
) {
|
||||
return requestClient.post<ProductSkuVO.Info>(
|
||||
`/ec/product/${productId}/specs/skus`,
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为已有 SKU 绑定规格(不改 sku_code)。
|
||||
* specValueIds 空则解绑回 legacy。
|
||||
*/
|
||||
export async function bindSkuSpecsApi(
|
||||
productId: number,
|
||||
skuId: number,
|
||||
data?: ProductSpecDTO.BindSkuSpecs,
|
||||
) {
|
||||
return requestClient.put<ProductSkuVO.Info>(
|
||||
`/ec/product/${productId}/specs/skus/${skuId}`,
|
||||
data ?? { specValueIds: [] },
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,8 @@ export namespace ProductDTO {
|
||||
mainImageId?: number;
|
||||
/** 商品 SKU 列表(可选) */
|
||||
skus?: Sku[];
|
||||
/** 规格维(与商品同事务;无 id=新增) */
|
||||
specs?: SpecItem[];
|
||||
}
|
||||
|
||||
/** 更新商品参数 */
|
||||
@@ -29,6 +31,25 @@ export namespace ProductDTO {
|
||||
mainImageId?: number;
|
||||
/** 商品 SKU 列表:id>0 更新,id=0 新增;未出现的已有 SKU 视为删除 */
|
||||
skus?: UpdateSku[];
|
||||
/** 规格维全量同步:有 id 更新,无 id 新增,未出现的删除 */
|
||||
specs?: SpecItem[];
|
||||
}
|
||||
|
||||
/** 商品规格维(创建/更新商品时一并提交) */
|
||||
export interface SpecItem {
|
||||
/** >0 更新已有;空/0 新增 */
|
||||
id?: number;
|
||||
name: string;
|
||||
sortOrder?: number;
|
||||
values?: SpecValueItem[];
|
||||
}
|
||||
|
||||
export interface SpecValueItem {
|
||||
/** >0 更新已有;空/0 新增 */
|
||||
id?: number;
|
||||
valueName: string;
|
||||
valueCode: string;
|
||||
sortOrder?: number;
|
||||
}
|
||||
|
||||
/** 商品 SKU DTO(创建时) */
|
||||
|
||||
@@ -19,6 +19,8 @@ export namespace ProductVO {
|
||||
productCode?: string;
|
||||
/** 主图 URL */
|
||||
mainImage?: string;
|
||||
/** 结构化规格维 */
|
||||
specs?: import('#/api/ec/product/spec').ProductSpecVO.Spec[];
|
||||
/** 创建时间 */
|
||||
createTime: string;
|
||||
/** 更新时间 */
|
||||
@@ -80,6 +82,10 @@ export namespace ProductVO {
|
||||
name: string;
|
||||
/** SKU 编码 */
|
||||
skuCode?: string;
|
||||
/** 规格组合键;空=未结构化 */
|
||||
specCombinationKey?: string;
|
||||
/** 已绑规格值 */
|
||||
specValues?: import('#/api/ec/product/spec').ProductSpecVO.SpecValue[];
|
||||
/** 商品成本 */
|
||||
productCost: number;
|
||||
/** 运费成本 */
|
||||
|
||||
+29
@@ -93,6 +93,19 @@ const skuColumns = [
|
||||
ellipsis: true,
|
||||
customRender: ({ text }: { text?: string }) => renderEllipsisText(text),
|
||||
},
|
||||
{
|
||||
title: '规格',
|
||||
key: 'specValues',
|
||||
width: 160,
|
||||
ellipsis: true,
|
||||
customRender: ({ record }: { record: ProductVO.SkuInfo }) => {
|
||||
const text = (record.specValues ?? [])
|
||||
.map((v) => v.valueName)
|
||||
.filter(Boolean)
|
||||
.join(' / ');
|
||||
return renderEllipsisText(text || (record.specCombinationKey ? '结构化' : '-'));
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '商品成本',
|
||||
dataIndex: 'productCost',
|
||||
@@ -271,6 +284,22 @@ defineExpose({
|
||||
<span>{{ product.createTime || '-' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="product.specs?.length"
|
||||
class="mt-2 border-t border-slate-200 pt-2 text-xs text-slate-600 dark:border-[hsl(240deg_3.7%_22%)] dark:text-slate-300"
|
||||
>
|
||||
<span class="text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">规格维:</span>
|
||||
<span
|
||||
v-for="(spec, i) in product.specs"
|
||||
:key="spec.id ?? i"
|
||||
>
|
||||
{{ i > 0 ? ';' : '' }}{{ spec.name }}({{
|
||||
(spec.values ?? [])
|
||||
.map((v) => `${v.valueName}/${v.valueCode}`)
|
||||
.join('、') || '无值'
|
||||
}})
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
+180
-31
@@ -21,11 +21,14 @@ import {
|
||||
|
||||
import { getCategoryTreeApi } from '#/api/ec/product/category';
|
||||
import { createProductApi, updateProductApi } from '#/api/ec/product';
|
||||
import { getProductSkuPageApi } from '#/api/ec/product/sku';
|
||||
import { uploadFile } from '#/utils/upload-file';
|
||||
import CategoryFormModal from '#/views/ec/product/category/components/CategoryFormModal.vue';
|
||||
import ProductSkuCostDrawer from './ProductSkuCostDrawer.vue';
|
||||
import ProductSkuDeleteConfirmModal from './ProductSkuDeleteConfirmModal.vue';
|
||||
import ProductSkuMigrateModal from './ProductSkuMigrateModal.vue';
|
||||
import ProductSkuBindSpecModal from './ProductSkuBindSpecModal.vue';
|
||||
import ProductSpecEditor from './ProductSpecEditor.vue';
|
||||
|
||||
interface Emits {
|
||||
(e: 'success'): void;
|
||||
@@ -35,6 +38,10 @@ defineOptions({ name: 'ProductFormModal' });
|
||||
|
||||
const emit = defineEmits<Emits>();
|
||||
|
||||
const productSpecEditorRef = ref<InstanceType<typeof ProductSpecEditor> | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
// 创建Vben Modal实例:内容区不滚动,由 SKU 列表占满剩余高度并独立滚动
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
title: '添加商品',
|
||||
@@ -69,6 +76,9 @@ const productSkuMigrateModalRef = ref<InstanceType<
|
||||
const productSkuDeleteModalRef = ref<InstanceType<
|
||||
typeof ProductSkuDeleteConfirmModal
|
||||
> | null>(null);
|
||||
const productSkuBindSpecModalRef = ref<InstanceType<
|
||||
typeof ProductSkuBindSpecModal
|
||||
> | null>(null);
|
||||
/** SKU 列表滚动容器:新增行后滚到底 */
|
||||
const skuListScrollRef = ref<HTMLElement | null>(null);
|
||||
|
||||
@@ -196,6 +206,10 @@ type SkuFormRow = ProductDTO.Sku & {
|
||||
_clientKey?: string;
|
||||
id?: number;
|
||||
costEffectiveFrom?: string;
|
||||
/** 规格组合键;空=未结构化 */
|
||||
specCombinationKey?: string;
|
||||
/** 已绑规格值 */
|
||||
specValues?: ProductVO.SkuInfo['specValues'];
|
||||
/** 已有图预览 URL(系统文件或渠道外链) */
|
||||
imageUrl?: string;
|
||||
/** 新选择待上传的文件 */
|
||||
@@ -211,6 +225,8 @@ function isPersistedSkuId(id?: number) {
|
||||
function mapSkuFields(spec: ProductVO.SkuInfo): ProductDTO.Sku & {
|
||||
costEffectiveFrom?: string;
|
||||
imageUrl?: string;
|
||||
specCombinationKey?: string;
|
||||
specValues?: ProductVO.SkuInfo['specValues'];
|
||||
} {
|
||||
return {
|
||||
name: spec.name || spec.skuCode || '',
|
||||
@@ -221,6 +237,8 @@ function mapSkuFields(spec: ProductVO.SkuInfo): ProductDTO.Sku & {
|
||||
costEffectiveFrom: spec.costEffectiveFrom,
|
||||
remark: spec.remark || '',
|
||||
imageUrl: spec.imageUrl || '',
|
||||
specCombinationKey: spec.specCombinationKey,
|
||||
specValues: spec.specValues,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -317,6 +335,14 @@ async function handleSubmit() {
|
||||
return;
|
||||
}
|
||||
|
||||
const specErr = productSpecEditorRef.value?.validateDraft?.();
|
||||
if (specErr) {
|
||||
message.error(specErr);
|
||||
return;
|
||||
}
|
||||
const specsPayload: ProductDTO.SpecItem[] =
|
||||
productSpecEditorRef.value?.getSpecsPayload?.() ?? [];
|
||||
|
||||
modalApi.setState({ confirmLoading: true });
|
||||
|
||||
// 准备提交数据
|
||||
@@ -356,24 +382,25 @@ async function handleSubmit() {
|
||||
|
||||
const updateData: ProductDTO.Update = {
|
||||
name: submitData.name,
|
||||
productCode: submitData.productCode || undefined,
|
||||
productCode: String(submitData.productCode || '').trim(),
|
||||
categoryId: submitData.categoryId,
|
||||
mainImageId: submitData.mainImageId,
|
||||
skus: skusPayload,
|
||||
specs: specsPayload,
|
||||
};
|
||||
const result = await updateProductApi(currentProductData.value.id, updateData);
|
||||
if (result.skuIdsCostChangedWithLinkedOrders?.length > 0) {
|
||||
message.success('商品和 SKU 更新成功,已标记 BI 待重算(请在工作台查看)');
|
||||
message.success('商品、规格和 SKU 更新成功,已标记 BI 待重算(请在工作台查看)');
|
||||
} else {
|
||||
message.success('商品和 SKU 更新成功');
|
||||
message.success('商品、规格和 SKU 更新成功');
|
||||
}
|
||||
} else {
|
||||
// 创建模式:统一使用创建接口,规格信息作为可选字段
|
||||
const createData: ProductDTO.Create = {
|
||||
name: submitData.name,
|
||||
productCode: submitData.productCode || undefined,
|
||||
productCode: String(submitData.productCode || '').trim(),
|
||||
categoryId: submitData.categoryId,
|
||||
mainImageId: submitData.mainImageId,
|
||||
specs: specsPayload,
|
||||
...(skus.value.length > 0 && {
|
||||
skus: skus.value.map(
|
||||
({
|
||||
@@ -388,14 +415,10 @@ async function handleSubmit() {
|
||||
}),
|
||||
};
|
||||
const createResult = await createProductApi(createData);
|
||||
if (skus.value.length > 0) {
|
||||
if (createResult.skuIdsCostChangedWithLinkedOrders?.length > 0) {
|
||||
message.success('商品和 SKU 创建成功,已标记 BI 待重算(请在工作台查看)');
|
||||
} else {
|
||||
message.success('商品和 SKU 创建成功');
|
||||
}
|
||||
if (createResult.skuIdsCostChangedWithLinkedOrders?.length > 0) {
|
||||
message.success('商品创建成功,已标记 BI 待重算(请在工作台查看)');
|
||||
} else {
|
||||
message.success('创建成功');
|
||||
message.success('商品创建成功');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -408,6 +431,27 @@ async function handleSubmit() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 按规格生成/添加 SKU 后刷新表单 SKU 列表 */
|
||||
async function onSpecSkusChanged() {
|
||||
const productId = currentProductData.value?.id;
|
||||
if (productId == null) return;
|
||||
try {
|
||||
const data = await getProductSkuPageApi({
|
||||
page: 1,
|
||||
pageSize: 500,
|
||||
filters: { productId },
|
||||
});
|
||||
applySkusFromProduct({
|
||||
...(currentProductData.value as ProductVO.Info),
|
||||
id: productId,
|
||||
skus: (data.records ?? []) as unknown as ProductVO.SkuInfo[],
|
||||
});
|
||||
emit('success');
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '刷新 SKU 列表失败');
|
||||
}
|
||||
}
|
||||
|
||||
// 关闭模态框
|
||||
function close() {
|
||||
modalApi.close();
|
||||
@@ -842,6 +886,20 @@ const skuColumns = [
|
||||
record: SkuFormRow;
|
||||
}) => renderSkuTextInput(record, 'skuCode', '请输入SKU 编码', '与同品 SKU 编码重复'),
|
||||
},
|
||||
{
|
||||
title: '规格',
|
||||
key: 'specValues',
|
||||
width: 120,
|
||||
ellipsis: true,
|
||||
customRender: ({ record }: { record: SkuFormRow }) => {
|
||||
const text = (record.specValues ?? [])
|
||||
.map((v) => v.valueName)
|
||||
.filter(Boolean)
|
||||
.join(' / ');
|
||||
if (text) return text;
|
||||
return record.specCombinationKey ? '已结构化' : '未绑定';
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '商品成本',
|
||||
dataIndex: 'productCost',
|
||||
@@ -897,26 +955,99 @@ const skuColumns = [
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 48,
|
||||
width: 112,
|
||||
align: 'center' as const,
|
||||
customRender: ({ index }: { index: number }) => {
|
||||
return h(
|
||||
Button,
|
||||
{
|
||||
type: 'text',
|
||||
danger: true,
|
||||
size: 'small',
|
||||
title: '删除',
|
||||
onClick: () => removeSku(index),
|
||||
},
|
||||
{
|
||||
icon: () => h(TrashIcon, { class: 'h-4 w-4' }),
|
||||
},
|
||||
customRender: ({
|
||||
record,
|
||||
index,
|
||||
}: {
|
||||
record: SkuFormRow;
|
||||
index: number;
|
||||
}) => {
|
||||
const children = [];
|
||||
if (isPersistedSkuId(record.id) && currentProductData.value?.id) {
|
||||
children.push(
|
||||
h(
|
||||
Button,
|
||||
{
|
||||
type: 'link',
|
||||
title: '绑定规格',
|
||||
style: { padding: '0 4px' },
|
||||
onClick: () => openBindSpec(record),
|
||||
},
|
||||
{ default: () => '规格' },
|
||||
),
|
||||
);
|
||||
}
|
||||
children.push(
|
||||
h(
|
||||
Button,
|
||||
{
|
||||
type: 'text',
|
||||
danger: true,
|
||||
title: '删除',
|
||||
onClick: () => removeSku(index),
|
||||
},
|
||||
{
|
||||
icon: () => h(TrashIcon, { class: 'h-4 w-4' }),
|
||||
},
|
||||
),
|
||||
);
|
||||
return h(Space, { size: 0 }, { default: () => children });
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function openBindSpec(record: SkuFormRow) {
|
||||
const pid = currentProductData.value?.id;
|
||||
if (pid == null || !isPersistedSkuId(record.id)) {
|
||||
message.warning('请先保存商品与该 SKU');
|
||||
return;
|
||||
}
|
||||
productSkuBindSpecModalRef.value?.open(pid, {
|
||||
id: Number(record.id),
|
||||
companyId: currentProductData.value?.companyId ?? 0,
|
||||
productId: pid,
|
||||
productName: formData.value.name || '',
|
||||
name: record.name,
|
||||
skuCode: record.skuCode,
|
||||
productCost: record.productCost ?? 0,
|
||||
shippingCost: record.shippingCost,
|
||||
otherCost: record.otherCost,
|
||||
costEffectiveFrom: record.costEffectiveFrom,
|
||||
remark: record.remark,
|
||||
imageUrl: record.imageUrl,
|
||||
specCombinationKey: record.specCombinationKey,
|
||||
specValues: record.specValues,
|
||||
createTime: '',
|
||||
updateTime: '',
|
||||
});
|
||||
}
|
||||
|
||||
function onBindSpecSuccess(vo: ProductVO.SkuInfo) {
|
||||
const idx = skus.value.findIndex((s) => s.id === vo.id);
|
||||
if (idx >= 0) {
|
||||
skus.value[idx] = {
|
||||
...skus.value[idx]!,
|
||||
specCombinationKey: vo.specCombinationKey,
|
||||
specValues: vo.specValues ?? [],
|
||||
};
|
||||
skus.value = [...skus.value];
|
||||
}
|
||||
const productSkus = currentProductData.value?.skus;
|
||||
if (productSkus) {
|
||||
const pIdx = productSkus.findIndex((s) => s.id === vo.id);
|
||||
if (pIdx >= 0) {
|
||||
productSkus[pIdx] = {
|
||||
...productSkus[pIdx]!,
|
||||
specCombinationKey: vo.specCombinationKey,
|
||||
specValues: vo.specValues ?? [],
|
||||
};
|
||||
}
|
||||
}
|
||||
emit('success');
|
||||
}
|
||||
|
||||
// 上传图片并获取图片ID
|
||||
async function uploadImageAndGetId(): Promise<number | undefined> {
|
||||
if (!newImageFile.value) {
|
||||
@@ -1082,10 +1213,14 @@ onUnmounted(() => {
|
||||
<Input v-model:value="formData.name" placeholder="请输入商品名称" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="商品编码" name="productCode">
|
||||
<Form.Item
|
||||
label="商品编码"
|
||||
name="productCode"
|
||||
:rules="[{ required: true, message: '请输入商品编码' }]"
|
||||
>
|
||||
<Input
|
||||
v-model:value="formData.productCode"
|
||||
placeholder="请输入商品编码"
|
||||
placeholder="请输入商品编码(公司内唯一)"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -1103,7 +1238,17 @@ onUnmounted(() => {
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
<!-- 规格管理:不用 Form.Item,避免栅格打断滚动高度链 -->
|
||||
<div class="mb-3 shrink-0">
|
||||
<ProductSpecEditor
|
||||
ref="productSpecEditorRef"
|
||||
:product-id="currentProductData?.id"
|
||||
:product-code="formData.productCode"
|
||||
:initial-specs="currentProductData?.specs"
|
||||
@skus-changed="onSpecSkusChanged"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- SKU:不用 Form.Item,避免栅格打断滚动高度链 -->
|
||||
<div class="flex min-h-0 flex-1 flex-col gap-3 overflow-hidden">
|
||||
<div class="flex shrink-0 items-center justify-between gap-2">
|
||||
<div class="flex items-center gap-2">
|
||||
@@ -1146,7 +1291,8 @@ onUnmounted(() => {
|
||||
v-if="isEdit && showSkus"
|
||||
class="shrink-0 text-xs text-slate-400"
|
||||
>
|
||||
已有 SKU 的成本只读;调价请点「管理成本」。新增 SKU 仍可填初始成本。
|
||||
已有 SKU 的成本只读;调价请点「管理成本」。新增 SKU 仍可填初始成本。已落库
|
||||
SKU 可点「规格」绑定规格维(不改编码)。
|
||||
</p>
|
||||
|
||||
<div
|
||||
@@ -1160,7 +1306,6 @@ onUnmounted(() => {
|
||||
:pagination="false"
|
||||
:row-key="(r: SkuFormRow) => (isPersistedSkuId(r.id) ? String(r.id) : r._clientKey ?? '')"
|
||||
:scroll="{ x: 980 }"
|
||||
size="small"
|
||||
>
|
||||
<template #emptyText>
|
||||
<div class="py-4 text-center text-gray-400">
|
||||
@@ -1183,5 +1328,9 @@ onUnmounted(() => {
|
||||
@success="onMigrateSuccess"
|
||||
/>
|
||||
<ProductSkuDeleteConfirmModal ref="productSkuDeleteModalRef" />
|
||||
<ProductSkuBindSpecModal
|
||||
ref="productSkuBindSpecModalRef"
|
||||
@success="onBindSpecSuccess"
|
||||
/>
|
||||
<CategoryFormModal ref="categoryFormModalRef" @success="reloadCategoryTree" />
|
||||
</template>
|
||||
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
<script lang="ts" setup>
|
||||
/**
|
||||
* 已有 SKU 绑定规格:写组合键与关系表,不改 sku_code。
|
||||
*/
|
||||
import type { ProductSpecVO } from '#/api/ec/product/spec';
|
||||
import type { ProductVO } from '#/api/ec/product/types';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
|
||||
import { Button, Select, Space, message } from 'ant-design-vue';
|
||||
|
||||
import {
|
||||
bindSkuSpecsApi,
|
||||
listProductSpecsApi,
|
||||
} from '#/api/ec/product/spec';
|
||||
|
||||
defineOptions({ name: 'ProductSkuBindSpecModal' });
|
||||
|
||||
const emit = defineEmits<{
|
||||
success: [sku: ProductVO.SkuInfo];
|
||||
}>();
|
||||
|
||||
const productId = ref<number>();
|
||||
const sku = ref<ProductVO.SkuInfo | null>(null);
|
||||
const specs = ref<ProductSpecVO.Spec[]>([]);
|
||||
const selectedBySpecId = ref<Record<number, number | undefined>>({});
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
|
||||
const title = computed(() => {
|
||||
const code = sku.value?.skuCode || sku.value?.name || '';
|
||||
return code ? `绑定规格 - ${code}` : '绑定规格';
|
||||
});
|
||||
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
title: '绑定规格',
|
||||
class: 'w-[480px]',
|
||||
confirmText: '保存绑定',
|
||||
cancelText: '取消',
|
||||
onConfirm: handleSave,
|
||||
});
|
||||
|
||||
async function open(pid: number, row: ProductVO.SkuInfo) {
|
||||
if (!pid || !row?.id) {
|
||||
message.warning('请先保存商品与 SKU');
|
||||
return;
|
||||
}
|
||||
productId.value = pid;
|
||||
sku.value = row;
|
||||
selectedBySpecId.value = {};
|
||||
loading.value = true;
|
||||
modalApi.setState({ title: title.value, confirmLoading: false });
|
||||
modalApi.open();
|
||||
try {
|
||||
const list = await listProductSpecsApi(pid);
|
||||
specs.value = list ?? [];
|
||||
if (specs.value.length === 0) {
|
||||
message.warning('请先配置并保存规格维');
|
||||
}
|
||||
// 预填已绑规格值
|
||||
const bound = row.specValues ?? [];
|
||||
for (const s of specs.value) {
|
||||
if (s.id == null) continue;
|
||||
const hit = bound.find((v) => v.specId === s.id);
|
||||
selectedBySpecId.value[s.id] = hit?.id;
|
||||
}
|
||||
modalApi.setState({ title: title.value });
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '加载规格失败');
|
||||
modalApi.close();
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSave() {
|
||||
if (productId.value == null || sku.value?.id == null) return;
|
||||
const ids: number[] = [];
|
||||
for (const s of specs.value) {
|
||||
if (s.id == null) continue;
|
||||
const vid = selectedBySpecId.value[s.id];
|
||||
if (vid != null) ids.push(vid);
|
||||
}
|
||||
saving.value = true;
|
||||
modalApi.setState({ confirmLoading: true });
|
||||
try {
|
||||
const vo = await bindSkuSpecsApi(productId.value, sku.value.id, {
|
||||
specValueIds: ids,
|
||||
});
|
||||
message.success(ids.length === 0 ? '已解除规格绑定' : '规格已绑定(编码未改)');
|
||||
emit('success', {
|
||||
...sku.value,
|
||||
...vo,
|
||||
specCombinationKey: vo.specCombinationKey,
|
||||
specValues: vo.specValues,
|
||||
} as ProductVO.SkuInfo);
|
||||
modalApi.close();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '绑定失败');
|
||||
} finally {
|
||||
saving.value = false;
|
||||
modalApi.setState({ confirmLoading: false });
|
||||
}
|
||||
}
|
||||
|
||||
async function handleUnbind() {
|
||||
if (productId.value == null || sku.value?.id == null) return;
|
||||
saving.value = true;
|
||||
modalApi.setState({ confirmLoading: true });
|
||||
try {
|
||||
const vo = await bindSkuSpecsApi(productId.value, sku.value.id, {
|
||||
specValueIds: [],
|
||||
});
|
||||
message.success('已解除规格绑定');
|
||||
emit('success', {
|
||||
...sku.value,
|
||||
...vo,
|
||||
specCombinationKey: undefined,
|
||||
specValues: [],
|
||||
} as ProductVO.SkuInfo);
|
||||
modalApi.close();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '解绑失败');
|
||||
} finally {
|
||||
saving.value = false;
|
||||
modalApi.setState({ confirmLoading: false });
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({ open });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Modal>
|
||||
<p class="mb-3 text-xs text-slate-500">
|
||||
可为外部同步 SKU 绑定规格组合,<strong>不修改 SKU 编码</strong>。允许缺维;清空选择并保存,或点「解除绑定」回到无结构。
|
||||
</p>
|
||||
<div v-if="loading" class="py-6 text-center text-sm text-slate-400">加载中…</div>
|
||||
<div v-else class="space-y-3">
|
||||
<div
|
||||
v-for="spec in specs.filter((s) => s.id)"
|
||||
:key="spec.id"
|
||||
class="flex items-center gap-2"
|
||||
>
|
||||
<span class="w-20 shrink-0 text-sm">{{ spec.name }}</span>
|
||||
<Select
|
||||
v-model:value="selectedBySpecId[spec.id!]"
|
||||
class="flex-1"
|
||||
allow-clear
|
||||
placeholder="不选则缺该维"
|
||||
:options="
|
||||
(spec.values ?? [])
|
||||
.filter((v) => v.id)
|
||||
.map((v) => ({
|
||||
label: `${v.valueName} (${v.valueCode})`,
|
||||
value: v.id!,
|
||||
}))
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
<p v-if="specs.length === 0" class="text-sm text-amber-600">暂无规格维</p>
|
||||
<Space class="pt-1">
|
||||
<Button
|
||||
danger
|
||||
size="small"
|
||||
:disabled="saving || !sku?.specCombinationKey"
|
||||
@click="handleUnbind"
|
||||
>
|
||||
解除绑定
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
</Modal>
|
||||
</template>
|
||||
+978
@@ -0,0 +1,978 @@
|
||||
<script lang="ts" setup>
|
||||
/**
|
||||
* 商品规格维编辑:选择器套用模板;草稿随商品创建/更新一并提交。
|
||||
*/
|
||||
import type { ProductDTO } from '#/api/ec/product/types';
|
||||
import type { ProductSpecVO } from '#/api/ec/product/spec';
|
||||
import type { SpecTemplateVO } from '#/api/ec/product/spec-template';
|
||||
import type { DropdownRender } from 'ant-design-vue/es/vc-select/BaseSelect';
|
||||
|
||||
import { computed, h, nextTick, ref, watch } from 'vue';
|
||||
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Select,
|
||||
Space,
|
||||
Table,
|
||||
message,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
import {
|
||||
createSkuFromSpecsApi,
|
||||
generateProductSkusApi,
|
||||
listProductSpecsApi,
|
||||
} from '#/api/ec/product/spec';
|
||||
import {
|
||||
listSpecTemplatesApi,
|
||||
saveProductAsSpecTemplateApi,
|
||||
} from '#/api/ec/product/spec-template';
|
||||
import SpecTemplateFormModal from '#/views/ec/product/spec-template/components/SpecTemplateFormModal.vue';
|
||||
|
||||
defineOptions({ name: 'ProductSpecEditor' });
|
||||
|
||||
const props = defineProps<{
|
||||
productId?: number | null;
|
||||
productCode?: string;
|
||||
/** 初始规格(编辑时从商品详情带入) */
|
||||
initialSpecs?: ProductSpecVO.Spec[];
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
skusChanged: [];
|
||||
}>();
|
||||
|
||||
const PlusIcon = createIconifyIcon('lucide:plus');
|
||||
const TrashIcon = createIconifyIcon('lucide:trash-2');
|
||||
const UpIcon = createIconifyIcon('lucide:chevron-up');
|
||||
const DownIcon = createIconifyIcon('lucide:chevron-down');
|
||||
const ArrowUpIcon = createIconifyIcon('lucide:arrow-up');
|
||||
const ArrowDownIcon = createIconifyIcon('lucide:arrow-down');
|
||||
|
||||
type DraftValue = {
|
||||
_key: string;
|
||||
id?: number;
|
||||
valueName: string;
|
||||
valueCode: string;
|
||||
sortOrder: number;
|
||||
};
|
||||
|
||||
type DraftSpec = {
|
||||
_key: string;
|
||||
id?: number;
|
||||
name: string;
|
||||
sortOrder: number;
|
||||
values: DraftValue[];
|
||||
};
|
||||
|
||||
const specs = ref<DraftSpec[]>([]);
|
||||
const showSpecs = ref(false);
|
||||
const dirty = ref(false);
|
||||
const generating = ref(false);
|
||||
const showAddSku = ref(false);
|
||||
const addSkuLoading = ref(false);
|
||||
const selectedBySpec = ref<Record<string, number | undefined>>({});
|
||||
const addSkuCost = ref({ productCost: 0, shippingCost: 0, otherCost: 0 });
|
||||
const addSkuCode = ref('');
|
||||
const addSkuName = ref('');
|
||||
const listScrollRef = ref<HTMLElement | null>(null);
|
||||
const templateFormModalRef = ref<InstanceType<
|
||||
typeof SpecTemplateFormModal
|
||||
> | null>(null);
|
||||
|
||||
/** 公司规格模板(选择器用) */
|
||||
const templates = ref<SpecTemplateVO.Info[]>([]);
|
||||
/** 规格名搜索词:spec._key → query */
|
||||
const specNameSearch = ref<Record<string, string>>({});
|
||||
/** 规格值名搜索词:specKey:valKey → query */
|
||||
const valueNameSearch = ref<Record<string, string>>({});
|
||||
/** 新建模板后回填到哪一行 */
|
||||
const pendingTemplateSpecKey = ref<string>();
|
||||
|
||||
let keySeq = 0;
|
||||
function nextKey(prefix: string) {
|
||||
return `${prefix}-${++keySeq}`;
|
||||
}
|
||||
|
||||
const canPersist = computed(
|
||||
() => props.productId != null && props.productId > 0,
|
||||
);
|
||||
|
||||
const savedSpecCount = computed(
|
||||
() => specs.value.filter((s) => s.id != null && s.id > 0).length,
|
||||
);
|
||||
|
||||
function toDraft(list?: ProductSpecVO.Spec[]): DraftSpec[] {
|
||||
return (list ?? []).map((s, si) => ({
|
||||
_key: nextKey('spec'),
|
||||
id: s.id,
|
||||
name: s.name || '',
|
||||
sortOrder: s.sortOrder ?? si,
|
||||
values: (s.values ?? []).map((v, vi) => ({
|
||||
_key: nextKey('val'),
|
||||
id: v.id,
|
||||
valueName: v.valueName || '',
|
||||
valueCode: v.valueCode || '',
|
||||
sortOrder: v.sortOrder ?? vi,
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
function resetFromProps() {
|
||||
specs.value = toDraft(props.initialSpecs);
|
||||
dirty.value = false;
|
||||
selectedBySpec.value = {};
|
||||
showSpecs.value = specs.value.length > 0;
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.productId,
|
||||
async (id) => {
|
||||
selectedBySpec.value = {};
|
||||
dirty.value = false;
|
||||
void loadTemplates();
|
||||
if (id != null && id > 0) {
|
||||
try {
|
||||
const list = await listProductSpecsApi(id);
|
||||
specs.value = toDraft(list);
|
||||
showSpecs.value = specs.value.length > 0;
|
||||
return;
|
||||
} catch {
|
||||
// 接口失败时回退初始值
|
||||
}
|
||||
}
|
||||
specs.value = toDraft(props.initialSpecs);
|
||||
showSpecs.value = specs.value.length > 0;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
watch(showSpecs, (open) => {
|
||||
if (open) void loadTemplates();
|
||||
});
|
||||
|
||||
async function loadTemplates() {
|
||||
try {
|
||||
templates.value = (await listSpecTemplatesApi()) ?? [];
|
||||
} catch {
|
||||
templates.value = [];
|
||||
}
|
||||
}
|
||||
|
||||
function findTemplateByName(name?: string) {
|
||||
const n = name?.trim();
|
||||
if (!n) return undefined;
|
||||
return templates.value.find((t) => t.name === n);
|
||||
}
|
||||
|
||||
/** 选中模板:写入维名并用模板值覆盖当前行规格值 */
|
||||
function applyTemplateToSpec(spec: DraftSpec, tpl: SpecTemplateVO.Info) {
|
||||
spec.name = tpl.name;
|
||||
const vals = tpl.values ?? [];
|
||||
if (vals.length > 0) {
|
||||
spec.values = vals.map((v, i) => ({
|
||||
_key: nextKey('val'),
|
||||
valueName: v.valueName || '',
|
||||
valueCode: v.valueCode || '',
|
||||
sortOrder: i,
|
||||
}));
|
||||
} else if (spec.values.length === 0) {
|
||||
spec.values = [
|
||||
{
|
||||
_key: nextKey('val'),
|
||||
valueName: '',
|
||||
valueCode: '',
|
||||
sortOrder: 0,
|
||||
},
|
||||
];
|
||||
}
|
||||
touchSpecs();
|
||||
}
|
||||
|
||||
function stripCustomPrefix(v: string) {
|
||||
return v.startsWith('__custom__:') ? v.slice('__custom__:'.length) : v;
|
||||
}
|
||||
|
||||
function onSpecNameSearch(spec: DraftSpec, q: string) {
|
||||
specNameSearch.value = { ...specNameSearch.value, [spec._key]: q };
|
||||
}
|
||||
|
||||
function specNameOptions(spec: DraftSpec) {
|
||||
const q = (specNameSearch.value[spec._key] || '').trim();
|
||||
let list = templates.value.map((t) => ({
|
||||
label: `${t.name}(${t.values?.length ?? 0})`,
|
||||
value: t.name,
|
||||
}));
|
||||
if (q) {
|
||||
const lower = q.toLowerCase();
|
||||
list = list.filter(
|
||||
(o) =>
|
||||
o.value.toLowerCase().includes(lower) ||
|
||||
o.label.toLowerCase().includes(lower),
|
||||
);
|
||||
}
|
||||
if (q && !templates.value.some((t) => t.name === q)) {
|
||||
list = [{ label: `自定义「${q}」`, value: `__custom__:${q}` }, ...list];
|
||||
}
|
||||
if (
|
||||
spec.name &&
|
||||
!list.some(
|
||||
(o) => o.value === spec.name || o.value === `__custom__:${spec.name}`,
|
||||
)
|
||||
) {
|
||||
list.unshift({ label: spec.name, value: spec.name });
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
function onSpecNameChange(spec: DraftSpec, raw?: string | null) {
|
||||
if (raw == null || raw === '') {
|
||||
spec.name = '';
|
||||
markDirty();
|
||||
return;
|
||||
}
|
||||
const name = stripCustomPrefix(String(raw)).trim();
|
||||
const tpl = findTemplateByName(name);
|
||||
if (tpl) {
|
||||
applyTemplateToSpec(spec, tpl);
|
||||
} else {
|
||||
spec.name = name;
|
||||
markDirty();
|
||||
}
|
||||
specNameSearch.value = { ...specNameSearch.value, [spec._key]: '' };
|
||||
}
|
||||
|
||||
function onSpecNameBlur(spec: DraftSpec) {
|
||||
const q = (specNameSearch.value[spec._key] || '').trim();
|
||||
if (!q) return;
|
||||
const tpl = findTemplateByName(q);
|
||||
if (tpl) {
|
||||
applyTemplateToSpec(spec, tpl);
|
||||
} else if (spec.name !== q) {
|
||||
spec.name = q;
|
||||
markDirty();
|
||||
}
|
||||
specNameSearch.value = { ...specNameSearch.value, [spec._key]: '' };
|
||||
}
|
||||
|
||||
function openCreateTemplateForSpec(spec: DraftSpec) {
|
||||
pendingTemplateSpecKey.value = spec._key;
|
||||
const defaultName = (
|
||||
specNameSearch.value[spec._key] ||
|
||||
spec.name ||
|
||||
''
|
||||
).trim();
|
||||
templateFormModalRef.value?.open(false, undefined, { defaultName });
|
||||
}
|
||||
|
||||
async function onTemplateFormSuccess(tpl?: SpecTemplateVO.Info) {
|
||||
await loadTemplates();
|
||||
const key = pendingTemplateSpecKey.value;
|
||||
pendingTemplateSpecKey.value = undefined;
|
||||
if (!tpl || !key) return;
|
||||
const spec = specs.value.find((s) => s._key === key);
|
||||
if (spec) {
|
||||
applyTemplateToSpec(spec, tpl);
|
||||
}
|
||||
}
|
||||
|
||||
function specNameDropdownRender(spec: DraftSpec): DropdownRender {
|
||||
return (opt) =>
|
||||
h('div', {}, [
|
||||
opt?.menuNode,
|
||||
h(
|
||||
'div',
|
||||
{
|
||||
style: {
|
||||
borderTop: '1px solid #f1f5f9',
|
||||
padding: '6px 8px',
|
||||
background: '#f8fafc',
|
||||
},
|
||||
},
|
||||
[
|
||||
h(
|
||||
Button,
|
||||
{
|
||||
type: 'link',
|
||||
size: 'small',
|
||||
block: true,
|
||||
style: {
|
||||
height: 'auto',
|
||||
padding: '4px 8px',
|
||||
textAlign: 'left' as const,
|
||||
},
|
||||
onMousedown: (e: MouseEvent) => e.preventDefault(),
|
||||
onClick: (e: MouseEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
openCreateTemplateForSpec(spec);
|
||||
},
|
||||
},
|
||||
{
|
||||
default: () => [
|
||||
h(PlusIcon, {
|
||||
class: 'mr-1 inline-block h-4 w-4 align-middle',
|
||||
}),
|
||||
h('span', null, '添加规格模板'),
|
||||
],
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
function valueSearchKey(spec: DraftSpec, val: DraftValue) {
|
||||
return `${spec._key}:${val._key}`;
|
||||
}
|
||||
|
||||
function valueNameOptions(spec: DraftSpec, val: DraftValue) {
|
||||
const q = (valueNameSearch.value[valueSearchKey(spec, val)] || '').trim();
|
||||
const tplVals = findTemplateByName(spec.name)?.values ?? [];
|
||||
let list = tplVals.map((v) => ({
|
||||
label: `${v.valueName}(${v.valueCode})`,
|
||||
value: v.valueName!,
|
||||
}));
|
||||
if (q) {
|
||||
const lower = q.toLowerCase();
|
||||
list = list.filter(
|
||||
(o) =>
|
||||
o.value.toLowerCase().includes(lower) ||
|
||||
o.label.toLowerCase().includes(lower),
|
||||
);
|
||||
}
|
||||
if (q && !tplVals.some((v) => v.valueName === q)) {
|
||||
list = [{ label: `自定义「${q}」`, value: `__custom__:${q}` }, ...list];
|
||||
}
|
||||
if (
|
||||
val.valueName &&
|
||||
!list.some(
|
||||
(o) =>
|
||||
o.value === val.valueName ||
|
||||
o.value === `__custom__:${val.valueName}`,
|
||||
)
|
||||
) {
|
||||
list.unshift({ label: val.valueName, value: val.valueName });
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
function onValueNameChange(
|
||||
spec: DraftSpec,
|
||||
val: DraftValue,
|
||||
raw?: string | null,
|
||||
) {
|
||||
if (raw == null || raw === '') {
|
||||
val.valueName = '';
|
||||
touchSpecs();
|
||||
return;
|
||||
}
|
||||
const name = stripCustomPrefix(String(raw)).trim();
|
||||
val.valueName = name;
|
||||
const hit = (findTemplateByName(spec.name)?.values ?? []).find(
|
||||
(v) => v.valueName === name,
|
||||
);
|
||||
if (hit?.valueCode) {
|
||||
val.valueCode = hit.valueCode;
|
||||
}
|
||||
valueNameSearch.value = {
|
||||
...valueNameSearch.value,
|
||||
[valueSearchKey(spec, val)]: '',
|
||||
};
|
||||
touchSpecs();
|
||||
}
|
||||
|
||||
function onValueNameBlur(spec: DraftSpec, val: DraftValue) {
|
||||
const key = valueSearchKey(spec, val);
|
||||
const q = (valueNameSearch.value[key] || '').trim();
|
||||
if (!q) return;
|
||||
const hit = (findTemplateByName(spec.name)?.values ?? []).find(
|
||||
(v) => v.valueName === q,
|
||||
);
|
||||
if (hit) {
|
||||
val.valueName = hit.valueName || q;
|
||||
if (hit.valueCode) val.valueCode = hit.valueCode;
|
||||
} else if (val.valueName !== q) {
|
||||
val.valueName = q;
|
||||
}
|
||||
valueNameSearch.value = { ...valueNameSearch.value, [key]: '' };
|
||||
touchSpecs();
|
||||
}
|
||||
|
||||
function markDirty() {
|
||||
dirty.value = true;
|
||||
}
|
||||
|
||||
function touchSpecs() {
|
||||
specs.value = [...specs.value];
|
||||
markDirty();
|
||||
}
|
||||
|
||||
async function addSpec() {
|
||||
showSpecs.value = true;
|
||||
specs.value.push({
|
||||
_key: nextKey('spec'),
|
||||
name: '',
|
||||
sortOrder: specs.value.length,
|
||||
values: [
|
||||
{
|
||||
_key: nextKey('val'),
|
||||
valueName: '',
|
||||
valueCode: '',
|
||||
sortOrder: 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
markDirty();
|
||||
await nextTick();
|
||||
const el = listScrollRef.value;
|
||||
if (el) {
|
||||
el.scrollTo({ top: el.scrollHeight, behavior: 'smooth' });
|
||||
}
|
||||
}
|
||||
|
||||
function removeSpec(index: number) {
|
||||
specs.value.splice(index, 1);
|
||||
reindexSort();
|
||||
touchSpecs();
|
||||
}
|
||||
|
||||
function moveSpec(index: number, delta: number) {
|
||||
const target = index + delta;
|
||||
if (target < 0 || target >= specs.value.length) return;
|
||||
const list = [...specs.value];
|
||||
const [row] = list.splice(index, 1);
|
||||
if (!row) return;
|
||||
list.splice(target, 0, row);
|
||||
specs.value = list;
|
||||
reindexSort();
|
||||
markDirty();
|
||||
}
|
||||
|
||||
function reindexSort() {
|
||||
specs.value.forEach((s, i) => {
|
||||
s.sortOrder = i;
|
||||
s.values.forEach((v, vi) => {
|
||||
v.sortOrder = vi;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function addValue(spec: DraftSpec) {
|
||||
spec.values.push({
|
||||
_key: nextKey('val'),
|
||||
valueName: '',
|
||||
valueCode: '',
|
||||
sortOrder: spec.values.length,
|
||||
});
|
||||
touchSpecs();
|
||||
}
|
||||
|
||||
function removeValue(spec: DraftSpec, index: number) {
|
||||
spec.values.splice(index, 1);
|
||||
spec.values.forEach((v, i) => {
|
||||
v.sortOrder = i;
|
||||
});
|
||||
touchSpecs();
|
||||
}
|
||||
|
||||
function normalizeValueCode(val: DraftValue) {
|
||||
const next = val.valueCode.trim().toUpperCase();
|
||||
if (next !== val.valueCode) {
|
||||
val.valueCode = next;
|
||||
touchSpecs();
|
||||
}
|
||||
}
|
||||
|
||||
/** 供商品创建/更新一并提交(有 id 更新,无/0 新增;未出现的由后端删除) */
|
||||
function getSpecsPayload(): ProductDTO.SpecItem[] {
|
||||
reindexSort();
|
||||
return specs.value.map((s, si) => ({
|
||||
id: s.id != null && s.id > 0 ? s.id : 0,
|
||||
name: s.name.trim(),
|
||||
sortOrder: s.sortOrder ?? si,
|
||||
values: s.values.map((v, vi) => ({
|
||||
id: v.id != null && v.id > 0 ? v.id : 0,
|
||||
valueName: v.valueName.trim(),
|
||||
valueCode: v.valueCode.trim().toUpperCase(),
|
||||
sortOrder: v.sortOrder ?? vi,
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
function validateDraft(): string | null {
|
||||
for (const s of specs.value) {
|
||||
if (!s.name.trim()) return '规格名称不能为空';
|
||||
if (s.values.length === 0) return `规格「${s.name}」至少需要一个规格值`;
|
||||
const names = new Set<string>();
|
||||
const codes = new Set<string>();
|
||||
for (const v of s.values) {
|
||||
if (!v.valueName.trim()) return `规格「${s.name}」存在空规格值名称`;
|
||||
if (!v.valueCode.trim()) return `规格「${s.name}」存在空规格值编码`;
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(v.valueCode.trim())) {
|
||||
return `规格值编码「${v.valueCode}」仅允许字母数字_-`;
|
||||
}
|
||||
const vn = v.valueName.trim();
|
||||
const vc = v.valueCode.trim().toUpperCase();
|
||||
if (names.has(vn)) return `规格「${s.name}」规格值名称重复`;
|
||||
if (codes.has(vc)) return `规格「${s.name}」规格值编码重复`;
|
||||
names.add(vn);
|
||||
codes.add(vc);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function reloadFromServer() {
|
||||
if (!canPersist.value) return;
|
||||
const list = await listProductSpecsApi(props.productId!);
|
||||
specs.value = toDraft(list);
|
||||
dirty.value = false;
|
||||
showSpecs.value = specs.value.length > 0;
|
||||
}
|
||||
|
||||
async function handleGenerate() {
|
||||
if (!canPersist.value) {
|
||||
message.warning('请先保存商品');
|
||||
return;
|
||||
}
|
||||
if (!props.productCode?.trim()) {
|
||||
message.warning('请先填写商品编码');
|
||||
return;
|
||||
}
|
||||
if (specs.value.length === 0) {
|
||||
message.warning('请先配置规格维并保存商品');
|
||||
return;
|
||||
}
|
||||
if (dirty.value) {
|
||||
message.warning('规格有未提交修改,请先保存商品后再生成 SKU');
|
||||
return;
|
||||
}
|
||||
Modal.confirm({
|
||||
title: '按规格生成 SKU?',
|
||||
content:
|
||||
'将按当前已保存规格做笛卡尔积,仅补缺失组合;编码为「商品编码-规格值编码…」。冲突则整批失败。',
|
||||
okText: '生成',
|
||||
cancelText: '取消',
|
||||
centered: true,
|
||||
onOk: async () => {
|
||||
generating.value = true;
|
||||
try {
|
||||
const created = await generateProductSkusApi(props.productId!, {
|
||||
productCost: 0,
|
||||
shippingCost: 0,
|
||||
otherCost: 0,
|
||||
});
|
||||
message.success(`已生成 ${created.length} 个 SKU`);
|
||||
emit('skusChanged');
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '生成失败');
|
||||
throw e;
|
||||
} finally {
|
||||
generating.value = false;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function openAddSkuPanel() {
|
||||
if (!canPersist.value) {
|
||||
message.warning('请先保存商品');
|
||||
return;
|
||||
}
|
||||
if (dirty.value) {
|
||||
message.warning('规格有未提交修改,请先保存商品');
|
||||
return;
|
||||
}
|
||||
if (savedSpecCount.value === 0) {
|
||||
message.warning('请先保存商品以写入规格维');
|
||||
return;
|
||||
}
|
||||
selectedBySpec.value = {};
|
||||
addSkuCost.value = { productCost: 0, shippingCost: 0, otherCost: 0 };
|
||||
addSkuCode.value = '';
|
||||
addSkuName.value = '';
|
||||
showAddSku.value = true;
|
||||
}
|
||||
|
||||
async function handleCreateFromSpecs() {
|
||||
const ids: number[] = [];
|
||||
for (const s of specs.value) {
|
||||
if (!s.id) continue;
|
||||
const vid = selectedBySpec.value[s._key];
|
||||
if (vid != null) ids.push(vid);
|
||||
}
|
||||
if (ids.length === 0) {
|
||||
message.warning('请至少选择一个规格值(允许缺维)');
|
||||
return;
|
||||
}
|
||||
addSkuLoading.value = true;
|
||||
try {
|
||||
await createSkuFromSpecsApi(props.productId!, {
|
||||
specValueIds: ids,
|
||||
skuCode: addSkuCode.value.trim() || undefined,
|
||||
name: addSkuName.value.trim() || undefined,
|
||||
productCost: addSkuCost.value.productCost,
|
||||
shippingCost: addSkuCost.value.shippingCost,
|
||||
otherCost: addSkuCost.value.otherCost,
|
||||
});
|
||||
message.success('SKU 已创建');
|
||||
showAddSku.value = false;
|
||||
emit('skusChanged');
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '创建失败');
|
||||
return Promise.reject(e);
|
||||
} finally {
|
||||
addSkuLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function valueColumns(spec: DraftSpec) {
|
||||
return [
|
||||
{
|
||||
title: '规格值',
|
||||
dataIndex: 'valueName',
|
||||
key: 'valueName',
|
||||
customRender: ({ record }: { record: DraftValue }) =>
|
||||
h(Select, {
|
||||
value: record.valueName || undefined,
|
||||
showSearch: true,
|
||||
allowClear: true,
|
||||
placeholder: '选择或输入',
|
||||
style: { width: '100%' },
|
||||
options: valueNameOptions(spec, record),
|
||||
filterOption: false,
|
||||
onSearch: (q: string) => {
|
||||
const k = valueSearchKey(spec, record);
|
||||
valueNameSearch.value = { ...valueNameSearch.value, [k]: q };
|
||||
},
|
||||
'onUpdate:value': (v: string | undefined) =>
|
||||
onValueNameChange(spec, record, v),
|
||||
onBlur: () => onValueNameBlur(spec, record),
|
||||
}),
|
||||
},
|
||||
{
|
||||
title: '编码',
|
||||
dataIndex: 'valueCode',
|
||||
key: 'valueCode',
|
||||
width: 160,
|
||||
customRender: ({ record }: { record: DraftValue }) =>
|
||||
h(Input, {
|
||||
value: record.valueCode,
|
||||
placeholder: '如 BLK',
|
||||
'onUpdate:value': (v: string) => {
|
||||
record.valueCode = v;
|
||||
markDirty();
|
||||
},
|
||||
onBlur: () => normalizeValueCode(record),
|
||||
}),
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
key: 'action',
|
||||
width: 56,
|
||||
align: 'center' as const,
|
||||
customRender: ({ index }: { index: number }) =>
|
||||
h(
|
||||
Button,
|
||||
{
|
||||
type: 'text',
|
||||
danger: true,
|
||||
title: '删除',
|
||||
onClick: () => removeValue(spec, index),
|
||||
},
|
||||
{ icon: () => h(TrashIcon, { class: 'h-4 w-4' }) },
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/** 将当前规格行另存为公司模板(需已落库的规格 id) */
|
||||
function handleSaveAsTemplateForSpec(spec: DraftSpec) {
|
||||
if (!canPersist.value) {
|
||||
message.warning('请先保存商品');
|
||||
return;
|
||||
}
|
||||
if (!spec.id || spec.id <= 0) {
|
||||
message.warning('请先保存商品以写入该规格,再另存为模板');
|
||||
return;
|
||||
}
|
||||
if (dirty.value) {
|
||||
message.warning('规格有未提交修改,请先保存商品再另存');
|
||||
return;
|
||||
}
|
||||
let nameOverride = '';
|
||||
Modal.confirm({
|
||||
title: '另存为规格模板',
|
||||
content: h('div', { class: 'space-y-3' }, [
|
||||
h(
|
||||
'p',
|
||||
{ class: 'mb-0 text-sm text-slate-500' },
|
||||
`将规格「${spec.name}」拷贝为公司模板(一个模板=一个维)`,
|
||||
),
|
||||
h(Input, {
|
||||
placeholder: '模板名称(可选,默认用规格名)',
|
||||
defaultValue: spec.name,
|
||||
onChange: (e: any) => {
|
||||
nameOverride = e?.target?.value ?? '';
|
||||
},
|
||||
}),
|
||||
]),
|
||||
okText: '保存',
|
||||
cancelText: '取消',
|
||||
centered: true,
|
||||
onOk: async () => {
|
||||
try {
|
||||
await saveProductAsSpecTemplateApi(props.productId!, {
|
||||
productSpecId: spec.id!,
|
||||
name: nameOverride.trim() || undefined,
|
||||
});
|
||||
message.success('已另存为模板');
|
||||
await loadTemplates();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '另存失败');
|
||||
return Promise.reject(e);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
getSpecsPayload,
|
||||
validateDraft,
|
||||
reloadFromServer,
|
||||
resetFromProps,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex min-h-0 flex-col gap-3 overflow-hidden">
|
||||
<div class="flex shrink-0 items-center justify-between gap-2">
|
||||
<div class="flex min-w-0 items-center gap-2">
|
||||
<span class="shrink-0 text-sm text-foreground/80">商品规格</span>
|
||||
<Space>
|
||||
<Button type="dashed" @click="showSpecs = !showSpecs">
|
||||
<template #icon>
|
||||
<component :is="showSpecs ? UpIcon : DownIcon" class="h-4 w-4" />
|
||||
</template>
|
||||
{{ showSpecs ? '收起规格' : '展开规格' }}
|
||||
</Button>
|
||||
<span
|
||||
v-if="specs.length > 0"
|
||||
class="text-xs text-slate-400"
|
||||
>
|
||||
{{ specs.length }} 维
|
||||
<template v-if="dirty"> · 将随商品保存</template>
|
||||
</span>
|
||||
</Space>
|
||||
</div>
|
||||
<Space v-if="showSpecs" wrap>
|
||||
<Button
|
||||
:loading="generating"
|
||||
:disabled="!canPersist"
|
||||
@click="handleGenerate"
|
||||
>
|
||||
生成全部 SKU
|
||||
</Button>
|
||||
<Button :disabled="!canPersist" @click="openAddSkuPanel">
|
||||
按规格添加
|
||||
</Button>
|
||||
<Button type="primary" @click="addSpec">
|
||||
<template #icon>
|
||||
<PlusIcon class="h-4 w-4" />
|
||||
</template>
|
||||
添加规格
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
<p
|
||||
v-if="showSpecs"
|
||||
class="mb-0 shrink-0 text-xs text-slate-400"
|
||||
>
|
||||
规格名从选择器选模板即可套用常用值;也可自定义。规格随商品一并保存(有 id
|
||||
更新,无 id 新增,删行即删除)。
|
||||
</p>
|
||||
|
||||
<div
|
||||
v-if="showSpecs"
|
||||
ref="listScrollRef"
|
||||
class="max-h-[32vh] overflow-y-auto rounded-lg border border-gray-200 bg-white p-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_14%)]"
|
||||
>
|
||||
<div
|
||||
v-if="specs.length === 0"
|
||||
class="py-4 text-center text-gray-400"
|
||||
>
|
||||
暂无规格,点击「添加规格」;规格名可从模板选择或自定义输入
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-for="(spec, si) in specs"
|
||||
:key="spec._key"
|
||||
class="mb-4 border-b border-slate-100 pb-4 last:mb-0 last:border-b-0 last:pb-0 dark:border-[hsl(240deg_3.7%_22%)]"
|
||||
>
|
||||
<div class="mb-2 flex flex-wrap items-center gap-2">
|
||||
<span class="w-14 shrink-0 text-xs text-slate-400">规格名</span>
|
||||
<Select
|
||||
:value="spec.name || undefined"
|
||||
class="!w-52"
|
||||
show-search
|
||||
allow-clear
|
||||
placeholder="选择或输入规格"
|
||||
:options="specNameOptions(spec)"
|
||||
:filter-option="false"
|
||||
:dropdown-render="specNameDropdownRender(spec)"
|
||||
@search="(q: string) => onSpecNameSearch(spec, q)"
|
||||
@change="(v: any) => onSpecNameChange(spec, v as string)"
|
||||
@blur="onSpecNameBlur(spec)"
|
||||
/>
|
||||
<Space :size="4">
|
||||
<Button
|
||||
type="text"
|
||||
title="上移"
|
||||
:disabled="si === 0"
|
||||
@click="moveSpec(si, -1)"
|
||||
>
|
||||
<template #icon>
|
||||
<ArrowUpIcon class="h-4 w-4" />
|
||||
</template>
|
||||
</Button>
|
||||
<Button
|
||||
type="text"
|
||||
title="下移"
|
||||
:disabled="si === specs.length - 1"
|
||||
@click="moveSpec(si, 1)"
|
||||
>
|
||||
<template #icon>
|
||||
<ArrowDownIcon class="h-4 w-4" />
|
||||
</template>
|
||||
</Button>
|
||||
<Button type="link" @click="addValue(spec)">
|
||||
<template #icon>
|
||||
<PlusIcon class="h-4 w-4" />
|
||||
</template>
|
||||
规格值
|
||||
</Button>
|
||||
<Button
|
||||
type="link"
|
||||
title="另存为模板"
|
||||
:disabled="!canPersist || !spec.id"
|
||||
@click="handleSaveAsTemplateForSpec(spec)"
|
||||
>
|
||||
另存为模板
|
||||
</Button>
|
||||
<Button
|
||||
type="text"
|
||||
danger
|
||||
title="删除规格"
|
||||
@click="removeSpec(si)"
|
||||
>
|
||||
<template #icon>
|
||||
<TrashIcon class="h-4 w-4" />
|
||||
</template>
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
<Table
|
||||
:columns="valueColumns(spec)"
|
||||
:data-source="spec.values"
|
||||
:pagination="false"
|
||||
:row-key="(r: DraftValue) => r._key"
|
||||
>
|
||||
<template #emptyText>
|
||||
<span class="text-xs text-slate-400">暂无规格值</span>
|
||||
</template>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
v-model:open="showAddSku"
|
||||
title="按规格值添加 SKU(可缺维)"
|
||||
:confirm-loading="addSkuLoading"
|
||||
ok-text="创建"
|
||||
destroy-on-close
|
||||
@ok="handleCreateFromSpecs"
|
||||
>
|
||||
<div class="space-y-3 py-2">
|
||||
<div
|
||||
v-for="spec in specs.filter((s) => s.id)"
|
||||
:key="spec._key"
|
||||
class="flex items-center gap-2"
|
||||
>
|
||||
<span class="w-20 shrink-0 text-sm">{{ spec.name }}</span>
|
||||
<Select
|
||||
v-model:value="selectedBySpec[spec._key]"
|
||||
class="flex-1"
|
||||
allow-clear
|
||||
placeholder="不选则缺该维"
|
||||
:options="
|
||||
spec.values
|
||||
.filter((v) => v.id)
|
||||
.map((v) => ({
|
||||
label: `${v.valueName} (${v.valueCode})`,
|
||||
value: v.id!,
|
||||
}))
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div class="mb-1 text-xs text-slate-500">
|
||||
SKU 编码(可选,空则按规则生成)
|
||||
</div>
|
||||
<Input
|
||||
v-model:value="addSkuCode"
|
||||
placeholder="自定义编码,如外部系统编码"
|
||||
allow-clear
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div class="mb-1 text-xs text-slate-500">SKU 名称(可选)</div>
|
||||
<Input
|
||||
v-model:value="addSkuName"
|
||||
placeholder="空则用规格值名拼接"
|
||||
allow-clear
|
||||
/>
|
||||
</div>
|
||||
<div class="grid grid-cols-3 gap-2">
|
||||
<div>
|
||||
<div class="mb-1 text-xs text-slate-500">商品成本</div>
|
||||
<InputNumber
|
||||
v-model:value="addSkuCost.productCost"
|
||||
class="w-full"
|
||||
:min="0"
|
||||
:precision="2"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div class="mb-1 text-xs text-slate-500">运费成本</div>
|
||||
<InputNumber
|
||||
v-model:value="addSkuCost.shippingCost"
|
||||
class="w-full"
|
||||
:min="0"
|
||||
:precision="2"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div class="mb-1 text-xs text-slate-500">其他成本</div>
|
||||
<InputNumber
|
||||
v-model:value="addSkuCost.otherCost"
|
||||
class="w-full"
|
||||
:min="0"
|
||||
:precision="2"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
<SpecTemplateFormModal
|
||||
ref="templateFormModalRef"
|
||||
@success="onTemplateFormSuccess"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
<script lang="ts" setup>
|
||||
/**
|
||||
* 规格模板创建/编辑:一个模板=一个规格维 + 规格值列表。
|
||||
*/
|
||||
import type { SpecTemplateDTO, SpecTemplateVO } from '#/api/ec/product/spec-template';
|
||||
|
||||
import { h, ref } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import {
|
||||
Button,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
Table,
|
||||
message,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
import {
|
||||
createSpecTemplateApi,
|
||||
getSpecTemplateApi,
|
||||
updateSpecTemplateApi,
|
||||
} from '#/api/ec/product/spec-template';
|
||||
|
||||
defineOptions({ name: 'SpecTemplateFormModal' });
|
||||
|
||||
const emit = defineEmits<{
|
||||
success: [template?: SpecTemplateVO.Info];
|
||||
}>();
|
||||
|
||||
const PlusIcon = createIconifyIcon('lucide:plus');
|
||||
const TrashIcon = createIconifyIcon('lucide:trash-2');
|
||||
|
||||
type DraftValue = {
|
||||
_key: string;
|
||||
id?: number;
|
||||
valueName: string;
|
||||
valueCode: string;
|
||||
sortOrder: number;
|
||||
};
|
||||
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
title: '规格模板',
|
||||
class: 'w-[640px]',
|
||||
draggable: true,
|
||||
contentClass: 'max-h-[70vh] overflow-y-auto',
|
||||
onConfirm: handleSubmit,
|
||||
});
|
||||
|
||||
const formRef = ref();
|
||||
const isEdit = ref(false);
|
||||
const templateId = ref<number>();
|
||||
const formData = ref({ name: '', remark: '', sortOrder: 0 });
|
||||
const values = ref<DraftValue[]>([]);
|
||||
|
||||
let keySeq = 0;
|
||||
function nextKey() {
|
||||
return `val-${++keySeq}`;
|
||||
}
|
||||
|
||||
function toDraft(list?: SpecTemplateVO.Value[]): DraftValue[] {
|
||||
return (list ?? []).map((v, i) => ({
|
||||
_key: nextKey(),
|
||||
id: v.id,
|
||||
valueName: v.valueName || '',
|
||||
valueCode: v.valueCode || '',
|
||||
sortOrder: v.sortOrder ?? i,
|
||||
}));
|
||||
}
|
||||
|
||||
function addValue() {
|
||||
values.value.push({
|
||||
_key: nextKey(),
|
||||
valueName: '',
|
||||
valueCode: '',
|
||||
sortOrder: values.value.length,
|
||||
});
|
||||
}
|
||||
|
||||
function removeValue(index: number) {
|
||||
values.value.splice(index, 1);
|
||||
}
|
||||
|
||||
function buildValuesPayload(): SpecTemplateDTO.ValueItem[] {
|
||||
return values.value.map((v, i) => ({
|
||||
id: v.id,
|
||||
valueName: v.valueName.trim(),
|
||||
valueCode: v.valueCode.trim().toUpperCase(),
|
||||
sortOrder: i,
|
||||
}));
|
||||
}
|
||||
|
||||
function validate(): string | null {
|
||||
if (!formData.value.name.trim()) return '请输入规格名称';
|
||||
if (values.value.length === 0) return '至少添加一个规格值';
|
||||
const names = new Set<string>();
|
||||
const codes = new Set<string>();
|
||||
for (const v of values.value) {
|
||||
if (!v.valueName.trim() || !v.valueCode.trim()) {
|
||||
return '规格值名称与编码不能为空';
|
||||
}
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(v.valueCode.trim())) {
|
||||
return `编码「${v.valueCode}」仅允许字母数字_-`;
|
||||
}
|
||||
const vn = v.valueName.trim();
|
||||
const vc = v.valueCode.trim().toUpperCase();
|
||||
if (names.has(vn) || codes.has(vc)) return '规格值名称或编码重复';
|
||||
names.add(vn);
|
||||
codes.add(vc);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function open(
|
||||
edit: boolean,
|
||||
record?: SpecTemplateVO.Info,
|
||||
options?: { defaultName?: string },
|
||||
) {
|
||||
isEdit.value = edit;
|
||||
templateId.value = record?.id;
|
||||
modalApi.setState({
|
||||
title: edit ? '编辑规格模板' : '新建规格模板',
|
||||
});
|
||||
if (edit && record?.id) {
|
||||
const detail = await getSpecTemplateApi(record.id);
|
||||
formData.value = {
|
||||
name: detail.name || '',
|
||||
remark: detail.remark || '',
|
||||
sortOrder: detail.sortOrder ?? 0,
|
||||
};
|
||||
values.value = toDraft(detail.values);
|
||||
} else {
|
||||
formData.value = {
|
||||
name: options?.defaultName?.trim() || '',
|
||||
remark: '',
|
||||
sortOrder: 0,
|
||||
};
|
||||
values.value = [
|
||||
{ _key: nextKey(), valueName: '', valueCode: '', sortOrder: 0 },
|
||||
];
|
||||
}
|
||||
modalApi.open();
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
await formRef.value?.validate?.();
|
||||
const err = validate();
|
||||
if (err) {
|
||||
message.error(err);
|
||||
return;
|
||||
}
|
||||
modalApi.setState({ confirmLoading: true });
|
||||
try {
|
||||
const payload = {
|
||||
name: formData.value.name.trim(),
|
||||
remark: formData.value.remark?.trim() || undefined,
|
||||
sortOrder: formData.value.sortOrder,
|
||||
values: buildValuesPayload(),
|
||||
};
|
||||
let saved: SpecTemplateVO.Info;
|
||||
if (isEdit.value && templateId.value != null) {
|
||||
saved = await updateSpecTemplateApi(templateId.value, payload);
|
||||
message.success('更新成功');
|
||||
} else {
|
||||
saved = await createSpecTemplateApi(payload);
|
||||
message.success('创建成功');
|
||||
}
|
||||
modalApi.close();
|
||||
emit('success', saved);
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '保存失败');
|
||||
} finally {
|
||||
modalApi.setState({ confirmLoading: false });
|
||||
}
|
||||
}
|
||||
|
||||
const valueColumns = [
|
||||
{
|
||||
title: '规格值',
|
||||
customRender: ({ record }: { record: DraftValue }) =>
|
||||
h(Input, {
|
||||
value: record.valueName,
|
||||
placeholder: '如黑色',
|
||||
'onUpdate:value': (v: string) => {
|
||||
record.valueName = v;
|
||||
},
|
||||
}),
|
||||
},
|
||||
{
|
||||
title: '编码',
|
||||
width: 160,
|
||||
customRender: ({ record }: { record: DraftValue }) =>
|
||||
h(Input, {
|
||||
value: record.valueCode,
|
||||
placeholder: '如 BLK',
|
||||
'onUpdate:value': (v: string) => {
|
||||
record.valueCode = v;
|
||||
},
|
||||
onBlur: () => {
|
||||
record.valueCode = record.valueCode.trim().toUpperCase();
|
||||
},
|
||||
}),
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
width: 56,
|
||||
align: 'center' as const,
|
||||
customRender: ({ index }: { index: number }) =>
|
||||
h(
|
||||
Button,
|
||||
{
|
||||
type: 'text',
|
||||
danger: true,
|
||||
onClick: () => removeValue(index),
|
||||
},
|
||||
{ icon: () => h(TrashIcon, { class: 'h-4 w-4' }) },
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
defineExpose({ open });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Modal>
|
||||
<Form ref="formRef" :model="formData" layout="vertical">
|
||||
<Form.Item
|
||||
label="规格名称"
|
||||
name="name"
|
||||
:rules="[{ required: true, message: '请输入规格名称,如颜色' }]"
|
||||
>
|
||||
<Input v-model:value="formData.name" placeholder="如颜色、尺码" />
|
||||
</Form.Item>
|
||||
<Form.Item label="备注" name="remark">
|
||||
<Input v-model:value="formData.remark" placeholder="可选" />
|
||||
</Form.Item>
|
||||
<Form.Item label="排序" name="sortOrder">
|
||||
<InputNumber v-model:value="formData.sortOrder" :min="0" class="w-32" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
|
||||
<div class="mb-2 flex items-center justify-between">
|
||||
<span class="text-sm text-foreground/80">规格值</span>
|
||||
<Button type="primary" @click="addValue">
|
||||
<template #icon>
|
||||
<PlusIcon class="h-4 w-4" />
|
||||
</template>
|
||||
添加规格值
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Table
|
||||
:columns="valueColumns"
|
||||
:data-source="values"
|
||||
:pagination="false"
|
||||
:row-key="(r: DraftValue) => r._key"
|
||||
/>
|
||||
</Modal>
|
||||
</template>
|
||||
@@ -0,0 +1,187 @@
|
||||
<script lang="ts" setup>
|
||||
/**
|
||||
* 规格模板列表:公司级单维模板(建公司或空列表时自动种子 款式/颜色/尺码/容量)。
|
||||
*/
|
||||
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||
import type { SpecTemplateVO } from '#/api/ec/product/spec-template';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import { Button, Popconfirm, Space, message } from 'ant-design-vue';
|
||||
|
||||
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||
import {
|
||||
deleteSpecTemplateApi,
|
||||
listSpecTemplatesApi,
|
||||
} from '#/api/ec/product/spec-template';
|
||||
import { PermissionGate } from '#/components/permission';
|
||||
import {
|
||||
syncVxeGridColumns,
|
||||
useActionColumnVisible,
|
||||
} from '#/composables/use-vxe-action-column';
|
||||
|
||||
import SpecTemplateFormModal from './components/SpecTemplateFormModal.vue';
|
||||
|
||||
defineOptions({ name: 'SpecTemplate' });
|
||||
|
||||
const PlusIcon = createIconifyIcon('lucide:plus');
|
||||
|
||||
const loading = ref(false);
|
||||
const formModalRef = ref<InstanceType<typeof SpecTemplateFormModal> | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const actionCodes = [
|
||||
'ec:product:spec-template:create',
|
||||
'ec:product:spec-template:update',
|
||||
'ec:product:spec-template:delete',
|
||||
];
|
||||
const showActionColumn = useActionColumnVisible(actionCodes);
|
||||
|
||||
function summarizeValues(row: SpecTemplateVO.Info) {
|
||||
const vals = row.values ?? [];
|
||||
if (vals.length === 0) return '-';
|
||||
return vals.map((v) => `${v.valueName}/${v.valueCode}`).join('、');
|
||||
}
|
||||
|
||||
const baseColumns: VxeGridProps<SpecTemplateVO.Info>['columns'] = [
|
||||
{ type: 'seq', width: 64, title: '序号' },
|
||||
{ field: 'name', title: '规格名称', minWidth: 120 },
|
||||
{
|
||||
field: 'values',
|
||||
title: '规格值',
|
||||
minWidth: 280,
|
||||
showOverflow: 'tooltip',
|
||||
formatter: ({ row }) => summarizeValues(row),
|
||||
},
|
||||
{
|
||||
field: 'sortOrder',
|
||||
title: '排序',
|
||||
width: 80,
|
||||
},
|
||||
{
|
||||
field: 'updateTime',
|
||||
title: '更新时间',
|
||||
minWidth: 160,
|
||||
},
|
||||
];
|
||||
|
||||
const actionColumn: NonNullable<
|
||||
VxeGridProps<SpecTemplateVO.Info>['columns']
|
||||
>[number] = {
|
||||
title: '操作',
|
||||
width: 160,
|
||||
fixed: 'right',
|
||||
slots: { default: 'action' },
|
||||
};
|
||||
|
||||
const tableColumns = computed(() =>
|
||||
showActionColumn.value
|
||||
? [...(baseColumns ?? []), actionColumn]
|
||||
: (baseColumns ?? []),
|
||||
);
|
||||
|
||||
const gridOptions: VxeGridProps<SpecTemplateVO.Info> = {
|
||||
columns: tableColumns.value,
|
||||
height: 'auto',
|
||||
border: true,
|
||||
stripe: true,
|
||||
rowConfig: { isHover: true },
|
||||
showOverflow: true,
|
||||
toolbarConfig: {
|
||||
custom: true,
|
||||
refresh: true,
|
||||
zoom: true,
|
||||
},
|
||||
data: [],
|
||||
pagerConfig: { enabled: false },
|
||||
proxyConfig: {
|
||||
ajax: {
|
||||
query: async () => {
|
||||
try {
|
||||
loading.value = true;
|
||||
const list = await listSpecTemplatesApi();
|
||||
return { items: list ?? [], total: list?.length ?? 0 };
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
message.error('加载规格模板失败');
|
||||
return { items: [], total: 0 };
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const [Grid, gridApi] = useVbenVxeGrid({
|
||||
gridOptions,
|
||||
showSearchForm: false,
|
||||
tableTitle: '规格模板',
|
||||
});
|
||||
syncVxeGridColumns(gridApi, tableColumns);
|
||||
|
||||
function refresh() {
|
||||
gridApi.reload();
|
||||
}
|
||||
|
||||
function handleAdd() {
|
||||
formModalRef.value?.open(false);
|
||||
}
|
||||
|
||||
function handleEdit(row: SpecTemplateVO.Info) {
|
||||
formModalRef.value?.open(true, row);
|
||||
}
|
||||
|
||||
async function handleDelete(row: SpecTemplateVO.Info) {
|
||||
try {
|
||||
await deleteSpecTemplateApi(row.id);
|
||||
message.success('删除成功');
|
||||
refresh();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '删除失败');
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page title="规格模板" auto-content-height>
|
||||
<template #description>
|
||||
<div class="mt-2 text-foreground/80">
|
||||
每个模板对应一个规格维(如颜色)及其常用值。新建公司会预置款式/颜色/尺码/容量;建品时可套用。
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<Grid :loading="loading">
|
||||
<template #toolbar-tools>
|
||||
<PermissionGate code="ec:product:spec-template:create">
|
||||
<Button type="primary" @click="handleAdd">
|
||||
<PlusIcon class="mr-1 h-4 w-4" />
|
||||
新建模板
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
</template>
|
||||
|
||||
<template
|
||||
v-if="showActionColumn"
|
||||
#action="{ row }: { row: SpecTemplateVO.Info }"
|
||||
>
|
||||
<Space>
|
||||
<PermissionGate code="ec:product:spec-template:update">
|
||||
<Button size="small" @click="handleEdit(row)">编辑</Button>
|
||||
</PermissionGate>
|
||||
<PermissionGate code="ec:product:spec-template:delete">
|
||||
<Popconfirm title="确定删除该模板?" @confirm="handleDelete(row)">
|
||||
<Button size="small" danger>删除</Button>
|
||||
</Popconfirm>
|
||||
</PermissionGate>
|
||||
</Space>
|
||||
</template>
|
||||
</Grid>
|
||||
|
||||
<SpecTemplateFormModal ref="formModalRef" @success="refresh" />
|
||||
</Page>
|
||||
</template>
|
||||
Reference in New Issue
Block a user