From 3138e69c305a7846ebaa52b1e78137a4e49cf105 Mon Sep 17 00:00:00 2001 From: ah-max150 Date: Sun, 6 Sep 2026 23:35:54 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=8A=A0=E5=85=A5=E8=A7=84=E6=A0=BC?= =?UTF-8?q?=E4=BD=93=E7=B3=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ecom-dmb-backend/docs/商品规格设计建议.md | 1693 +++++++++++++++++ .../sql/design/ec/ec_product_design.sql | 6 +- .../sql/design/ec/ec_product_spec_design.sql | 52 + .../sql/design/ec/ec_spec_template_design.sql | 34 + .../V20260910__ec_product_code_not_null.sql | 23 + .../migration/V20260910b__ec_product_spec.sql | 55 + .../V20260910c__ec_spec_template.sql | 67 + ...d__ec_spec_template_seed_all_companies.sql | 47 + .../product/model/dto/CreateProductDTO.java | 6 + .../product/model/dto/UpdateProductDTO.java | 10 +- .../ec/product/model/vo/ProductVO.java | 5 + .../service/impl/ProductServiceImpl.java | 40 +- .../ec/product/sku/model/po/ProductSkuPO.java | 4 + .../ec/product/sku/model/vo/ProductSkuVO.java | 7 + .../controller/ProductSpecController.java | 99 + .../product/spec/domain/ProductSpecCodes.java | 87 + .../mapper/ProductSkuSpecValueMapper.java | 9 + .../spec/mapper/ProductSpecMapper.java | 9 + .../spec/mapper/ProductSpecValueMapper.java | 9 + .../spec/model/dto/BindSkuSpecsDTO.java | 16 + .../spec/model/dto/CreateSkuFromSpecsDTO.java | 34 + .../model/dto/GenerateProductSkusDTO.java | 19 + .../model/dto/ReplaceProductSpecsDTO.java | 45 + .../spec/model/po/ProductSkuSpecValuePO.java | 23 + .../product/spec/model/po/ProductSpecPO.java | 43 + .../spec/model/po/ProductSpecValuePO.java | 49 + .../product/spec/model/vo/ProductSpecVO.java | 15 + .../spec/model/vo/ProductSpecValueVO.java | 14 + .../spec/service/ProductSpecService.java | 36 + .../service/impl/ProductSpecServiceImpl.java | 604 ++++++ .../controller/SpecTemplateController.java | 73 + .../template/mapper/SpecTemplateMapper.java | 9 + .../mapper/SpecTemplateValueMapper.java | 9 + .../model/dto/ApplySpecTemplateDTO.java | 17 + .../model/dto/CreateSpecTemplateDTO.java | 22 + .../model/dto/ReplaceSpecTemplateDTO.java | 32 + .../model/dto/SaveProductAsTemplateDTO.java | 15 + .../model/dto/UpdateSpecTemplateDTO.java | 20 + .../template/model/po/SpecTemplatePO.java | 43 + .../model/po/SpecTemplateValuePO.java | 37 + .../template/model/vo/SpecTemplateVO.java | 21 + .../model/vo/SpecTemplateValueVO.java | 13 + .../template/service/SpecTemplateService.java | 42 + .../service/impl/SpecTemplateServiceImpl.java | 551 ++++++ .../service/impl/CompanyServiceImpl.java | 9 +- .../src/api/ec/product/sku/types/types.vo.ts | 4 + .../src/api/ec/product/spec-template/index.ts | 127 ++ .../web-antd/src/api/ec/product/spec/index.ts | 119 ++ .../src/api/ec/product/types/types.dto.ts | 21 + .../src/api/ec/product/types/types.vo.ts | 6 + .../list/components/ProductDetailModal.vue | 29 + .../list/components/ProductFormModal.vue | 211 +- .../components/ProductSkuBindSpecModal.vue | 176 ++ .../list/components/ProductSpecEditor.vue | 978 ++++++++++ .../components/SpecTemplateFormModal.vue | 261 +++ .../views/ec/product/spec-template/index.vue | 187 ++ 56 files changed, 6149 insertions(+), 43 deletions(-) create mode 100644 ecom-dmb-backend/docs/商品规格设计建议.md create mode 100644 ecom-dmb-backend/sql/design/ec/ec_product_spec_design.sql create mode 100644 ecom-dmb-backend/sql/design/ec/ec_spec_template_design.sql create mode 100644 ecom-dmb-backend/sql/migration/V20260910__ec_product_code_not_null.sql create mode 100644 ecom-dmb-backend/sql/migration/V20260910b__ec_product_spec.sql create mode 100644 ecom-dmb-backend/sql/migration/V20260910c__ec_spec_template.sql create mode 100644 ecom-dmb-backend/sql/migration/V20260910d__ec_spec_template_seed_all_companies.sql create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/controller/ProductSpecController.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/domain/ProductSpecCodes.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/mapper/ProductSkuSpecValueMapper.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/mapper/ProductSpecMapper.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/mapper/ProductSpecValueMapper.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/dto/BindSkuSpecsDTO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/dto/CreateSkuFromSpecsDTO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/dto/GenerateProductSkusDTO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/dto/ReplaceProductSpecsDTO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/po/ProductSkuSpecValuePO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/po/ProductSpecPO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/po/ProductSpecValuePO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/vo/ProductSpecVO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/vo/ProductSpecValueVO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/service/ProductSpecService.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/service/impl/ProductSpecServiceImpl.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/controller/SpecTemplateController.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/mapper/SpecTemplateMapper.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/mapper/SpecTemplateValueMapper.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/ApplySpecTemplateDTO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/CreateSpecTemplateDTO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/ReplaceSpecTemplateDTO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/SaveProductAsTemplateDTO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/UpdateSpecTemplateDTO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/po/SpecTemplatePO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/po/SpecTemplateValuePO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/vo/SpecTemplateVO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/vo/SpecTemplateValueVO.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/service/SpecTemplateService.java create mode 100644 ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/service/impl/SpecTemplateServiceImpl.java create mode 100644 ecom-dmb-frontend/apps/web-antd/src/api/ec/product/spec-template/index.ts create mode 100644 ecom-dmb-frontend/apps/web-antd/src/api/ec/product/spec/index.ts create mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductSkuBindSpecModal.vue create mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductSpecEditor.vue create mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/ec/product/spec-template/components/SpecTemplateFormModal.vue create mode 100644 ecom-dmb-frontend/apps/web-antd/src/views/ec/product/spec-template/index.vue diff --git a/ecom-dmb-backend/docs/商品规格设计建议.md b/ecom-dmb-backend/docs/商品规格设计建议.md new file mode 100644 index 00000000..da8bc8aa --- /dev/null +++ b/ecom-dmb-backend/docs/商品规格设计建议.md @@ -0,0 +1,1693 @@ +# ERP 商品规格与 SKU 数据模型设计 + +## 1. 目标 + +为现有 ERP 系统增加完整的商品规格(Spec)和 SKU 管理能力。 + +核心目标: + +1. 一个商品(Product/SPU)可以拥有多个规格。 +2. 一个规格可以拥有多个规格值。 +3. 一个 SKU 是一个商品下若干规格值的组合。 +4. SKU 必须能够明确知道自己的规格组合。 +5. 同一个商品下,相同规格组合只能存在一个 SKU。 +6. 支持无规格商品。 +7. SKU 作为库存、成本、销售价格、条码等业务数据的最小商品单位。 +8. 不将平台商品 SKU 与内部 ERP SKU 强耦合,为后续多平台 OMS 对接保留扩展空间。 +9. 第一阶段不引入复杂的全局规格模板系统,规格直接属于商品。 + +--- + +## 1.1 落地拍板(2026-09-06) + +| # | 议题 | 结论 | +|---|------|------| +| 1 | 遗留无结构多 SKU | **永久允许**。`spec_combination_key` 为空表示未结构化;导入 / 渠道自动建品继续写此类 SKU。 | +| 2 | 结构化商品建 SKU 是否必须维齐全 | **允许缺维**(例如只选颜色、不选尺码)。 | +| 3 | PDD 自动建品 / 导入 | **一律 legacy 扁平 SKU**,不解析平台 spec 字符串进规格维。 | +| 4 | 生成 SKU 时 `sku_code` 冲突 | **整批事务失败**。 | +| — | 商品编码 | **`product_code` 非空**;存量空值用迁移脚本补齐(如 `P{id}`)后再加 NOT NULL。 | +| — | SKU 编码生成 | `product_code-value_code…`(按规格 sort);规格组合**可选**生成。 | +| — | 无规格默认 SKU 编码 | 与商品编码相同(`product_code`);若已占用则失败提示手工处理。 | +| — | 已有 SKU 绑规格 | **允许**。写 `spec_combination_key` + 关系表,**不改 `sku_code`**;`specValueIds` 空=解绑回 legacy。 | + +### 规格模板拍板(2026-09-06) + +| # | 议题 | 结论 | +|---|------|------| +| 1 | 归属 | **仅公司级**;建公司时种子默认维(列表为空时也会兜底种子) | +| 2 | 套用方式 | **单维模板套入**,可勾选该维下哪些值 | +| 3 | 套用后关系 | **拷贝断开**;改模板不影响已有商品 | +| 4 | 合并规则 | **同名维合并**,只追加尚不存在的值;名称/编码冲突则**整次失败** | +| 5 | 是否生成 SKU | **否**;套用只写规格维/值 | +| 6 | 权限 | **独立**:`ec:product:spec-template:read/create/update/delete` | +| — | 表结构 | **两表**:`ec_spec_template`(一模板=一维)+ `ec_spec_template_value` | +| — | 默认种子 | 款式 / 颜色 / 尺码 / 容量(含常用值) | + +--- + +## 1.2 本迭代已落地(后端骨架) + +* 迁移 `V20260910`:空 `product_code` 补 `P{id}` 后 NOT NULL +* 迁移 `V20260910b`:`ec_product_spec` / `ec_product_spec_value` / `ec_product_sku_spec_value` + `spec_combination_key` +* 迁移 `V20260910c`:两表规格模板 + 权限/菜单;建公司种子默认维 +* API:商品规格 CRUD/生成/绑定;规格模板 CRUD/套用/另存 +* 创建/更新商品:`productCode` 校验必填 +* 前端:商品表单规格编辑器;规格模板页;从模板套用 + +--- + +# 2. 核心概念 + +## 2.1 Product / SPU + +`product` 表示一个商品的抽象定义。 + +例如: + +> Nike 男士短袖 T 恤 + +这是一个商品 SPU。 + +它可以拥有: + +* 颜色 +* 尺码 + +--- + +## 2.2 Spec / 商品规格 + +例如: + +```text +颜色 +尺码 +``` + +规格属于商品。 + +一个商品可以有多个规格。 + +--- + +## 2.3 Spec Value / 规格值 + +例如: + +```text +颜色 +├── 黑色 +├── 白色 +└── 红色 + +尺码 +├── S +├── M +└── L +``` + +规格值属于规格。 + +--- + +## 2.4 SKU + +SKU 是一个商品具体的规格组合。 + +例如: + +```text +黑色 + M +黑色 + L +白色 + M +白色 + L +``` + +每一个组合对应一个独立 SKU。 + +SKU 是库存、成本、条码等业务数据的最小单位。 + +--- + +# 3. 数据模型 + +整体关系: + +```text +product + │ + ├── product_spec + │ │ + │ └── product_spec_value + │ + └── product_sku + │ + └── product_sku_spec_value +``` + +完整关系: + +```text +Product + │ + │ 1:N + ▼ +ProductSpec + │ + │ 1:N + ▼ +ProductSpecValue + + +Product + │ + │ 1:N + ▼ +ProductSku + │ + │ N:M + ▼ +ProductSpecValue +``` + +--- + +# 4. 数据库表 + +以下以 MySQL 为例。 + +表名前缀按照现有项目规范调整。 + +--- + +## 4.1 商品表 + +已有商品表: + +```text +ec_product +``` + +不要求为了规格功能重构现有商品表。 + +商品规格通过 `product_id` 关联。 + +现有字段至少应该能够提供: + +```text +id +name +... +``` + +如果当前项目已经存在商品表,应优先复用现有表。 + +--- + +# 5. 商品规格表 + +表: + +```text +ec_product_spec +``` + +建议结构: + +```sql +CREATE TABLE ec_product_spec ( + id BIGINT UNSIGNED NOT NULL COMMENT '规格ID', + product_id BIGINT UNSIGNED NOT NULL COMMENT '商品ID', + name VARCHAR(100) NOT NULL COMMENT '规格名称,例如颜色、尺码', + sort INT NOT NULL DEFAULT 0 COMMENT '排序值', + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + + PRIMARY KEY (id), + UNIQUE KEY uk_product_spec_name (product_id, name), + KEY idx_product_id (product_id) +) COMMENT='商品规格'; +``` + +## 字段说明 + +### product_id + +所属商品。 + +例如: + +```text +product_id = 100 +``` + +表示该规格属于商品 100。 + +--- + +### name + +规格名称。 + +例如: + +```text +颜色 +尺码 +容量 +版本 +材质 +``` + +--- + +### sort + +规格显示顺序。 + +例如: + +```text +颜色 sort = 1 +尺码 sort = 2 +``` + +前端展示: + +```text +颜色 +尺码 +``` + +--- + +## 约束 + +同一个商品下不能存在两个相同名称的规格: + +```text +商品 100 + 颜色 +商品 100 + 颜色 +``` + +不允许。 + +因此使用: + +```sql +UNIQUE(product_id, name) +``` + +--- + +# 6. 商品规格值表 + +表: + +```text +ec_product_spec_value +``` + +建议结构: + +```sql +CREATE TABLE ec_product_spec_value ( + id BIGINT UNSIGNED NOT NULL COMMENT '规格值ID', + spec_id BIGINT UNSIGNED NOT NULL COMMENT '规格ID', + value VARCHAR(100) NOT NULL COMMENT '规格值展示名,例如黑色、M、128GB', + value_code VARCHAR(64) NOT NULL COMMENT '规格值编码,用于生成 SKU 编码', + sort INT NOT NULL DEFAULT 0 COMMENT '排序值', + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + + PRIMARY KEY (id), + UNIQUE KEY uk_spec_value (spec_id, value), + UNIQUE KEY uk_spec_value_code (spec_id, value_code), + KEY idx_spec_id (spec_id) +) COMMENT='商品规格值'; +``` + +例如: + +```text +ec_product_spec + +id product_id name +1 100 颜色 +2 100 尺码 +``` + +对应: + +```text +ec_product_spec_value + +id spec_id value value_code +11 1 黑色 BLK +12 1 白色 WHT + +21 2 S S +22 2 M M +23 2 L L +``` + +### value_code 说明 + +* 同一规格下 `value_code` 唯一(`UNIQUE(spec_id, value_code)`)。 +* 编码建议:短、稳定、仅 `[A-Za-z0-9_-]`,避免中文与空格,便于拼进 `sku_code`。 +* 已被 SKU 引用的规格值:**禁止修改 `value_code`**(与禁止改展示语义同理);否则历史 `sku_code` 与生成规则会漂移。可停用后新增编码。 +* 现网适配时字段名可改为项目惯例(如 `code`),语义不变。 + +--- + +# 7. SKU 表 + +表: + +```text +ec_product_sku +``` + +建议结构: + +```sql +CREATE TABLE ec_product_sku ( + id BIGINT UNSIGNED NOT NULL COMMENT 'SKU ID', + product_id BIGINT UNSIGNED NOT NULL COMMENT '商品ID', + + sku_code VARCHAR(100) NOT NULL COMMENT '内部SKU编码', + + barcode VARCHAR(100) NULL COMMENT '商品条码', + + name VARCHAR(255) NULL COMMENT 'SKU名称,可选', + + price DECIMAL(18,2) NOT NULL DEFAULT 0 COMMENT '销售价格', + cost_price DECIMAL(18,2) NOT NULL DEFAULT 0 COMMENT '成本价', + + spec_combination_key VARCHAR(500) NOT NULL COMMENT '规格组合唯一键', + + status TINYINT NOT NULL DEFAULT 1 COMMENT '状态:1启用 0禁用', + + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + + PRIMARY KEY (id), + + UNIQUE KEY uk_sku_code (sku_code), + + UNIQUE KEY uk_product_combination ( + product_id, + spec_combination_key + ), + + KEY idx_product_id (product_id), + KEY idx_barcode (barcode) + +) COMMENT='商品SKU'; +``` + +--- + +# 8. SKU 与规格值关系表 + +表: + +```text +ec_product_sku_spec_value +``` + +建议结构: + +```sql +CREATE TABLE ec_product_sku_spec_value ( + sku_id BIGINT UNSIGNED NOT NULL COMMENT 'SKU ID', + spec_value_id BIGINT UNSIGNED NOT NULL COMMENT '规格值ID', + + PRIMARY KEY (sku_id, spec_value_id), + + KEY idx_spec_value_id (spec_value_id) + +) COMMENT='SKU规格值关系'; +``` + +例如: + +```text +SKU001 = 黑色 + M +``` + +对应: + +```text +sku_id spec_value_id +10001 11 +10001 22 +``` + +--- + +# 9. SKU 组合唯一性 + +这是整个设计中非常重要的一点。 + +例如商品: + +```text +颜色: +黑色 +白色 + +尺码: +S +M +``` + +合法 SKU: + +```text +黑色 + S +黑色 + M +白色 + S +白色 + M +``` + +但是不允许: + +```text +SKU001 = 黑色 + M +SKU002 = 黑色 + M +``` + +--- + +## 9.1 为什么不能只依赖关系表唯一索引? + +因为: + +```text +sku_id spec_value_id +10001 11 +10001 22 + +10002 11 +10002 22 +``` + +数据库无法通过普通: + +```sql +UNIQUE(sku_id, spec_value_id) +``` + +判断: + +```text +10001 = 11 + 22 +10002 = 11 + 22 +``` + +属于相同规格组合。 + +--- + +# 10. spec_combination_key + +在 SKU 表保存规格组合 Key: + +```text +spec_combination_key +``` + +例如: + +```text +颜色黑色 = spec_value_id 11 +尺码M = spec_value_id 22 +``` + +排序后: + +```text +11_22 +``` + +那么: + +```text +SKU001 +product_id = 100 +spec_combination_key = 11_22 +``` + +数据库: + +```sql +UNIQUE(product_id, spec_combination_key) +``` + +即可保证: + +```text +商品100 + 11_22 +``` + +只能存在一个 SKU。 + +--- + +# 11. 组合 Key 生成规则 + +生成 `spec_combination_key` 时: + +1. 获取 SKU 所有规格值 ID。 +2. 按 `spec_value_id` 数值升序排序。 +3. 使用 `_` 拼接。 + +例如: + +```text +[22, 11] +``` + +排序: + +```text +[11, 22] +``` + +最终: + +```text +11_22 +``` + +而不是: + +```text +22_11 +``` + +这样: + +```text +黑色 + M +``` + +和: + +```text +M + 黑色 +``` + +最终得到相同的组合 Key。 + +> 注意:`spec_combination_key` 只负责**唯一性**;`sku_code` 的可读拼接规则见 **§11.1**,二者排序维度不同,不要混用。 + +--- + +# 11.1 商品编码与 SKU 编码生成规则(补充) + +## 商品编码 `product_code` + +* **现状**:`ec_product.product_code` 公司内唯一,可空。 +* **规划**:后续将商品编码改为**必填**(创建/更新商品时强制;存量数据需先补齐再收紧约束)。 +* 本规格阶段:若走「按规格组合生成 SKU」路径,**当时必须已有 `product_code`**,否则拒绝生成并提示先填写商品编码。 + +## 规格值编码 `value_code` + +见 §6:每个规格值除展示名外必须有编码,用于拼接 SKU 编码。 + +## SKU 编码生成(可选笛卡尔积) + +规格组合**可以**生成 SKU,但**不是**创建规格后强制立刻生成;由用户在 UI 上选择「生成 SKU」触发(也可后续手工建 SKU 并自填编码)。 + +生成时: + +```text +sku_code = product_code + "-" + value_code₁ + "-" + value_code₂ + ... + "-" + value_codeₙ +``` + +其中 `value_code₁ … value_codeₙ` 按所属 **规格的 `sort` 升序**排列(同 sort 再按 `spec_id`),保证: + +```text +颜色(sort=1)=BLK + 尺码(sort=2)=M → NIKE-TEE-BLK-M +``` + +而不是按 `spec_value_id` 乱序。 + +示例: + +```text +product_code = NIKE-TEE + +颜色 BLK / WHT +尺码 S / M + +可选生成: +NIKE-TEE-BLK-S +NIKE-TEE-BLK-M +NIKE-TEE-WHT-S +NIKE-TEE-WHT-M +``` + +### 约束 + +1. 生成前校验:`product_code` 非空;每个参与组合的规格值均有非空 `value_code`。 +2. 生成的 `sku_code` 仍受现网约束:**公司内唯一**(`uk_ec_product_sku_company_code`);冲突时整批失败或跳过冲突项并回报(实现时二选一,推荐整批事务失败更安全)。 +3. 无规格商品:不拼规格值编码;默认 SKU 编码策略可与商品编码相同或 `product_code + "-DEFAULT"`(实现时与现网习惯对齐,写入文档约定即可)。 +4. 用户仍可手工指定/修改 `sku_code`(在未产生订单匹配依赖前);一旦被订单/渠道大量引用,修改需走既有管控规则。 +5. **不要**用 `spec_combination_key` 直接当 `sku_code`;前者是内部唯一键,后者是业务编码。 + +--- + +# 12. SKU 创建示例 + +商品: + +```text +product_id = 100 +``` + +规格: + +```text +颜色: +11 黑色 +12 白色 + +尺码: +21 S +22 M +23 L +``` + +创建: + +```text +黑色 + M +``` + +系统得到: + +```text +spec_value_ids = [11, 22] +``` + +排序: + +```text +[11, 22] +``` + +生成: + +```text +spec_combination_key = "11_22" +``` + +SKU: + +```text +id = 10001 +product_id = 100 +sku_code = SKU001 +spec_combination_key = 11_22 +``` + +关系表: + +```text +10001 11 +10001 22 +``` + +--- + +# 13. 无规格商品 + +必须支持无规格商品。 + +例如: + +```text +矿泉水 550ml +``` + +商品只有一个销售单位,没有: + +```text +颜色 +尺码 +容量 +``` + +也应该能够创建 SKU。 + +例如: + +```text +product_id = 200 + +SKU001 +``` + +此时: + +```text +spec_combination_key = "" +``` + +或者: + +```text +spec_combination_key = "DEFAULT" +``` + +推荐使用: + +```text +DEFAULT +``` + +因此: + +```text +UNIQUE(product_id, spec_combination_key) +``` + +仍然可以保证一个无规格商品只有一个默认 SKU。 + +--- + +# 14. SKU 与库存 + +SKU 是商品库存管理的最小单位。 + +不要简单地把真实库存直接放在: + +```text +ec_product +``` + +中。 + +例如: + +```text +Nike T恤 + +黑色 + S +黑色 + M +白色 + S +白色 + M +``` + +每个 SKU 都可能拥有独立库存。 + +后续库存建议单独设计: + +```text +ec_inventory +``` + +例如: + +```text +warehouse_id +sku_id +quantity +available_quantity +locked_quantity +``` + +形成: + +```text +仓库 + │ + └── SKU库存 +``` + +这样支持: + +```text +仓库A +黑色M = 100 + +仓库B +黑色M = 50 +``` + +而不是直接在 SKU 上记录总库存。 + +如果当前系统已有库存表,则直接复用现有库存模型。 + +--- + +# 15. SKU 与成本 + +成本应该以 SKU 为核心。 + +例如: + +```text +黑色 + M +成本 = 30 + +白色 + M +成本 = 32 +``` + +因此: + +```text +ec_product_sku.cost_price +``` + +可以作为当前 SKU 成本价。 + +如果 ERP 后续需要完整的成本历史: + +```text +采购成本 +加权平均成本 +批次成本 +供应商成本 +``` + +再独立设计成本相关表。 + +第一阶段不要把成本系统复杂化。 + +--- + +# 16. SKU 与条码 + +条码属于 SKU。 + +例如: + +```text +黑色 + M +barcode = 690000000001 + +黑色 + L +barcode = 690000000002 +``` + +因此: + +```text +ec_product_sku.barcode +``` + +应该允许为空,但如果存在条码,建议增加唯一约束: + +```sql +UNIQUE KEY uk_barcode (barcode) +``` + +但是如果现有业务存在多仓、多公司、多租户,需要根据租户/公司维度确定唯一范围。 + +例如 SaaS ERP: + +```sql +UNIQUE(company_id, barcode) +``` + +不要直接全局唯一。 + +--- + +# 17. 商品、SKU 和平台商品不要混为一谈 + +后续系统可能对接: + +```text +淘宝 +拼多多 +抖音 +京东 +1688 +``` + +平台商品的规格体系可能不同。 + +例如 ERP 内部: + +```text +内部商品 +Nike T恤 + +黑色 + M +``` + +拼多多: + +```text +平台商品 +颜色=黑 +尺码=M +``` + +抖音: + +```text +平台商品 +颜色=经典黑 +尺码=M +``` + +因此: + +```text +内部 Product +内部 SKU +``` + +与: + +```text +平台 Product +平台 SKU +``` + +不要直接使用同一个 SKU ID。 + +后续可以增加映射: + +```text +ec_platform_product +ec_platform_sku +ec_platform_product_mapping +ec_platform_sku_mapping +``` + +例如: + +```text +内部 SKU +10001 + + ↓ + +拼多多 SKU +PDD99881 + + ↓ + +抖音 SKU +DY88221 +``` + +这部分本次商品规格功能暂时不要实现,只需要保证当前模型不会阻碍后续扩展。 + +--- + +# 18. 删除规则 + +规格和规格值不能随意物理删除。 + +尤其是已经被 SKU 使用的规格值。 + +例如: + +```text +黑色 +``` + +已经被: + +```text +SKU001 +SKU002 +``` + +使用。 + +此时不能直接删除规格值。 + +推荐规则: + +## 商品规格 + +如果规格下存在 SKU 使用的规格值: + +```text +禁止删除 +``` + +--- + +## 规格值 + +如果已经被 SKU 使用: + +```text +禁止物理删除 +``` + +可以考虑增加: + +```text +status +``` + +或者直接保留历史数据。 + +--- + +## SKU + +如果已经产生订单、库存等业务数据: + +```text +不要物理删除 +``` + +使用: + +```text +status = disabled +``` + +进行停用。 + +--- + +# 19. 修改规格的规则 + +必须避免修改已经影响历史 SKU 的规格语义。 + +例如: + +```text +颜色 +├── 黑色 +└── 白色 +``` + +已经创建: + +```text +SKU001 = 黑色 + M +``` + +不能把: + +```text +黑色 +``` + +直接修改成: + +```text +红色 +``` + +否则历史 SKU 的含义会发生变化。 + +推荐: + +```text +删除/停用旧规格值 +新增新的规格值 +``` + +而不是修改已经被 SKU 使用的规格值。 + +--- + +# 20. 创建商品时的推荐流程 + +前端提交: + +```json +{ + "name": "Nike T恤", + "productCode": "NIKE-TEE", + "specs": [ + { + "name": "颜色", + "values": [ + { "value": "黑色", "valueCode": "BLK" }, + { "value": "白色", "valueCode": "WHT" } + ] + }, + { + "name": "尺码", + "values": [ + { "value": "S", "valueCode": "S" }, + { "value": "M", "valueCode": "M" }, + { "value": "L", "valueCode": "L" } + ] + } + ], + "generateSkus": true +} +``` + +`generateSkus` 为可选开关:`true` 时在事务内按 §11.1 生成笛卡尔积 SKU;`false` 时只落规格维,SKU 稍后手工或再次触发生成。 + +后端: + +### Step 1 + +创建: + +```text +product(须有 product_code;规划上后续改为全站必填) +``` + +### Step 2 + +创建: + +```text +product_spec +``` + +例如: + +```text +颜色 +尺码 +``` + +### Step 3 + +创建: + +```text +product_spec_value(含 value + value_code) +``` + +例如: + +```text +黑色/BLK +白色/WHT +S/S +M/M +L/L +``` + +### Step 4(仅当用户选择生成 SKU) + +生成 SKU 笛卡尔积,并为每个组合按 §11.1 生成: + +```text +sku_code = NIKE-TEE-BLK-S +... +``` + +### Step 5 + +为每个组合创建: + +```text +product_sku +``` + +### Step 6 + +创建: + +```text +product_sku_spec_value +``` + +关系。 + +若用户**未**选择生成,则停在 Step 3;允许稍后调用「按当前规格生成缺失 SKU」接口(只补尚不存在的 `spec_combination_key`)。 + +--- + +# 21. SKU 笛卡尔积 + +例如: + +```text +颜色: +黑色 +白色 + +尺码: +S +M +``` + +组合数量: + +```text +2 × 2 = 4 +``` + +生成: + +```text +黑色 + S +黑色 + M +白色 + S +白色 + M +``` + +如果: + +```text +颜色 = 5 +尺码 = 10 +容量 = 3 +``` + +SKU 数量: + +```text +5 × 10 × 3 = 150 +``` + +后端必须注意防止 SKU 数量无限膨胀。 + +第一阶段可以增加合理限制,例如: + +```text +单商品 SKU 数量上限 +``` + +具体数值根据现有系统业务决定,不要写死在数据库设计中。 + +--- + +# 22. 事务要求 + +创建/修改商品规格和 SKU 必须使用数据库事务。 + +例如: + +```text +BEGIN + +创建商品规格 +创建规格值 +创建 SKU +创建 SKU 规格关系 + +COMMIT +``` + +如果任何一步失败: + +```text +ROLLBACK +``` + +避免出现: + +```text +规格创建成功 +SKU 创建了一半 +关系表只创建了一部分 +``` + +造成脏数据。 + +--- + +# 23. API 建议 + +第一阶段可以提供: + +```text +POST /products +GET /products/{id} +PUT /products/{id} + +GET /products/{id}/specs +POST /products/{id}/specs +PUT /products/{id}/specs/{specId} +DELETE /products/{id}/specs/{specId} + +GET /products/{id}/skus +POST /products/{id}/skus +PUT /products/{id}/skus/{skuId} +``` + +如果现有项目已经有商品 CRUD,应遵循现有 API 风格,不强制改变已有接口。 + +--- + +# 24. 查询商品详情 + +商品详情建议返回: + +```json +{ + "id": 100, + "name": "Nike T恤", + "specs": [ + { + "id": 1, + "name": "颜色", + "values": [ + { + "id": 11, + "value": "黑色" + }, + { + "id": 12, + "value": "白色" + } + ] + }, + { + "id": 2, + "name": "尺码", + "values": [ + { + "id": 21, + "value": "S" + }, + { + "id": 22, + "value": "M" + }, + { + "id": 23, + "value": "L" + } + ] + } + ], + "skus": [ + { + "id": 10001, + "skuCode": "SKU001", + "barcode": "690000000001", + "price": 99, + "costPrice": 50, + "specValues": [ + { + "specId": 1, + "specValueId": 11, + "value": "黑色" + }, + { + "specId": 2, + "specValueId": 22, + "value": "M" + } + ] + } + ] +} +``` + +前端可以直接根据这个结构渲染规格选择器和 SKU 表格。 + +--- + +# 25. 数据一致性检查 + +后端创建 SKU 时必须验证: + +## 规则 1 + +所有 `spec_value_id` 必须属于当前商品。 + +不能出现: + +```text +商品 A +``` + +引用: + +```text +商品 B 的规格值 +``` + +--- + +## 规则 2 + +一个 SKU 对同一个规格只能选择一个规格值。 + +例如: + +```text +SKU001 + +颜色 = 黑色 +颜色 = 白色 +``` + +这是非法数据。 + +一个 SKU: + +```text +一个 spec +最多一个 spec_value +``` + +--- + +## 规则 3 + +SKU 必须包含商品定义的所有必要规格。 + +例如商品定义: + +```text +颜色 +尺码 +``` + +SKU: + +```text +黑色 +``` + +如果系统规定所有规格都是必选,那么这是非法 SKU。 + +--- + +## 规则 4 + +不能出现重复 SKU 规格组合。 + +使用: + +```text +spec_combination_key +``` + +进行数据库层面的最终保证。 + +--- + +# 26. 不建议的设计 + +第一阶段不要设计成: + +```text +product +product_sku +``` + +然后: + +```text +product_sku.spec_json +``` + +例如: + +```json +{ + "颜色": "黑色", + "尺码": "M" +} +``` + +JSON 可以作为辅助冗余字段,但不应该作为核心关系模型。 + +核心关系仍然应该是: + +```text +product + ↓ +product_spec + ↓ +product_spec_value + ↓ +product_sku + ↓ +product_sku_spec_value +``` + +--- + +# 27. 不建议第一阶段引入的功能 + +本次需求不要过度设计。 + +暂时不要实现: + +```text +全局规格模板 +品牌规格模板 +类目规格模板 +平台规格映射 +复杂属性系统 +SKU 批次 +SKU 序列号 +SKU 多单位 +SKU 包装层级 +SKU 变体图片 +SKU 多仓库存 +成本历史 +采购价历史 +``` + +这些可以作为后续独立需求。 + +--- + +# 28. 后续扩展方向 + +当前模型完成后,可以自然扩展: + +```text + Product + │ + ┌────────────┼────────────┐ + │ │ │ + Spec SKU Platform Product + │ │ │ + SpecValue │ Platform SKU + │ │ + └──── Mapping ─┘ +``` + +后续可以增加: + +```text +SKU 图片 +SKU 条码 +SKU 库存 +SKU 仓库库存 +SKU 采购价 +SKU 供应商 +SKU 成本历史 +平台 SKU 映射 +平台规格映射 +``` + +而不需要推翻当前模型。 + +--- + +# 29. 实现要求 + +Coding Agent 实现时遵循以下原则: + +1. **优先适配现有项目结构和命名规范。** +2. 不要重构现有商品模块。 +3. 先检查当前数据库中是否已经存在商品、SKU、库存相关表。 +4. 如果已经存在 SKU 表,应优先扩展现有 SKU 模型,而不是重复创建。 +5. 数据库字段命名遵循项目现有规范。 +6. ID 类型遵循项目现有 ID 生成策略。 +7. 如果项目使用 MyBatis Plus / Prisma / TypeORM 等 ORM,遵循当前项目已有实践。 +8. 所有商品规格、规格值、SKU 的创建和修改操作必须保证事务一致性。 +9. SKU 规格组合必须通过 `spec_combination_key` 保证数据库层面的唯一性。 +10. 后端必须校验 SKU 引用的规格值属于当前商品。 +11. 不允许通过修改已经被 SKU 使用的规格值来改变历史 SKU 的语义。 +12. 删除操作需要检查关联关系。 +13. 不要为了本需求引入新的基础设施。 +14. 不要提前实现平台商品 SKU 映射。 +15. 保持 API 与现有项目 API 风格一致。 +16. 实现完成后补充数据库 migration。 +17. 补充必要的单元测试/集成测试,至少覆盖: + + * 创建无规格商品 + * 创建单规格商品 + * 创建多规格商品 + * 可选生成 SKU 组合(generateSkus=true/false) + * 按 product_code + value_code(规格 sort 序)生成 sku_code + * 缺少 product_code / value_code 时拒绝生成 + * 重复规格组合 + * 非当前商品规格值 + * 删除已被 SKU 使用的规格值 + * 修改已被 SKU 使用的规格值 / value_code + * SKU 组合唯一性 + * 公司内 sku_code 冲突 + +18. **规格值必须有 `value_code`;SKU 编码生成规则见 §11.1。** +19. **商品编码后续必填**:实现规格生成 SKU 时即要求 `product_code`;全站 NOT NULL 可另开迁移任务补齐存量。 + +--- + +# 30. 最终目标 + +实现完成后,系统至少能够完整表达: + +```text +商品:Nike T恤 + +规格: +├── 颜色 +│ ├── 黑色 +│ └── 白色 +│ +└── 尺码 + ├── S + ├── M + └── L + +SKU: +├── 黑色 + S → sku_code = NIKE-TEE-BLK-S +├── 黑色 + M → sku_code = NIKE-TEE-BLK-M +├── 黑色 + L → sku_code = NIKE-TEE-BLK-L +├── 白色 + S → sku_code = NIKE-TEE-WHT-S +├── 白色 + M → sku_code = NIKE-TEE-WHT-M +└── 白色 + L → sku_code = NIKE-TEE-WHT-L +``` + +编码规则:`商品编码-规格值编码…`(按规格 sort);组合唯一仍靠 `spec_combination_key`。 + +并且: + +```text +每个 SKU + ↓ +唯一规格组合 + ↓ +唯一 SKU 编码 + ↓ +可关联库存 + ↓ +可关联成本 + ↓ +可关联条码 + ↓ +后续可关联平台 SKU +``` + +核心数据模型保持: + +```text +ec_product + │ + ├── ec_product_spec + │ │ + │ └── ec_product_spec_value + │ + └── ec_product_sku + │ + └── ec_product_sku_spec_value +``` + +该模型作为第一阶段商品规格系统的基础数据模型。 diff --git a/ecom-dmb-backend/sql/design/ec/ec_product_design.sql b/ecom-dmb-backend/sql/design/ec/ec_product_design.sql index f3811060..042fc576 100644 --- a/ecom-dmb-backend/sql/design/ec/ec_product_design.sql +++ b/ecom-dmb-backend/sql/design/ec/ec_product_design.sql @@ -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, diff --git a/ecom-dmb-backend/sql/design/ec/ec_product_spec_design.sql b/ecom-dmb-backend/sql/design/ec/ec_product_spec_design.sql new file mode 100644 index 00000000..e7ce6bb1 --- /dev/null +++ b/ecom-dmb-backend/sql/design/ec/ec_product_spec_design.sql @@ -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; diff --git a/ecom-dmb-backend/sql/design/ec/ec_spec_template_design.sql b/ecom-dmb-backend/sql/design/ec/ec_spec_template_design.sql new file mode 100644 index 00000000..7cb3710b --- /dev/null +++ b/ecom-dmb-backend/sql/design/ec/ec_spec_template_design.sql @@ -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; diff --git a/ecom-dmb-backend/sql/migration/V20260910__ec_product_code_not_null.sql b/ecom-dmb-backend/sql/migration/V20260910__ec_product_code_not_null.sql new file mode 100644 index 00000000..9aa5a5ca --- /dev/null +++ b/ecom-dmb-backend/sql/migration/V20260910__ec_product_code_not_null.sql @@ -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 '商品编码(公司内唯一,必填)'; diff --git a/ecom-dmb-backend/sql/migration/V20260910b__ec_product_spec.sql b/ecom-dmb-backend/sql/migration/V20260910b__ec_product_spec.sql new file mode 100644 index 00000000..18fb314c --- /dev/null +++ b/ecom-dmb-backend/sql/migration/V20260910b__ec_product_spec.sql @@ -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; diff --git a/ecom-dmb-backend/sql/migration/V20260910c__ec_spec_template.sql b/ecom-dmb-backend/sql/migration/V20260910c__ec_spec_template.sql new file mode 100644 index 00000000..0c3268fd --- /dev/null +++ b/ecom-dmb-backend/sql/migration/V20260910c__ec_spec_template.sql @@ -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 = '规格模板'; diff --git a/ecom-dmb-backend/sql/migration/V20260910d__ec_spec_template_seed_all_companies.sql b/ecom-dmb-backend/sql/migration/V20260910d__ec_spec_template_seed_all_companies.sql new file mode 100644 index 00000000..239703af --- /dev/null +++ b/ecom-dmb-backend/sql/migration/V20260910d__ec_spec_template_seed_all_companies.sql @@ -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`) + ); diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/model/dto/CreateProductDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/model/dto/CreateProductDTO.java index b675e391..581e089b 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/model/dto/CreateProductDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/model/dto/CreateProductDTO.java @@ -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 skus; + /** 可选;与商品同事务写入规格维(id 空=新增)。 */ + @Valid + private List specs; + @Data public static class ProductSkuDTO { diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/model/dto/UpdateProductDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/model/dto/UpdateProductDTO.java index 9c4a2294..500498d4 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/model/dto/UpdateProductDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/model/dto/UpdateProductDTO.java @@ -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 skus; + /** + * 传入则全量同步规格维(有 id 更新,无 id 新增,未出现的删除)。 + */ + @Valid + private List specs; + @Data public static class ProductSkuUpdateDTO { diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/model/vo/ProductVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/model/vo/ProductVO.java index 4c80cba2..0284fd00 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/model/vo/ProductVO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/model/vo/ProductVO.java @@ -67,6 +67,11 @@ public class ProductVO { */ private Long updateBy; + /** + * 商品规格维(结构化) + */ + private List specs; + /** * 商品 SKU 列表 */ diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/service/impl/ProductServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/service/impl/ProductServiceImpl.java index 30e0df32..ee1708ff 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/service/impl/ProductServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/service/impl/ProductServiceImpl.java @@ -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 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 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 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 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 im rawCostChangedSkuIds, newSkuIdsFromCodeWithOrders); } + if (updateProductDTO.getSpecs() != null) { + ReplaceProductSpecsDTO specsDto = new ReplaceProductSpecsDTO(); + specsDto.setSpecs(updateProductDTO.getSpecs()); + productSpecService.replaceSpecs(id, specsDto); + } + // 返回结果:成本变更且有关联订单的规格 ∪ 新增规格(编码非空)且有关联订单的规格 UpdateProductResultDTO result = new UpdateProductResultDTO(); LinkedHashSet syncUnion = new LinkedHashSet<>(); @@ -720,6 +738,15 @@ public class ProductServiceImpl extends ServiceImpl im .collect(Collectors.toList()); productVO.setSkus(skuVOs); + productVO.setSpecs(productSpecService.listByProductId(product.getId())); + if (!skuVOs.isEmpty()) { + Map> 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 im return productSkuService.toVo(productSku); } - /** 公司内商品编码唯一;未填不校验。 */ + /** 公司内商品编码唯一;必填。 */ private void assertProductCodeUnique(Long companyId, String productCode, Long excludeId) { String code = normalizeProductCode(productCode); - if (code == null) { - return; - } LambdaQueryWrapper uniqueWrapper = new LambdaQueryWrapper<>(); uniqueWrapper.eq(ProductPO::getCompanyId, companyId) .eq(ProductPO::getProductCode, code); @@ -744,10 +768,10 @@ public class ProductServiceImpl extends ServiceImpl im } } - /** 空白编码规范为 null,不参与唯一约束。 */ + /** 商品编码必填并 trim。 */ private static String normalizeProductCode(String productCode) { if (productCode == null || productCode.isBlank()) { - return null; + throw new BusinessException("商品编码不能为空"); } return productCode.trim(); } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/sku/model/po/ProductSkuPO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/sku/model/po/ProductSkuPO.java index c32cbe18..57bc6c41 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/sku/model/po/ProductSkuPO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/sku/model/po/ProductSkuPO.java @@ -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; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/sku/model/vo/ProductSkuVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/sku/model/vo/ProductSkuVO.java index 1fec8f71..69e527bd 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/sku/model/vo/ProductSkuVO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/sku/model/vo/ProductSkuVO.java @@ -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 specValues; + private String imageUrl; private BigDecimal productCost; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/controller/ProductSpecController.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/controller/ProductSpecController.java new file mode 100644 index 00000000..398535b3 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/controller/ProductSpecController.java @@ -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(@PathVariable Long productId) { + return ApiResponse.success("获取成功", productSpecService.listByProductId(productId)); + } + + @PutMapping + @RequirePermission(value = "ec:product:update", description = "保存商品规格", allowSuper = true) + public ApiResponse> 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> generateSkus(@PathVariable Long productId, + @RequestBody(required = false) GenerateProductSkusDTO dto) { + List 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 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 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> 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 saveAsTemplate(@PathVariable Long productId, + @Valid @RequestBody SaveProductAsTemplateDTO dto) { + return ApiResponse.success("保存成功", specTemplateService.saveProductAsTemplate(productId, dto)); + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/domain/ProductSpecCodes.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/domain/ProductSpecCodes.java new file mode 100644 index 00000000..848a3e08 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/domain/ProductSpecCodes.java @@ -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 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 values, + Map specById) { + String pc = productCode == null ? "" : productCode.trim(); + if (pc.isEmpty()) { + throw new IllegalArgumentException("商品编码不能为空"); + } + if (values == null || values.isEmpty()) { + return pc; + } + List 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 values, + Map specById) { + if (values == null || values.isEmpty()) { + return "默认"; + } + List 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("/")); + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/mapper/ProductSkuSpecValueMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/mapper/ProductSkuSpecValueMapper.java new file mode 100644 index 00000000..ba7c81fb --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/mapper/ProductSkuSpecValueMapper.java @@ -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 { +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/mapper/ProductSpecMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/mapper/ProductSpecMapper.java new file mode 100644 index 00000000..59b831ae --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/mapper/ProductSpecMapper.java @@ -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 { +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/mapper/ProductSpecValueMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/mapper/ProductSpecValueMapper.java new file mode 100644 index 00000000..1caeb4ee --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/mapper/ProductSpecValueMapper.java @@ -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 { +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/dto/BindSkuSpecsDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/dto/BindSkuSpecsDTO.java new file mode 100644 index 00000000..d55677e0 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/dto/BindSkuSpecsDTO.java @@ -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 specValueIds; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/dto/CreateSkuFromSpecsDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/dto/CreateSkuFromSpecsDTO.java new file mode 100644 index 00000000..7ca4df7d --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/dto/CreateSkuFromSpecsDTO.java @@ -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 specValueIds; + + /** 可选;空则自动生成 */ + private String skuCode; + + /** 可选;空则用规格值名拼接 */ + private String name; + + @NotNull(message = "商品成本不能为空") + private BigDecimal productCost; + + private BigDecimal shippingCost; + + private BigDecimal otherCost; + + private String remark; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/dto/GenerateProductSkusDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/dto/GenerateProductSkusDTO.java new file mode 100644 index 00000000..1bed69f0 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/dto/GenerateProductSkusDTO.java @@ -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; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/dto/ReplaceProductSpecsDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/dto/ReplaceProductSpecsDTO.java new file mode 100644 index 00000000..37f08332 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/dto/ReplaceProductSpecsDTO.java @@ -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 specs; + + @Data + public static class SpecItem { + /** 已有规格维 ID;空表示新增 */ + private Long id; + + @NotBlank(message = "规格名称不能为空") + private String name; + + private Integer sortOrder; + + @Valid + private List 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; + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/po/ProductSkuSpecValuePO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/po/ProductSkuSpecValuePO.java new file mode 100644 index 00000000..947cabe1 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/po/ProductSkuSpecValuePO.java @@ -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; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/po/ProductSpecPO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/po/ProductSpecPO.java new file mode 100644 index 00000000..fc74ce42 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/po/ProductSpecPO.java @@ -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; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/po/ProductSpecValuePO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/po/ProductSpecValuePO.java new file mode 100644 index 00000000..0ae8aa14 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/po/ProductSpecValuePO.java @@ -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; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/vo/ProductSpecVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/vo/ProductSpecVO.java new file mode 100644 index 00000000..a183a6f7 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/vo/ProductSpecVO.java @@ -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 values; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/vo/ProductSpecValueVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/vo/ProductSpecValueVO.java new file mode 100644 index 00000000..a0c07724 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/model/vo/ProductSpecValueVO.java @@ -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; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/service/ProductSpecService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/service/ProductSpecService.java new file mode 100644 index 00000000..c4ac26ec --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/service/ProductSpecService.java @@ -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 listByProductId(Long productId); + + List replaceSpecs(Long productId, ReplaceProductSpecsDTO dto); + + /** 笛卡尔积生成缺失结构化 SKU;sku_code 冲突则整批失败。 */ + List 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> listSkuSpecValues(Collection skuIds); +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/service/impl/ProductSpecServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/service/impl/ProductSpecServiceImpl.java new file mode 100644 index 00000000..19e37029 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/service/impl/ProductSpecServiceImpl.java @@ -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 listByProductId(Long productId) { + ProductPO product = requireProduct(productId); + return loadSpecTree(product.getId()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public List replaceSpecs(Long productId, ReplaceProductSpecsDTO dto) { + ProductPO product = requireProduct(productId); + Long companyId = product.getCompanyId(); + Long userId = currentUserContext.getCurrentUserId(); + List items = + dto.getSpecs() == null ? List.of() : dto.getSpecs(); + + Set keepSpecIds = new HashSet<>(); + Set 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 values = + item.getValues() == null ? List.of() : item.getValues(); + Set nameSeen = new HashSet<>(); + Set 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 existingValues = valueMapper.selectList(new LambdaQueryWrapper() + .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 existingSpecs = specMapper.selectList(new LambdaQueryWrapper() + .eq(ProductSpecPO::getProductId, productId)); + for (ProductSpecPO s : existingSpecs) { + if (keepSpecIds.contains(s.getId())) { + continue; + } + long remain = valueMapper.selectCount(new LambdaQueryWrapper() + .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 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 specs = specMapper.selectList(new LambdaQueryWrapper() + .eq(ProductSpecPO::getProductId, productId) + .orderByAsc(ProductSpecPO::getSortOrder) + .orderByAsc(ProductSpecPO::getId)); + if (specs.isEmpty()) { + throw new BusinessException("请先配置商品规格后再生成 SKU"); + } + Map specById = specs.stream() + .collect(Collectors.toMap(ProductSpecPO::getId, s -> s, (a, b) -> a)); + + List> dimValues = new ArrayList<>(); + for (ProductSpecPO spec : specs) { + List vals = valueMapper.selectList(new LambdaQueryWrapper() + .eq(ProductSpecValuePO::getSpecId, spec.getId()) + .orderByAsc(ProductSpecValuePO::getSortOrder) + .orderByAsc(ProductSpecValuePO::getId)); + if (vals.isEmpty()) { + throw new BusinessException("规格「" + spec.getName() + "」下没有规格值"); + } + dimValues.add(vals); + } + + List> combos = cartesian(dimValues); + if (combos.size() > ProductSpecCodes.MAX_GENERATED_SKUS) { + throw new BusinessException("生成 SKU 数量超过上限 " + ProductSpecCodes.MAX_GENERATED_SKUS + + "(当前 " + combos.size() + "),请减少规格值"); + } + + // 预检:组合键 / sku_code 冲突则整批失败 + Set existingKeys = skuMapper.selectList(new LambdaQueryWrapper() + .eq(ProductSkuPO::getProductId, productId) + .isNotNull(ProductSkuPO::getSpecCombinationKey)) + .stream() + .map(ProductSkuPO::getSpecCombinationKey) + .filter(StringUtils::hasText) + .collect(Collectors.toSet()); + Set existingCodes = skuMapper.selectList(new LambdaQueryWrapper() + .eq(ProductSkuPO::getCompanyId, companyId)) + .stream() + .map(ProductSkuPO::getSkuCode) + .filter(StringUtils::hasText) + .map(String::trim) + .collect(Collectors.toSet()); + + List toCreate = new ArrayList<>(); + for (List combo : combos) { + List 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 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() + .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 rawIds = dto != null && dto.getSpecValueIds() != null + ? dto.getSpecValueIds() : List.of(); + List 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() + .eq(ProductSkuSpecValuePO::getSkuId, skuId)); + skuMapper.update(null, new LambdaUpdateWrapper() + .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 rawValueIds) { + List valueIds = rawValueIds.stream().filter(Objects::nonNull).distinct().toList(); + if (valueIds.isEmpty()) { + throw new BusinessException("请至少选择一个规格值"); + } + List 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 specIds = new HashSet<>(); + for (ProductSpecValuePO v : values) { + if (!specIds.add(v.getSpecId())) { + throw new BusinessException("同一规格维只能选择一个规格值"); + } + } + Map 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 w = new LambdaQueryWrapper() + .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 values) { + skuSpecValueMapper.delete(new LambdaQueryWrapper() + .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 values, + Map specById) { + } + + @Override + public Map> listSkuSpecValues(Collection skuIds) { + if (skuIds == null || skuIds.isEmpty()) { + return Map.of(); + } + List rels = skuSpecValueMapper.selectList( + new LambdaQueryWrapper() + .in(ProductSkuSpecValuePO::getSkuId, skuIds)); + if (rels.isEmpty()) { + return Map.of(); + } + Set valueIds = rels.stream().map(ProductSkuSpecValuePO::getSpecValueId).collect(Collectors.toSet()); + Map valueMap = valueMapper.selectBatchIds(valueIds).stream() + .collect(Collectors.toMap(ProductSpecValuePO::getId, v -> v, (a, b) -> a)); + Map> 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() + .eq(ProductSkuSpecValuePO::getSpecValueId, specValueId)) > 0; + } + + private List loadSpecTree(Long productId) { + List specs = specMapper.selectList(new LambdaQueryWrapper() + .eq(ProductSpecPO::getProductId, productId) + .orderByAsc(ProductSpecPO::getSortOrder) + .orderByAsc(ProductSpecPO::getId)); + if (specs.isEmpty()) { + return List.of(); + } + List specIds = specs.stream().map(ProductSpecPO::getId).toList(); + Map> valuesBySpec = valueMapper.selectList( + new LambdaQueryWrapper() + .in(ProductSpecValuePO::getSpecId, specIds) + .orderByAsc(ProductSpecValuePO::getSortOrder) + .orderByAsc(ProductSpecValuePO::getId)) + .stream() + .collect(Collectors.groupingBy(ProductSpecValuePO::getSpecId)); + List result = new ArrayList<>(); + for (ProductSpecPO s : specs) { + ProductSpecVO vo = new ProductSpecVO(); + vo.setId(s.getId()); + vo.setName(s.getName()); + vo.setSortOrder(s.getSortOrder()); + List 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> cartesian(List> dims) { + List> result = new ArrayList<>(); + result.add(new ArrayList<>()); + for (List dim : dims) { + List> next = new ArrayList<>(); + for (List prefix : result) { + for (ProductSpecValuePO v : dim) { + List row = new ArrayList<>(prefix); + row.add(v); + next.add(row); + } + } + result = next; + } + return result; + } + + private record PendingSku(String combinationKey, String skuCode, String displayName, + List values) { + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/controller/SpecTemplateController.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/controller/SpecTemplateController.java new file mode 100644 index 00000000..61bd0e48 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/controller/SpecTemplateController.java @@ -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() { + return ApiResponse.success("获取成功", specTemplateService.listForCompany()); + } + + @GetMapping("/{id}") + @RequirePermission(value = "ec:product:spec-template:read", description = "查询规格模板详情", allowSuper = true) + public ApiResponse get(@PathVariable Long id) { + return ApiResponse.success("获取成功", specTemplateService.get(id)); + } + + @PostMapping + @RequirePermission(value = "ec:product:spec-template:create", description = "创建规格模板", allowSuper = true) + public ApiResponse 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 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 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 delete(@PathVariable Long id) { + specTemplateService.delete(id); + return ApiResponse.success("删除成功", null); + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/mapper/SpecTemplateMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/mapper/SpecTemplateMapper.java new file mode 100644 index 00000000..712dc7a4 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/mapper/SpecTemplateMapper.java @@ -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 { +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/mapper/SpecTemplateValueMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/mapper/SpecTemplateValueMapper.java new file mode 100644 index 00000000..ff6a5270 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/mapper/SpecTemplateValueMapper.java @@ -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 { +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/ApplySpecTemplateDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/ApplySpecTemplateDTO.java new file mode 100644 index 00000000..ebd1e1b5 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/ApplySpecTemplateDTO.java @@ -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 templateValueIds; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/CreateSpecTemplateDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/CreateSpecTemplateDTO.java new file mode 100644 index 00000000..9be1848e --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/CreateSpecTemplateDTO.java @@ -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 values; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/ReplaceSpecTemplateDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/ReplaceSpecTemplateDTO.java new file mode 100644 index 00000000..0a1f575d --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/ReplaceSpecTemplateDTO.java @@ -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 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; + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/SaveProductAsTemplateDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/SaveProductAsTemplateDTO.java new file mode 100644 index 00000000..aa81e6d5 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/SaveProductAsTemplateDTO.java @@ -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; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/UpdateSpecTemplateDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/UpdateSpecTemplateDTO.java new file mode 100644 index 00000000..aa09c65d --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/dto/UpdateSpecTemplateDTO.java @@ -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 values; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/po/SpecTemplatePO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/po/SpecTemplatePO.java new file mode 100644 index 00000000..cc64c706 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/po/SpecTemplatePO.java @@ -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; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/po/SpecTemplateValuePO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/po/SpecTemplateValuePO.java new file mode 100644 index 00000000..448d2f90 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/po/SpecTemplateValuePO.java @@ -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; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/vo/SpecTemplateVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/vo/SpecTemplateVO.java new file mode 100644 index 00000000..fcb2d093 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/vo/SpecTemplateVO.java @@ -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 values; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/vo/SpecTemplateValueVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/vo/SpecTemplateValueVO.java new file mode 100644 index 00000000..65de7a8a --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/model/vo/SpecTemplateValueVO.java @@ -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; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/service/SpecTemplateService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/service/SpecTemplateService.java new file mode 100644 index 00000000..3fb4d415 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/service/SpecTemplateService.java @@ -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 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 applyToProduct(Long productId, ApplySpecTemplateDTO dto); + + /** 从商品某一规格维拷贝创建本公司模板。 */ + SpecTemplateVO saveProductAsTemplate(Long productId, SaveProductAsTemplateDTO dto); + + /** 为公司种子默认规格维(款式/颜色/尺码/容量),已存在则跳过。 */ + void seedDefaultTemplates(Long companyId, Long userId); +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/service/impl/SpecTemplateServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/service/impl/SpecTemplateServiceImpl.java new file mode 100644 index 00000000..8169e123 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ec/product/spec/template/service/impl/SpecTemplateServiceImpl.java @@ -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 listForCompany() { + Long companyId = currentUserContext.getCurrentCompanyId(); + if (countByCompany(companyId) == 0) { + seedDefaultTemplates(companyId, currentUserContext.getCurrentUserId()); + } + List templates = templateMapper.selectList(new LambdaQueryWrapper() + .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 items = + dto.getValues() == null ? List.of() : dto.getValues(); + doReplaceContent(id, items); + return get(id); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public List applyToProduct(Long productId, ApplySpecTemplateDTO dto) { + SpecTemplatePO template = requireCompanyTemplate(dto.getTemplateId()); + List selected = filterTemplateValues(template.getId(), dto); + if (selected.isEmpty()) { + throw new BusinessException("未选中任何模板规格值"); + } + + List 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 items) { + Set keepValueIds = new HashSet<>(); + Set nameSeen = new HashSet<>(); + Set 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 existing = valueMapper.selectList(new LambdaQueryWrapper() + .eq(SpecTemplateValuePO::getTemplateId, templateId)); + for (SpecTemplateValuePO v : existing) { + if (!keepValueIds.contains(v.getId())) { + valueMapper.deleteById(v.getId()); + } + } + } + + /** 按勾选过滤模板值;空表示全部值。 */ + private List filterTemplateValues(Long templateId, ApplySpecTemplateDTO dto) { + List all = toValueVos(loadValues(templateId)); + if (dto.getTemplateValueIds() == null || dto.getTemplateValueIds().isEmpty()) { + return all; + } + Set 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 existing, + SpecTemplatePO template, + List templateValues) { + List items = new ArrayList<>(); + Map 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 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 templateValues) { + List values = + item.getValues() == null ? new ArrayList<>() : new ArrayList<>(item.getValues()); + item.setValues(values); + + Map byName = values.stream() + .collect(Collectors.toMap(ReplaceProductSpecsDTO.ValueItem::getValueName, v -> v, (a, b) -> a)); + Map 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 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 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 toVoList(List templates) { + if (templates.isEmpty()) { + return List.of(); + } + List templateIds = templates.stream().map(SpecTemplatePO::getId).toList(); + Map> valuesByTemplate = valueMapper.selectList( + new LambdaQueryWrapper() + .in(SpecTemplateValuePO::getTemplateId, templateIds) + .orderByAsc(SpecTemplateValuePO::getSortOrder) + .orderByAsc(SpecTemplateValuePO::getId)) + .stream() + .collect(Collectors.groupingBy(SpecTemplateValuePO::getTemplateId)); + + List 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 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 loadValues(Long templateId) { + return valueMapper.selectList(new LambdaQueryWrapper() + .eq(SpecTemplateValuePO::getTemplateId, templateId) + .orderByAsc(SpecTemplateValuePO::getSortOrder) + .orderByAsc(SpecTemplateValuePO::getId)); + } + + private List toValueVos(List values) { + List 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 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() + .eq(SpecTemplatePO::getCompanyId, companyId)); + } + + private boolean existsByCompanyAndName(Long companyId, String name) { + return templateMapper.selectCount(new LambdaQueryWrapper() + .eq(SpecTemplatePO::getCompanyId, companyId) + .eq(SpecTemplatePO::getName, name)) > 0; + } + + private void assertCompanyNameAvailable(Long companyId, String name, Long excludeId) { + LambdaQueryWrapper w = new LambdaQueryWrapper() + .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); + } + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/org/company/service/impl/CompanyServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/org/company/service/impl/CompanyServiceImpl.java index 1e1b4e3f..25fba2c5 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/org/company/service/impl/CompanyServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/org/company/service/impl/CompanyServiceImpl.java @@ -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 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 im this.companyMemberService = companyMemberService; this.passwordEncoder = passwordEncoder; this.licenseValidator = licenseValidator; + this.specTemplateService = specTemplateService; } /** @@ -166,6 +170,9 @@ public class CompanyServiceImpl extends ServiceImpl im // 初始化公司岗位 initCompanyPositions(company.getId(), creatorId); + // 初始化默认规格模板 + specTemplateService.seedDefaultTemplates(company.getId(), creatorId); + // 转换为VO并返回 return convertToVO(company); } diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/sku/types/types.vo.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/sku/types/types.vo.ts index dc164484..4a2f84fa 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/sku/types/types.vo.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/sku/types/types.vo.ts @@ -17,6 +17,10 @@ export namespace ProductSkuVO { name: string; /** SKU 编码 */ skuCode?: string; + /** 规格组合键;空=未结构化 */ + specCombinationKey?: string; + /** 已绑规格值 */ + specValues?: import('#/api/ec/product/spec').ProductSpecVO.SpecValue[]; /** 商品成本 */ productCost: number; /** 运费成本 */ diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/spec-template/index.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/spec-template/index.ts new file mode 100644 index 00000000..dd507cc1 --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/spec-template/index.ts @@ -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( + '/ec/product/spec-templates', + ); +} + +export async function getSpecTemplateApi(id: number) { + return requestClient.get( + `/ec/product/spec-templates/${id}`, + ); +} + +export async function createSpecTemplateApi(data: SpecTemplateDTO.Create) { + return requestClient.post( + '/ec/product/spec-templates', + data, + ); +} + +export async function updateSpecTemplateApi( + id: number, + data: SpecTemplateDTO.Update, +) { + return requestClient.put( + `/ec/product/spec-templates/${id}`, + data, + ); +} + +export async function replaceSpecTemplateContentApi( + id: number, + data: SpecTemplateDTO.ReplaceContent, +) { + return requestClient.put( + `/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( + `/ec/product/${productId}/specs/apply-template`, + data, + ); +} + +export async function saveProductAsSpecTemplateApi( + productId: number, + data: SpecTemplateDTO.SaveAs, +) { + return requestClient.post( + `/ec/product/${productId}/specs/save-as-template`, + data, + ); +} diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/spec/index.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/spec/index.ts new file mode 100644 index 00000000..ef89a4d5 --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/spec/index.ts @@ -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( + `/ec/product/${productId}/specs`, + ); +} + +/** 覆盖保存商品规格维 */ +export async function replaceProductSpecsApi( + productId: number, + data: ProductSpecDTO.Replace, +) { + return requestClient.put( + `/ec/product/${productId}/specs`, + data, + ); +} + +/** 按规格笛卡尔积生成缺失 SKU */ +export async function generateProductSkusApi( + productId: number, + data?: ProductSpecDTO.GenerateSkus, +) { + return requestClient.post( + `/ec/product/${productId}/specs/generate-skus`, + data ?? {}, + ); +} + +/** 按所选规格值创建 SKU(可缺维;skuCode 可自定义) */ +export async function createSkuFromSpecsApi( + productId: number, + data: ProductSpecDTO.CreateSkuFromSpecs, +) { + return requestClient.post( + `/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( + `/ec/product/${productId}/specs/skus/${skuId}`, + data ?? { specValueIds: [] }, + ); +} diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/types/types.dto.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/types/types.dto.ts index 0bb28f9f..b67979e7 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/types/types.dto.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/types/types.dto.ts @@ -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(创建时) */ diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/types/types.vo.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/types/types.vo.ts index 8b5e0d1f..8c89e87d 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/types/types.vo.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ec/product/types/types.vo.ts @@ -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; /** 运费成本 */ diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductDetailModal.vue b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductDetailModal.vue index abe54196..bbc076ef 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductDetailModal.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductDetailModal.vue @@ -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({ {{ product.createTime || '-' }} +
+ 规格维: + + {{ i > 0 ? ';' : '' }}{{ spec.name }}({{ + (spec.values ?? []) + .map((v) => `${v.valueName}/${v.valueCode}`) + .join('、') || '无值' + }}) + +
diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductFormModal.vue b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductFormModal.vue index b3aa75c8..a9e2ffcd 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductFormModal.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductFormModal.vue @@ -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(); +const productSpecEditorRef = ref | null>( + null, +); + // 创建Vben Modal实例:内容区不滚动,由 SKU 列表占满剩余高度并独立滚动 const [Modal, modalApi] = useVbenModal({ title: '添加商品', @@ -69,6 +76,9 @@ const productSkuMigrateModalRef = ref | null>(null); +const productSkuBindSpecModalRef = ref | null>(null); /** SKU 列表滚动容器:新增行后滚到底 */ const skuListScrollRef = ref(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 { if (!newImageFile.value) { @@ -1082,10 +1213,14 @@ onUnmounted(() => { - + @@ -1103,7 +1238,17 @@ onUnmounted(() => { - +
+ +
+ +
@@ -1146,7 +1291,8 @@ onUnmounted(() => { v-if="isEdit && showSkus" class="shrink-0 text-xs text-slate-400" > - 已有 SKU 的成本只读;调价请点「管理成本」。新增 SKU 仍可填初始成本。 + 已有 SKU 的成本只读;调价请点「管理成本」。新增 SKU 仍可填初始成本。已落库 + SKU 可点「规格」绑定规格维(不改编码)。

{ :pagination="false" :row-key="(r: SkuFormRow) => (isPersistedSkuId(r.id) ? String(r.id) : r._clientKey ?? '')" :scroll="{ x: 980 }" - size="small" > diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductSkuBindSpecModal.vue b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductSkuBindSpecModal.vue new file mode 100644 index 00000000..84b82d4c --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductSkuBindSpecModal.vue @@ -0,0 +1,176 @@ + + + diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductSpecEditor.vue b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductSpecEditor.vue new file mode 100644 index 00000000..dba2dd64 --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductSpecEditor.vue @@ -0,0 +1,978 @@ + + + diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/spec-template/components/SpecTemplateFormModal.vue b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/spec-template/components/SpecTemplateFormModal.vue new file mode 100644 index 00000000..958e790c --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/spec-template/components/SpecTemplateFormModal.vue @@ -0,0 +1,261 @@ + + + diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/spec-template/index.vue b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/spec-template/index.vue new file mode 100644 index 00000000..27c65a07 --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/spec-template/index.vue @@ -0,0 +1,187 @@ + + +