diff --git a/furniture-3d-system/docs/workflow/1688-dropship-integration.md b/furniture-3d-system/docs/workflow/1688-dropship-integration.md index b842d9d2..205e7278 100644 --- a/furniture-3d-system/docs/workflow/1688-dropship-integration.md +++ b/furniture-3d-system/docs/workflow/1688-dropship-integration.md @@ -21,11 +21,13 @@ archive foreign key is introduced. | After-sale cost rate | After-sale amount / real performance; blank for zero denominator | | Gross profit | Real performance - clear sales cost - send freight | | SKU operator | DF barcode/day distinct `ider`, latest nonempty value in selected period | -| Unit cost | DF barcode/day single-unit observations first; otherwise `goods_cost / goods_count`; latest available daily cost in selected period | +| Total cost | Latest available daily `unitCost + estimatedFreight` in selected period; missing components are displayed as zero | +| Unit cost | Latest available daily DF cost from `goods_count = 1` observations; the existing product cost excludes freight; missing values are displayed as zero | +| Estimated freight | Average `send_freight` for the same DF barcode/day where `goods_count = 1`; the stored value remains null when no quantity-one observations exist and the page displays zero | The archive's existing `shipAmount` continues to use `clear_goods_cost`. It must not be substituted for the dropship module's `salesAmount`. -Cost ties use single-unit frequency, total frequency, then descending unit cost. +Cost ties use quantity-one frequency, total frequency, then descending unit cost. The page displays total cost before unit cost and estimated freight. ## Deployment Prerequisites @@ -52,8 +54,8 @@ included in this change. module view permission `newProduct1688DropshipData`, images, filters, totals, and trend comparisons. The existing daily schedule then maintains the data. -The migration only adds `skuOperator` (empty by default), `unitCost` (nullable), -and `salesAmount` (nullable). Historical facts need a backfill; the ordinary +The migrations add `skuOperator` (empty by default), `unitCost` (nullable), +`estimatedFreight` (nullable), and `salesAmount` (nullable). Historical facts need a backfill; the ordinary seven-day refresh does not populate all older dates. Until backfilled, unknown sales totals display as `--`, not zero or shipped amount. diff --git a/furniture-3d-system/docs/架构设计/BOM成本预估v2-agent方案设计-20260916.md b/furniture-3d-system/docs/架构设计/BOM成本预估v2-agent方案设计-20260916.md new file mode 100644 index 00000000..5cb86c86 --- /dev/null +++ b/furniture-3d-system/docs/架构设计/BOM成本预估v2-agent方案设计-20260916.md @@ -0,0 +1,188 @@ +# BOM 成本预估 v2(agent 方案)设计文档 + +> 日期:2026-09-16 +> 状态:设计稿,待评审 +> 前置阅读:`docs/项目总览.md`、`src/server/services/bom-costing/agent/`(已建成的引擎) +> 关联会话结论:1688 以图搜图锚定为过渡方案(双重失败已实测证伪),终局为 agent 估算 + 公司数据 + +## 1. 一句话定位 + +**粘贴竞品链接 → 几分钟后得到一张诚实的成本预估卡。** + +原始需求从未变过。v2 的一切设计决策都回到这句话:数字 + 构成故事 + 诚实的区间,工序全部退到幕后。 + +## 2. v1 的教训(为什么 v2 长这样) + +| v1 的问题 | 根因 | v2 的对策 | +|---|---|---| +| 工序暴露给用户(逐图泳道、五阶段时间线、重算模式、复核流) | 工程美德当成了产品 | 一根进度条 + 一张卡;审计链存在但默认隐藏 | +| 27 个 SKU 全量核算(用户等十几分钟才见结果) | 首结果时间没有被设计 | 首批 3 个精算先出结果,其余按需点算,结果缓存 | +| 十几分钟等待 | 按 SKU 串行/并发全量跑 | case 级一次运行,2-3 分钟 | +| 复杂度随精度承诺膨胀 | 用流程堆精度 | 用数据+校准逼近精度(±10% 是"尽量"的校准目标) | +| 1688 锚定顶替估算 | 上线压力下的权宜 | 1688 永远是后台交叉验证信号 | + +**必须保留的教训**:用户会锚定数字。区间 + 置信度 + 不确定点是答案的一部分,不是脚注——这是"给一个数"和"给一个诚实的数"的差别。 + +## 3. 设计总纲(五条,裁决一切分歧) + +1. **预估,不是核算**:输出是带区间与置信度的假设生成器,供决策筛选,永不承诺报价级精度。 +2. **agent 主导分析,代码承载确定性**:看什么图、怎么拆结构、查什么价格由 agent 决定;一切数值计算(汇总、区间合成、损耗)由确定性代码完成。模型永不算数、永不编价。 +3. **价格只认公司数据**:历史 BOM 镜像是唯一定价依据(检索→分类中位→cohort→损耗四级回退);1688 行情仅作后台交叉验证,永不成为展示价。 +4. **前端来源中性(不可触碰)**:界面永不出现 1688 字样/报价/链接;一切序列化出口经过 `src/lib/bom-costing/public-estimate-text.ts`。 +5. **实测闸门**:agent 流程未经回测与真实案例对比验证(偏差分布达标)前,不替换任何线上行为。 + +## 4. 用户形态 + +### 4.1 默认入口:预估卡 + 全量 SKU 按需核算 + +**覆盖率是需求,等待时间是体验问题**——所有 SKU 都要能出结果,但采用"先出一批、其余按需点算"的渐进交付: + +``` +粘贴链接 → [进度条:抓取中 → 分析中 → 出预估](2-3 分钟)→ + +┌────────────────────────────────────────┐ +│ 源氏木语 白蜡木实木衣柜 │ +│ 预计出厂成本 ¥260 – 380(首批 3 个 SKU)│ +│ 置信度:中等 │ +│ 板材 ¥180± · 五金 ¥25± · 加工+人工 ¥60± · 包材 ¥15± │ +│ 依据:8 张商品图 + 公司历史 BOM 12 条 │ +│ 不确定:板厚未确认;铰链数量按两门推定 │ +└────────────────────────────────────────┘ +SKU 列表(27 个): + [¥260.29 已核算] (3) 原木色 0.9米两门 ← 首批自动精算 + [¥375.48 已核算] (7) 原木色 1.0米 ← 首批自动精算 + [¥406.77 已核算] (18) 原木色 1.96米 ← 首批自动精算 + [点击核算] (4) 原木色 0.9米/高2.2米 ← 用户点击后单独运行 + [点击核算] ... ← 已算结果缓存,不重跑 +──────────────────────────────────────── +商品图片(保留现有形式:主图/SKU图/详情图 分类浏览 + 大图预览) +``` + +- **首批自动精算**:默认 3 个代表性 SKU(跨度原则:最小/最大/中间,或按材质/结构差异选),2-3 分钟出卡——用户立刻有结果。 +- **其余 SKU 按需点算**:未核算的 SKU 显示占位按钮,用户点击触发单 SKU agent 运行(复用现有 per-SKU runner,1-2 分钟/个);**结果持久缓存**,重复点击不重跑。 +- 进度状态只有三个:抓取中 / 分析中 / 出预估(含失败态与重试按钮)。 +- **渐进展开**:点构成 → BOM 行明细;点行 → 证据(哪张图、哪条镜像参考行)。审计链存在,默认折叠。 +- **商品图片保留现有展示形式**(主图/SKU 图/详情图分类 + 逐图状态 + 大图预览):用户需要直接查看竞品链接内容,图片是判断依据,不是工程噪声。 + +### 4.2 深度模式(保留现有工作台) + +需要全量 27 SKU 拆解、人工核对、证据溯源的用户,从预估卡一键进入现有工作台。v2 验证前工作台不动;验证后它降级为二级入口,不再是默认。 + +## 5. 架构:case 级 agent 运行 + +### 5.1 运行编排(新,核心增量) + +交付模型:**首批自动精算 + 其余按需点算**。现有 per-SKU runner 是按需点算的执行体,case 级编排负责首批选择与结果汇总。 + +``` +阶段一:runBomCostingAgentEstimateForCase(caseId)(首批) + 1. 取案例简报(标题/渠道/已解析品类 skill)+ 归档素材 + SKU 清单(含尺寸) + 2. 代码侧选首批 SKU(默认 3 个:最小/最大/中间,或按材质/结构差异; + 单 SKU 商品即为它自己) + 3. 逐个运行现有 per-SKU agent 循环(结构行 + 查价) + 4. 代码侧汇总出 EstimateCard:卡面五行/区间/置信度 + SKU 列表状态 + (已核算 3 / 待核算 24) + +阶段二:按需点算(用户驱动) + 用户点击未核算 SKU → 单 SKU agent 运行(现有 runner)→ + 结果持久缓存 → 卡面/SKU 列表实时更新 +``` + +- 首批预算:≤24 轮 / ≤32 次模型调用 / ≤8 分钟(per-SKU 预算 × 3 + 编排开销)。 +- **结果缓存**:per-SKU 结果按 (caseId, skuId, 引擎版本) 持久化;点击已核算 SKU 直接展示缓存,不重跑。SKU 重算 = 显式刷新动作(换引擎版本或用户主动重跑)。 +- 失败语义:首批中单个 SKU 失败 → 该 SKU 标记失败可单独重试,不拖垮整卡;结构成功但价格饥饿 → 出结果但区间放宽 + 不确定点说明(PARTIAL 是合法产物)。 +- 并发上限与幂等:同一 SKU 的点算请求可去重合并(进行中重复点击返回同一运行)。 + +### 5.2 输出契约:EstimateCard(case 级) + +```ts +interface BomEstimateCard { + caseId: string + title: string + skus: Array<{ // 全量 SKU 清单 + 状态 + externalSkuId: string + name: string + status: 'ESTIMATED' | 'PENDING' | 'FAILED' | 'RUNNING' + estimate?: BomCostingAgentEstimate // 已核算时:行/区间/置信度/evidence + cachedAt?: string + }> + firstBatchSkuIds: string[] // 首批自动精算的 SKU + breakdown: Array<{ // 卡面五行(由已核算 SKU 的行汇总;随点算增长) + category: 'BOARD'|'STEEL'|'ACCESSORY'|'PACKAGING'|'PROCESSING'|'LABOR' + total: number | null // null = 该组无价,卡面显示"待补" + }> + totalRange: { min: number; max: number } // 当前已核算 SKU 的区间包络 + confidence: number // 已核算 SKU 的最小置信度 + openQuestions: string[] // 卡面"不确定"(已核算 SKU 的并集) + usage: { rounds; modelCalls; elapsedMs } +} +``` + +原则:明细(行级)保留在各 SKU 的 estimate 里供展开;卡面只消费 breakdown/totalRange/confidence/openQuestions,并随按需点算增量更新。 + +### 5.3 价格供给(核心依赖,最大缺口) + +首测"定价饥饿"的根治项——把 v1 场景服务的回退链包装成 agent 工具: + +| 优先级 | 工具 | 包装自 | +|---|---|---| +| P0 | 尺寸感知镜像检索(分类/材质词/尺寸/参考 SKU 多级过滤) | `findReferenceCandidates` | +| P0 | 分类画像中位价 | `fillCategoryProfileFallbacks` | +| P1 | 同类 cohort 报价 | `resolveCohortQuote` | +| P1 | 历史损耗率 | `applyHistoricalLossFactorFallbacks` | +| P2 | AI 补估(置信度上限 0.75 + 标记复核) | 现有 estimator | + +工具输出纪律:摘要级(无供应商/店铺/链接),带 sourceRowId 供 evidence 引用,单位明确。**1688 工具维持现状**(只透出状态/参考价/区间/可比数四个中性字段)。 + +### 5.4 数据与知识资产接入(全部保留,形态不变) + +| 资产 | v2 中的角色 | 接入形态 | +|---|---|---| +| 历史 BOM 镜像(每日 MSSQL 同步) | 唯一价格依据 | 工具(5.3) | +| 品类 Skill(5 个)+ 结构先验 | agent 脑中的专家清单:必备组件、证据纪律、校验规则 | 提示词注入(`renderBomCostingAgentSkillKnowledge`,已建成) | +| 材质目录 | 材质身份唯一权威 | 工具(已接线) | +| 商品抓取/归档/抠图 | 看图取证的素材 | 工具 + mission 组装(已接线;抠图模型待切 remove-background) | +| 1688 行情 | 后台交叉验证信号 | 工具(已接线,中性摘要) | + +### 5.5 校准闭环(±10% "尽量"的实现方式) + +- **回测**:历史 BOM 镜像抽 20-50 个真实 SKU,同一规则/agent 重算 vs 真实成本,产出误差分布(复用 `backtest:bom-cost-reference` 基建)。 +- **shadow 对比**:agent 结果与现行引擎结果对同一案例并排落库(工程域),持续记录偏差(`report:bom-cost-shadow-divergence` 同款模式)。 +- **阈值语义**:±10% 是回测循环追的校准目标(按品类分段看分布),不是单案例门禁。偏差大 → 调工具/知识/提示词 → 再回测。 +- 未过门槛 → agent 流程保持旁路,线上仍是现行方案。 + +## 6. 前端形态 + +- **新入口**:`/bom-costing` 默认视图替换为预估卡流(粘贴框 → 卡 → SKU 列表 → 图片浏览)。 +- **商品图片**:保留现有展示形式(主图/SKU 图/详情图分类 tab + 大图预览 + 逐图状态),用户需要直接查看竞品内容;它从"处理进度件"回归"内容主体"。 +- **SKU 列表**:已核算显示价格,未核算显示"点击核算"按钮(运行中显示进度态);点击结果写缓存并即时更新卡面。 +- **组件**:新 `BomEstimateCard`(平台组件体系 + 白曜石规范),状态只有 加载/成功/失败(可重试)。 +- **现有工作台**:不动,作为深度模式从卡进入。 +- **移动端**:卡、SKU 列表与图片浏览响应式。 +- 红线复检:卡面文案经过 `publicEstimateWarningText` 清洗;evidence 展开层同样不得出现来源敏感词。 + +## 7. 落地顺序(每步可独立验证) + +| 步骤 | 内容 | 验收 | +|---|---|---| +| ① | 价格回退工具(P0 两个) | 对已知案例重跑,未定价行显著下降 | +| ② | 首批编排 + EstimateCard 契约 + 按需点算与结果缓存 | 单案例 2-8 分钟出首批卡;点击未核算 SKU 增量出结果且缓存生效 | +| ③ | 预估卡前端(含 SKU 列表与现有图片浏览)+ 三态进度 | 真人走通 粘贴→出卡→点算其他 SKU→看图核对 全流程 | +| ④ | 回测 + shadow 接入,按品类出基线报告 | 误差分布报告(对照 ±10% 目标) | +| ⑤ | 实测样本扩到 5-10 案例,按品类定门槛 | 达标 → 翻转默认入口;未达标 → 继续迭代 | + +## 8. 红线(重申) + +1. 前端永不出现 1688 相关内容;一切文本出口过脱敏契约。 +2. agent 引擎在过实测闸门前保持旁路(不替换线上行为)。 +3. 区间 + 置信度 + 不确定点是答案的一部分,任何展示形态不得省略。 +4. 单价只来自工具结果;总额只由代码汇总。 +5. 现有工作台在 v2 过门槛前不删不改语义。 + +## 9. 当前资产清单(截至本文日期) + +已建成:agent 契约/工具层/循环/网关适配/skill 知识渲染/per-SKU runner(27 测试)、镜像与材质只读仓储、1688 中性摘要工具、板材开料工具、shadow 报表、trial 试跑脚本、生产真实案例(源氏木语 27 SKU)对照数据。 + +待建:价格回退工具(5.3 表)、case 级编排、EstimateCard 契约与前端、回测接入。 + +外部依赖:1688 新 key(当前过期,影响搜图与 A/B 实测,不影响 ①② 开发)。 diff --git a/furniture-3d-system/package.json b/furniture-3d-system/package.json index a3dab57a..1b33ef76 100644 --- a/furniture-3d-system/package.json +++ b/furniture-3d-system/package.json @@ -23,6 +23,9 @@ "sync:jst-sku-product-archive": "tsx scripts/sync-jst-sku-product-archive.ts", "sync:bom-cost-reference": "tsx scripts/sync-bom-cost-reference.ts", "backtest:bom-cost-reference": "tsx scripts/backtest-bom-cost-reference.ts", + "report:bom-cost-shadow-divergence": "tsx scripts/report-bom-cost-shadow-divergence.ts", + "report:bom-agent-baseline": "tsx scripts/report-bom-agent-baseline.ts", + "trial:bom-costing-agent": "tsx scripts/run-bom-costing-agent-trial.ts", "import:yunshan-created-at": "tsx scripts/import-yunshan-product-created-at.ts", "import:product-archive-drawing-media": "tsx scripts/import-product-archive-drawing-media.ts", "db:verify-master-data": "node scripts/verify-master-data-foundation.js", diff --git a/furniture-3d-system/prisma/migrations/20260916000000_add_bom_costing_agent_sku_estimate/migration.sql b/furniture-3d-system/prisma/migrations/20260916000000_add_bom_costing_agent_sku_estimate/migration.sql new file mode 100644 index 00000000..d23580b0 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20260916000000_add_bom_costing_agent_sku_estimate/migration.sql @@ -0,0 +1,21 @@ +-- CreateTable +CREATE TABLE IF NOT EXISTS "BomCostingAgentSkuEstimate" ( + "id" TEXT NOT NULL, + "caseId" TEXT NOT NULL, + "skuId" TEXT NOT NULL, + "externalSkuId" TEXT NOT NULL DEFAULT '', + "engineVersion" TEXT NOT NULL, + "status" TEXT NOT NULL, + "estimate" JSONB NOT NULL, + "usage" JSONB, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "BomCostingAgentSkuEstimate_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX IF NOT EXISTS "BomCostingAgentSkuEstimate_skuId_engineVersion_key" ON "BomCostingAgentSkuEstimate"("skuId", "engineVersion"); + +-- CreateIndex +CREATE INDEX IF NOT EXISTS "BomCostingAgentSkuEstimate_caseId_idx" ON "BomCostingAgentSkuEstimate"("caseId"); diff --git a/furniture-3d-system/prisma/migrations/20260918100000_add_dropship_1688_sourcing_tasks/migration.sql b/furniture-3d-system/prisma/migrations/20260918100000_add_dropship_1688_sourcing_tasks/migration.sql new file mode 100644 index 00000000..bfc37916 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20260918100000_add_dropship_1688_sourcing_tasks/migration.sql @@ -0,0 +1,42 @@ +CREATE TABLE "Dropship1688SourcingTask" ( + "id" TEXT NOT NULL, + "sourceArchiveId" TEXT NOT NULL, + "sourceSpu" TEXT NOT NULL DEFAULT '', + "sourceBarcode" VARCHAR(100) NOT NULL, + "sourceCostPrice" DECIMAL(24,4), + "sourceSkuOperator" TEXT NOT NULL DEFAULT '', + "sourceDateFrom" DATE NOT NULL, + "sourceDateTo" DATE NOT NULL, + "purchaserUserId" TEXT NOT NULL, + "purchaserName" TEXT NOT NULL, + "supplierName" TEXT NOT NULL DEFAULT '', + "quoted_price_tax_included" DECIMAL(24,4), + "invoiceTaxPoint" DECIMAL(8,4), + "sourcingMode" TEXT NOT NULL DEFAULT '', + "jianshangBarcode" TEXT NOT NULL DEFAULT '', + "acceptedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "Dropship1688SourcingTask_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "Dropship1688SourcingTask_sourceBarcode_purchaserUserId_key" + ON "Dropship1688SourcingTask"("sourceBarcode", "purchaserUserId"); + +CREATE INDEX "Dropship1688SourcingTask_sourceArchiveId_idx" + ON "Dropship1688SourcingTask"("sourceArchiveId"); + +CREATE INDEX "Dropship1688SourcingTask_purchaserName_idx" + ON "Dropship1688SourcingTask"("purchaserName"); + +CREATE INDEX "Dropship1688SourcingTask_sourceSpu_idx" + ON "Dropship1688SourcingTask"("sourceSpu"); + +CREATE INDEX "Dropship1688SourcingTask_sourceSkuOperator_idx" + ON "Dropship1688SourcingTask"("sourceSkuOperator"); + +CREATE INDEX "Dropship1688SourcingTask_purchaserUserId_acceptedAt_idx" + ON "Dropship1688SourcingTask"("purchaserUserId", "acceptedAt"); + +CREATE INDEX "Dropship1688SourcingTask_acceptedAt_idx" + ON "Dropship1688SourcingTask"("acceptedAt"); diff --git a/furniture-3d-system/prisma/migrations/20260918180000_add_dropship_estimated_freight/migration.sql b/furniture-3d-system/prisma/migrations/20260918180000_add_dropship_estimated_freight/migration.sql new file mode 100644 index 00000000..8c430c72 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20260918180000_add_dropship_estimated_freight/migration.sql @@ -0,0 +1,3 @@ +-- Store the quantity-one freight estimate separately from the existing total freight fact. +ALTER TABLE "SupplyChainProductArchiveSalesPerformanceDaily" + ADD COLUMN "estimatedFreight" DECIMAL(24,4); diff --git a/furniture-3d-system/prisma/schema.prisma b/furniture-3d-system/prisma/schema.prisma index 03f98c1d..fd577b2c 100644 --- a/furniture-3d-system/prisma/schema.prisma +++ b/furniture-3d-system/prisma/schema.prisma @@ -781,6 +781,7 @@ model SupplyChainProductArchiveSalesPerformanceDaily { // DF daily enrichment; empty/null until the source history is backfilled. skuOperator String @default("") unitCost Decimal? @db.Decimal(24, 4) + estimatedFreight Decimal? @db.Decimal(24, 4) // Separate from shipAmount; NULL denotes history not yet refreshed. salesAmount Decimal? @db.Decimal(24, 4) shipAmount Decimal @db.Decimal(24, 4) @@ -807,6 +808,36 @@ model SupplyChainProductArchiveSalesPerformanceDaily { @@index([syncedAt]) } +// 1688 代发商品的采购寻源承接快照。 +// 不建立业务外键:商品档案或账号变化后,仍需保留承接时的条码、人员和成本依据。 +model Dropship1688SourcingTask { + id String @id @default(cuid()) + sourceArchiveId String + sourceSpu String @default("") + sourceBarcode String @db.VarChar(100) + sourceCostPrice Decimal? @db.Decimal(24, 4) + sourceSkuOperator String @default("") + sourceDateFrom DateTime @db.Date + sourceDateTo DateTime @db.Date + purchaserUserId String + purchaserName String + supplierName String @default("") + quotedPriceTaxIncluded Decimal? @map("quoted_price_tax_included") @db.Decimal(24, 4) + invoiceTaxPoint Decimal? @db.Decimal(8, 4) + sourcingMode String @default("") + jianshangBarcode String @default("") + acceptedAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@unique([sourceBarcode, purchaserUserId]) + @@index([sourceArchiveId]) + @@index([purchaserName]) + @@index([sourceSpu]) + @@index([sourceSkuOperator]) + @@index([purchaserUserId, acceptedAt]) + @@index([acceptedAt]) +} + model SupplyChainProductArchiveSalesSyncRun { id String @id @default(cuid()) startedAt DateTime @default(now()) @@ -4313,3 +4344,21 @@ model HomeQuickLink { @@index([enabled, sortOrder]) } + +/// BOM agent 旁路引擎的单 SKU 估算缓存(工程域;主键语义:skuId + engineVersion)。 +/// 纯新增表,不与现有业务模型建外键关系;在 agent 流程过实测闸门前仅供工程侧工具使用。 +model BomCostingAgentSkuEstimate { + id String @id @default(cuid()) + caseId String + skuId String + externalSkuId String @default("") + engineVersion String + status String + estimate Json + usage Json? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@unique([skuId, engineVersion]) + @@index([caseId]) +} diff --git a/furniture-3d-system/scripts/report-bom-agent-baseline.ts b/furniture-3d-system/scripts/report-bom-agent-baseline.ts new file mode 100644 index 00000000..1ba2c9d1 --- /dev/null +++ b/furniture-3d-system/scripts/report-bom-agent-baseline.ts @@ -0,0 +1,281 @@ +import { loadEnvConfig } from '@next/env' +import { Prisma } from '@prisma/client' +import { mkdir, writeFile } from 'node:fs/promises' +import path from 'node:path' +import { bomCostingScenarioRepository } from '../src/server/repositories/bom-costing-scenario.repository' + +loadEnvConfig(process.cwd()) + +/** + * BOM agent 基线报告(工程域,第④步 · 第一部分): + * 1) 定价覆盖率探测——对既有案例的 BOM 行,用新的回退工具链 + * (尺寸感知候选检索 → 分类画像中位)做确定性试定价,零模型费用, + * 回答“定价饥饿根治了吗”。 + * 2) shadow 偏差聚合——读取 agent 缓存表中已核算 SKU,对比现行引擎落库价格。 + * 缓存为空时提示先运行 trial --card。 + * 输出只进工程域(stdout / --json)。 + */ + +type CliOptions = { caseId: string; json: boolean } + +function parseArgs(argv: string[]): CliOptions { + const options: CliOptions = { caseId: '', json: false } + for (const argument of argv) { + if (argument === '--help' || argument === '-h') { + console.log([ + '用法: npm run report:bom-agent-baseline -- --case=<案例ID> [--json]', + '', + ' --case= 指定 READY 案例 ID', + ' --json 以 JSON 输出完整报告', + ].join('\n')) + process.exit(0) + } else if (argument.startsWith('--case=')) { + options.caseId = argument.slice('--case='.length).trim() + } else if (argument === '--json') { + options.json = true + } else { + throw new Error(`未知参数:${argument}(--help 查看用法)`) + } + } + if (!options.caseId) throw new Error('必须指定 --case=<案例ID>') + return options +} + +interface LineProbe { + lineId: string + category: string + partName: string + materialName: string + v1Priced: boolean + candidatesHit: boolean + profileFallback: boolean + candidateCount: number + candidateUnitPriceRange: [number, number] | null +} + +function decimalNumber(value: unknown): number | null { + if (value === null || value === undefined) return null + const parsed = Number(value) + return Number.isFinite(parsed) ? parsed : null +} + +// 隧道不稳定(已知,远端频繁重置连接):对连接类失败做长容忍重试。 +async function withRetry(operation: () => Promise, attempts = 8): Promise { + let lastError: unknown + for (let attempt = 1; attempt <= attempts; attempt += 1) { + try { + return await operation() + } catch (error) { + lastError = error + const message = String(error instanceof Error ? error.message : error) + if (!/Connection terminated|Can't reach database|timed out|Closed|reset/i.test(message)) throw error + await new Promise((resolve) => setTimeout(resolve, 2_000)) + } + } + throw lastError +} + +async function probeLine(syncRunId: string, line: { + id: string + category: string + partName: string + materialName: string + lengthMm: Prisma.Decimal | null + widthMm: Prisma.Decimal | null + resolvedUnitPrice: Prisma.Decimal | null +}): Promise { + const candidates = await withRetry(() => bomCostingScenarioRepository.findReferenceCandidates({ + syncRunId, + category: line.category, + partName: line.partName || null, + materialName: line.materialName || null, + lengthMm: decimalNumber(line.lengthMm), + widthMm: decimalNumber(line.widthMm), + limit: 10, + })) + let profileFallback = false + if (candidates.length === 0) { + const cohortCandidates = await withRetry(() => bomCostingScenarioRepository.findCategoryCohortCandidates({ + syncRunId, + category: line.category, + limit: 500, + })) + profileFallback = cohortCandidates.length > 0 + } + const prices = candidates + .map((candidate) => decimalNumber(candidate.unitPrice)) + .filter((value): value is number => value !== null && value > 0) + return { + lineId: line.id, + category: line.category, + partName: line.partName, + materialName: line.materialName, + v1Priced: decimalNumber(line.resolvedUnitPrice) !== null, + candidatesHit: candidates.length > 0, + profileFallback, + candidateCount: candidates.length, + candidateUnitPriceRange: prices.length > 0 + ? [Math.min(...prices), Math.max(...prices)] + : null, + } +} + +async function main() { + const options = parseArgs(process.argv.slice(2)) + await mkdir(path.join(process.cwd(), 'node_modules', 'server-only'), { recursive: true }) + await writeFile(path.join(process.cwd(), 'node_modules', 'server-only', 'index.js'), 'module.exports = {}\n') + const { prisma } = await import('../src/lib/prisma') + try { + const { latestSuccessful } = await withRetry(() => bomCostingScenarioRepository.findLatestSyncStatuses()) + if (!latestSuccessful) throw new Error('镜像没有成功同步批次,无法探测') + const skus = await withRetry(() => prisma.bomCostingSku.findMany({ + where: { caseId: options.caseId }, + orderBy: { sortOrder: 'asc' }, + select: { + id: true, + externalSkuId: true, + name: true, + bomLines: { + select: { + id: true, + category: true, + partName: true, + materialName: true, + lengthMm: true, + widthMm: true, + resolvedUnitPrice: true, + }, + }, + }, + })) + if (skus.length === 0) throw new Error('案例没有 SKU') + + // shadow 部分:agent 缓存(可能为空;表未迁移时降级为不可用) + let cached: Array<{ skuId: string; status: string; estimate: unknown }> = [] + let cacheUnavailable: string | null = null + try { + cached = await prisma.bomCostingAgentSkuEstimate.findMany({ + where: { caseId: options.caseId, engineVersion: 'bom-costing-agent-card/v1' }, + select: { skuId: true, status: true, estimate: true }, + }) + } catch { + cacheUnavailable = '缓存表未创建(迁移未应用),shadow 对比暂不可用' + } + const scenarioBySku = new Map( + (await withRetry(() => prisma.bomCostingScenario.findMany({ + where: { caseId: options.caseId, kind: 'SAME_MATERIAL', isCurrent: true }, + select: { skuId: true, totalCost: true, realtimeMarketQuote: true }, + }))).map((scenario) => [scenario.skuId, scenario]), + ) + // v1 的行级定价在场景行(动态成本阶段),不在源 BOM 行的 resolvedUnitPrice。 + const scenarioLinesBySku = new Map() + const scenarioLines = await withRetry(() => prisma.bomCostingScenarioLine.findMany({ + where: { scenario: { caseId: options.caseId, kind: 'SAME_MATERIAL', isCurrent: true } }, + select: { unitPrice: true, subtotal: true, estimateLow: true, scenario: { select: { skuId: true } } }, + })) + for (const line of scenarioLines) { + const lineSkuId = line.scenario.skuId + const entry = scenarioLinesBySku.get(lineSkuId) ?? { priced: 0, total: 0 } + entry.total += 1 + if ( + (line.unitPrice !== null && Number(line.unitPrice) > 0) || + line.subtotal !== null || line.estimateLow !== null + ) entry.priced += 1 + scenarioLinesBySku.set(lineSkuId, entry) + } + + const skuReports: Array> = [] + let totalLines = 0 + let totalCandidatesHit = 0 + let totalProfileFallback = 0 + let totalV1Priced = 0 + const categoryStats = new Map() + + // 只探测前 3 个 SKU(覆盖探测是确定性的,3 个足以代表;全量探测耗时线性增长) + let totalV1Lines = 0 + for (const sku of skus.slice(0, 3)) { + const probes: LineProbe[] = [] + for (const line of sku.bomLines) { + probes.push(await probeLine(latestSuccessful.id, line)) + } + const candidatesHit = probes.filter((probe) => probe.candidatesHit).length + const profileFallback = probes.filter((probe) => probe.profileFallback && !probe.candidatesHit).length + totalLines += probes.length + totalCandidatesHit += candidatesHit + totalProfileFallback += profileFallback + for (const probe of probes) { + const stats = categoryStats.get(probe.category) ?? { lines: 0, candidatesHit: 0, profileFallback: 0, v1Priced: 0 } + stats.lines += 1 + if (probe.candidatesHit) stats.candidatesHit += 1 + else if (probe.profileFallback) stats.profileFallback += 1 + categoryStats.set(probe.category, stats) + } + const scenario = scenarioBySku.get(sku.id) + const quote = (scenario?.realtimeMarketQuote ?? null) as Record | null + const cachedEstimate = cached.find((entry) => entry.skuId === sku.id) + const v1ScenarioLines = scenarioLinesBySku.get(sku.id) ?? { priced: 0, total: 0 } + totalV1Priced += v1ScenarioLines.priced + totalV1Lines += v1ScenarioLines.total + skuReports.push({ + externalSkuId: sku.externalSkuId, + name: sku.name.slice(0, 20), + lines: probes.length, + candidatesHit, + profileFallback, + unpriced: probes.length - candidatesHit - profileFallback, + v1Priced: v1ScenarioLines.priced, + v1LineTotal: v1ScenarioLines.total, + currentEngineTotal: scenario?.totalCost === null || scenario?.totalCost === undefined ? null : Number(scenario.totalCost), + structuralCost: quote?.structuralCost ?? null, + anchorCost: quote?.procurementCost ?? null, + agentCached: cachedEstimate ? cachedEstimate.status : 'NONE', + }) + } + + const report = { + caseId: options.caseId, + probedSkuCount: Math.min(3, skus.length), + totalSkuCount: skus.length, + priceCoverage: { + totalLines, + candidatesHit: totalCandidatesHit, + profileFallback: totalProfileFallback, + unpriced: totalLines - totalCandidatesHit - totalProfileFallback, + coveragePct: totalLines === 0 ? null : Number((((totalCandidatesHit + totalProfileFallback) / totalLines) * 100).toFixed(1)), + v1Priced: totalV1Priced, + v1CoveragePct: totalV1Lines === 0 ? null : Number(((totalV1Priced / totalV1Lines) * 100).toFixed(1)), + }, + byCategory: [...categoryStats.entries()].map(([category, stats]) => ({ category, ...stats })), + skus: skuReports, + shadow: { + cachedSkuCount: cached.length, + note: cacheUnavailable ?? (cached.length === 0 ? '缓存为空:先运行 trial --card 生成 agent 结果后重跑本报告' : undefined), + }, + generatedAt: new Date().toISOString(), + } + + if (options.json) { + console.log(JSON.stringify(report, null, 2)) + } else { + console.log(`案例 ${options.caseId} 基线探测(前 ${report.probedSkuCount}/${report.totalSkuCount} SKU,${totalLines} 行)`) + console.log(`新工具链覆盖:候选命中 ${totalCandidatesHit} + 画像兜底 ${totalProfileFallback} = ${report.priceCoverage.coveragePct}%(未定价 ${report.priceCoverage.unpriced})`) + console.log(`v1 场景行已定价:${totalV1Priced}/${totalV1Lines}(${report.priceCoverage.v1CoveragePct}%)`) + console.log('--- 按分类 ---') + for (const [category, stats] of categoryStats) { + console.log(` ${category}: ${stats.lines} 行,候选 ${stats.candidatesHit},画像 ${stats.profileFallback}`) + } + console.log('--- 逐 SKU ---') + for (const sku of skuReports) { + console.log(` ${sku.externalSkuId} ${sku.name} | 行=${sku.lines} 候选=${sku.candidatesHit} 画像=${sku.profileFallback} 未定价=${sku.unpriced} | v1定价行=${sku.v1Priced}/${sku.v1LineTotal} | 现行总价=${sku.currentEngineTotal} 结构=${sku.structuralCost} 锚定=${sku.anchorCost} | agent缓存=${sku.agentCached}`) + } + console.log(`shadow:${report.shadow.cachedSkuCount} 个缓存结果${report.shadow.note ? `(${report.shadow.note})` : ''}`) + } + } finally { + await prisma.$disconnect() + } +} + +main().catch((error) => { + console.error(error instanceof Error ? error.message : error) + process.exit(1) +}) diff --git a/furniture-3d-system/scripts/run-bom-costing-agent-trial.ts b/furniture-3d-system/scripts/run-bom-costing-agent-trial.ts index 2c0c7082..64ca9492 100644 --- a/furniture-3d-system/scripts/run-bom-costing-agent-trial.ts +++ b/furniture-3d-system/scripts/run-bom-costing-agent-trial.ts @@ -26,6 +26,7 @@ type CliOptions = { skuId: string | null maxImages: number json: boolean + card: boolean } const DEFAULT_MAX_IMAGES = 8 @@ -37,15 +38,18 @@ function parseArgs(argv: string[]): CliOptions { skuId: null, maxImages: DEFAULT_MAX_IMAGES, json: false, + card: false, } for (const argument of argv) { if (argument === '--help' || argument === '-h') { console.log([ '用法: npm run trial:bom-costing-agent -- --case=<案例ID> [--sku=] [--max-images=N] [--json]', + ' 或: npm run trial:bom-costing-agent -- --case=<案例ID> --card [--json] (case 级预估卡:首批自动精算)', ' 或: npm run trial:bom-costing-agent -- --latest=N (最近 N 个 READY 案例的主 SKU)', '', ' --case= 指定案例 ID(与 --latest 二选一)', ' --sku= 指定 SKU 记录 ID(默认取排序最前的 SKU)', + ' --card case 级运行:首批代表 SKU 精算并输出预估卡(其余 SKU 可用 --sku 按需点算)', ' --max-images=N 送入模型的图片上限,默认 8', ' --json 以 JSON 输出完整结果(含 trace)', '', @@ -68,6 +72,8 @@ function parseArgs(argv: string[]): CliOptions { throw new Error('--max-images must be an integer between 1 and 16') } options.maxImages = maxImages + } else if (argument === '--card') { + options.card = true } else if (argument === '--json') { options.json = true } else { @@ -90,8 +96,55 @@ function agentTotalFromResult(result: BomCostingAgentRunResult) { return Math.round(total * 100) / 100 } +async function runCardMode(options: CliOptions) { + await ensureServerOnlyStub() + const { prisma } = await import('../src/lib/prisma') + const { runBomCostingAgentEstimateForCase, estimateSkuOnDemand } = await import( + '../src/server/services/bom-costing/agent/bom-costing-agent-case-runner' + ) + try { + if (!options.caseId) throw new Error('--card 模式必须指定 --case=<案例ID>') + console.log(`case 级预估卡运行中(首批自动精算):case=${options.caseId}`) + const { card } = await runBomCostingAgentEstimateForCase({ + caseId: options.caseId, + options: { maxImages: options.maxImages }, + }) + if (options.json) { + console.log(JSON.stringify(card, null, 2)) + return + } + console.log(`\n=== ${card.title} ===`) + console.log(`预计出厂成本区间(已核算 ${card.estimatedSkuCount} SKU):${card.totalRange ? `¥${card.totalRange.min} ~ ¥${card.totalRange.max}` : '--'}`) + console.log(`置信度:${card.confidence === null ? '--' : `${Math.round(card.confidence * 100)}%`}`) + console.log('构成:' + card.breakdown.map((row) => `${row.category} ${row.total === null ? '待补' : `¥${row.total}`}`).join(' · ')) + if (card.openQuestions.length > 0) { + console.log('不确定:' + card.openQuestions.slice(0, 5).join(';')) + } + console.log('') + for (const sku of card.skus) { + const marker = sku.firstBatch ? '[首批]' : ' ' + const price = sku.status === 'ESTIMATED' && sku.estimate + ? `¥${sku.estimate.estimateRange.min}~${sku.estimate.estimateRange.max}` + : sku.status === 'FAILED' ? '核算失败(可重试)' : '点击核算' + console.log(` ${marker} ${sku.externalSkuId} ${sku.name.slice(0, 22)} | ${price}`) + } + if (options.skuId) { + console.log(`\n按需点算:sku=${options.skuId}`) + const entry = await estimateSkuOnDemand({ caseId: options.caseId, skuId: options.skuId }) + const estimate = entry.runResult?.estimate + console.log(` 结果:${entry.status}${estimate ? ` ¥${estimate.estimateRange.min}~${estimate.estimateRange.max} 置信度 ${Math.round(estimate.confidence * 100)}%` : ''}`) + } + } finally { + await prisma.$disconnect() + } +} + async function main() { const options = parseArgs(process.argv.slice(2)) + if (options.card) { + await runCardMode(options) + return + } await ensureServerOnlyStub() const { prisma } = await import('../src/lib/prisma') const { runBomCostingAgentTrialForSku } = await import( diff --git a/furniture-3d-system/src/app/api/bom-costing/cases/[id]/agent-estimate/route.ts b/furniture-3d-system/src/app/api/bom-costing/cases/[id]/agent-estimate/route.ts new file mode 100644 index 00000000..0100ca98 --- /dev/null +++ b/furniture-3d-system/src/app/api/bom-costing/cases/[id]/agent-estimate/route.ts @@ -0,0 +1,79 @@ +import { NextRequest } from 'next/server' +import { AppError, ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { bomCostingAccessService } from '@/server/services/bom-costing/bom-costing-access.service' +import { bomCostingAgentRepository } from '@/server/repositories/bom-costing-agent.repository' +import { + estimateSkuOnDemand, + getAgentEstimateCard, + runBomCostingAgentEstimateForCase, +} from '@/server/services/bom-costing/agent/bom-costing-agent-case-runner' + +type RouteContext = { + params: Promise<{ id: string }> +} + +async function buildCasePreview(caseId: string) { + const card = await getAgentEstimateCard(caseId) + if (!card) throw new AppError(ErrorCode.BOM_COSTING_CASE_NOT_FOUND) + const assets = await bomCostingAgentRepository.listArchivedAssetsForCase(caseId) + return { + card, + images: assets.map((asset) => ({ + assetId: asset.id, + kind: asset.kind, + url: asset.storedUrl || asset.originalUrl, + skuTags: Array.isArray(asset.externalSkuIds) + ? (asset.externalSkuIds as unknown[]).filter((item): item is string => + typeof item === 'string' && item.trim() !== '') + : [], + })), + } +} + +export async function GET(request: NextRequest, context: RouteContext) { + return handleRequest( + request, + async (ctx) => { + const { id } = await context.params + try { + await bomCostingAccessService.assertCanView(ctx.user) + return jsonSuccess(await buildCasePreview(decodeURIComponent(id)), 200, ctx.requestId) + } catch (error) { + if (error instanceof AppError) { + return jsonError(error.code, error.message, error.statusCode, ctx.requestId) + } + throw error + } + }, + { requireAuth: true }, + ) +} + +export async function POST(request: NextRequest, context: RouteContext) { + return handleRequest( + request, + async (ctx) => { + const { id } = await context.params + const caseId = decodeURIComponent(id) + try { + await bomCostingAccessService.assertCanView(ctx.user) + const body = await request.json().catch(() => ({})) as { skuId?: string } + // agent 估算走旁路引擎:POST 触发运行(case 首批 或 单 SKU 按需), + // 完成后返回聚合卡片。运行时长可达数分钟,调用方需耐心等待。 + if (body.skuId) { + await estimateSkuOnDemand({ caseId, skuId: body.skuId }) + } else { + await runBomCostingAgentEstimateForCase({ caseId }) + } + return jsonSuccess(await buildCasePreview(caseId), 200, ctx.requestId) + } catch (error) { + if (error instanceof AppError) { + return jsonError(error.code, error.message, error.statusCode, ctx.requestId) + } + throw error + } + }, + { requireAuth: true }, + ) +} diff --git a/furniture-3d-system/src/app/api/installation-demo-workbench/share/route.ts b/furniture-3d-system/src/app/api/installation-demo-workbench/share/route.ts index 43cfe07b..2970e5ba 100644 --- a/furniture-3d-system/src/app/api/installation-demo-workbench/share/route.ts +++ b/furniture-3d-system/src/app/api/installation-demo-workbench/share/route.ts @@ -4,6 +4,40 @@ import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' import { installationDemoShareService } from '@/server/services' import { buildInstallationDemoShareUrl } from './share-url' +export async function GET(request: NextRequest) { + return handleRequest( + request, + async (ctx) => { + try { + const snapshot = await installationDemoShareService.getOwned( + ctx.user, + request.nextUrl.searchParams.get('drawingId'), + ) + return jsonSuccess( + { + share: snapshot + ? { + token: snapshot.token, + url: buildInstallationDemoShareUrl(snapshot.token, request.nextUrl.origin), + expiresAt: snapshot.expiresAt, + snapshot, + } + : null, + }, + 200, + ctx.requestId, + ) + } catch (error) { + if (error instanceof AppError) { + return jsonError(error.code, error.message, error.statusCode, ctx.requestId) + } + throw error + } + }, + { requireAuth: true }, + ) +} + export async function POST(request: NextRequest) { return handleRequest( request, diff --git a/furniture-3d-system/src/app/api/installation-demo-workbench/share/sync/route.ts b/furniture-3d-system/src/app/api/installation-demo-workbench/share/sync/route.ts new file mode 100644 index 00000000..4937ba06 --- /dev/null +++ b/furniture-3d-system/src/app/api/installation-demo-workbench/share/sync/route.ts @@ -0,0 +1,44 @@ +import { NextRequest } from 'next/server' +import { AppError, ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { installationDemoShareService } from '@/server/services' +import { buildInstallationDemoShareUrl } from '../share-url' + +export async function POST(request: NextRequest) { + return handleRequest( + request, + async (ctx) => { + try { + const body = await request.json().catch(() => ({})) + const token = (body as { token?: unknown } | null)?.token + if (typeof token !== 'string' || !token.trim()) { + return jsonError( + ErrorCode.VALIDATION_REQUIRED_FIELD, + '缺少分享链接 token', + 400, + ctx.requestId, + ) + } + const snapshot = await installationDemoShareService.sync(ctx.user, body, token) + return jsonSuccess( + { + share: { + token: snapshot.token, + url: buildInstallationDemoShareUrl(snapshot.token, request.nextUrl.origin), + expiresAt: snapshot.expiresAt, + snapshot, + }, + }, + 200, + ctx.requestId, + ) + } catch (error) { + if (error instanceof AppError) { + return jsonError(error.code, error.message, error.statusCode, ctx.requestId) + } + throw error + } + }, + { requireAuth: true }, + ) +} diff --git a/furniture-3d-system/src/app/api/internal/operation-logs/failure-notification/run/route.ts b/furniture-3d-system/src/app/api/internal/operation-logs/failure-notification/run/route.ts new file mode 100644 index 00000000..156be21c --- /dev/null +++ b/furniture-3d-system/src/app/api/internal/operation-logs/failure-notification/run/route.ts @@ -0,0 +1,28 @@ +import { NextRequest } from 'next/server' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { ErrorCode } from '@/server/core/errors' +import { operationLogFailureNotificationService } from '@/server/services/operation-log-failure-notification.service' + +async function runTestPush() { + const result = await operationLogFailureNotificationService.sendTestNotification() + return jsonSuccess(result, 200) +} + +// 排障与验收入口:携带 worker 密钥触发;管理员(徐霞客)会话触发。 +export async function POST(request: NextRequest) { + const expectedSecret = process.env.BOM_COSTING_WORKER_SECRET || '' + const providedSecret = request.headers.get('x-worker-secret') || '' + if (expectedSecret && providedSecret === expectedSecret) { + return runTestPush() + } + return handleRequest( + request, + async (ctx) => { + if (ctx.user?.name !== '徐霞客') { + return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '仅徐霞客可触发失败日志通知测试', 403, ctx.requestId) + } + return runTestPush() + }, + { requireAuth: true }, + ) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/filter-options/route.test.ts b/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/filter-options/route.test.ts index e8b48b78..e1168769 100644 --- a/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/filter-options/route.test.ts +++ b/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/filter-options/route.test.ts @@ -28,11 +28,12 @@ describe('1688 dropship filter options route', () => { it('uses the authenticated supply-chain permission wrapper and preserves exact filter values', async () => { const response = await GET(request({ field: 'sku', dateFrom: '2026-09-01', dateTo: '2026-09-07', + keyword: '卧室', optionQuery: '白色', columnFilters: JSON.stringify({ spu: { mode: 'include', values: ['', ' DF-1 ', ' DF-1 '] } }), })) expect(handleRequest).toHaveBeenCalledWith(expect.anything(), expect.any(Function), { requireAuth: true }) expect(dropship1688DataService.listFilterOptions).toHaveBeenCalledWith({ - field: 'sku', keyword: '', dateFrom: '2026-09-01', dateTo: '2026-09-07', + field: 'sku', keyword: '卧室', optionQuery: '白色', dateFrom: '2026-09-01', dateTo: '2026-09-07', filters: { spu: { mode: 'include', values: ['', ' DF-1 '] } }, }) expect(response).toMatchObject({ success: true, data: { values: ['', 'SKU-1'] }, status: 200 }) @@ -42,6 +43,7 @@ describe('1688 dropship filter options route', () => { { field: 'color' }, { field: 'sku', dateFrom: '2026-02-31' }, { field: 'sku', columnFilters: '{' }, + { field: 'sku', optionQuery: 'x'.repeat(501) }, { field: 'sku', columnFilters: JSON.stringify({ sku: { mode: 'include', values: [3] } }) }, { field: 'sku', columnFilters: JSON.stringify({ other: { mode: 'include', values: [] } }) }, ])('rejects invalid filter input: %j', async (params) => { @@ -53,17 +55,22 @@ describe('1688 dropship filter options route', () => { const values = Array.from({ length: 5000 }, (_, index) => `DF-SKU-${index}`) const response = await POST({ headers: new Headers(), - json: async () => ({ field: 'spu', filters: { sku: { mode: 'include', values } } }), + json: async () => ({ + field: 'spu', keyword: '卧室', optionQuery: '白色', + filters: { sku: { mode: 'include', values } }, + }), } as NextRequest) expect(response).toMatchObject({ success: true, status: 200 }) expect(handleRequest).toHaveBeenCalledWith(expect.anything(), expect.any(Function), { requireAuth: true }) const input = jest.mocked(dropship1688DataService.listFilterOptions).mock.calls[0][0] expect(new Set(input.filters?.sku?.values)).toEqual(new Set(values)) + expect(input).toMatchObject({ field: 'spu', keyword: '卧室', optionQuery: '白色' }) }) it.each([ { field: 'color' }, { field: 'sku', dateTo: '2026-02-31' }, + { field: 'sku', optionQuery: 'x'.repeat(501) }, { field: 'sku', filters: { sku: { mode: 'include', values: [3] } } }, ])('rejects invalid POST input: %j', async (body) => { expect(await POST({ headers: new Headers(), json: async () => body } as NextRequest)).toMatchObject({ success: false, status: 400 }) diff --git a/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/filter-options/route.ts b/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/filter-options/route.ts index bc10820a..369eeb36 100644 --- a/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/filter-options/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/filter-options/route.ts @@ -13,6 +13,7 @@ const dateSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine((value) => { const querySchema = z.object({ field: z.enum(FILTER_FIELDS), keyword: z.string().max(500).optional().default(''), + optionQuery: z.string().max(500).optional().default(''), dateFrom: dateSchema.optional(), dateTo: dateSchema.optional(), columnFilters: z.string().max(500_000).optional(), @@ -27,6 +28,7 @@ export async function GET(request: NextRequest) { const parsed = querySchema.safeParse({ field: request.nextUrl.searchParams.get('field') || undefined, keyword: request.nextUrl.searchParams.get('keyword') || undefined, + optionQuery: request.nextUrl.searchParams.get('optionQuery') || undefined, dateFrom: request.nextUrl.searchParams.get('dateFrom') || undefined, dateTo: request.nextUrl.searchParams.get('dateTo') || undefined, columnFilters: request.nextUrl.searchParams.get('columnFilters') || undefined, @@ -47,6 +49,7 @@ export async function GET(request: NextRequest) { const data = await dropship1688DataService.listFilterOptions({ field: parsed.data.field, keyword: parsed.data.keyword, + optionQuery: parsed.data.optionQuery, dateFrom: parsed.data.dateFrom, dateTo: parsed.data.dateTo, filters: normalizeDropship1688Filters(validation.data), diff --git a/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-export/route.test.ts b/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-export/route.test.ts new file mode 100644 index 00000000..78d9df34 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-export/route.test.ts @@ -0,0 +1,49 @@ +/** @jest-environment node */ + +const mockHandleRequest = jest.fn() +const mockListTasksForExport = jest.fn() + +jest.mock('@/server/core/response', () => ({ + handleRequest: (...args: unknown[]) => mockHandleRequest(...args), +})) +jest.mock('@/server/services/dropship-1688-sourcing.service', () => ({ + dropship1688SourcingService: { + listTasksForExport: (...args: unknown[]) => mockListTasksForExport(...args), + }, +})) + +import ExcelJS from 'exceljs' +import { POST } from './route' + +describe('POST sourcing export', () => { + beforeEach(() => { + jest.clearAllMocks() + mockHandleRequest.mockImplementation(async (_request, handler) => handler({ requestId: 'request-1' })) + mockListTasksForExport.mockResolvedValue([{ + id: 'task-1', sourceArchiveId: 'archive-1', sourceSpu: 'SPU-ONE', sourceBarcode: 'DF-ONE', + sourceCostPrice: '34.2900', sourceSkuOperator: '运营甲', sourceDateFrom: '2026-09-01', + sourceDateTo: '2026-09-10', purchaserUserId: 'buyer-1', purchaserName: '采购甲', + supplierName: '', quotedPriceTaxIncluded: '50.0000', invoiceTaxPoint: '13.0000', + sourcingMode: '代发', jianshangBarcode: 'JS-001', acceptedAt: '', updatedAt: '', + sku: 'SKU-ONE', hasImage: false, + }]) + }) + + it('exports every row matching the server-side filters as a round-trip workbook', async () => { + const filters = { + purchaserNames: ['采购甲'], + sourceSpus: ['SPU-ONE'], + sourceSkuOperators: ['运营甲'], + } + const response = await POST({ json: async () => ({ filters }) } as never) + expect(mockListTasksForExport).toHaveBeenCalledWith({ filters }) + expect(response.headers.get('content-type')).toContain('spreadsheetml.sheet') + expect(response.headers.get('content-disposition')).toContain('.xlsx') + expect(response.headers.get('x-exported-rows')).toBe('1') + + const workbook = new ExcelJS.Workbook() + await workbook.xlsx.load(Buffer.from(await response.arrayBuffer()) as ExcelJS.Buffer) + expect(workbook.getWorksheet('寻源明细')?.getCell('B2').value).toBe('DF-ONE') + expect(workbook.getWorksheet('寻源明细')?.getCell('H2').value).toBe('采购甲') + }) +}) diff --git a/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-export/route.ts b/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-export/route.ts new file mode 100644 index 00000000..b0a40e1f --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-export/route.ts @@ -0,0 +1,29 @@ +import { NextRequest, NextResponse } from 'next/server' +import { + createDropship1688SourcingWorkbook, + DROPSHIP_1688_SOURCING_WORKBOOK_MIME, +} from '@/lib/dropship-1688-sourcing-workbook' +import { handleRequest } from '@/server/core/response' +import { dropship1688SourcingService } from '@/server/services/dropship-1688-sourcing.service' + +export async function POST(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const tasks = await dropship1688SourcingService.listTasksForExport( + await request.json().catch(() => null), + ) + const workbook = await createDropship1688SourcingWorkbook(tasks) + const body = new ArrayBuffer(workbook.byteLength) + new Uint8Array(body).set(workbook) + const date = new Date().toISOString().slice(0, 10) + const fileName = encodeURIComponent(`1688代发寻源明细-${date}.xlsx`) + return new NextResponse(body, { + headers: { + 'Content-Type': DROPSHIP_1688_SOURCING_WORKBOOK_MIME, + 'Content-Disposition': `attachment; filename*=UTF-8''${fileName}`, + 'Cache-Control': 'private, no-store', + 'X-Exported-Rows': String(tasks.length), + 'X-Request-Id': ctx.requestId, + }, + }) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-import/route.test.ts b/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-import/route.test.ts new file mode 100644 index 00000000..48134357 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-import/route.test.ts @@ -0,0 +1,90 @@ +/** @jest-environment node */ + +const mockHandleRequest = jest.fn() +const mockJsonSuccess = jest.fn() +const mockImportRows = jest.fn() + +jest.mock('@/server/core/response', () => ({ + handleRequest: (...args: unknown[]) => mockHandleRequest(...args), + jsonSuccess: (...args: unknown[]) => mockJsonSuccess(...args), +})) +jest.mock('@/server/services/dropship-1688-sourcing.service', () => ({ + dropship1688SourcingService: { + importRows: (...args: unknown[]) => mockImportRows(...args), + }, +})) + +import { createDropship1688SourcingWorkbook } from '@/lib/dropship-1688-sourcing-workbook' + +class MockFile { + name = '寻源明细.xlsx' + type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' + size: number + + constructor(private readonly bytes: Uint8Array) { + this.size = bytes.byteLength + } + + async arrayBuffer() { + const output = new ArrayBuffer(this.bytes.byteLength) + new Uint8Array(output).set(this.bytes) + return output + } +} + +describe('POST sourcing import', () => { + const originalFile = global.File + + beforeAll(() => { + Object.defineProperty(global, 'File', { configurable: true, value: MockFile }) + }) + + afterAll(() => { + Object.defineProperty(global, 'File', { configurable: true, value: originalFile }) + }) + + beforeEach(() => { + jest.clearAllMocks() + mockHandleRequest.mockImplementation(async (_request, handler) => handler({ + requestId: 'request-1', + user: { id: 'buyer-1', name: '采购甲', role: 'USER', businessRoles: ['PURCHASING'] }, + })) + mockImportRows.mockResolvedValue({ updated: 1 }) + mockJsonSuccess.mockImplementation((data) => Response.json({ data })) + }) + + it('parses the exported workbook and sends editable rows to the service', async () => { + const bytes = await createDropship1688SourcingWorkbook([{ + sourceSpu: 'SPU-ONE', sourceBarcode: 'DF-ONE', sourceCostPrice: '34.2900', + quotedPriceTaxIncluded: '50.0000', invoiceTaxPoint: '13.0000', + sourceSkuOperator: '运营甲', purchaserName: '采购甲', supplierName: '供应商甲', + sourcingMode: '代发', jianshangBarcode: 'JS-001', + }]) + const file = new MockFile(bytes) + const { POST } = await import('./route') + const response = await POST({ + headers: new Headers(), + formData: async () => ({ get: () => file }), + } as never) + + expect(mockImportRows).toHaveBeenCalledWith([{ + rowNumber: 2, sourceBarcode: 'DF-ONE', purchaserName: '采购甲', + supplierName: '供应商甲', quotedPriceTaxIncluded: '50', invoiceTaxPoint: '13', + sourcingMode: '代发', jianshangBarcode: 'JS-001', + }], expect.objectContaining({ id: 'buyer-1' })) + await expect(response.json()).resolves.toEqual({ data: { updated: 1 } }) + }) + + it('rejects an oversized declared multipart body before parsing form data', async () => { + const formData = jest.fn() + const { POST } = await import('./route') + + await expect(POST({ + headers: new Headers({ 'content-length': String(11 * 1024 * 1024 + 1) }), + formData, + } as never)).rejects.toMatchObject({ message: 'Excel 文件不能超过10MB' }) + + expect(formData).not.toHaveBeenCalled() + expect(mockImportRows).not.toHaveBeenCalled() + }) +}) diff --git a/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-import/route.ts b/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-import/route.ts new file mode 100644 index 00000000..cf914c72 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-import/route.ts @@ -0,0 +1,50 @@ +import { NextRequest } from 'next/server' +import { + DROPSHIP_1688_SOURCING_WORKBOOK_MIME, + parseDropship1688SourcingWorkbook, +} from '@/lib/dropship-1688-sourcing-workbook' +import { AppError, ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonSuccess } from '@/server/core/response' +import { dropship1688SourcingService } from '@/server/services/dropship-1688-sourcing.service' + +const MAX_FILE_SIZE = 10 * 1024 * 1024 +const MAX_MULTIPART_BODY_SIZE = MAX_FILE_SIZE + 1024 * 1024 + +export async function POST(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const contentLengthHeader = request.headers.get('content-length') + if (contentLengthHeader !== null) { + const contentLength = Number(contentLengthHeader) + if (Number.isFinite(contentLength) && contentLength > MAX_MULTIPART_BODY_SIZE) { + throw new AppError(ErrorCode.VALIDATION_OUT_OF_RANGE, 'Excel 文件不能超过10MB') + } + } + + const form = await request.formData() + const file = form.get('file') + if (!(file instanceof File)) { + throw new AppError(ErrorCode.VALIDATION_REQUIRED_FIELD, '请选择需要导入的 Excel 文件') + } + if (file.size > MAX_FILE_SIZE) { + throw new AppError(ErrorCode.VALIDATION_OUT_OF_RANGE, 'Excel 文件不能超过10MB') + } + if (!file.name.toLowerCase().endsWith('.xlsx') && file.type !== DROPSHIP_1688_SOURCING_WORKBOOK_MIME) { + throw new AppError(ErrorCode.VALIDATION_INVALID_FORMAT, '仅支持 .xlsx 文件') + } + + let rows + try { + rows = await parseDropship1688SourcingWorkbook(Buffer.from(await file.arrayBuffer())) + } catch (error) { + const message = error instanceof Error && error.message.startsWith('导入文件') + ? error.message + : 'Excel 文件无法解析,请使用“导出模板”生成的 .xlsx 文件' + throw new AppError( + ErrorCode.VALIDATION_INVALID_FORMAT, + message, + ) + } + const result = await dropship1688SourcingService.importRows(rows, ctx.user) + return jsonSuccess(result, 200, ctx.requestId) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-list/route.test.ts b/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-list/route.test.ts new file mode 100644 index 00000000..44c4731e --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-list/route.test.ts @@ -0,0 +1,74 @@ +/** @jest-environment node */ + +const mockHandleRequest = jest.fn() +const mockJsonError = jest.fn() +const mockJsonSuccess = jest.fn() +const mockListPage = jest.fn() + +jest.mock('@/server/core/response', () => ({ + handleRequest: (...args: unknown[]) => mockHandleRequest(...args), + jsonError: (...args: unknown[]) => mockJsonError(...args), + jsonSuccess: (...args: unknown[]) => mockJsonSuccess(...args), +})) +jest.mock('@/server/services/dropship-1688-sourcing.service', () => ({ + dropship1688SourcingService: { listPage: (...args: unknown[]) => mockListPage(...args) }, +})) + +import { NextRequest } from 'next/server' +import { GET } from './route' + +function request(query = '') { + return new NextRequest(`http://localhost/api/supply-chain/1688-dropship-data/sourcing-list${query}`) +} + +describe('GET sourcing list', () => { + beforeEach(() => { + jest.clearAllMocks() + mockHandleRequest.mockImplementation(async (_request, handler) => handler({ requestId: 'request-1' })) + mockJsonSuccess.mockImplementation((data, status) => ({ success: true, data, status })) + mockJsonError.mockImplementation((_code, message, status) => ({ success: false, message, status })) + mockListPage.mockResolvedValue({ rows: [], total: 0, page: 1, pageSize: 50, totalPages: 1 }) + }) + + it('loads a fixed 50-row page with repeated server-side filters', async () => { + const response = await GET(request( + '?page=3&purchaser=%E9%87%87%E8%B4%AD%E7%94%B2&purchaser=%E9%87%87%E8%B4%AD%E4%B9%99' + + '&spu=SPU-ONE&operator=%E8%BF%90%E8%90%A5%E7%94%B2', + )) + + expect(response).toMatchObject({ success: true, status: 200 }) + expect(mockHandleRequest).toHaveBeenCalledWith(expect.any(NextRequest), expect.any(Function), { requireAuth: true }) + expect(mockListPage).toHaveBeenCalledWith({ + page: 3, + pageSize: 50, + filters: { + purchaserNames: ['采购甲', '采购乙'], + sourceSpus: ['SPU-ONE'], + sourceSkuOperators: ['运营甲'], + }, + }) + }) + + it('defaults to the first unfiltered page', async () => { + await GET(request()) + expect(mockListPage).toHaveBeenCalledWith({ + page: 1, + pageSize: 50, + filters: { purchaserNames: [], sourceSpus: [], sourceSkuOperators: [] }, + }) + }) + + it.each([ + '?page=0', + '?page=1.5', + `?purchaser=${'x'.repeat(201)}`, + '?spu=', + ])('rejects invalid query input: %s', async (query) => { + expect(await GET(request(query))).toMatchObject({ + success: false, + status: 400, + message: '寻源明细筛选参数不正确', + }) + expect(mockListPage).not.toHaveBeenCalled() + }) +}) diff --git a/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-list/route.ts b/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-list/route.ts new file mode 100644 index 00000000..4e0f5ffe --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/1688-dropship-data/sourcing-list/route.ts @@ -0,0 +1,48 @@ +import { NextRequest } from 'next/server' +import { z } from 'zod' +import { DROPSHIP_1688_SOURCING_PAGE_SIZE } from '@/lib/dropship-1688-sourcing' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { dropship1688SourcingService } from '@/server/services/dropship-1688-sourcing.service' + +const filterValuesSchema = z.array(z.string().trim().min(1).max(200)).max(100) + +const querySchema = z.object({ + page: z.coerce.number().int().min(1).max(1_000_000).default(1), + purchaserNames: filterValuesSchema.default([]), + sourceSpus: filterValuesSchema.default([]), + sourceSkuOperators: filterValuesSchema.default([]), +}).strict().transform((input) => ({ + page: input.page, + filters: { + purchaserNames: [...new Set(input.purchaserNames)], + sourceSpus: [...new Set(input.sourceSpus)], + sourceSkuOperators: [...new Set(input.sourceSkuOperators)], + }, +})) + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const parsed = querySchema.safeParse({ + page: request.nextUrl.searchParams.get('page') || undefined, + purchaserNames: request.nextUrl.searchParams.getAll('purchaser'), + sourceSpus: request.nextUrl.searchParams.getAll('spu'), + sourceSkuOperators: request.nextUrl.searchParams.getAll('operator'), + }) + if (!parsed.success) { + return jsonError( + ErrorCode.VALIDATION_INVALID_FORMAT, + '寻源明细筛选参数不正确', + 400, + ctx.requestId, + ) + } + + const data = await dropship1688SourcingService.listPage({ + page: parsed.data.page, + pageSize: DROPSHIP_1688_SOURCING_PAGE_SIZE, + filters: parsed.data.filters, + }) + return jsonSuccess(data, 200, ctx.requestId) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/bom-costing/estimate/EstimateClient.tsx b/furniture-3d-system/src/app/bom-costing/estimate/EstimateClient.tsx new file mode 100644 index 00000000..10c4e0e6 --- /dev/null +++ b/furniture-3d-system/src/app/bom-costing/estimate/EstimateClient.tsx @@ -0,0 +1,251 @@ +'use client' + +import { useState } from 'react' +import { Button } from '@/components/ui/Button' +import { Input } from '@/components/ui/Input' +import { ToastContainer, useToast } from '@/components/ui/Toast' +import { cn } from '@/lib/utils' +import type { BomEstimateCard } from '@/server/services/bom-costing/agent/agent-estimate-card' + +type Phase = 'idle' | 'creating' | 'analyzing' | 'ready' | 'error' + +interface PreviewImage { + assetId: string + kind: 'MAIN' | 'SKU' | 'DETAIL' + url: string + skuTags: string[] +} + +const IMAGE_TABS: Array<{ key: PreviewImage['kind'] | 'ALL'; label: string }> = [ + { key: 'ALL', label: '全部' }, + { key: 'MAIN', label: '主图' }, + { key: 'SKU', label: 'SKU 图' }, + { key: 'DETAIL', label: '详情图' }, +] + +const BREAKDOWN_LABELS: Record = { + BOARD: '板材', + STEEL: '钢材', + ACCESSORY: '五金', + PACKAGING: '包材', + PROCESSING: '加工', + LABOR: '人工', +} + +function confidenceLabel(value: number | null) { + if (value === null) return '待确认' + if (value >= 0.8) return '较高' + if (value >= 0.6) return '中等' + return '较低' +} + +export default function EstimateClient() { + const toast = useToast() + const { toasts, removeToast } = useToast() + const [sourceUrl, setSourceUrl] = useState('') + const [phase, setPhase] = useState('idle') + const [errorMessage, setErrorMessage] = useState('') + const [caseId, setCaseId] = useState(null) + const [card, setCard] = useState(null) + const [images, setImages] = useState([]) + const [imageTab, setImageTab] = useState('ALL') + const [selectedImageId, setSelectedImageId] = useState(null) + const [pendingSkuId, setPendingSkuId] = useState(null) + + async function handleEstimate() { + if (!sourceUrl.trim()) return + setPhase('creating') + setErrorMessage('') + setCard(null) + setImages([]) + try { + const createRes = await fetch('/api/bom-costing/cases', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ sourceUrl: sourceUrl.trim() }), + }) + const createData = await createRes.json() + const newCaseId: string | undefined = createData?.data?.case?.id + if (!createData.success || !newCaseId) { + throw new Error(createData?.error?.message || '无法创建核算案例,请检查链接') + } + setCaseId(newCaseId) + setPhase('analyzing') + const runRes = await fetch(`/api/bom-costing/cases/${newCaseId}/agent-estimate`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({}), + }) + const runData = await runRes.json() + if (!runData.success) { + throw new Error(runData?.error?.message || '预估失败,请稍后重试') + } + setCard(runData.data.card as BomEstimateCard) + setImages(runData.data.images as PreviewImage[]) + setPhase('ready') + } catch (error) { + setPhase('error') + setErrorMessage(error instanceof Error ? error.message : '预估失败,请稍后重试') + } + } + + async function handleEstimateSku(skuId: string) { + if (!caseId) return + setPendingSkuId(skuId) + try { + const res = await fetch(`/api/bom-costing/cases/${caseId}/agent-estimate`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ skuId }), + }) + const data = await res.json() + if (!data.success) throw new Error(data?.error?.message || '核算失败') + setCard(data.data.card as BomEstimateCard) + toast.success('该 SKU 已完成核算') + } catch (error) { + toast.error(error instanceof Error ? error.message : '核算失败') + } finally { + setPendingSkuId(null) + } + } + + const visibleImages = images.filter((image) => imageTab === 'ALL' || image.kind === imageTab) + const selectedImage = visibleImages.find((image) => image.assetId === selectedImageId) ?? visibleImages[0] ?? null + const busy = phase === 'creating' || phase === 'analyzing' + + return ( +
+ +
+

BOM 成本预估

+

粘贴竞品链接,先出代表 SKU 的成本预估,其余 SKU 点击逐个核算(v2 预览)。

+
+ +
+ setSourceUrl(event.target.value)} + placeholder="粘贴竞品商品链接(淘宝/天猫/1688/京东/抖音)" + disabled={busy} + className="h-9 flex-1 text-xs" + /> + +
+ + {busy && ( +
+ + {phase === 'creating' ? '正在读取竞品资料与归档图片…' : 'AI 正在看图拆结构、检索公司历史价格…(约 2-3 分钟,请保持页面打开)'} +
+ )} + {phase === 'error' && ( +
+ {errorMessage} +
+ )} + + {card && phase === 'ready' && ( +
+
+

{card.title || '竞品成本预估'}

+
+ + {card.totalRange ? `¥${card.totalRange.min} – ${card.totalRange.max}` : '暂未形成区间'} + + + 置信度 {confidenceLabel(card.confidence)}{card.confidence !== null ? ` ${Math.round(card.confidence * 100)}%` : ''} + + 已核算 {card.estimatedSkuCount}/{card.skus.length} 个 SKU +
+
+ {card.breakdown.map((row) => ( + + {BREAKDOWN_LABELS[row.category] ?? row.category} + {row.total === null ? '待补' : `¥${row.total}`} + + ))} +
+ {card.openQuestions.length > 0 && ( +

+ 不确定:{card.openQuestions.slice(0, 4).join(';')} +

+ )} +
+ +
+

SKU 列表

+
    + {card.skus.map((sku) => ( +
  • +
    + {sku.externalSkuId} + {sku.name} + {sku.firstBatch && ( + 首批 + )} +
    + {sku.status === 'ESTIMATED' && sku.estimate ? ( + + ¥{sku.estimate.estimateRange.min} – {sku.estimate.estimateRange.max} + + ) : sku.status === 'FAILED' ? ( + + ) : ( + + )} +
  • + ))} +
+
+ + {images.length > 0 && ( +
+
+

商品图片

+
+ {IMAGE_TABS.map((tab) => ( + + ))} +
+
+ {selectedImage && ( + /* eslint-disable-next-line @next/next/no-img-element */ + 竞品图片 + )} +
+ {visibleImages.map((image) => ( + + ))} +
+
+ )} +
+ )} +
+ ) +} diff --git a/furniture-3d-system/src/app/bom-costing/estimate/page.tsx b/furniture-3d-system/src/app/bom-costing/estimate/page.tsx new file mode 100644 index 00000000..4c4a8dec --- /dev/null +++ b/furniture-3d-system/src/app/bom-costing/estimate/page.tsx @@ -0,0 +1,16 @@ +import { redirect } from 'next/navigation' +import { requireSession } from '@/lib/server-session' +import { bomCostingAccessService } from '@/server/services/bom-costing/bom-costing-access.service' +import EstimateClient from './EstimateClient' + +export const metadata = { + title: 'BOM 成本预估(v2 预览)', +} + +export default async function BomEstimatePage() { + const { authUser } = await requireSession('/login') + if (!(await bomCostingAccessService.canView(authUser))) { + redirect('/intake') + } + return +} diff --git a/furniture-3d-system/src/app/installation-demo-workbench/InstallationDemoWorkbenchClient.tsx b/furniture-3d-system/src/app/installation-demo-workbench/InstallationDemoWorkbenchClient.tsx index 24db6309..cc4cf8a0 100644 --- a/furniture-3d-system/src/app/installation-demo-workbench/InstallationDemoWorkbenchClient.tsx +++ b/furniture-3d-system/src/app/installation-demo-workbench/InstallationDemoWorkbenchClient.tsx @@ -13,7 +13,6 @@ import type { InstallationDemoQrShareDTO, } from "@/lib/installation-demo-share-types"; import { - createInstallationDemoShareLink, fetchInstallationDemoNumberingConfig, saveInstallationDemoNumberingConfig, syncInstallationDemoQrShare, @@ -49,6 +48,7 @@ import { } from "./lib/installationExplosionNumberingDisplay"; import { buildHardwareCompositeTemplate, + isHardwareCompositePart, resolveHardwareCompositeCandidateGroups, } from "./lib/installationHardwareComposite"; import { @@ -100,6 +100,7 @@ import { useInstallationPartTexturePresentation } from "./hooks/useInstallationP import { useInstallationPartCatalog } from "./hooks/useInstallationPartCatalog"; import { useInstallationPreviewController } from "./hooks/useInstallationPreviewController"; import { useInstallationDrawingTools } from "./hooks/useInstallationDrawingTools"; +import { useInstallationShareLink } from "./hooks/useInstallationShareLink"; import { useInstallationDrawingOverviewCaptureFrame } from "./hooks/useInstallationDrawingOverviewCaptureFrame"; import { useInstallationDrawingActionCaptureFrame } from "./hooks/useInstallationDrawingActionCaptureFrame"; import { useInstallationStepActionCamera } from "./hooks/useInstallationStepActionCamera"; @@ -150,6 +151,7 @@ type PreviewNodeSelectHandler = NonNullable< interface HardwareCompositeCandidateDraft { partId: string; groups: string[][]; + composite: boolean; } interface InstallationDemoWorkbenchClientProps { @@ -221,11 +223,6 @@ export default function InstallationDemoWorkbenchClient({ const [numberingSnapshotMessage, setNumberingSnapshotMessage] = useState< string | null >(null); - const [shareUrl, setShareUrl] = useState(null); - const [shareExpiresAt, setShareExpiresAt] = useState(null); - const [shareLoading, setShareLoading] = useState(false); - const [shareMessage, setShareMessage] = useState(null); - const [shareCopied, setShareCopied] = useState(false); const [qrShareUrl, setQrShareUrl] = useState(null); const [qrShareLoading, setQrShareLoading] = useState(false); const [qrShareMessage, setQrShareMessage] = useState(null); @@ -1634,7 +1631,7 @@ export default function InstallationDemoWorkbenchClient({ template, }); setHardwareCompositeCandidate( - groups.length > 0 ? { partId, groups } : null, + groups.length > 0 ? { partId, groups, composite: true } : null, ); setHardwareCompositeDefinitionPartId(null); setHardwareCompositeDraftNodeNames([]); @@ -1657,10 +1654,17 @@ export default function InstallationDemoWorkbenchClient({ hardwareCompositeCandidate.partId !== partId ) return; - numberingCatalog.appendHardwareCompositeGroups( - partId, - hardwareCompositeCandidate.groups, - ); + if (hardwareCompositeCandidate.composite) { + numberingCatalog.appendHardwareCompositeGroups( + partId, + hardwareCompositeCandidate.groups, + ); + } else { + numberingCatalog.assignNodesToPart( + partId, + hardwareCompositeCandidate.groups.flat(), + ); + } setHardwareCompositeCandidate(null); }, [hardwareCompositeCandidate, numberingCatalog], @@ -1671,6 +1675,7 @@ export default function InstallationDemoWorkbenchClient({ const engine = previewEngineRef.current ?? previewEngine; const part = numberingCatalog.parts.find((item) => item.id === partId); if (!engine || !part || part.kind !== "hardware") return; + const composite = isHardwareCompositePart(part); const representativeNodeName = part.nodeName ?? getPartNodeNames(part)[0] ?? null; @@ -1695,7 +1700,7 @@ export default function InstallationDemoWorkbenchClient({ numberingCatalog.setSelectedPartId(partId); setHardwareCompositeCandidate( - groups.length > 0 ? { partId, groups } : null, + groups.length > 0 ? { partId, groups, composite } : null, ); }, [modelNodeNames, numberingCatalog, previewEngine], @@ -1706,6 +1711,7 @@ export default function InstallationDemoWorkbenchClient({ partId: hardwareCompositeCandidate.partId, groupCount: hardwareCompositeCandidate.groups.length, nodeCount: hardwareCompositeCandidate.groups.flat().length, + composite: hardwareCompositeCandidate.composite, } : null; @@ -1941,16 +1947,75 @@ export default function InstallationDemoWorkbenchClient({ ], ); + const shareContentRevision = useMemo( + () => + JSON.stringify({ + drawingId: selectedDrawingId, + modelUrl, + uploadedModel, + parts: partCatalog.parts, + numberingParts: numberingCatalog.parts, + drawingTools: drawingTools.selectedTools, + numberingView: savedNumberingView, + numberingSnapshot: confirmedNumberingSnapshotBatch, + nodeMaterialConfigs: nodeMaterials.nodeMaterialConfigs, + steps: stepEditor.steps, + confirmedAt: drawingAutoCapture.confirmedAt, + confirmedImageMode: drawingAutoCapture.confirmedImageMode, + drawingCaptures: drawingCapture.captures, + drawingTextAnnotations: + drawingTextAnnotations.annotationsByTargetKey, + }), + [ + confirmedNumberingSnapshotBatch, + drawingAutoCapture.confirmedAt, + drawingAutoCapture.confirmedImageMode, + drawingCapture.captures, + drawingTextAnnotations.annotationsByTargetKey, + drawingTools.selectedTools, + modelUrl, + nodeMaterials.nodeMaterialConfigs, + numberingCatalog.parts, + partCatalog.parts, + savedNumberingView, + selectedDrawingId, + stepEditor.steps, + uploadedModel, + ], + ); + const { + token: shareToken, + url: shareUrl, + expiresAt: shareExpiresAt, + loading: shareLoading, + message: shareMessage, + copied: shareCopied, + setMessage: setShareMessage, + update: handleCreateShare, + copy: handleCopyShare, + } = useInstallationShareLink({ + drawingId: selectedDrawingId, + canShare: catalog.access.canShare, + disabledReason: shareDisabledReason, + contentRevision: shareContentRevision, + materialDirty: nodeMaterials.dirty, + confirmedAt: drawingAutoCapture.confirmedAt, + confirmedImageMode: drawingAutoCapture.confirmedImageMode, + prepareNumberingSnapshotBatch: prepareNumberingSnapshotBatchForShare, + buildShareInput: buildCurrentShareInput, + }); + const handleConfirmedQrShare = useCallback( (share: InstallationDemoQrShareDTO) => { setQrShareUrl(share.url); setQrShareMessage("二维码内容已同步为当前确认图纸"); - setShareUrl(null); - setShareExpiresAt(null); - setShareCopied(false); - setShareMessage("图纸已更新,请重新生成分享链接"); + setShareMessage( + shareToken + ? "图纸已更新,已有分享链接将自动同步" + : "图纸已更新,可以生成分享链接", + ); }, - [], + [setShareMessage, shareToken], ); const buildConfirmedShareInput = useCallback( ( @@ -1966,59 +2031,6 @@ export default function InstallationDemoWorkbenchClient({ onQrShareSynced: handleConfirmedQrShare, }); - const handleCreateShare = useCallback(async () => { - if (shareDisabledReason) { - setShareMessage(shareDisabledReason ?? "当前演示还不能分享"); - return; - } - - setShareLoading(true); - setShareMessage(null); - setShareCopied(false); - - try { - const includeDrawing = Boolean(drawingAutoCapture.confirmedAt); - const shareImageMode = includeDrawing - ? (drawingAutoCapture.confirmedImageMode ?? "line-art") - : "original"; - const numberingSnapshotBatch = - await prepareNumberingSnapshotBatchForShare(shareImageMode); - if (!numberingSnapshotBatch) { - throw new Error( - includeDrawing - ? "已确认图纸当前模式的部件或工具图读取失败,请重新确认图纸" - : "部件或工具图读取失败,请先保存部件编号图", - ); - } - const input = buildCurrentShareInput( - numberingSnapshotBatch, - includeDrawing, - drawingAutoCapture.confirmedImageMode, - ); - if (!input) throw new Error("当前演示还不能分享"); - const share = await createInstallationDemoShareLink(input); - setShareUrl(share.url); - setShareExpiresAt(share.expiresAt); - setShareMessage( - input.drawingDocument - ? "分享链接已生成,永久有效" - : "分享链接已生成;图纸尚未确认,当前仅开放安装动画", - ); - } catch (error) { - setShareMessage( - error instanceof Error ? error.message : "分享链接生成失败", - ); - } finally { - setShareLoading(false); - } - }, [ - buildCurrentShareInput, - drawingAutoCapture.confirmedAt, - drawingAutoCapture.confirmedImageMode, - prepareNumberingSnapshotBatchForShare, - shareDisabledReason, - ]); - const handleSyncQrShare = useCallback(async () => { if (shareDisabledReason) { setQrShareMessage(shareDisabledReason ?? "当前演示还不能分享"); @@ -2069,19 +2081,6 @@ export default function InstallationDemoWorkbenchClient({ shareDisabledReason, ]); - const handleCopyShare = useCallback(() => { - if (!shareUrl) return; - void navigator.clipboard - .writeText(shareUrl) - .then(() => { - setShareCopied(true); - window.setTimeout(() => setShareCopied(false), 1600); - }) - .catch(() => { - setShareMessage("复制失败,可以手动选中链接复制"); - }); - }, [shareUrl]); - const selectRelativeStep = useCallback( (offset: -1 | 1) => { const nextStep = stepEditor.steps[preview.activeStepIndex + offset]; @@ -2493,7 +2492,7 @@ export default function InstallationDemoWorkbenchClient({ ) : null; return ( -
+
void hardwareCompositeDefinitionPartId: string | null hardwareCompositeDraftNodeNames: string[] - hardwareCompositeCandidate: { partId: string; groupCount: number; nodeCount: number } | null + hardwareCompositeCandidate: { + partId: string + groupCount: number + nodeCount: number + composite: boolean + } | null onBeginHardwareCompositeDefinition: (partId: string) => void onConfirmHardwareCompositeDefinition: (partId: string) => void onCancelHardwareCompositeDefinition: () => void diff --git a/furniture-3d-system/src/app/installation-demo-workbench/components/InstallationDrawingToolSelection.tsx b/furniture-3d-system/src/app/installation-demo-workbench/components/InstallationDrawingToolSelection.tsx index 87e68602..9a44c70c 100644 --- a/furniture-3d-system/src/app/installation-demo-workbench/components/InstallationDrawingToolSelection.tsx +++ b/furniture-3d-system/src/app/installation-demo-workbench/components/InstallationDrawingToolSelection.tsx @@ -52,21 +52,19 @@ export function InstallationDrawingToolSelection({ {tools.map((tool) => { const selected = selectedToolIdSet.has(tool.id) return ( - + ) })}
diff --git a/furniture-3d-system/src/app/installation-demo-workbench/components/InstallationInspector.tsx b/furniture-3d-system/src/app/installation-demo-workbench/components/InstallationInspector.tsx index 92bc50bd..02e49d6c 100644 --- a/furniture-3d-system/src/app/installation-demo-workbench/components/InstallationInspector.tsx +++ b/furniture-3d-system/src/app/installation-demo-workbench/components/InstallationInspector.tsx @@ -91,7 +91,12 @@ interface InstallationInspectorProps { onDeleteNumberingPart: (partId: string) => void hardwareCompositeDefinitionPartId: string | null hardwareCompositeDraftNodeNames: string[] - hardwareCompositeCandidate: { partId: string; groupCount: number; nodeCount: number } | null + hardwareCompositeCandidate: { + partId: string + groupCount: number + nodeCount: number + composite: boolean + } | null onBeginHardwareCompositeDefinition: (partId: string) => void onConfirmHardwareCompositeDefinition: (partId: string) => void onCancelHardwareCompositeDefinition: () => void diff --git a/furniture-3d-system/src/app/installation-demo-workbench/components/InstallationSharePanel.tsx b/furniture-3d-system/src/app/installation-demo-workbench/components/InstallationSharePanel.tsx index e1a69704..a8c08948 100644 --- a/furniture-3d-system/src/app/installation-demo-workbench/components/InstallationSharePanel.tsx +++ b/furniture-3d-system/src/app/installation-demo-workbench/components/InstallationSharePanel.tsx @@ -219,7 +219,7 @@ export function InstallationSharePanel({ className="inline-flex h-9 flex-1 items-center justify-center gap-1.5 rounded-[6px] bg-[#2d3335] px-3 text-[12px] font-black text-white transition hover:bg-[#3d4345] disabled:cursor-not-allowed disabled:opacity-35" > {shareUrl ? : } - {loading ? '生成中' : shareUrl ? '重新生成' : '生成链接'} + {loading ? '处理中' : shareUrl ? '更新链接内容' : '生成链接'} {shareUrl ? ( - {canManageImports && row.importRecordIds?.length ? ( + {canDeleteImports && row.importRecordIds?.length ? ( +
+ ))} + + )} + + + +
{optionList}
+ ) : ( + <> + {optionList} + {control.kind === 'dateRange' && ( +
+ setDateFrom(event.target.value)} + /> + 至 + setDateTo(event.target.value)} + /> +
+ )} + )}
@@ -212,9 +392,51 @@ const clear = () => { .archive-header-filter-trigger.active { color: #2563eb; } .archive-header-filter-popover { position: absolute; top: calc(100% + 7px); left: 0; z-index: 20; - width: 286px; padding: 10px; border: 1px solid #d4d4d8; border-radius: 6px; + display: flex; flex-direction: column; + width: 300px; max-height: var(--popover-max-height, 520px); padding: 10px; + border: 1px solid #d4d4d8; border-radius: 6px; background: #fff; box-shadow: 0 10px 24px rgba(0, 0, 0, 0.12); text-align: left; + transform: translateX(var(--popover-shift, 0px)); + } + .archive-header-filter-popover.is-above { top: auto; bottom: calc(100% + 7px); } + .archive-header-filter-popover.is-text { width: 520px; } + .archive-header-filter-body { display: flex; flex: 1 1 auto; min-height: 0; gap: 12px; } + .archive-header-filter-rules { + display: flex; flex: 0 0 190px; flex-direction: column; min-height: 0; + padding-right: 12px; border-right: 1px solid #e4e4e7; + } + .archive-header-filter-normalcode { + display: flex; flex: 0 0 auto; align-items: center; gap: 7px; + padding: 8px; margin-bottom: 12px; border-radius: 5px; background: #fafafa; + color: #27272a; font-size: 12px; line-height: 1.4; cursor: pointer; + } + .archive-header-filter-normalcode:hover { background: #f4f4f5; } + .archive-header-filter-normalcode input { width: 14px; height: 14px; margin: 0; flex: 0 0 auto; accent-color: #27272a; } + .archive-header-filter-rules-label { flex: 0 0 auto; margin: 0 0 6px 1px; color: #71717a; font-size: 12px; } + .archive-header-filter-rule-list { + display: flex; flex: 0 1 auto; min-height: 0; flex-direction: column; gap: 5px; + padding: 7px; border-radius: 5px; background: #fafafa; overflow-y: auto; + } + .archive-header-filter-rule { display: flex; align-items: center; gap: 5px; } + .archive-header-filter-rule input { + min-width: 0; flex: 1; height: 28px; padding: 0 8px; border: 1px solid #d4d4d8; + border-radius: 4px; background: #fff; color: #27272a; font-size: 12px; outline: none; + } + .archive-header-filter-rule input:focus { border-color: #52525b; } + .archive-header-filter-rule-remove { + display: inline-flex; align-items: center; justify-content: center; + width: 24px; height: 24px; flex: 0 0 auto; padding: 0; border: none; border-radius: 4px; + background: transparent; color: #a1a1aa; cursor: pointer; + } + .archive-header-filter-rule-remove:hover { background: #e4e4e7; color: #b91c1c; } + .archive-header-filter-add-rule { + flex: 0 0 auto; margin-top: 8px; padding: 0; border: none; background: transparent; + color: #2563eb; font-size: 12px; font-weight: 600; cursor: pointer; + } + .archive-header-filter-add-rule:hover { text-decoration: underline; } + .archive-header-filter-values { + display: flex; flex: 1 1 auto; min-width: 0; min-height: 0; flex-direction: column; } .archive-header-filter-dates { display: flex; align-items: center; gap: 5px; } .archive-header-filter-dates input { @@ -222,8 +444,11 @@ const clear = () => { border-radius: 4px; color: #3f3f46; font-size: 11px; outline: none; } .archive-header-filter-dates span { color: #71717a; font-size: 12px; } - .archive-header-filter-actions { display: flex; justify-content: flex-end; gap: 7px; margin-top: 10px; } - .archive-header-filter-actions button { height: 28px; padding: 0 10px; border-radius: 4px; font-size: 12px; cursor: pointer; } + .archive-header-filter-actions { + display: flex; flex: 0 0 auto; justify-content: flex-end; gap: 7px; + margin-top: 10px; padding-top: 10px; border-top: 1px solid #e4e4e7; + } + .archive-header-filter-actions button { height: 28px; padding: 0 12px; border-radius: 4px; font-size: 12px; cursor: pointer; } .archive-header-filter-clear { border: 1px solid #d4d4d8; background: #fff; color: #52525b; } .archive-header-filter-apply { border: 1px solid #27272a; background: #27272a; color: #fff; } `} diff --git a/furniture-3d-system/src/app/supply-chain/database/product-archive/useProductArchiveViewPreferences.ts b/furniture-3d-system/src/app/supply-chain/database/product-archive/useProductArchiveViewPreferences.ts index 7539ad0a..a66bdd16 100644 --- a/furniture-3d-system/src/app/supply-chain/database/product-archive/useProductArchiveViewPreferences.ts +++ b/furniture-3d-system/src/app/supply-chain/database/product-archive/useProductArchiveViewPreferences.ts @@ -5,8 +5,11 @@ import { PRODUCT_ARCHIVE_EMPTY_FILTER_VALUE, PRODUCT_ARCHIVE_FILTER_OPTION_KEYS, PRODUCT_ARCHIVE_SALES_STATUSES, + PRODUCT_ARCHIVE_TEXT_FILTER_KEYS, + type ProductArchiveExcludeRule, type ProductArchiveFilters, type ProductArchiveSalesStatus, + type ProductArchiveTextFilterKey, } from '@/lib/supply-chain-product-archive' const STORAGE_KEY = 'supply_chain_product_archive_view_v1' @@ -42,6 +45,36 @@ function cleanStringArray(value: unknown): string[] | undefined { return normalized.length ? normalized : undefined } +const TEXT_FILTER_KEY_SET: ReadonlySet = new Set(PRODUCT_ARCHIVE_TEXT_FILTER_KEYS) + +/** 「只看正常编码」的列白名单归一(去重、去掉非文本列)。 */ +function cleanNormalCodeOnly(value: unknown): ProductArchiveTextFilterKey[] | undefined { + const values = Array.isArray(value) ? value : [] + const normalized = [...new Set( + values.filter((item): item is ProductArchiveTextFilterKey => + typeof item === 'string' && TEXT_FILTER_KEY_SET.has(item)), + )] + return normalized.length ? normalized : undefined +} + +/** 「排除以…开头」规则归一(去空、去非文本列、按列+关键词去重)。 */ +function cleanExcludeRules(value: unknown): ProductArchiveExcludeRule[] | undefined { + const values = Array.isArray(value) ? value : [] + const rules: ProductArchiveExcludeRule[] = [] + const seen = new Set() + for (const item of values) { + if (!isRecord(item)) continue + const field = item.field + const startsWith = cleanString(item.startsWith) + if (typeof field !== 'string' || !TEXT_FILTER_KEY_SET.has(field) || !startsWith) continue + const dedupeKey = `${field}\u0000${startsWith.toUpperCase()}` + if (seen.has(dedupeKey)) continue + seen.add(dedupeKey) + rules.push({ field: field as ProductArchiveTextFilterKey, startsWith }) + } + return rules.length ? rules : undefined +} + function sanitizeFilters(value: unknown): ProductArchiveFilters { if (!isRecord(value)) return {} @@ -69,6 +102,11 @@ function sanitizeFilters(value: unknown): ProductArchiveFilters { if (normalized) filters[key] = normalized } + const normalCodeOnly = cleanNormalCodeOnly(value.normalCodeOnly) + if (normalCodeOnly) filters.normalCodeOnly = normalCodeOnly + const excludeStartsWith = cleanExcludeRules(value.excludeStartsWith) + if (excludeStartsWith) filters.excludeStartsWith = excludeStartsWith + return filters } diff --git a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipAcceptanceButton.test.tsx b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipAcceptanceButton.test.tsx new file mode 100644 index 00000000..4eb5cb83 --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipAcceptanceButton.test.tsx @@ -0,0 +1,138 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { DropshipAcceptanceButton } from './DropshipAcceptanceButton' +import { claimDropship1688Sourcing } from './sourcing.actions' + +const refresh = jest.fn() + +jest.mock('next/navigation', () => ({ useRouter: () => ({ refresh }) })) +jest.mock('./sourcing.actions', () => ({ claimDropship1688Sourcing: jest.fn() })) + +const props = { + acceptanceRevision: '', + barcode: 'DF-A1AD000205', + dateFrom: '2026-09-01', + dateTo: '2026-09-10', + alreadyAccepted: false, + canAccept: true, + purchaserCount: 0, +} + +describe('DropshipAcceptanceButton', () => { + let alertSpy: jest.SpyInstance + + beforeEach(() => { + jest.clearAllMocks() + alertSpy = jest.spyOn(window, 'alert').mockImplementation(() => undefined) + }) + + afterEach(() => { + alertSpy.mockRestore() + }) + + it('shows the available count and disables acceptance without permission', () => { + const { rerender } = render() + const deniedButton = screen.getByRole('button', { name: '承接 0/3' }) + expect(deniedButton).toBeDisabled() + expect(deniedButton).toHaveAttribute('title', '当前账号没有承接权限') + expect(deniedButton).toHaveAttribute('data-state', 'permission') + + rerender() + const availableButton = screen.getByRole('button', { name: '承接 2/3' }) + expect(availableButton).toBeEnabled() + expect(availableButton).toHaveAttribute('data-state', 'available') + expect(claimDropship1688Sourcing).not.toHaveBeenCalled() + }) + + it('keeps an accepted button non-full until three purchasers have accepted', () => { + const { rerender } = render( + , + ) + const acceptedButton = screen.getByRole('button', { name: '已承接 1/3' }) + expect(acceptedButton).toBeDisabled() + expect(acceptedButton).toHaveAttribute('data-state', 'accepted') + + rerender() + const fullButton = screen.getByRole('button', { name: '已满 3/3' }) + expect(fullButton).toBeDisabled() + expect(fullButton).toHaveAttribute('data-state', 'full') + expect(fullButton).toHaveAttribute('title', '已满3名采购') + }) + + it('locks while submitting, then marks success locally and refreshes server data', async () => { + let resolveClaim: ((value: { ok: true }) => void) | undefined + jest.mocked(claimDropship1688Sourcing).mockImplementation(() => new Promise((resolve) => { + resolveClaim = resolve + })) + render() + + fireEvent.click(screen.getByRole('button', { name: '承接 0/3' })) + const pendingButton = screen.getByRole('button', { name: '承接中' }) + expect(pendingButton).toBeDisabled() + fireEvent.click(pendingButton) + expect(claimDropship1688Sourcing).toHaveBeenCalledTimes(1) + expect(claimDropship1688Sourcing).toHaveBeenCalledWith({ + barcode: 'DF-A1AD000205', + dateFrom: '2026-09-01', + dateTo: '2026-09-10', + }) + + resolveClaim?.({ ok: true }) + await waitFor(() => expect(screen.getByRole('button', { name: '已承接 1/3' })).toBeDisabled()) + expect(refresh).toHaveBeenCalledTimes(1) + expect(alertSpy).not.toHaveBeenCalled() + }) + + it('clears optimistic acceptance after the server confirms and later revokes it', async () => { + jest.mocked(claimDropship1688Sourcing).mockResolvedValue({ ok: true }) + const { rerender } = render() + + fireEvent.click(screen.getByRole('button', { name: '承接 0/3' })) + await waitFor(() => expect(screen.getByRole('button', { name: '已承接 1/3' })).toBeDisabled()) + + rerender( + , + ) + expect(screen.getByRole('button', { name: '已承接 1/3' })).toBeDisabled() + + rerender() + const available = screen.getByRole('button', { name: '承接 0/3' }) + expect(available).toBeEnabled() + expect(available).toHaveAttribute('data-state', 'available') + }) + + it('shows an action error and allows retrying', async () => { + jest.mocked(claimDropship1688Sourcing) + .mockResolvedValueOnce({ ok: false, message: '当前商品暂时无法承接' }) + .mockResolvedValueOnce({ ok: true }) + render() + + fireEvent.click(screen.getByRole('button', { name: '承接 0/3' })) + await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('当前商品暂时无法承接')) + expect(screen.getByRole('button', { name: '承接 0/3' })).toBeEnabled() + expect(refresh).not.toHaveBeenCalled() + + fireEvent.click(screen.getByRole('button', { name: '承接 0/3' })) + await waitFor(() => expect(refresh).toHaveBeenCalledTimes(1)) + expect(screen.getByRole('button', { name: '已承接 1/3' })).toBeDisabled() + expect(claimDropship1688Sourcing).toHaveBeenCalledTimes(2) + }) + + it('shows thrown errors and falls back to a clear message for unknown failures', async () => { + jest.mocked(claimDropship1688Sourcing) + .mockRejectedValueOnce(new Error('服务暂不可用')) + .mockRejectedValueOnce(null) + render() + + fireEvent.click(screen.getByRole('button', { name: '承接 0/3' })) + await waitFor(() => expect(alertSpy).toHaveBeenLastCalledWith('服务暂不可用')) + fireEvent.click(screen.getByRole('button', { name: '承接 0/3' })) + await waitFor(() => expect(alertSpy).toHaveBeenLastCalledWith('承接失败,请稍后重试')) + expect(screen.getByRole('button', { name: '承接 0/3' })).toBeEnabled() + expect(refresh).not.toHaveBeenCalled() + }) +}) diff --git a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipAcceptanceButton.tsx b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipAcceptanceButton.tsx new file mode 100644 index 00000000..e452acbe --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipAcceptanceButton.tsx @@ -0,0 +1,109 @@ +'use client' + +import { useRef, useState } from 'react' +import { Handshake } from 'lucide-react' +import { useRouter } from 'next/navigation' +import { DROPSHIP_1688_MAX_PURCHASERS } from '@/lib/dropship-1688-sourcing' +import { claimDropship1688Sourcing } from './sourcing.actions' + +type DropshipAcceptanceButtonProps = { + acceptanceRevision: string + barcode: string + dateFrom: string + dateTo: string + alreadyAccepted: boolean + canAccept: boolean + purchaserCount: number +} + +const DEFAULT_ERROR_MESSAGE = '承接失败,请稍后重试' + +export function DropshipAcceptanceButton({ + acceptanceRevision, + ...props +}: DropshipAcceptanceButtonProps) { + return +} + +function DropshipAcceptanceButtonState({ + barcode, + dateFrom, + dateTo, + alreadyAccepted, + canAccept, + purchaserCount, +}: Omit) { + const router = useRouter() + const submitting = useRef(false) + const [pending, setPending] = useState(false) + const [acceptedLocally, setAcceptedLocally] = useState(false) + const accepted = alreadyAccepted || acceptedLocally + const displayedCount = Math.min( + DROPSHIP_1688_MAX_PURCHASERS, + Math.max(0, purchaserCount) + (acceptedLocally && !alreadyAccepted ? 1 : 0), + ) + const full = displayedCount >= DROPSHIP_1688_MAX_PURCHASERS + const disabled = !canAccept || accepted || full || pending + const state = !canAccept + ? 'permission' + : full + ? 'full' + : accepted + ? 'accepted' + : pending + ? 'pending' + : 'available' + const label = pending + ? '承接中' + : full + ? `已满 ${displayedCount}/${DROPSHIP_1688_MAX_PURCHASERS}` + : accepted + ? `已承接 ${displayedCount}/${DROPSHIP_1688_MAX_PURCHASERS}` + : `承接 ${displayedCount}/${DROPSHIP_1688_MAX_PURCHASERS}` + const title = !canAccept + ? '当前账号没有承接权限' + : full + ? `已满${DROPSHIP_1688_MAX_PURCHASERS}名采购` + : accepted + ? `你已承接,当前${displayedCount}/${DROPSHIP_1688_MAX_PURCHASERS}人` + : pending + ? '正在承接' + : `当前${displayedCount}/${DROPSHIP_1688_MAX_PURCHASERS}人承接` + + async function accept() { + if (disabled || submitting.current) return + submitting.current = true + setPending(true) + + try { + const result = await claimDropship1688Sourcing({ barcode, dateFrom, dateTo }) + if (!result.ok) { + window.alert(result.message?.trim() || DEFAULT_ERROR_MESSAGE) + return + } + setAcceptedLocally(true) + router.refresh() + } catch (error) { + window.alert( + error instanceof Error && error.message.trim() + ? error.message + : DEFAULT_ERROR_MESSAGE, + ) + } finally { + submitting.current = false + setPending(false) + } + } + + return ( + + ) +} diff --git a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipFieldFilter.test.tsx b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipFieldFilter.test.tsx new file mode 100644 index 00000000..55362eea --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipFieldFilter.test.tsx @@ -0,0 +1,399 @@ +import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react' +import type { Dropship1688Filters } from '@/lib/dropship-1688-filters' +import { + DropshipAutoSubmitDateField, + DropshipFieldFilter, + DropshipFieldFilterGroup, +} from './DropshipFieldFilter' +import { saveDropship1688Filters } from './filters.actions' + +const push = jest.fn() + +jest.mock('next/navigation', () => ({ useRouter: () => ({ push }) })) +jest.mock('./filters.actions', () => ({ saveDropship1688Filters: jest.fn() })) + +function response(body: unknown, ok = true) { + return { ok, json: async () => body } as Response +} + +let fetchMock: jest.Mock + +function values(count: number) { + return Array.from({ length: count }, (_, index) => `VALUE-${index}`) +} + +function renderFilter( + filters: Dropship1688Filters = {}, + overrides: { keyword?: string } = {}, +) { + return render(filterUi(filters, overrides)) +} + +function filterUi( + filters: Dropship1688Filters = {}, + overrides: { keyword?: string } = {}, +) { + return ( + + + + ) +} + +function openSelect(filters: Dropship1688Filters = {}) { + renderFilter(filters) + const trigger = screen.getByRole('button', { name: '运营筛选' }) + fireEvent.click(trigger) +} + +describe('DropshipFieldFilter', () => { + beforeEach(() => { + jest.clearAllMocks() + fetchMock = jest.fn(async () => response({ success: true, data: { values: values(3) } })) + global.fetch = fetchMock as unknown as typeof fetch + jest.mocked(saveDropship1688Filters).mockResolvedValue('r'.repeat(64)) + }) + + it('submits the form whenever either date changes', () => { + const submitted = jest.fn() + render( + { + event.preventDefault() + submitted() + }}> + + + , + ) + + fireEvent.change(screen.getByLabelText('开始日期'), { + target: { value: '2026-08-01' }, + }) + expect(submitted).toHaveBeenCalledTimes(1) + + fireEvent.change(screen.getByLabelText('结束日期'), { + target: { value: '2026-08-31' }, + }) + expect(submitted).toHaveBeenCalledTimes(2) + }) + + it('summarizes an include selection and an exclude selection differently', () => { + const { rerender } = render(filterUi({ + skuOperator: { mode: 'include', values: ['运营甲', '运营乙'] }, + })) + expect(screen.getByRole('button', { name: '运营筛选' })).toHaveTextContent('已选 2 项') + + rerender(filterUi({ skuOperator: { mode: 'exclude', values: ['运营甲'] } })) + expect(screen.getByRole('button', { name: '运营筛选' })).toHaveTextContent('排除 1 项') + + rerender(filterUi({ skuOperator: { mode: 'include', values: [] } })) + expect(screen.getByRole('button', { name: '运营筛选' })).toHaveTextContent('已选 0 项') + }) + + it('loads candidates through the shared filter-options endpoint with the current filters', async () => { + openSelect({ sku: { mode: 'include', values: ['SKU-1'] } }) + + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)) + const body = JSON.parse(String(fetchMock.mock.calls[0][1]?.body)) + expect(body).toEqual({ + field: 'skuOperator', + keyword: '', + optionQuery: '', + dateFrom: '2026-09-01', + dateTo: '2026-09-07', + filters: { sku: { mode: 'include', values: ['SKU-1'] } }, + }) + await waitFor(() => expect(screen.getByRole('checkbox', { name: 'VALUE-0' })).toBeInTheDocument()) + }) + + it('keeps the page keyword separate when the option query changes', async () => { + render( + + + , + ) + fireEvent.click(screen.getByRole('button', { name: 'SKU筛选' })) + expect(screen.getByText('请输入关键词搜索')).toBeVisible() + expect(fetchMock).not.toHaveBeenCalled() + + fireEvent.change(screen.getByRole('searchbox', { name: '搜索SKU' }), { + target: { value: '甲' }, + }) + + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)) + const body = JSON.parse(String(fetchMock.mock.calls[0][1]?.body)) + expect(body.keyword).toBe('卧室') + expect(body.optionQuery).toBe('甲') + }) + + it('filters purchaser candidates locally without repeating the server request', async () => { + render( + + + , + ) + fireEvent.click(screen.getByRole('button', { name: '采购筛选' })) + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)) + fireEvent.change(screen.getByRole('searchbox', { name: '搜索采购' }), { + target: { value: 'VALUE-1' }, + }) + await waitFor(() => expect(screen.getByRole('checkbox', { name: 'VALUE-1' })).toBeVisible()) + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 300)) + }) + expect(fetchMock).toHaveBeenCalledTimes(1) + }) + + it('applies the checked values as an include filter without an apply button', async () => { + openSelect() + fireEvent.click(await screen.findByRole('checkbox', { name: 'VALUE-1' })) + + await waitFor(() => expect(push).toHaveBeenCalledTimes(1), { timeout: 2000 }) + const target = decodeURIComponent(String(push.mock.calls[0][0])) + expect(target).toContain('"skuOperator":{"mode":"include","values":["VALUE-1"]}') + expect(saveDropship1688Filters).not.toHaveBeenCalled() + // 弹层保持打开,与寻源明细的筛选一致。 + expect(screen.getByRole('dialog', { name: '运营选项' })).toBeVisible() + }) + + it('coalesces rapid checking into a single navigation', async () => { + openSelect() + await screen.findByRole('checkbox', { name: 'VALUE-0' }) + fireEvent.click(screen.getByRole('checkbox', { name: 'VALUE-0' })) + fireEvent.click(screen.getByRole('checkbox', { name: 'VALUE-1' })) + fireEvent.click(screen.getByRole('checkbox', { name: 'VALUE-2' })) + + await waitFor(() => expect(push).toHaveBeenCalledTimes(1), { timeout: 2000 }) + const target = decodeURIComponent(String(push.mock.calls[0][0])) + expect(target).toContain('"values":["VALUE-0","VALUE-1","VALUE-2"]') + await waitFor(() => expect(push).toHaveBeenCalledTimes(1), { timeout: 800 }) + }) + + it('removes the field filter through 清空', async () => { + openSelect({ skuOperator: { mode: 'include', values: ['运营甲'] } }) + await screen.findByRole('checkbox', { name: 'VALUE-0' }) + fireEvent.click(screen.getByRole('button', { name: '清空' })) + + await waitFor(() => expect(push).toHaveBeenCalledTimes(1), { timeout: 2000 }) + const target = decodeURIComponent(String(push.mock.calls[0][0])) + expect(target).not.toContain('skuOperator') + expect(target).not.toContain('columnFilters') + }) + + it('warns before replacing an exclude filter and can clear it directly', async () => { + openSelect({ skuOperator: { mode: 'exclude', values: ['运营甲'] } }) + expect(screen.getByText(/当前筛选是排除模式/)).toBeVisible() + const clear = screen.getByRole('button', { name: '清空' }) + expect(clear).toBeEnabled() + fireEvent.click(clear) + await waitFor(() => expect(push).toHaveBeenCalledTimes(1), { timeout: 2000 }) + expect(decodeURIComponent(String(push.mock.calls[0][0]))).not.toContain('skuOperator') + }) + + it('can clear an explicit empty include filter', async () => { + openSelect({ skuOperator: { mode: 'include', values: [] } }) + const clear = screen.getByRole('button', { name: '清空' }) + expect(clear).toBeEnabled() + fireEvent.click(clear) + await waitFor(() => expect(push).toHaveBeenCalledTimes(1), { timeout: 2000 }) + expect(decodeURIComponent(String(push.mock.calls[0][0]))).not.toContain('skuOperator') + }) + + it('merges rapid selections from different fields into one navigation', async () => { + render( + + + + , + ) + + fireEvent.click(screen.getByRole('button', { name: '采购筛选' })) + fireEvent.click(await screen.findByRole('checkbox', { name: 'VALUE-0' })) + fireEvent.click(screen.getByRole('button', { name: 'SPU筛选' })) + const spuDialog = screen.getByRole('dialog', { name: 'SPU选项' }) + expect(within(spuDialog).getByText('请输入关键词搜索')).toBeVisible() + fireEvent.change(within(spuDialog).getByRole('searchbox', { name: '搜索SPU' }), { + target: { value: 'VALUE' }, + }) + fireEvent.click(await within(spuDialog).findByRole('checkbox', { name: 'VALUE-1' })) + + await waitFor(() => expect(push).toHaveBeenCalledTimes(1), { timeout: 2000 }) + const target = decodeURIComponent(String(push.mock.calls[0][0])) + expect(target).toContain('"purchaser":{"mode":"include","values":["VALUE-0"]}') + expect(target).toContain('"spu":{"mode":"include","values":["VALUE-1"]}') + }) + + it('uses the current date and keyword inputs when a filter auto-applies', async () => { + render( +
+ + + + + + + +
, + ) + fireEvent.change(screen.getByRole('textbox', { name: '开始日期' }), { + target: { value: '2026-08-01' }, + }) + fireEvent.change(screen.getByRole('textbox', { name: '商品检索' }), { + target: { value: '卧室' }, + }) + fireEvent.click(screen.getByRole('button', { name: '运营筛选' })) + fireEvent.click(await screen.findByRole('checkbox', { name: 'VALUE-0' })) + + await waitFor(() => expect(push).toHaveBeenCalledTimes(1), { timeout: 2000 }) + const target = decodeURIComponent(String(push.mock.calls[0][0])) + expect(target).toContain('dateFrom=2026-08-01') + expect(target).toContain('keyword=卧室') + expect(target).toContain('"skuOperator":{"mode":"include","values":["VALUE-0"]}') + }) + + it('flushes a pending filter before an immediate date change', async () => { + render( +
+ + + + + + , + ) + fireEvent.click(screen.getByRole('button', { name: '运营筛选' })) + fireEvent.click(await screen.findByRole('checkbox', { name: 'VALUE-1' })) + fireEvent.change(screen.getByLabelText('开始日期'), { + target: { value: '2026-08-01' }, + }) + + await waitFor(() => expect(push).toHaveBeenCalledTimes(1), { timeout: 2000 }) + const target = decodeURIComponent(String(push.mock.calls[0][0])) + expect(target).toContain('dateFrom=2026-08-01') + expect(target).toContain('"skuOperator":{"mode":"include","values":["VALUE-1"]}') + }) + + it('replays a query submitted while a large filter save is in flight', async () => { + const manyValues = Array.from({ length: 150 }, (_, index) => `VALUE-${index}-${'x'.repeat(20)}`) + fetchMock = jest.fn(async () => response({ success: true, data: { values: manyValues } })) + global.fetch = fetchMock as unknown as typeof fetch + let resolveSave!: (value: string) => void + const save = new Promise((resolve) => { resolveSave = resolve }) + jest.mocked(saveDropship1688Filters).mockReturnValue(save) + + render( +
+ + + + + +
, + ) + fireEvent.click(screen.getByRole('button', { name: '运营筛选' })) + await screen.findByRole('checkbox', { name: manyValues[0] }) + fireEvent.click(screen.getByRole('button', { name: '全选全部' })) + await waitFor(() => expect(saveDropship1688Filters).toHaveBeenCalledTimes(1), { timeout: 2000 }) + + fireEvent.change(screen.getByRole('textbox', { name: '商品检索' }), { + target: { value: 'DF-LATEST' }, + }) + fireEvent.click(screen.getByRole('button', { name: '查询' })) + await act(async () => resolveSave('r'.repeat(64))) + + await waitFor(() => expect(saveDropship1688Filters).toHaveBeenCalledTimes(2), { timeout: 2000 }) + await waitFor(() => expect(push).toHaveBeenCalledTimes(1), { timeout: 2000 }) + expect(decodeURIComponent(String(push.mock.calls[0][0]))).toContain('keyword=DF-LATEST') + }) + + it('stops retrying automatically after saving a large selection fails', async () => { + const manyValues = Array.from({ length: 150 }, (_, index) => `VALUE-${index}-${'x'.repeat(20)}`) + fetchMock = jest.fn(async () => response({ success: true, data: { values: manyValues } })) + global.fetch = fetchMock as unknown as typeof fetch + jest.mocked(saveDropship1688Filters).mockRejectedValue(new Error('offline')) + + openSelect() + await screen.findByRole('checkbox', { name: manyValues[0] }) + fireEvent.click(screen.getByRole('button', { name: '全选全部' })) + fireEvent.click(screen.getByRole('button', { name: '运营筛选' })) + + expect(await screen.findByRole('alert')).toHaveTextContent('筛选保存失败,请重试') + expect(screen.queryByRole('dialog', { name: '运营选项' })).not.toBeInTheDocument() + await new Promise((resolve) => setTimeout(resolve, 500)) + expect(saveDropship1688Filters).toHaveBeenCalledTimes(1) + expect(screen.getByRole('button', { name: '运营筛选' })).toHaveTextContent('全部运营') + }) + + it('renders a windowed slice instead of every candidate', async () => { + fetchMock = jest.fn(async () => response({ success: true, data: { values: values(60) } })) + global.fetch = fetchMock as unknown as typeof fetch + + openSelect() + await waitFor(() => expect(screen.getAllByRole('checkbox')).toHaveLength(16)) + expect(screen.queryByRole('checkbox', { name: 'VALUE-40' })).not.toBeInTheDocument() + }) + + it('offers a retry after a failed candidate load', async () => { + fetchMock = jest.fn(async () => response({ success: false, error: { message: '候选值加载失败' } }, false)) + global.fetch = fetchMock as unknown as typeof fetch + + openSelect() + expect(await screen.findByRole('alert')).toHaveTextContent('候选值加载失败') + + fetchMock = jest.fn(async () => response({ success: true, data: { values: values(3) } })) + global.fetch = fetchMock as unknown as typeof fetch + fireEvent.click(screen.getByRole('button', { name: '重试' })) + await waitFor(() => expect(screen.getByRole('checkbox', { name: 'VALUE-0' })).toBeInTheDocument()) + }) +}) diff --git a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipFieldFilter.tsx b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipFieldFilter.tsx new file mode 100644 index 00000000..a51587e2 --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipFieldFilter.tsx @@ -0,0 +1,511 @@ +'use client' + +import { Check, ChevronDown, LoaderCircle, Search, X } from 'lucide-react' +import { useRouter } from 'next/navigation' +import { + createContext, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, + useTransition, + type ReactNode, +} from 'react' +import { + DROPSHIP1688_FILTER_MAX_BYTES, + serializeDropship1688Filters, + type Dropship1688FilterField, + type Dropship1688Filters, +} from '@/lib/dropship-1688-filters' +import styles from './dropship-1688-data.module.css' +import { saveDropship1688Filters } from './filters.actions' + +const ROW_HEIGHT = 30 +const WINDOW_SIZE = 16 +const LIST_MAX_HEIGHT = 240 +const SEARCH_DEBOUNCE_MS = 250 +const POPOVER_WIDTH = 296 +const APPLY_DEBOUNCE_MS = 300 + +type FilterGroupContextValue = { + filters: Dropship1688Filters + pending: boolean + saving: boolean + readPeriod: () => { dateFrom: string; dateTo: string; keyword: string } + scheduleSelection: (field: Dropship1688FilterField, values: string[]) => void + cancelScheduledApply: () => void +} + +const FilterGroupContext = createContext(null) + +export function DropshipAutoSubmitDateField({ + name, + label, + defaultValue, +}: { + name: 'dateFrom' | 'dateTo' + label: string + defaultValue: string +}) { + return ( + + ) +} + +export function DropshipFieldFilterGroup({ + dateFrom, + dateTo, + keyword, + filters, + children, +}: { + dateFrom: string + dateTo: string + keyword: string + filters: Dropship1688Filters + children: ReactNode +}) { + const router = useRouter() + const [workingFilters, setWorkingFilters] = useState(filters) + const [saving, setSaving] = useState(false) + const [saveError, setSaveError] = useState('') + const [pending, startTransition] = useTransition() + const filtersRef = useRef(filters) + const committedFiltersRef = useRef(filters) + const periodRef = useRef({ dateFrom, dateTo, keyword }) + const applyTimer = useRef | null>(null) + const desiredFilters = useRef(null) + const applyingRef = useRef(false) + const groupRef = useRef(null) + + periodRef.current = { dateFrom, dateTo, keyword } + + const readPeriod = useCallback(() => { + const fallback = periodRef.current + const form = groupRef.current?.closest('form') + const value = (name: string, defaultValue: string) => { + const control = form?.elements.namedItem(name) + return control instanceof HTMLInputElement ? control.value : defaultValue + } + return { + dateFrom: value('dateFrom', fallback.dateFrom), + dateTo: value('dateTo', fallback.dateTo), + keyword: value('keyword', fallback.keyword), + } + }, []) + + useEffect(() => { + committedFiltersRef.current = filters + if (applyingRef.current || desiredFilters.current) return + filtersRef.current = filters + setWorkingFilters(filters) + }, [filters]) + + const flushApply = useCallback(async () => { + const target = desiredFilters.current + if (!target) return + if (applyingRef.current) { + applyTimer.current = setTimeout(() => void flushApply(), 200) + return + } + applyingRef.current = true + setSaving(true) + setSaveError('') + try { + const { dateFrom, dateTo, keyword } = readPeriod() + const serialized = serializeDropship1688Filters(target) + if (new Blob([serialized]).size > DROPSHIP1688_FILTER_MAX_BYTES) { + throw new Error('筛选条件过多,请缩小选择范围') + } + const params = new URLSearchParams(window.location.search) + params.set('dateFrom', dateFrom) + params.set('dateTo', dateTo) + params.set('keyword', keyword) + params.delete('page') + params.delete('filterRef') + params.delete('columnFilters') + if (encodeURIComponent(serialized).length > 2000) { + params.set('filterRef', await saveDropship1688Filters(target)) + } else if (serialized) { + params.set('columnFilters', serialized) + } + // A newer selection or form submission arrived while a large filter was saving. + // Skip the stale navigation; the finally block will flush the latest request. + if (desiredFilters.current !== target) return + desiredFilters.current = null + startTransition(() => router.push(`${window.location.pathname}?${params}`, { scroll: false })) + } catch (reason) { + if (desiredFilters.current === target) { + desiredFilters.current = null + filtersRef.current = committedFiltersRef.current + setWorkingFilters(committedFiltersRef.current) + setSaveError(reason instanceof Error && reason.message.startsWith('筛选条件过多') + ? reason.message + : '筛选保存失败,请重试') + } + } finally { + setSaving(false) + applyingRef.current = false + if (desiredFilters.current) { + applyTimer.current = setTimeout(() => void flushApply(), 120) + } + } + }, [readPeriod, router]) + + const scheduleSelection = useCallback((field: Dropship1688FilterField, values: string[]) => { + const next: Dropship1688Filters = { ...filtersRef.current } + if (values.length === 0) delete next[field] + else next[field] = { mode: 'include', values } + filtersRef.current = next + desiredFilters.current = next + setWorkingFilters(next) + setSaveError('') + if (applyTimer.current) clearTimeout(applyTimer.current) + applyTimer.current = setTimeout(() => void flushApply(), APPLY_DEBOUNCE_MS) + }, [flushApply]) + + const cancelScheduledApply = useCallback(() => { + // Opening another filter is part of the same selection interaction. Keep the + // latest filter state queued until the user finishes choosing there instead + // of navigating with only the first field's condition. + if (applyTimer.current) { + clearTimeout(applyTimer.current) + applyTimer.current = null + } + }, []) + + useEffect(() => () => { + if (applyTimer.current) clearTimeout(applyTimer.current) + }, []) + + useEffect(() => { + const form = groupRef.current?.closest('form') + if (!form) return + const handleSubmit = (event: SubmitEvent) => { + if (!desiredFilters.current && !applyingRef.current && !pending) return + event.preventDefault() + // Preserve a query made while another save/navigation is in flight. A fresh + // object keeps the queued request distinct from the target currently saving. + if (applyingRef.current || pending) { + desiredFilters.current = { ...filtersRef.current } + } + if (applyTimer.current) clearTimeout(applyTimer.current) + if (!applyingRef.current) void flushApply() + } + form.addEventListener('submit', handleSubmit) + return () => form.removeEventListener('submit', handleSubmit) + }, [flushApply, pending]) + + return ( + +
+ {children} + {saveError ? ( +

{saveError}

+ ) : null} +
+
+ ) +} + +/** + * 数据明细筛选行的单个筛选项。 + * 与寻源明细的筛选控件保持同样的「搜索 + 勾选」交互,但候选项与筛选状态都走服务端: + * 候选来自 filter-options 接口,勾选结果沿用列筛选的 filters / filterRef 持久化口径。 + * 选项可能有几万个,所以列表做窗口化渲染,并由服务端候选搜索缩小范围。 + */ +export function DropshipFieldFilter({ + field, + noun, + allLabel, +}: { + field: Dropship1688FilterField + /** 字段名,例如「运营」,用于拼出「运营筛选」「搜索运营」。 */ + noun: string + allLabel: string +}) { + const group = useContext(FilterGroupContext) + if (!group) throw new Error('DropshipFieldFilter must be used inside DropshipFieldFilterGroup') + const { + filters, + pending, + saving, + readPeriod, + scheduleSelection, + cancelScheduledApply, + } = group + const fieldLabel = `${noun}筛选` + const [open, setOpen] = useState(false) + const [search, setSearch] = useState('') + const [debouncedSearch, setDebouncedSearch] = useState('') + const [values, setValues] = useState([]) + const [selection, setSelection] = useState([]) + const [loading, setLoading] = useState(false) + const [error, setError] = useState('') + const [retry, setRetry] = useState(0) + const [scrollTop, setScrollTop] = useState(0) + // 触发器靠屏幕右缘时,弹层改为向左展开,避免溢出视口。 + const [alignRight, setAlignRight] = useState(false) + const containerRef = useRef(null) + const searchRef = useRef(null) + const listRef = useRef(null) + const serializedFilters = useMemo( + () => { + const candidateFilters = { ...filters } + delete candidateFilters[field] + return serializeDropship1688Filters(candidateFilters) + }, + [field, filters], + ) + const current = filters[field] + const excludeMode = current?.mode === 'exclude' + const selected = useMemo( + () => (current?.mode === 'include' ? current.values : []), + [current], + ) + const selectedSet = useMemo(() => new Set(selection), [selection]) + const remoteSearch = field === 'spu' || field === 'sku' || field === 'barcode' + const remoteOptionQuery = remoteSearch + ? debouncedSearch + : '' + const waitingForQuery = remoteSearch && !remoteOptionQuery.trim() + const matches = useMemo(() => { + const query = debouncedSearch.trim().toLocaleLowerCase() + if (!query) return values + return values.filter((value) => value.toLocaleLowerCase().includes(query)) + }, [debouncedSearch, values]) + const windowStart = Math.max(0, Math.floor(scrollTop / ROW_HEIGHT) - 3) + const summary = excludeMode && current && current.values.length > 0 + ? `排除 ${current.values.length} 项` + : current?.mode === 'include' && current.values.length === 0 + ? '已选 0 项' + : selected.length === 0 + ? allLabel + : selected.length === 1 + ? selected[0] + : `已选 ${selected.length} 项` + + useEffect(() => { + const timer = setTimeout(() => setDebouncedSearch(search), SEARCH_DEBOUNCE_MS) + return () => clearTimeout(timer) + }, [search]) + + useEffect(() => { + if (!open || !waitingForQuery) return + setValues(selected) + setLoading(false) + setError('') + }, [open, selected, waitingForQuery]) + + useEffect(() => { + if (!open || waitingForQuery) return + const controller = new AbortController() + async function load() { + setLoading(true) + setError('') + try { + const { dateFrom, dateTo, keyword } = readPeriod() + const response = await fetch('/api/supply-chain/1688-dropship-data/filter-options', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + field, + keyword, + optionQuery: remoteOptionQuery, + dateFrom: dateFrom || undefined, + dateTo: dateTo || undefined, + filters: JSON.parse(serializedFilters || '{}'), + }), + signal: controller.signal, + }) + const payload = await response.json() + if (!response.ok || !payload.success || !Array.isArray(payload.data?.values)) { + throw new Error(payload.error?.message || '候选值加载失败') + } + if (!controller.signal.aborted) setValues(payload.data.values) + } catch (reason) { + if (!controller.signal.aborted) { + setError(reason instanceof Error ? reason.message : '候选值加载失败') + } + } finally { + if (!controller.signal.aborted) setLoading(false) + } + } + void load() + return () => controller.abort() + }, [open, field, remoteOptionQuery, readPeriod, serializedFilters, retry, waitingForQuery]) + + useEffect(() => { + if (!open) return + searchRef.current?.focus() + const handlePointerDown = (event: MouseEvent) => { + if (!containerRef.current?.contains(event.target as Node)) setOpen(false) + } + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') setOpen(false) + } + document.addEventListener('pointerdown', handlePointerDown) + document.addEventListener('keydown', handleKeyDown) + return () => { + document.removeEventListener('pointerdown', handlePointerDown) + document.removeEventListener('keydown', handleKeyDown) + } + }, [open]) + + useEffect(() => { + // jsdom 没有实现 Element.scrollTo,测试环境里用可选调用兜住。 + listRef.current?.scrollTo?.({ top: 0 }) + setScrollTop(0) + }, [debouncedSearch, open]) + + function scheduleApply(nextSelection: string[]) { + setSelection(nextSelection) + scheduleSelection(field, nextSelection) + } + + useEffect(() => { + if (open) setSelection(selected) + }, [open, selected]) + + function close() { + setOpen(false) + setSearch('') + } + + return ( +
+ {fieldLabel} + + {open ? ( +
+
+
+
+ + + {selection.length > 0 ? `已选 ${selection.length} 项` : '未筛选,显示全部'} +
+ {excludeMode ? ( +

+ 当前筛选是排除模式,勾选后会改为包含模式。 +

+ ) : null} +
setScrollTop(event.currentTarget.scrollTop)} + > + {loading ? ( +

加载中…

+ ) : error ? ( +
+ {error} + +
+ ) : matches.length === 0 ? ( +

+ {waitingForQuery + ? '请输入关键词搜索' + : debouncedSearch.trim() + ? `没有匹配「${debouncedSearch.trim()}」的选项` + : '没有可选项'} +

+ ) : ( +
+
+ {matches.slice(windowStart, windowStart + WINDOW_SIZE).map((value) => ( + + ))} +
+
+ )} +
+
+ ) : null} +
+ ) +} diff --git a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipSourcingRow.test.tsx b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipSourcingRow.test.tsx new file mode 100644 index 00000000..5598e07a --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipSourcingRow.test.tsx @@ -0,0 +1,142 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import type { Dropship1688SourcingTaskDto } from '@/server/services/dropship-1688-sourcing.service' +import { DropshipSourcingRow } from './DropshipSourcingRow' +import { revokeDropship1688SourcingTask } from './sourcing.actions' + +const refresh = jest.fn() + +jest.mock('next/navigation', () => ({ useRouter: () => ({ refresh }) })) +jest.mock('./sourcing.actions', () => ({ + updateDropship1688SourcingTask: jest.fn(), + revokeDropship1688SourcingTask: jest.fn(), +})) + +function task(overrides: Partial = {}): Dropship1688SourcingTaskDto { + return { + id: 'task-1', + sourceArchiveId: 'archive-1', + sourceSpu: 'SPU-ONE', + sourceBarcode: 'DF-ONE', + sourceCostPrice: '70.0000', + sourceSkuOperator: '运营甲', + sourceDateFrom: '2026-09-01', + sourceDateTo: '2026-09-10', + purchaserUserId: 'buyer-1', + purchaserName: '采购甲', + supplierName: '', + quotedPriceTaxIncluded: null, + invoiceTaxPoint: null, + sourcingMode: '', + jianshangBarcode: '', + acceptedAt: '2026-09-16T01:00:00.000Z', + updatedAt: '2026-09-16T01:00:00.000Z', + sku: 'SKU-ONE', + hasImage: false, + ...overrides, + } +} + +function renderRow(options: { + task?: Dropship1688SourcingTaskDto + editable?: boolean + revocable?: boolean +} = {}) { + return render( + + + + +
, + ) +} + +const revokeName = '撤销 DF-ONE 采购甲 的承接' + +describe('DropshipSourcingRow revoke', () => { + let alertSpy: jest.SpyInstance + let confirmSpy: jest.SpyInstance + + beforeEach(() => { + jest.clearAllMocks() + alertSpy = jest.spyOn(window, 'alert').mockImplementation(() => undefined) + confirmSpy = jest.spyOn(window, 'confirm').mockReturnValue(true) + }) + + afterEach(() => { + alertSpy.mockRestore() + confirmSpy.mockRestore() + }) + + it('offers revoke next to edit for an own acceptance that has no jianshang barcode', () => { + renderRow() + const revoke = screen.getByRole('button', { name: revokeName }) + expect(revoke).toBeEnabled() + expect(revoke).toHaveAttribute('title', '撤销承接') + expect(screen.getByRole('button', { name: '编辑 DF-ONE 采购甲 的寻源明细' })).toBeEnabled() + }) + + it('disables revoke for another purchaser acceptance', () => { + renderRow({ editable: false, revocable: false }) + const revoke = screen.getByRole('button', { name: revokeName }) + expect(revoke).toBeDisabled() + expect(revoke).toHaveAttribute('title', '只能撤销本人承接的寻源任务') + }) + + it('keeps an administrator edit-capable but unable to revoke another purchaser acceptance', () => { + renderRow({ editable: true, revocable: false }) + expect(screen.getByRole('button', { name: '编辑 DF-ONE 采购甲 的寻源明细' })).toBeEnabled() + expect(screen.getByRole('button', { name: revokeName })).toBeDisabled() + }) + + it('disables revoke once a jianshang barcode is filled in', () => { + renderRow({ task: task({ jianshangBarcode: 'JS-001' }) }) + expect(screen.getByText('已启用')).toBeVisible() + const revoke = screen.getByRole('button', { name: revokeName }) + expect(revoke).toBeDisabled() + expect(revoke).toHaveAttribute('title', '已填写简尚条码,不能撤销') + }) + + it('revokes the acceptance after confirmation and refreshes both views', async () => { + jest.mocked(revokeDropship1688SourcingTask).mockResolvedValue({ ok: true }) + renderRow() + fireEvent.click(screen.getByRole('button', { name: revokeName })) + await waitFor(() => expect(revokeDropship1688SourcingTask).toHaveBeenCalledWith({ taskId: 'task-1' })) + expect(confirmSpy).toHaveBeenCalledWith(expect.stringContaining('DF-ONE')) + expect(confirmSpy).toHaveBeenCalledWith(expect.stringContaining('采购甲')) + expect(refresh).toHaveBeenCalled() + expect(screen.getByRole('button', { name: revokeName })).toBeDisabled() + expect(screen.getByRole('button', { name: revokeName })).toHaveTextContent('已撤销') + }) + + it('does not revoke anything when the confirmation is dismissed', () => { + confirmSpy.mockReturnValue(false) + renderRow() + fireEvent.click(screen.getByRole('button', { name: revokeName })) + expect(revokeDropship1688SourcingTask).not.toHaveBeenCalled() + expect(refresh).not.toHaveBeenCalled() + }) + + it('surfaces a domain failure without refreshing', async () => { + jest.mocked(revokeDropship1688SourcingTask).mockResolvedValue({ + ok: false, + message: '该寻源任务已填写简尚条码,不能撤销', + }) + renderRow() + fireEvent.click(screen.getByRole('button', { name: revokeName })) + await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('该寻源任务已填写简尚条码,不能撤销')) + expect(refresh).not.toHaveBeenCalled() + }) + + it('hides unexpected transport failures behind a safe message', async () => { + jest.mocked(revokeDropship1688SourcingTask).mockRejectedValue(new Error('database-secret')) + renderRow() + fireEvent.click(screen.getByRole('button', { name: revokeName })) + await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('撤销失败,请稍后重试')) + expect(alertSpy).not.toHaveBeenCalledWith('database-secret') + expect(refresh).not.toHaveBeenCalled() + }) +}) diff --git a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipSourcingRow.tsx b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipSourcingRow.tsx new file mode 100644 index 00000000..ff58ad08 --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipSourcingRow.tsx @@ -0,0 +1,301 @@ +'use client' + +import { LoaderCircle, Pencil, Save, Undo2, X } from 'lucide-react' +import { useRouter } from 'next/navigation' +import { useEffect, useRef, useState } from 'react' +import { createPortal } from 'react-dom' +import type { Dropship1688SourcingTaskDto } from '@/server/services/dropship-1688-sourcing.service' +import { DropshipImageCell } from './DropshipImageCell' +import { revokeDropship1688SourcingTask, updateDropship1688SourcingTask } from './sourcing.actions' +import styles from './dropship-1688-data.module.css' + +type SourcingDraft = { + supplierName: string + quotedPriceTaxIncluded: string + invoiceTaxPoint: string + sourcingMode: string + jianshangBarcode: string +} + +const SOURCING_MODES = ['入库', '代发'] as const +const DECIMAL_SCALE = BigInt(10_000) +const ZERO = BigInt(0) +const ACCEPTED_AT_PATTERN = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/ + +function acceptedAtText(value: string) { + const match = ACCEPTED_AT_PATTERN.exec(value) + if (!match || Number.isNaN(Date.parse(value))) return '--' + // acceptedAt is a PostgreSQL TIMESTAMP (without time zone). Prisma's pg adapter + // tags that stored Shanghai wall-clock value with Z, so converting it again would add 8 hours. + return `${match[1]}-${match[2]}-${match[3]} ${match[4]}:${match[5]}:${match[6]}` +} + +function decimalInputText(value: string | null) { + if (!value) return '' + const [whole, fraction = ''] = value.split('.') + const compactFraction = fraction.replace(/0+$/, '') + return compactFraction ? `${whole}.${compactFraction}` : whole +} + +function taskDraft(task: Dropship1688SourcingTaskDto): SourcingDraft { + return { + supplierName: task.supplierName, + quotedPriceTaxIncluded: decimalInputText(task.quotedPriceTaxIncluded), + invoiceTaxPoint: decimalInputText(task.invoiceTaxPoint), + sourcingMode: SOURCING_MODES.includes(task.sourcingMode as typeof SOURCING_MODES[number]) + ? task.sourcingMode + : '', + jianshangBarcode: task.jianshangBarcode, + } +} + +function sameDraft(left: SourcingDraft, right: SourcingDraft) { + return Object.keys(left).every((key) => left[key as keyof SourcingDraft] === right[key as keyof SourcingDraft]) +} + +function decimalDifference(quotedPrice: string, sourceCostPrice: string | null) { + if (!sourceCostPrice || !/^\d+(?:\.\d{1,4})?$/.test(quotedPrice)) return null + const toScaledInteger = (value: string) => { + const [whole, fraction = ''] = value.split('.') + return BigInt(whole) * DECIMAL_SCALE + BigInt(fraction.padEnd(4, '0')) + } + return toScaledInteger(quotedPrice) - toScaledInteger(sourceCostPrice) +} + +function differenceText(value: bigint | null) { + if (value === null) return '--' + const sign = value > ZERO ? '+' : value < ZERO ? '-' : '' + const absolute = value < ZERO ? -value : value + const whole = absolute / DECIMAL_SCALE + const fraction = (absolute % DECIMAL_SCALE).toString().padStart(4, '0').replace(/0+$/, '') + return `${sign}¥${whole}.${fraction.padEnd(2, '0')}` +} + +export function DropshipSourcingRow({ task, editable, revocable, onRevoked }: { + task: Dropship1688SourcingTaskDto + editable: boolean + revocable: boolean + onRevoked?: () => void +}) { + const initialDraft = taskDraft(task) + const [draft, setDraft] = useState(initialDraft) + const [savedDraft, setSavedDraft] = useState(initialDraft) + const [editing, setEditing] = useState(false) + const [saving, setSaving] = useState(false) + const [revoking, setRevoking] = useState(false) + const [revoked, setRevoked] = useState(false) + const [feedback, setFeedback] = useState<{ type: 'success' | 'error'; message: string } | null>(null) + const router = useRouter() + const revokeSubmitting = useRef(false) + const dirty = !sameDraft(draft, savedDraft) + const fieldPrefix = `${task.sourceBarcode} ${task.purchaserName}` + const draftComparison = decimalDifference(draft.quotedPriceTaxIncluded, task.sourceCostPrice) + const savedComparison = decimalDifference(savedDraft.quotedPriceTaxIncluded, task.sourceCostPrice) + const draftComparisonClass = draftComparison === null || draftComparison === ZERO + ? styles.sourcingComparisonNeutral + : draftComparison > ZERO + ? styles.sourcingComparisonPositive + : styles.sourcingComparisonNegative + const savedComparisonClass = savedComparison === null || savedComparison === ZERO + ? styles.sourcingComparisonNeutral + : savedComparison > ZERO + ? styles.sourcingComparisonPositive + : styles.sourcingComparisonNegative + const enabled = savedDraft.jianshangBarcode.trim().length > 0 + const acceptedAt = acceptedAtText(task.acceptedAt) + const canRevoke = revocable && !enabled && !revoked + const revokeTitle = revoked + ? '已撤销,正在刷新' + : !revocable + ? '只能撤销本人承接的寻源任务' + : enabled + ? '已填写简尚条码,不能撤销' + : '撤销承接' + + useEffect(() => { + if (!editing) return + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape' && !saving) closeEditor() + } + window.addEventListener('keydown', handleKeyDown) + return () => window.removeEventListener('keydown', handleKeyDown) + }) + + function setField(field: keyof SourcingDraft, value: string) { + setDraft((current) => ({ ...current, [field]: value })) + setFeedback(null) + } + + function openEditor() { + if (!editable) return + setDraft(savedDraft) + setFeedback(null) + setEditing(true) + } + + function closeEditor() { + if (saving) return + setDraft(savedDraft) + setFeedback(null) + setEditing(false) + } + + async function save() { + if (!editable || saving || !dirty) return + setSaving(true) + setFeedback(null) + try { + const result = await updateDropship1688SourcingTask({ taskId: task.id, ...draft }) + if (!result.ok) { + setFeedback({ type: 'error', message: result.message }) + return + } + const normalized = taskDraft(result.task) + setDraft(normalized) + setSavedDraft(normalized) + setFeedback({ type: 'success', message: '已保存' }) + setEditing(false) + } catch { + setFeedback({ type: 'error', message: '保存失败,请稍后重试' }) + } finally { + setSaving(false) + } + } + + async function revoke() { + if (!canRevoke || revokeSubmitting.current) return + const confirmed = window.confirm( + `确认撤销这次承接吗?\n代发条码:${task.sourceBarcode}\n采购:${task.purchaserName}\n` + + '撤销后该采购在此条码上的承接记录会被删除,已填写的供应商和报价也会一并丢失,且无法恢复。', + ) + if (!confirmed) return + revokeSubmitting.current = true + setRevoking(true) + setFeedback(null) + try { + const result = await revokeDropship1688SourcingTask({ taskId: task.id }) + if (!result.ok) { + window.alert(result.message?.trim() || '撤销失败,请稍后重试') + return + } + setRevoked(true) + onRevoked?.() + router.refresh() + } catch { + // The action already maps domain failures to safe messages; anything thrown here is + // infrastructure-level, so never surface the raw error text to the user. + window.alert('撤销失败,请稍后重试') + } finally { + revokeSubmitting.current = false + setRevoking(false) + } + } + + return <> + + + + + {feedback?.type === 'success' ? feedback.message : ''} + + + + + + + {enabled ? '已启用' : '未启用'} + + + + + + {task.sourceSpu || '--'} + {task.sourceBarcode} + {task.sourceCostPrice ? `¥${Number(task.sourceCostPrice).toFixed(2)}` : '--'} + {savedDraft.quotedPriceTaxIncluded ? `¥${savedDraft.quotedPriceTaxIncluded}` : '--'} + + {differenceText(savedComparison)} + + {savedDraft.invoiceTaxPoint ? `${savedDraft.invoiceTaxPoint}%` : '--'} + {task.sourceSkuOperator || '--'} + {task.purchaserName} + {savedDraft.supplierName || '--'} + {savedDraft.sourcingMode || '--'} + {savedDraft.jianshangBarcode || '--'} + + {editing && typeof document !== 'undefined' ? createPortal( +
{ + if (event.target === event.currentTarget) closeEditor() + }}> +
{ + event.preventDefault() + void save() + }}> +
+
+

编辑寻源明细

+

{task.sourceBarcode} · 采购:{task.purchaserName} · 代发成本价:{task.sourceCostPrice ? `¥${Number(task.sourceCostPrice).toFixed(2)}` : '--'}

+
+ +
+
+ + +
+ 对比 + {differenceText(draftComparison)} +
+ + + +
+ {feedback?.type === 'error' ?

{feedback.message}

: null} +
+ + +
+
+
, + document.body, + ) : null} + +} diff --git a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipWorkspace.test.tsx b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipWorkspace.test.tsx new file mode 100644 index 00000000..fa419ccb --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipWorkspace.test.tsx @@ -0,0 +1,245 @@ +import { fireEvent, render, screen, waitFor, within } from '@testing-library/react' +import { DropshipWorkspace } from './DropshipWorkspace' + +const routerRefresh = jest.fn() + +jest.mock('./sourcing.actions', () => ({ + updateDropship1688SourcingTask: jest.fn(), + revokeDropship1688SourcingTask: jest.fn(), +})) +jest.mock('next/navigation', () => ({ useRouter: () => ({ refresh: routerRefresh }) })) + +function sourcingTask(overrides: Record = {}) { + return { + id: 'task-1', sourceArchiveId: 'archive-1', sourceBarcode: 'DF-ONE', + sourceCostPrice: '70.0000', sourceSkuOperator: '运营甲', sourceDateFrom: '2026-09-01', + sourceDateTo: '2026-09-10', purchaserUserId: 'buyer-1', purchaserName: '采购甲', + supplierName: '', quotedPriceTaxIncluded: null, invoiceTaxPoint: null, + sourcingMode: '', jianshangBarcode: '', + acceptedAt: '2026-09-16T17:23:45.000Z', updatedAt: '2026-09-16T17:23:45.000Z', + sourceSpu: 'SPU-ONE', sku: 'SKU-ONE', hasImage: false, ...overrides, + } +} + +function sourcingPage(overrides: Record = {}) { + return { + rows: [sourcingTask()], + total: 1, + page: 1, + pageSize: 50, + totalPages: 1, + filterOptions: { + purchaserNames: ['采购甲', '采购乙'], + sourceSpus: ['SPU-ONE', 'SPU-TWO'], + sourceSkuOperators: ['运营甲', '运营乙'], + }, + ...overrides, + } +} + +function jsonResponse(data: unknown, headers: Record = {}) { + return { + ok: true, + headers: new Headers(headers), + json: async () => ({ data }), + blob: async () => new Blob(['workbook']), + } as Response +} + +function renderWorkspace(props: Partial[0]> = {}) { + return render( +
真实业绩
¥818,312.29
} + actorUserId="buyer-1" + {...props} + > + + 下一页 +
商品明细
+
, + ) +} + +describe('DropshipWorkspace', () => { + const fetchMock = jest.fn() + const originalFetch = global.fetch + const originalCreateObjectUrl = URL.createObjectURL + const originalRevokeObjectUrl = URL.revokeObjectURL + + beforeAll(() => { + global.fetch = fetchMock + URL.createObjectURL = jest.fn(() => 'blob:workbook') + URL.revokeObjectURL = jest.fn() + }) + + afterAll(() => { + global.fetch = originalFetch + URL.createObjectURL = originalCreateObjectUrl + URL.revokeObjectURL = originalRevokeObjectUrl + }) + + beforeEach(() => { + jest.clearAllMocks() + fetchMock.mockResolvedValue(jsonResponse(sourcingPage())) + }) + + it('keeps sourcing lazy and preserves the mounted detail panel across tab switches', async () => { + renderWorkspace() + const details = screen.getByRole('tab', { name: '数据明细' }) + const sourcing = screen.getByRole('tab', { name: '寻源明细' }) + const input = screen.getByRole('textbox', { name: '商品检索' }) + const table = screen.getByTestId('table-scroll') + + expect(fetchMock).not.toHaveBeenCalled() + fireEvent.change(input, { target: { value: 'DF-456' } }) + table.scrollLeft = 300 + table.scrollTop = 200 + fireEvent.click(sourcing) + + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)) + expect(fetchMock.mock.calls[0][0]).toBe( + '/api/supply-chain/1688-dropship-data/sourcing-list?page=1', + ) + expect(await screen.findByRole('cell', { name: 'DF-ONE' })).toBeVisible() + expect(screen.getByText('¥818,312.29')).not.toBeVisible() + + fireEvent.click(details) + expect(screen.getByRole('textbox', { name: '商品检索' })).toBe(input) + expect(input).toHaveValue('DF-456') + expect(table.scrollLeft).toBe(300) + expect(table.scrollTop).toBe(200) + expect(screen.getByRole('link', { name: '下一页' })).toHaveAttribute( + 'href', '?dateFrom=2026-09-01&page=2&filterRef=saved', + ) + }) + + it('supports keyboard tab navigation and exposes the sourcing table contract', async () => { + renderWorkspace() + const details = screen.getByRole('tab', { name: '数据明细' }) + const sourcing = screen.getByRole('tab', { name: '寻源明细' }) + fireEvent.keyDown(details, { key: 'ArrowRight' }) + expect(sourcing).toHaveFocus() + await screen.findByRole('cell', { name: 'DF-ONE' }) + + const table = screen.getByRole('table', { name: '寻源明细表' }) + expect(within(table).getAllByRole('columnheader').map((header) => header.textContent)).toEqual([ + '操作', '承接日期', '是否启用', '产品图片', '代发SPU', '代发条码', '代发成本价', '报价(含税)', + '对比', '发票税点', 'SKU运营', '采购', '供应商', '模式', '简尚条码', + ]) + expect(within(table).getByRole('cell', { name: '2026-09-16 17:23:45' })).toBeVisible() + expect(screen.getByRole('navigation', { name: '寻源明细分页' })).toHaveTextContent('每页 50 条') + + fireEvent.keyDown(sourcing, { key: 'Home' }) + expect(details).toHaveFocus() + }) + + it('runs purchaser, SPU and operator filters on the server and resets to page one', async () => { + fetchMock + .mockResolvedValueOnce(jsonResponse(sourcingPage({ + rows: Array.from({ length: 50 }, (_, index) => sourcingTask({ id: `task-${index}`, sourceBarcode: `DF-${index}` })), + total: 51, + totalPages: 2, + }))) + .mockResolvedValueOnce(jsonResponse(sourcingPage({ + rows: [sourcingTask({ id: 'task-2', sourceBarcode: 'DF-TWO', purchaserName: '采购乙' })], + total: 51, + page: 2, + totalPages: 2, + }))) + + renderWorkspace() + fireEvent.click(screen.getByRole('tab', { name: '寻源明细' })) + await screen.findByText('51 条') + fireEvent.click(screen.getByRole('button', { name: '下一页' })) + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2)) + expect(fetchMock.mock.calls[1][0]).toContain('page=2') + + fetchMock.mockResolvedValueOnce(jsonResponse(sourcingPage({ + rows: [sourcingTask({ id: 'task-2', sourceBarcode: 'DF-TWO', purchaserName: '采购乙' })], + total: 1, + }))) + fireEvent.click(screen.getByRole('button', { name: '采购筛选' })) + fireEvent.click(screen.getByRole('checkbox', { name: '采购乙' })) + + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3)) + const requestUrl = String(fetchMock.mock.calls[2][0]) + expect(requestUrl).toContain('page=1') + expect(requestUrl).toContain(`purchaser=${encodeURIComponent('采购乙')}`) + expect(await screen.findByRole('cell', { name: 'DF-TWO' })).toBeVisible() + }) + + it('exports all matching rows by filters instead of sending current-page task IDs', async () => { + fetchMock.mockImplementation(async (input: RequestInfo | URL) => { + const url = String(input) + if (url.endsWith('/sourcing-export')) { + return jsonResponse(null, { 'X-Exported-Rows': '75' }) + } + return jsonResponse(sourcingPage({ total: 75, totalPages: 2 })) + }) + const anchorClick = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) + renderWorkspace({ canExportSourcing: true }) + fireEvent.click(screen.getByRole('tab', { name: '寻源明细' })) + await screen.findByText('75 条') + + fireEvent.click(screen.getByRole('button', { name: '采购筛选' })) + fireEvent.click(screen.getByRole('checkbox', { name: '采购乙' })) + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2)) + const exportButton = screen.getByRole('button', { name: '导出模板' }) + await waitFor(() => expect(exportButton).toBeEnabled()) + fireEvent.click(exportButton) + + await screen.findByText('已导出 75 条寻源数据') + const exportCall = fetchMock.mock.calls.find(([url]) => String(url).endsWith('/sourcing-export')) + expect(exportCall?.[1]).toMatchObject({ method: 'POST' }) + expect(JSON.parse(String((exportCall?.[1] as RequestInit).body))).toEqual({ + filters: { + purchaserNames: ['采购乙'], + sourceSpus: [], + sourceSkuOperators: [], + }, + }) + expect(anchorClick).toHaveBeenCalled() + anchorClick.mockRestore() + }) + + it('reloads the active server page after importing a workbook', async () => { + fetchMock.mockImplementation(async (input: RequestInfo | URL) => { + const url = String(input) + if (url.endsWith('/sourcing-import')) return jsonResponse({ updated: 2 }) + return jsonResponse(sourcingPage()) + }) + const { container } = renderWorkspace({ canImportSourcing: true }) + fireEvent.click(screen.getByRole('tab', { name: '寻源明细' })) + await screen.findByRole('cell', { name: 'DF-ONE' }) + + const file = new File(['xlsx'], '寻源明细.xlsx', { + type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + }) + const input = container.querySelector('input[type="file"]')! + fireEvent.change(input, { target: { files: [file] } }) + + await screen.findByText('导入完成,已更新 2 条寻源数据') + await waitFor(() => { + const listCalls = fetchMock.mock.calls.filter(([url]) => String(url).includes('/sourcing-list?')) + expect(listCalls).toHaveLength(2) + }) + expect(routerRefresh).toHaveBeenCalled() + }) + + it('derives row edit and revoke capabilities from the actor instead of an RSC task-id list', async () => { + fetchMock.mockResolvedValue(jsonResponse(sourcingPage({ + rows: [ + sourcingTask(), + sourcingTask({ id: 'task-2', purchaserUserId: 'buyer-2', purchaserName: '采购乙' }), + ], + total: 2, + }))) + renderWorkspace({ canEditSourcing: true }) + fireEvent.click(screen.getByRole('tab', { name: '寻源明细' })) + + expect(await screen.findByRole('button', { name: '编辑 DF-ONE 采购甲 的寻源明细' })).toBeEnabled() + expect(screen.getByRole('button', { name: '撤销 DF-ONE 采购甲 的承接' })).toBeEnabled() + expect(screen.getByRole('button', { name: '编辑 DF-ONE 采购乙 的寻源明细' })).toBeDisabled() + expect(screen.getByRole('button', { name: '撤销 DF-ONE 采购乙 的承接' })).toBeDisabled() + }) +}) diff --git a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipWorkspace.tsx b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipWorkspace.tsx new file mode 100644 index 00000000..6bcb9b24 --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/DropshipWorkspace.tsx @@ -0,0 +1,408 @@ +'use client' + +import { ArrowLeft, ArrowRight, Download, LoaderCircle, RefreshCw, Upload } from 'lucide-react' +import { useRouter } from 'next/navigation' +import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from 'react' +import type { Dropship1688SourcingPageDto } from '@/server/services/dropship-1688-sourcing.service' +import { DropshipSourcingRow } from './DropshipSourcingRow' +import { SourcingFilterSelect } from './SourcingFilterSelect' +import styles from './dropship-1688-data.module.css' + +const TABS = [ + { key: 'details', label: '数据明细' }, + { key: 'sourcing', label: '寻源明细' }, +] as const + +const SOURCING_COLUMNS = [ + { key: 'actions', label: '操作', width: 176 }, + { key: 'acceptedAt', label: '承接日期', width: 168 }, + { key: 'enabled', label: '是否启用', width: 110 }, + { key: 'image', label: '产品图片', width: 150 }, + { key: 'sourceSpu', label: '代发SPU', width: 160 }, + { key: 'sourceBarcode', label: '代发条码', width: 170 }, + { key: 'sourceCostPrice', label: '代发成本价', width: 150 }, + { key: 'quotedPriceTaxIncluded', label: '报价(含税)', width: 150 }, + { key: 'comparison', label: '对比', width: 160 }, + { key: 'invoiceTaxPoint', label: '发票税点', width: 130 }, + { key: 'sourceSkuOperator', label: 'SKU运营', width: 160 }, + { key: 'purchaserName', label: '采购', width: 150 }, + { key: 'supplierName', label: '供应商', width: 180 }, + { key: 'sourcingMode', label: '模式', width: 130 }, + { key: 'jianshangBarcode', label: '简尚条码', width: 170 }, +] as const + +type View = typeof TABS[number]['key'] + +async function responseMessage(response: Response, fallback: string) { + try { + const payload = await response.json() as { error?: { message?: string } } + return payload.error?.message || fallback + } catch { + return fallback + } +} + +function appendValues(params: URLSearchParams, key: string, values: readonly string[]) { + values.forEach((value) => params.append(key, value)) +} + +export function DropshipWorkspace({ + summary, + actorUserId, + canEditAllSourcing = false, + canEditSourcing = false, + canExportSourcing = false, + canImportSourcing = false, + children, +}: { + summary: ReactNode + actorUserId: string + canEditAllSourcing?: boolean + canEditSourcing?: boolean + canExportSourcing?: boolean + canImportSourcing?: boolean + children: ReactNode +}) { + const [view, setView] = useState('details') + const [purchaserFilter, setPurchaserFilter] = useState([]) + const [spuFilter, setSpuFilter] = useState([]) + const [operatorFilter, setOperatorFilter] = useState([]) + const [sourcingPage, setSourcingPage] = useState(null) + const [sourcingPageNumber, setSourcingPageNumber] = useState(1) + const [sourcingLoading, setSourcingLoading] = useState(false) + const [sourcingError, setSourcingError] = useState('') + const [sourcingRevision, setSourcingRevision] = useState(0) + const [transferring, setTransferring] = useState<'export' | 'import' | null>(null) + const [transferFeedback, setTransferFeedback] = useState<{ type: 'success' | 'error'; message: string } | null>(null) + const id = useId() + const buttons = useRef>([]) + const fileInput = useRef(null) + const router = useRouter() + const rows = sourcingPage?.rows ?? [] + const total = sourcingPage?.total ?? 0 + const currentPage = sourcingPage?.page ?? sourcingPageNumber + const totalPages = sourcingPage?.totalPages ?? 1 + const hasSourcingFilters = Boolean( + purchaserFilter.length || spuFilter.length || operatorFilter.length, + ) + + useEffect(() => { + if (view !== 'sourcing') return + + const controller = new AbortController() + const params = new URLSearchParams({ page: String(sourcingPageNumber) }) + appendValues(params, 'purchaser', purchaserFilter) + appendValues(params, 'spu', spuFilter) + appendValues(params, 'operator', operatorFilter) + + setSourcingLoading(true) + setSourcingError('') + void (async () => { + try { + const response = await fetch( + `/api/supply-chain/1688-dropship-data/sourcing-list?${params.toString()}`, + { signal: controller.signal }, + ) + if (!response.ok) { + throw new Error(await responseMessage(response, '寻源明细加载失败,请稍后重试')) + } + const payload = await response.json() as { data?: Dropship1688SourcingPageDto } + if (!payload.data || !Array.isArray(payload.data.rows)) { + throw new Error('寻源明细返回格式不正确') + } + if (controller.signal.aborted) return + setSourcingPage(payload.data) + if (payload.data.page !== sourcingPageNumber) { + setSourcingPageNumber(payload.data.page) + } + } catch (error) { + if (controller.signal.aborted) return + setSourcingError(error instanceof Error ? error.message : '寻源明细加载失败,请稍后重试') + } finally { + if (!controller.signal.aborted) setSourcingLoading(false) + } + })() + + return () => controller.abort() + }, [operatorFilter, purchaserFilter, sourcingPageNumber, sourcingRevision, spuFilter, view]) + + function handleKeyDown(event: KeyboardEvent, index: number) { + let next: number + switch (event.key) { + case 'ArrowRight': next = (index + 1) % TABS.length; break + case 'ArrowLeft': next = (index + TABS.length - 1) % TABS.length; break + case 'Home': next = 0; break + case 'End': next = TABS.length - 1; break + default: return + } + event.preventDefault() + setView(TABS[next].key) + buttons.current[next]?.focus() + } + + function resetSourcingFilters() { + setPurchaserFilter([]) + setSpuFilter([]) + setOperatorFilter([]) + setSourcingPageNumber(1) + setTransferFeedback(null) + } + + function changeSourcingFilter(setter: (values: string[]) => void, values: string[]) { + setter(values) + setSourcingPageNumber(1) + setTransferFeedback(null) + } + + function reloadSourcing() { + setSourcingRevision((revision) => revision + 1) + } + + async function exportSourcingTasks() { + if (total === 0 || transferring) return + setTransferring('export') + setTransferFeedback(null) + try { + const response = await fetch('/api/supply-chain/1688-dropship-data/sourcing-export', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + filters: { + purchaserNames: purchaserFilter, + sourceSpus: spuFilter, + sourceSkuOperators: operatorFilter, + }, + }), + }) + if (!response.ok) throw new Error(await responseMessage(response, '导出失败,请稍后重试')) + const blob = await response.blob() + const url = URL.createObjectURL(blob) + const anchor = document.createElement('a') + anchor.href = url + anchor.download = `1688代发寻源明细-${new Date().toISOString().slice(0, 10)}.xlsx` + anchor.click() + URL.revokeObjectURL(url) + const exportedRows = Number.parseInt(response.headers.get('X-Exported-Rows') ?? '', 10) + setTransferFeedback({ + type: 'success', + message: `已导出 ${Number.isSafeInteger(exportedRows) ? exportedRows : total} 条寻源数据`, + }) + } catch (error) { + setTransferFeedback({ + type: 'error', + message: error instanceof Error ? error.message : '导出失败,请稍后重试', + }) + } finally { + setTransferring(null) + } + } + + async function importSourcingTasks(file: File) { + if (transferring) return + setTransferring('import') + setTransferFeedback(null) + try { + const form = new FormData() + form.set('file', file) + const response = await fetch('/api/supply-chain/1688-dropship-data/sourcing-import', { + method: 'POST', + body: form, + }) + if (!response.ok) throw new Error(await responseMessage(response, '导入失败,请检查文件后重试')) + const payload = await response.json() as { data?: { updated?: number } } + const updated = payload.data?.updated ?? 0 + setTransferFeedback({ type: 'success', message: `导入完成,已更新 ${updated} 条寻源数据` }) + reloadSourcing() + router.refresh() + } catch (error) { + setTransferFeedback({ + type: 'error', + message: error instanceof Error ? error.message : '导入失败,请检查文件后重试', + }) + } finally { + setTransferring(null) + } + } + + return ( +
+
+
+ {TABS.map((tab, index) => ( + + ))} +
+
+ + +
+ ) +} diff --git a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/SourcingFilterSelect.test.tsx b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/SourcingFilterSelect.test.tsx new file mode 100644 index 00000000..62b065e5 --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/SourcingFilterSelect.test.tsx @@ -0,0 +1,104 @@ +import { fireEvent, render, screen } from '@testing-library/react' +import { useState } from 'react' +import { SourcingFilterSelect } from './SourcingFilterSelect' + +function Harness({ options }: { options: readonly string[] }) { + const [selected, setSelected] = useState([]) + return ( + + ) +} + +function openList(options: readonly string[] = ['采购甲', '采购乙', '采购丙']) { + render() + const trigger = screen.getByRole('button', { name: '采购筛选' }) + fireEvent.click(trigger) + return trigger +} + +describe('SourcingFilterSelect', () => { + it('summarizes the current selection on the trigger', () => { + const trigger = openList() + expect(trigger).toHaveTextContent('全部采购') + expect(trigger).toHaveAttribute('data-active', 'false') + + fireEvent.click(screen.getByRole('checkbox', { name: '采购甲' })) + expect(trigger).toHaveTextContent('采购甲') + expect(trigger).toHaveAttribute('data-active', 'true') + + fireEvent.click(screen.getByRole('checkbox', { name: '采购乙' })) + expect(trigger).toHaveTextContent('已选 2 项') + }) + + it('lists every option and toggles a value off again', () => { + openList(['采购甲', '采购乙']) + expect(screen.getAllByRole('checkbox')).toHaveLength(2) + + const option = screen.getByRole('checkbox', { name: '采购甲' }) + fireEvent.click(option) + expect(option).toBeChecked() + fireEvent.click(option) + expect(option).not.toBeChecked() + expect(screen.getByRole('button', { name: '采购筛选' })).toHaveTextContent('全部采购') + }) + + it('searches the option list and reports when nothing matches', () => { + openList(['采购甲', '采购乙', '运营丙']) + fireEvent.change(screen.getByRole('searchbox', { name: '搜索采购' }), { + target: { value: '乙' }, + }) + expect(screen.getByRole('checkbox', { name: '采购乙' })).toBeInTheDocument() + expect(screen.queryByRole('checkbox', { name: '采购甲' })).not.toBeInTheDocument() + + fireEvent.change(screen.getByRole('searchbox', { name: '搜索采购' }), { + target: { value: '不存在' }, + }) + expect(screen.getByText('没有匹配「不存在」的选项')).toBeVisible() + }) + + it('checks only the currently matching options when using bulk select', () => { + const trigger = openList(['采购甲', '采购乙', '采购丙']) + fireEvent.change(screen.getByRole('searchbox', { name: '搜索采购' }), { + target: { value: '采购' }, + }) + fireEvent.click(screen.getByRole('button', { name: '全选当前结果' })) + expect(trigger).toHaveTextContent('已选 3 项') + + fireEvent.change(screen.getByRole('searchbox', { name: '搜索采购' }), { + target: { value: '丙' }, + }) + fireEvent.click(screen.getByRole('button', { name: '清空' })) + expect(trigger).toHaveTextContent('全部采购') + }) + + it('disables bulk select when every matching option is already checked', () => { + openList(['采购甲']) + const selectAll = screen.getByRole('button', { name: '全选全部' }) + expect(selectAll).toBeEnabled() + fireEvent.click(selectAll) + expect(selectAll).toBeDisabled() + }) + + it('closes on Escape and on an outside click', () => { + openList() + expect(screen.getByRole('dialog', { name: '采购选项' })).toBeVisible() + fireEvent.keyDown(document, { key: 'Escape' }) + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + + fireEvent.click(screen.getByRole('button', { name: '采购筛选' })) + expect(screen.getByRole('dialog')).toBeVisible() + fireEvent.mouseDown(document.body) + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + }) + + it('tells the user when there is nothing to choose from', () => { + openList([]) + expect(screen.getByText('暂无可选项')).toBeVisible() + }) +}) diff --git a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/SourcingFilterSelect.tsx b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/SourcingFilterSelect.tsx new file mode 100644 index 00000000..25f2c333 --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/SourcingFilterSelect.tsx @@ -0,0 +1,165 @@ +'use client' + +import { Check, ChevronDown, Search, X } from 'lucide-react' +import { useEffect, useMemo, useRef, useState } from 'react' +import styles from './dropship-1688-data.module.css' + +const LIST_MAX_HEIGHT = 232 +const POPOVER_WIDTH = 296 + +/** + * 寻源明细的工具条筛选项。 + * 选项数量会随承接记录增长,因此这里不使用原生 select,而是带搜索的可多选勾选列表。 + * 约定:selected 为空数组表示「全部」,与工具条原有的「全部采购 / 全部SPU / 全部运营」语义一致。 + */ +export function SourcingFilterSelect({ + noun, + allLabel, + options, + selected, + onChange, +}: { + /** 字段名,例如「采购」,用于拼出「采购筛选」「搜索采购」「采购选项」。 */ + noun: string + /** 未筛选时触发器显示的文案,例如「全部采购」。 */ + allLabel: string + options: readonly string[] + selected: readonly string[] + onChange: (next: string[]) => void +}) { + const fieldLabel = `${noun}筛选` + const [open, setOpen] = useState(false) + const [search, setSearch] = useState('') + // 触发器靠屏幕右缘时,弹层改为向左展开,避免溢出视口。 + const [alignRight, setAlignRight] = useState(false) + const containerRef = useRef(null) + const searchRef = useRef(null) + + const selectedSet = useMemo(() => new Set(selected), [selected]) + const matching = useMemo(() => { + const query = search.trim().toLocaleLowerCase() + if (!query) return options + return options.filter((option) => option.toLocaleLowerCase().includes(query)) + }, [options, search]) + const matchingChecked = matching.reduce((count, option) => count + Number(selectedSet.has(option)), 0) + const allMatchingChecked = matching.length > 0 && matchingChecked === matching.length + + const summary = selected.length === 0 + ? allLabel + : selected.length === 1 + ? selected[0] + : `已选 ${selected.length} 项` + + useEffect(() => { + if (!open) return + searchRef.current?.focus() + }, [open]) + + useEffect(() => { + if (!open) return + const handlePointerDown = (event: MouseEvent) => { + if (!containerRef.current?.contains(event.target as Node)) setOpen(false) + } + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') setOpen(false) + } + document.addEventListener('mousedown', handlePointerDown) + document.addEventListener('keydown', handleKeyDown) + return () => { + document.removeEventListener('mousedown', handlePointerDown) + document.removeEventListener('keydown', handleKeyDown) + } + }, [open]) + + function close() { + setOpen(false) + setSearch('') + } + + function toggle(option: string) { + onChange(selectedSet.has(option) + ? selected.filter((value) => value !== option) + : [...selected, option]) + } + + function checkAllMatching() { + onChange([...new Set([...selected, ...matching])]) + } + + return ( +
+ {fieldLabel} + + {open ? ( +
+
+
+
+ + + {selected.length > 0 ? `已选 ${selected.length} 项` : '未筛选,显示全部'} +
+
+ {options.length === 0 ? ( +

暂无可选项

+ ) : matching.length === 0 ? ( +

没有匹配「{search.trim()}」的选项

+ ) : matching.map((option) => { + const checked = selectedSet.has(option) + return ( + + ) + })} +
+
+ ) : null} +
+ ) +} diff --git a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/dropship-1688-data.module.css b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/dropship-1688-data.module.css index 901a3d46..5a87c8dd 100644 --- a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/dropship-1688-data.module.css +++ b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/dropship-1688-data.module.css @@ -10,17 +10,865 @@ .toolbar { display: flex; + flex-wrap: wrap; + flex-shrink: 0; min-height: 54px; align-items: center; justify-content: space-between; - gap: 24px; + gap: 10px 18px; padding: 9px 18px; border-bottom: 1px solid var(--sc-border); background: var(--sc-surface); } +.workspaceNavigation { + display: flex; + flex-shrink: 0; + justify-content: flex-start; + padding: 6px 18px 6px 0; + border-bottom: 1px solid var(--sc-border); + background: var(--sc-surface); +} + +.workspaceTabs { + display: inline-flex; + flex: 0 0 auto; + align-items: center; + gap: 3px; + padding: 3px; + border: 1px solid var(--sc-border); + border-radius: 6px; + background: var(--sc-surface-muted); +} + +.workspacePanel { + position: relative; + display: flex; + flex: 1; + min-height: 0; + flex-direction: column; +} + +.workspaceTabs button { + min-height: 26px; +} + +.workspacePanel[hidden] { + display: none; +} + +.sourcingTableRegion { + flex: 1; + min-height: 0; + padding: 14px 18px 72px; +} + +.sourcingToolbar { + display: flex; + min-height: 58px; + flex-wrap: wrap; + flex-shrink: 0; + align-items: flex-end; + gap: 8px 18px; + padding: 9px 18px; + border-bottom: 1px solid var(--sc-border); + background: var(--sc-surface); +} + +.sourcingFilters, +.sourcingTransferActions { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 8px; +} + +.sourcingFilters { + flex: 1 1 auto; +} + +.sourcingFilterField { + position: relative; + display: flex; + min-width: 142px; + flex-direction: column; + gap: 4px; +} + +.sourcingFilterLabel { + color: var(--sc-muted); + font-size: 11px; +} + +.sourcingFilterTrigger { + display: flex; + width: 100%; + height: 32px; + min-width: 0; + align-items: center; + justify-content: space-between; + gap: 6px; + border: 1px solid var(--sc-border); + border-radius: 5px; + padding: 0 8px 0 9px; + outline: none; + background: var(--sc-surface); + color: var(--sc-ink); + font: inherit; + font-size: 12px; + letter-spacing: 0; + cursor: pointer; +} + +.sourcingFilterTrigger:hover { + border-color: #71717a; +} + +.sourcingFilterTrigger:focus-visible { + border-color: #71717a; + box-shadow: 0 0 0 2px rgba(82, 82, 91, .1); +} + +.sourcingFilterTrigger[data-active='true'] { + border-color: #27272a; + font-weight: 600; +} + +.sourcingFilterTriggerText { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.sourcingFilterPopover { + position: absolute; + top: calc(100% + 6px); + left: 0; + z-index: 60; + display: flex; + width: min(296px, calc(100vw - 40px)); + flex-direction: column; + gap: 10px; + padding: 12px; + border: 1px solid var(--sc-border); + border-radius: 8px; + background: var(--sc-surface); + box-shadow: 0 10px 24px rgba(24, 24, 27, .12); + color: var(--sc-ink); + font-size: 12px; +} + +.sourcingFilterSearch { + display: flex; + height: 32px; + align-items: center; + gap: 8px; + border: 1px solid var(--sc-border); + border-radius: 6px; + padding: 0 9px; + background: var(--sc-surface); + color: var(--sc-muted); +} + +.sourcingFilterSearch input { + width: 100%; + min-width: 0; + border: 0; + outline: none; + background: transparent; + color: var(--sc-ink); + font: inherit; + font-size: 12px; +} + +.sourcingFilterSearch > button { + display: inline-flex; + flex: none; + align-items: center; + border: 0; + padding: 0; + background: transparent; + color: var(--sc-muted); + cursor: pointer; +} + +.sourcingFilterActions { + display: flex; + align-items: center; + gap: 8px; +} + +.sourcingFilterActions button { + height: 28px; + border: 1px solid var(--sc-border); + border-radius: 5px; + padding: 0 10px; + background: var(--sc-surface); + color: var(--sc-ink); + font: inherit; + font-size: 12px; + cursor: pointer; +} + +.sourcingFilterActions button:hover:not(:disabled) { + background: var(--sc-hover); +} + +.sourcingFilterActions button:disabled { + border-color: var(--sc-border); + color: var(--sc-subtle); + cursor: not-allowed; +} + +.sourcingFilterActions > span { + margin-left: auto; + color: var(--sc-subtle); + font-size: 11px; +} + +.sourcingFilterList { + overflow-y: auto; + overscroll-behavior: contain; +} + +.sourcingFilterOption { + position: relative; + display: flex; + align-items: center; + gap: 8px; + border-radius: 5px; + padding: 7px 8px; + cursor: pointer; +} + +.sourcingFilterOption:hover { + background: var(--sc-hover); +} + +.sourcingFilterOption input { + position: absolute; + width: 1px; + height: 1px; + margin: 0; + opacity: 0; + pointer-events: none; +} + +.sourcingFilterOptionBox { + display: inline-flex; + width: 15px; + height: 15px; + flex: none; + align-items: center; + justify-content: center; + border: 1px solid var(--sc-border); + border-radius: 4px; + background: var(--sc-surface); + color: transparent; +} + +.sourcingFilterOption input:checked + .sourcingFilterOptionBox { + border-color: #27272a; + background: #27272a; + color: #fff; +} + +.sourcingFilterOption input:focus-visible + .sourcingFilterOptionBox { + box-shadow: 0 0 0 2px rgba(82, 82, 91, .2); +} + +.sourcingFilterOptionText { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.sourcingFilterEmpty { + margin: 0; + padding: 10px 6px; + color: var(--sc-subtle); + text-align: center; +} + +/* 数据明细筛选行的单个筛选项:触发器跟随筛选行 34px,弹层与勾选列表复用 sourcingFilter* 的观感。 */ +.dropshipFilterGroup { + display: contents; +} + +.dropshipFilterGroupError { + flex: 1 0 100%; + margin: 0; + color: #b91c1c; + font-size: 12px; + line-height: 1.4; +} + +.dropshipFilterField { + position: relative; + display: flex; + min-width: 142px; + flex-direction: column; + gap: 5px; +} + +.dropshipFilterLabel { + color: var(--sc-muted); + font-size: 11px; +} + +.dropshipFilterTrigger { + display: flex; + width: 100%; + height: 34px; + min-width: 0; + align-items: center; + justify-content: space-between; + gap: 6px; + border: 1px solid var(--sc-border); + border-radius: 5px; + padding: 0 9px; + outline: none; + background: var(--sc-surface); + color: var(--sc-ink); + font: inherit; + font-size: 12px; + letter-spacing: 0; + cursor: pointer; +} + +.dropshipFilterTrigger:hover:not(:disabled) { + border-color: #71717a; +} + +.dropshipFilterTrigger:focus-visible { + border-color: #71717a; + box-shadow: 0 0 0 2px rgba(82, 82, 91, .1); +} + +.dropshipFilterTrigger[data-active='true'] { + border-color: #27272a; + font-weight: 600; +} + +.dropshipFilterTrigger:disabled { + color: var(--sc-subtle); + cursor: not-allowed; +} + +.dropshipFilterTriggerText { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* 选项行定高,供窗口化渲染按行高切片。 */ +.dropshipFilterNotice { + margin: 0; + color: var(--sc-subtle); + font-size: 11px; + line-height: 1.5; +} + +.dropshipFilterError { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 8px 6px; + color: #b91c1c; +} + +.dropshipFilterError > button { + flex: none; + height: 24px; + border: 1px solid var(--sc-border); + border-radius: 4px; + padding: 0 7px; + background: var(--sc-surface); + color: var(--sc-ink); + font: inherit; + font-size: 11px; + cursor: pointer; +} + +.sourcingResetButton, +.sourcingTransferActions button { + display: inline-flex; + height: 32px; + align-items: center; + justify-content: center; + gap: 5px; + border: 1px solid var(--sc-border); + border-radius: 5px; + padding: 0 10px; + background: var(--sc-surface); + color: var(--sc-muted); + font: inherit; + font-size: 12px; + white-space: nowrap; + cursor: pointer; +} + +.sourcingTransferActions button { + border-color: #3f3f46; + color: #27272a; +} + +.sourcingResetButton:hover:not(:disabled), +.sourcingTransferActions button:hover:not(:disabled) { + background: #f4f4f5; + color: #18181b; +} + +.sourcingResetButton:disabled, +.sourcingTransferActions button:disabled { + cursor: not-allowed; + opacity: .5; +} + +.sourcingTransferActions { + flex: 0 0 auto; +} + +.sourcingTransferActions > span { + min-width: 44px; + color: var(--sc-subtle); + font-size: 12px; + text-align: right; +} + +.sourcingTransferSuccess, +.sourcingTransferError { + width: 100%; + margin: 0; + font-size: 12px; +} + +.sourcingTransferSuccess { + color: #15803d; +} + +.sourcingTransferError { + color: #b91c1c; +} + +.sourcingTableScroll { + height: 100%; + overflow: auto; + border: 1px solid var(--sc-border); + background: var(--sc-surface); +} + +.table.sourcingTable { + min-width: 2314px; +} + +.sourcingTable td.sourcingEmpty { + height: 180px; + color: var(--sc-subtle); + font-size: 13px; + text-align: center; +} + +.sourcingLoading, +.sourcingLoadError { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 7px; +} + +.sourcingLoadError { + flex-direction: column; + color: #b91c1c; +} + +.sourcingLoadError button { + height: 30px; + border: 1px solid var(--sc-border); + border-radius: 5px; + padding: 0 10px; + background: var(--sc-surface); + color: var(--sc-ink); + font: inherit; + cursor: pointer; +} + +.sourcingEditableCell { + padding: 5px 7px !important; +} + +.sourcingEditableCell input, +.sourcingEditableCell select { + width: 100%; + height: 32px; + min-width: 0; + padding: 0 8px; + border: 1px solid #d4d4d8; + border-radius: 4px; + outline: none; + background: #fff; + color: #27272a; + font: inherit; + letter-spacing: 0; + text-align: left; +} + +.sourcingEditableCell select { + cursor: pointer; +} + +.sourcingEditableCell input:focus, +.sourcingEditableCell select:focus { + border-color: #71717a; + box-shadow: 0 0 0 2px rgba(82, 82, 91, .1); +} + +.sourcingEditableCell input:disabled, +.sourcingEditableCell select:disabled { + border-color: transparent; + background: transparent; + color: #71717a; + cursor: not-allowed; +} + +.sourcingComparisonCell { + padding: 5px 10px !important; + font-variant-numeric: tabular-nums; + font-weight: 600; + text-align: center !important; +} + +.sourcingComparisonPositive { + color: #15803d; +} + +.sourcingComparisonNegative { + color: #dc2626; +} + +.sourcingComparisonNeutral { + color: #71717a; +} + +.sourcingEnabledCell { + text-align: center !important; +} + +.sourcingAcceptedAtCell { + color: var(--sc-muted) !important; + font-variant-numeric: tabular-nums; +} + +.sourcingEnabled, +.sourcingDisabled { + display: inline-flex; + min-width: 54px; + height: 24px; + align-items: center; + justify-content: center; + border-radius: 4px; + font-size: 12px; + font-weight: 600; + letter-spacing: 0; +} + +.sourcingEnabled { + background: #dcfce7; + color: #15803d; +} + +.sourcingDisabled { + background: #f4f4f5; + color: #71717a; +} + +.sourcingActionHeader, +.sourcingActionCell { + position: sticky !important; + left: 0; + background: var(--sc-surface-muted) !important; + box-shadow: 1px 0 0 var(--sc-border); +} + +.sourcingActionHeader { + z-index: 3 !important; +} + +.sourcingActionCell { + z-index: 2; + text-align: center !important; + vertical-align: middle; +} + +.sourcingActionCell > button { + display: inline-flex; + height: 30px; + align-items: center; + justify-content: center; + gap: 5px; + padding: 0 10px; + border: 1px solid #3f3f46; + border-radius: 4px; + background: #fff; + color: #27272a; + font: inherit; + font-weight: 600; + cursor: pointer; +} + +.sourcingActionCell > button:hover, +.sourcingActionCell > button:focus-visible { + background: #27272a; + color: #fff; +} + +.sourcingActionCell > button:disabled { + border-color: #e4e4e7; + background: #f4f4f5; + color: #a1a1aa; + cursor: not-allowed; +} + +.sourcingActionCell > button.sourcingRevokeButton { + margin-left: 6px; +} + +.sourcingActionCell > button.sourcingRevokeButton:hover, +.sourcingActionCell > button.sourcingRevokeButton:focus-visible { + border-color: #b91c1c; + background: #b91c1c; + color: #fff; +} + +.sourcingActionCell > button.sourcingRevokeButton:disabled { + border-color: #e4e4e7; + background: #f4f4f5; + color: #a1a1aa; +} + +.sourcingEditorBackdrop { + position: fixed; + inset: 0; + z-index: 150; + display: flex; + align-items: center; + justify-content: center; + padding: 20px; + background: rgba(24, 24, 27, .28); +} + +.sourcingEditor { + display: flex; + width: min(720px, calc(100vw - 40px)); + max-height: calc(100vh - 40px); + flex-direction: column; + overflow: auto; + border: 1px solid #e4e4e7; + border-radius: 8px; + background: #fff; + box-shadow: 0 18px 50px rgba(24, 24, 27, .18); + color: #27272a; +} + +.sourcingEditorHeader { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + padding: 18px 20px; + border-bottom: 1px solid #e4e4e7; +} + +.sourcingEditorHeader h2 { + margin: 0; + font-size: 17px; + font-weight: 680; + letter-spacing: 0; +} + +.sourcingEditorHeader p { + margin: 5px 0 0; + color: #71717a; + font-size: 12px; +} + +.sourcingEditorHeader > button { + display: inline-grid; + width: 30px; + height: 30px; + flex: 0 0 auto; + place-items: center; + padding: 0; + border: 0; + border-radius: 4px; + background: transparent; + color: #71717a; + cursor: pointer; +} + +.sourcingEditorHeader > button:hover { + background: #f4f4f5; + color: #27272a; +} + +.sourcingEditorGrid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 16px; + padding: 20px; +} + +.sourcingEditorGrid label, +.sourcingEditorCalculated { + display: flex; + min-width: 0; + flex-direction: column; + gap: 6px; +} + +.sourcingEditorGrid label > span, +.sourcingEditorCalculated > span { + color: #52525b; + font-size: 12px; + font-weight: 600; +} + +.sourcingEditorGrid input, +.sourcingEditorGrid select, +.sourcingEditorCalculated output { + width: 100%; + height: 36px; + min-width: 0; + box-sizing: border-box; + border: 1px solid #d4d4d8; + border-radius: 5px; + padding: 0 10px; + outline: none; + background: #fff; + font: inherit; + font-size: 13px; + letter-spacing: 0; +} + +.sourcingEditorGrid input:focus, +.sourcingEditorGrid select:focus { + border-color: #71717a; + box-shadow: 0 0 0 2px rgba(82, 82, 91, .1); +} + +.sourcingEditorCalculated output { + display: flex; + align-items: center; + background: #fafafa; + font-variant-numeric: tabular-nums; + font-weight: 650; +} + +.sourcingEditorError { + margin: 0; + padding: 0 20px 12px; + color: #b91c1c; + font-size: 12px; +} + +.sourcingEditorFooter { + display: flex; + justify-content: flex-end; + gap: 10px; + padding: 14px 20px; + border-top: 1px solid #e4e4e7; + background: #fafafa; +} + +.sourcingEditorFooter button { + display: inline-flex; + height: 34px; + align-items: center; + justify-content: center; + gap: 6px; + padding: 0 14px; + border: 1px solid #d4d4d8; + border-radius: 5px; + background: #fff; + color: #27272a; + font: inherit; + cursor: pointer; +} + +.sourcingEditorFooter button:disabled { + cursor: not-allowed; + opacity: .55; +} + +.sourcingEditorFooter .sourcingEditorSave { + border-color: #27272a; + background: #27272a; + color: #fff; +} + +.sourcingSaveCell { + padding: 4px 7px !important; +} + +.sourcingSaveCell button { + display: inline-flex; + width: 30px; + height: 30px; + align-items: center; + justify-content: center; + padding: 0; + border: 1px solid #3f3f46; + border-radius: 4px; + background: #3f3f46; + color: #fff; + cursor: pointer; +} + +.sourcingSaveCell button:disabled { + border-color: #e4e4e7; + background: #f4f4f5; + color: #a1a1aa; + cursor: not-allowed; +} + +.sourcingSaveStatus, +.sourcingSaveError { + display: block; + height: 16px; + margin-top: 2px; + overflow: hidden; + font-size: 10px; + line-height: 16px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.sourcingSaveStatus { + position: absolute; + right: 4px; + bottom: 1px; + left: 4px; + margin-top: 0; + color: #3f6212; + text-align: center; +} + +.sourcingSaveError { + color: #b91c1c; +} + +.sourcingSpinner { + animation: sourcing-spin .8s linear infinite; +} + +@keyframes sourcing-spin { + to { transform: rotate(360deg); } +} + .titleLine { display: flex; + flex-wrap: wrap; align-items: baseline; gap: 10px; } @@ -32,28 +880,32 @@ letter-spacing: 0; } -.titleLine span, -.toolbar p { +.titleLine span { color: var(--sc-subtle); font-size: 12px; } -.toolbar p { - margin: 4px 0 0; -} - .summary { display: flex; + flex-wrap: wrap; + gap: 8px 0; + max-width: 100%; margin: 0; + text-align: center; white-space: nowrap; } .summary > div { - min-width: 112px; - padding: 0 18px; + min-width: 100px; + padding: 0 14px; border-left: 1px solid var(--sc-border); } +.summary > div:first-child { + padding-left: 0; + border-left: 0; +} + .summary dt { color: var(--sc-subtle); font-size: 11px; @@ -68,6 +920,7 @@ .filters { display: flex; + flex-wrap: wrap; align-items: flex-end; gap: 9px; padding: 10px 18px; @@ -87,18 +940,18 @@ white-space: nowrap; } -.filters label { +.filters > label { display: flex; flex-direction: column; gap: 5px; } -.filters label > span { +.filters > label > span { color: var(--sc-muted); font-size: 11px; } -.filters input { +.filters > label > input { height: 34px; min-width: 138px; border: 1px solid var(--sc-border); @@ -112,21 +965,11 @@ letter-spacing: 0; } -.filters input:focus { +.filters > label > input:focus { border-color: #71717a; box-shadow: 0 0 0 2px rgba(82, 82, 91, .1); } -.keywordField { - flex: 1; - max-width: 320px; -} - -.keywordField input { - width: 100%; -} - -.searchButton, .resetButton { display: inline-flex; height: 34px; @@ -142,13 +985,6 @@ white-space: nowrap; } -.searchButton { - border-color: #3f3f46; - background: #3f3f46; - color: #fff; - cursor: pointer; -} - .resetButton { background: var(--sc-surface); color: var(--sc-muted); @@ -169,7 +1005,7 @@ .table { width: 100%; - min-width: 2028px; + min-width: 2242px; table-layout: fixed; border-collapse: separate; border-spacing: 0; @@ -489,8 +1325,85 @@ } .trendCell { - padding-right: 18px !important; - padding-left: 18px !important; + padding-right: 12px !important; + padding-left: 12px !important; +} + +.trendWithActions { + display: grid; + grid-template-columns: 158px 84px; + align-items: center; + justify-content: center; + gap: 8px; +} + +.rowActions { + display: flex; + flex-direction: column; + gap: 4px; +} + +.rowActions button { + display: inline-flex; + width: 84px; + height: 24px; + align-items: center; + justify-content: center; + gap: 4px; + padding: 0 6px; + border: 1px solid var(--sc-border); + border-radius: 4px; + background: var(--sc-surface); + color: var(--sc-muted); + font: inherit; + font-size: 11px; + line-height: 1; +} + +.rowActions button:not(:disabled) { + color: var(--sc-ink); + cursor: pointer; +} + +.rowActions button:not(:disabled):hover, +.rowActions button:not(:disabled):focus-visible { + border-color: #2563eb; + color: #2563eb; +} + +.rowActions button:disabled { + cursor: not-allowed; +} + +.rowActions button[data-state='full'], +.rowActions button[data-state='permission'] { + background: var(--sc-surface-muted); + color: var(--sc-subtle); +} + +.rowActions button[data-state='accepted'] { + background: var(--sc-surface); + color: var(--sc-ink); +} + +.table td.purchaserCell { + overflow: visible; + white-space: normal; +} + +.purchaserNames { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: center; + gap: 2px 8px; + line-height: 1.5; +} + +.purchaserNames span:not(:last-child)::after { + margin-left: 8px; + color: var(--sc-subtle); + content: '·'; } .trendButton { @@ -990,12 +1903,14 @@ padding: 0 9px; border: 1px solid var(--sc-border); border-radius: 4px; + background: var(--sc-surface); + font: inherit; text-decoration: none; } .pageButton { - background: var(--sc-surface); color: var(--sc-ink); + cursor: pointer; } .pageButton:hover { @@ -1021,9 +1936,9 @@ } .summary > div { - flex: 1; - min-width: 0; - padding: 0 10px; + flex: 1 1 auto; + min-width: max-content; + padding: 0 8px; } .summary > div:first-child { @@ -1093,14 +2008,46 @@ min-width: 0; } - .keywordField { - max-width: none; - } - .tableRegion { padding: 10px 10px 64px; } + .sourcingTableRegion { + padding: 10px; + } + + .sourcingToolbar { + align-items: stretch; + padding: 10px; + } + + .sourcingFilters, + .sourcingTransferActions { + width: 100%; + } + + .sourcingFilters label { + flex: 1 1 140px; + } + + .sourcingTransferActions { + justify-content: flex-end; + } + + .sourcingEditorBackdrop { + align-items: flex-end; + padding: 10px; + } + + .sourcingEditor { + width: 100%; + max-height: calc(100vh - 20px); + } + + .sourcingEditorGrid { + grid-template-columns: 1fr; + } + .pagination { bottom: 10px; overflow-x: auto; diff --git a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/page.test.tsx b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/page.test.tsx index b14229d1..da3a2d8b 100644 --- a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/page.test.tsx +++ b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/page.test.tsx @@ -1,18 +1,27 @@ -import { render, screen } from '@testing-library/react' +import { render, screen, within } from '@testing-library/react' import Dropship1688DataPage from './page' +import { requireSession } from '@/lib/server-session' import { dropship1688DataService } from '@/server/services/dropship-1688-data.service' import { dropship1688FilterStateService } from '@/server/services/dropship-1688-filter-state.service' +import { dropship1688SourcingService } from '@/server/services/dropship-1688-sourcing.service' +import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service' -jest.mock('@/lib/server-session', () => ({ requireSession: jest.fn(async () => ({ authUser: { id: 'local-user' } })) })) +jest.mock('next/navigation', () => ({ + redirect: jest.fn(), + useRouter: () => ({ refresh: jest.fn() }), +})) +jest.mock('@/lib/server-session', () => ({ requireSession: jest.fn() })) jest.mock('@/server/services/supply-chain-permission-settings.service', () => ({ - supplyChainPermissionSettingsService: { getUserAccess: jest.fn(async () => ({ view: true })) }, + supplyChainPermissionSettingsService: { getUserAccess: jest.fn() }, })) jest.mock('@/server/services/dropship-1688-data.service', () => ({ dropship1688DataService: { listPage: jest.fn() } })) jest.mock('@/server/services/dropship-1688-filter-state.service', () => ({ dropship1688FilterStateService: { load: jest.fn() }, })) +jest.mock('@/server/services/dropship-1688-sourcing.service', () => ({ + dropship1688SourcingService: { listPurchasersByBarcodes: jest.fn() }, +})) jest.mock('./SalesTrendPopover', () => ({ SalesTrendPopover: () => null })) -jest.mock('./DropshipHeaderFilter', () => ({ DropshipHeaderFilter: () => null })) const filters = { sku: { mode: 'include' as const, values: ['SKU-1', 'SKU-2'] } } const filterRef = 'c'.repeat(64) @@ -20,15 +29,94 @@ const filterRef = 'c'.repeat(64) describe('1688 dropship page filter state', () => { beforeEach(() => { jest.clearAllMocks() + jest.mocked(requireSession).mockResolvedValue({ + authUser: { + id: 'local-user', email: 'viewer@example.com', name: '查看人', role: 'USER', + status: 'ACTIVE', businessRoles: [], + }, + } as never) + jest.mocked(supplyChainPermissionSettingsService.getUserAccess).mockResolvedValue({ + view: true, edit: true, download: true, + }) jest.mocked(dropship1688FilterStateService.load).mockResolvedValue(filters) + jest.mocked(dropship1688SourcingService.listPurchasersByBarcodes).mockResolvedValue({}) jest.mocked(dropship1688DataService.listPage).mockResolvedValue({ rows: [], total: 100, page: 1, pageSize: 50, totalPages: 2, dateFrom: '2026-09-01', dateTo: '2026-09-07', keyword: '', filters, dataUpdatedThrough: '2026-09-07', - summary: { shipQty: '0', salesAmount: '0', realPerformance: '0' }, + summary: { + shipQty: '0', salesAmount: '0', realPerformance: '0', grossProfit: '0', afterSaleCostRate: '', + totalProducts: '100', productsWithSalesAmount: '70', + }, }) }) + it('shows seven summary metrics in order without the redundant update metadata', async () => { + const listPage = jest.mocked(dropship1688DataService.listPage) + const emptyPage = await listPage({}) + listPage.mockResolvedValue({ + ...emptyPage, + summary: { + salesAmount: '1234.5', realPerformance: '1000', shipQty: '12345', + grossProfit: '125.5', afterSaleCostRate: '0.025', + totalProducts: '100', productsWithSalesAmount: '70', + }, + }) + render(await Dropship1688DataPage({})) + const panel = screen.getByRole('tabpanel', { name: '数据明细' }) + const summary = panel.querySelector('dl')! + expect(within(summary).getAllByRole('term').map((term) => term.textContent)).toEqual([ + '销售金额', '真实业绩', '发货件数', '毛利额', '售后成本率', '总商品数', '有销售金额商品数', + ]) + expect(within(summary).getAllByRole('definition').map((value) => value.textContent)).toEqual([ + '¥1,234.50', '¥1,000.00', '12,345', '¥125.50', '2.50%', '100', '70', + ]) + expect(within(panel).queryByText('数据更新至 2026-09-07')).not.toBeInTheDocument() + expect(within(panel).queryByText('当前共 100 个商品')).not.toBeInTheDocument() + }) + + it('shows a dash for an undefined summary cost rate', async () => { + render(await Dropship1688DataPage({})) + expect(screen.getByText('售后成本率', { selector: 'dt' }).nextElementSibling).toHaveTextContent('--') + }) + + it('includes the accepting purchaser column in the empty table span', async () => { + render(await Dropship1688DataPage({})) + const table = screen.getByRole('table') + const headers = within(table).getAllByRole('columnheader') + expect(headers.slice(2, 5).map((header) => header.textContent)).toEqual(['销售趋势', '承接采购', '总成本']) + expect(within(table).getByRole('cell', { name: '当前筛选条件下没有商品' })).toHaveAttribute('colspan', String(headers.length)) + }) + + it('uses sourcing-style toolbar filters in the requested order without table-header filters', async () => { + const legacyFilters = { + ...filters, + barcode: { mode: 'include' as const, values: ['DF-A'] }, + } + render(await Dropship1688DataPage({ searchParams: Promise.resolve({ + keyword: 'DF-A', + columnFilters: JSON.stringify(legacyFilters), + }) })) + + const form = screen.getByRole('form', { name: '数据明细筛选' }) + const filterTriggers = within(form).getAllByRole('button') + .filter((button) => button.getAttribute('aria-haspopup') === 'dialog') + expect(filterTriggers.map((button) => button.getAttribute('aria-label'))).toEqual([ + '采购筛选', '运营筛选', 'SPU筛选', 'SKU筛选', + ]) + expect(within(form).queryByRole('button', { name: '条码筛选' })).not.toBeInTheDocument() + expect(within(form).queryByRole('searchbox', { name: '商品检索' })).not.toBeInTheDocument() + expect(within(form).queryByRole('button', { name: '查询' })).not.toBeInTheDocument() + expect(within(screen.getByRole('table')).queryByRole('button', { name: /筛选/ })).not.toBeInTheDocument() + expect(dropship1688DataService.listPage).toHaveBeenCalledWith(expect.objectContaining({ + keyword: '', + filters, + })) + const next = new URL(screen.getByRole('link', { name: '下一页' }).getAttribute('href')!, 'http://localhost') + expect(next.searchParams.has('keyword')).toBe(false) + expect(next.searchParams.get('columnFilters')).toBe(JSON.stringify(filters)) + }) + it('loads user-scoped saved filters and preserves the short reference across form and pagination', async () => { render(await Dropship1688DataPage({ searchParams: Promise.resolve({ filterRef }) })) expect(dropship1688FilterStateService.load).toHaveBeenCalledWith('local-user', filterRef) @@ -67,7 +155,7 @@ describe('1688 dropship page filter state', () => { rows: [{ id: 'df-example', barcode: 'DF-EXAMPLE/01', spu: 'DF-SPU', sku: 'DF-SKU', image: 'https://images.example.com/product.png', color: '', skuOperator: '', - costPrice: '', shipQty: '', salesAmount: '', afterSaleAmount: '', realPerformance: '', + totalCost: '75.50', costPrice: '70', estimatedFreight: '5.50', shipQty: '', salesAmount: '', afterSaleAmount: '', realPerformance: '', afterSaleCostRate: '', grossProfit: '', grossMargin: '', trend: [], comparisonTrend: [], }], }) @@ -75,5 +163,102 @@ describe('1688 dropship page filter state', () => { expect(screen.getByRole('img', { name: 'DF-SKU' })).toHaveAttribute( 'src', '/api/supply-chain/1688-dropship-data/source-image?barcode=DF-EXAMPLE%2F01', ) + const table = screen.getByRole('table') + const headers = within(table).getAllByRole('columnheader') + const cells = within(table).getAllByRole('cell') + const purchasingIndex = headers.findIndex((header) => header.textContent === '承接采购') + expect(cells).toHaveLength(headers.length) + const actions = within(cells[purchasingIndex - 1]).getByRole('group', { name: 'DF-SKU 承接采购操作' }) + expect(within(actions).getAllByRole('button').map((button) => button.textContent)).toEqual(['承接 0/3']) + expect(within(actions).getByRole('button', { name: '承接 0/3' })).toBeDisabled() + expect(cells[purchasingIndex]).toHaveTextContent('--') + expect(cells[purchasingIndex + 1]).toHaveTextContent('¥75.50') + expect(cells[purchasingIndex + 2]).toHaveTextContent('¥70.00') + expect(cells[purchasingIndex + 3]).toHaveTextContent('¥5.50') + }) + + it('shows every purchaser and marks only the current purchaser as accepted', async () => { + jest.mocked(requireSession).mockResolvedValue({ + authUser: { + id: 'buyer-1', email: 'buyer@example.com', name: '采购甲', role: 'USER', + status: 'ACTIVE', businessRoles: ['PURCHASING'], + }, + } as never) + const emptyPage = await jest.mocked(dropship1688DataService.listPage)({}) + jest.mocked(dropship1688DataService.listPage).mockResolvedValue({ + ...emptyPage, + rows: [{ + id: 'df-example', barcode: 'DF-EXAMPLE', spu: 'DF-SPU', sku: 'DF-SKU', + image: '', color: '', skuOperator: '运营甲', totalCost: '75.50', costPrice: '70', estimatedFreight: '5.50', shipQty: '', + salesAmount: '', afterSaleAmount: '', realPerformance: '', afterSaleCostRate: '', + grossProfit: '', grossMargin: '', trend: [], comparisonTrend: [], + }], + }) + jest.mocked(dropship1688SourcingService.listPurchasersByBarcodes).mockResolvedValue({ + 'DF-EXAMPLE': [ + { userId: 'buyer-1', name: '采购甲', acceptedAt: '2026-09-16T01:00:00.000Z' }, + { userId: 'buyer-2', name: '采购乙', acceptedAt: '2026-09-16T02:00:00.000Z' }, + ], + }) + + render(await Dropship1688DataPage({ searchParams: Promise.resolve({}) })) + + const table = screen.getByRole('table', { name: '' }) + const headers = within(table).getAllByRole('columnheader') + const cells = within(table).getAllByRole('cell') + const purchasingIndex = headers.findIndex((header) => header.textContent === '承接采购') + expect(cells[purchasingIndex]).toHaveTextContent('采购甲') + expect(cells[purchasingIndex]).toHaveTextContent('采购乙') + const acceptedButton = screen.getByRole('button', { name: '已承接 2/3' }) + expect(acceptedButton).toBeDisabled() + expect(acceptedButton).toHaveAttribute('data-state', 'accepted') + + expect(dropship1688SourcingService.listPurchasersByBarcodes).toHaveBeenCalledWith(['DF-EXAMPLE']) + }) + + it('keeps every sourcing write control disabled without operation permission', async () => { + jest.mocked(requireSession).mockResolvedValue({ + authUser: { + id: 'buyer-1', email: 'buyer@example.com', name: '采购甲', role: 'USER', + status: 'ACTIVE', businessRoles: ['PURCHASING'], + }, + } as never) + jest.mocked(supplyChainPermissionSettingsService.getUserAccess).mockResolvedValue({ + view: true, edit: false, download: true, + }) + const emptyPage = await jest.mocked(dropship1688DataService.listPage)({}) + jest.mocked(dropship1688DataService.listPage).mockResolvedValue({ + ...emptyPage, + rows: [{ + id: 'df-example', barcode: 'DF-EXAMPLE', spu: 'DF-SPU', sku: 'DF-SKU', image: '', + color: '', skuOperator: '运营甲', totalCost: '75.50', costPrice: '70', estimatedFreight: '5.50', shipQty: '', salesAmount: '', + afterSaleAmount: '', realPerformance: '', afterSaleCostRate: '', grossProfit: '', + grossMargin: '', trend: [], comparisonTrend: [], + }], + }) + render(await Dropship1688DataPage({ searchParams: Promise.resolve({}) })) + expect(screen.getByRole('button', { name: '承接 0/3' })).toBeDisabled() + }) + + it('lets an administrator accept a task without the purchasing business role', async () => { + jest.mocked(requireSession).mockResolvedValue({ + authUser: { + id: 'admin-1', email: 'admin@example.com', name: '管理员', role: 'ADMIN', + status: 'ACTIVE', businessRoles: [], + }, + } as never) + const emptyPage = await jest.mocked(dropship1688DataService.listPage)({}) + jest.mocked(dropship1688DataService.listPage).mockResolvedValue({ + ...emptyPage, + rows: [{ + id: 'df-example', barcode: 'DF-EXAMPLE', spu: 'DF-SPU', sku: 'DF-SKU', image: '', + color: '', skuOperator: '运营甲', totalCost: '75.50', costPrice: '70', estimatedFreight: '5.50', shipQty: '', salesAmount: '', + afterSaleAmount: '', realPerformance: '', afterSaleCostRate: '', grossProfit: '', + grossMargin: '', trend: [], comparisonTrend: [], + }], + }) + + render(await Dropship1688DataPage({ searchParams: Promise.resolve({}) })) + expect(screen.getByRole('button', { name: '承接 0/3' })).toBeEnabled() }) }) diff --git a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/page.tsx b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/page.tsx index cbda5fbf..829df474 100644 --- a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/page.tsx +++ b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/page.tsx @@ -1,13 +1,21 @@ -import { ArrowLeft, ArrowRight, Filter, RefreshCw, Search } from 'lucide-react' +import { ArrowLeft, ArrowRight, Filter, RefreshCw } from 'lucide-react' import { redirect } from 'next/navigation' +import { hasBusinessRole, isAdmin } from '@/lib/role-scope' import { requireSession } from '@/lib/server-session' import { dropship1688DataService } from '@/server/services/dropship-1688-data.service' import { dropship1688FilterStateService } from '@/server/services/dropship-1688-filter-state.service' +import { dropship1688SourcingService } from '@/server/services/dropship-1688-sourcing.service' import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service' import styles from './dropship-1688-data.module.css' +import { DropshipAcceptanceButton } from './DropshipAcceptanceButton' import { SalesTrendPopover } from './SalesTrendPopover' -import { DropshipHeaderFilter } from './DropshipHeaderFilter' +import { + DropshipAutoSubmitDateField, + DropshipFieldFilter, + DropshipFieldFilterGroup, +} from './DropshipFieldFilter' import { DropshipImageCell } from './DropshipImageCell' +import { DropshipWorkspace } from './DropshipWorkspace' import { parseDropship1688Filters, serializeDropship1688Filters, type Dropship1688Filters } from '@/lib/dropship-1688-filters' export const dynamic = 'force-dynamic' @@ -67,15 +75,18 @@ function pageHref(input: { const COLUMNS = [ { label: '产品图片', width: 108 }, { label: '真实业绩', width: 132 }, - { label: '销售趋势', width: 188 }, + { label: '销售趋势', width: 286 }, + { label: '承接采购', width: 132 }, + { label: '总成本', width: 132 }, { label: '成本价', width: 132 }, + { label: '预估运费', width: 132 }, { label: '发货件数', width: 132 }, { label: '售后金额', width: 132 }, { label: '售后成本率', width: 132 }, - { label: 'SKU运营', width: 132, filterField: 'skuOperator' }, - { label: 'SPU', width: 132, filterField: 'spu' }, - { label: 'SKU', width: 132, filterField: 'sku' }, - { label: '条码', width: 148, filterField: 'barcode' }, + { label: 'SKU运营', width: 132 }, + { label: 'SPU', width: 132 }, + { label: 'SKU', width: 132 }, + { label: '条码', width: 148 }, { label: '颜色', width: 132 }, { label: '销售金额', width: 132 }, { label: '毛利额', width: 132 }, @@ -97,12 +108,11 @@ export default async function Dropship1688DataPage({ const params = await searchParams const dateFrom = firstValue(params?.dateFrom) const dateTo = firstValue(params?.dateTo) - const keyword = firstValue(params?.keyword) const filterRef = firstValue(params?.filterRef) - const filters = filterRef + const loadedFilters = filterRef ? await dropship1688FilterStateService.load(authUser.id, filterRef) : parseDropship1688Filters(firstValue(params?.columnFilters)) - if (filters === null) { + if (loadedFilters === null) { return (

1688代发数据明细

@@ -113,52 +123,63 @@ export default async function Dropship1688DataPage({
) } + // 条码筛选和商品检索已从工具栏移除,旧链接中的对应条件也不能继续隐式生效。 + const filters = { ...loadedFilters } + delete filters.barcode const requestedPage = Number.parseInt(firstValue(params?.page), 10) const data = await dropship1688DataService.listPage({ dateFrom, dateTo, - keyword, + keyword: '', filters, page: Number.isSafeInteger(requestedPage) ? requestedPage : 1, }) + const purchasersByBarcode = await dropship1688SourcingService.listPurchasersByBarcodes( + data.rows.map((row) => row.barcode), + ) + const administrator = isAdmin(authUser) + const canAccept = access.edit && (administrator || hasBusinessRole(authUser, 'PURCHASING')) const previousHref = pageHref({ ...data, filterRef, page: Math.max(1, data.page - 1) }) const nextHref = pageHref({ ...data, filterRef, page: Math.min(data.totalPages, data.page + 1) }) return ( -
-
-
-
-

1688代发数据明细

- 本地 DF 数据 -
-

数据更新至 {data.dataUpdatedThrough || '--'},当前共 {integerText(String(data.total))} 个商品

-
+ -
发货件数
{integerText(data.summary.shipQty)}
销售金额
{moneyText(data.summary.salesAmount)}
真实业绩
{moneyText(data.summary.realPerformance)}
+
发货件数
{integerText(data.summary.shipQty)}
+
毛利额
{moneyText(data.summary.grossProfit)}
+
售后成本率
{percentText(data.summary.afterSaleCostRate)}
+
总商品数
{integerText(data.summary.totalProducts)}
+
有销售金额商品数
{integerText(data.summary.productsWithSalesAmount)}
-
+ } + actorUserId={authUser.id} + canEditAllSourcing={access.edit && administrator} + canEditSourcing={canAccept} + canExportSourcing={access.download} + canImportSourcing={canAccept} + > -
+ {filterRef ? : }
筛选
- - - - + + + + + + + + 重置 @@ -176,19 +197,7 @@ export default async function Dropship1688DataPage({ {COLUMNS.map((column) => ( - - {column.label} - {'filterField' in column && ( - - )} - + {column.label} ))} @@ -198,39 +207,69 @@ export default async function Dropship1688DataPage({ 当前筛选条件下没有商品 - ) : data.rows.map((row) => ( - - - - - {moneyText(row.realPerformance)} - - - - {moneyText(row.costPrice)} - {row.shipQty ? integerText(row.shipQty) : '--'} - {moneyText(row.afterSaleAmount)} - {percentText(row.afterSaleCostRate)} - {row.skuOperator || '--'} - {row.spu || '--'} - {row.sku || '--'} - {row.barcode} - {row.color || '--'} - {moneyText(row.salesAmount)} - {moneyText(row.grossProfit)} - {percentText(row.grossMargin)} - - ))} + ) : data.rows.map((row) => { + const purchasers = purchasersByBarcode[row.barcode.toUpperCase()] ?? [] + return ( + + + + + {moneyText(row.realPerformance)} + +
+ +
+ `${purchaser.userId}:${purchaser.acceptedAt}`) + .sort() + .join(',')} + barcode={row.barcode} + dateFrom={data.dateFrom} + dateTo={data.dateTo} + alreadyAccepted={purchasers.some((purchaser) => purchaser.userId === authUser.id)} + canAccept={canAccept} + purchaserCount={purchasers.length} + /> +
+
+ + + {purchasers.length > 0 ? ( +
purchaser.name).join('、')}> + {purchasers.map((purchaser) => ( + {purchaser.name} + ))} +
+ ) : '--'} + + {moneyText(row.totalCost)} + {moneyText(row.costPrice)} + {moneyText(row.estimatedFreight)} + {row.shipQty ? integerText(row.shipQty) : '--'} + {moneyText(row.afterSaleAmount)} + {percentText(row.afterSaleCostRate)} + {row.skuOperator || '--'} + {row.spu || '--'} + {row.sku || '--'} + {row.barcode} + {row.color || '--'} + {moneyText(row.salesAmount)} + {moneyText(row.grossProfit)} + {percentText(row.grossMargin)} + + ) + })}
@@ -252,6 +291,6 @@ export default async function Dropship1688DataPage({ )} 每页 {data.pageSize} 条 - + ) } diff --git a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/sourcing.actions.test.ts b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/sourcing.actions.test.ts new file mode 100644 index 00000000..0c08bd0b --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/sourcing.actions.test.ts @@ -0,0 +1,158 @@ +jest.mock('next/cache', () => ({ revalidatePath: jest.fn() })) +jest.mock('@/lib/server-session', () => ({ requireSession: jest.fn() })) +jest.mock('@/server/services/dropship-1688-sourcing.service', () => ({ + dropship1688SourcingService: { claim: jest.fn(), update: jest.fn(), revoke: jest.fn() }, +})) +jest.mock('@/server/services/supply-chain-permission-settings.service', () => ({ + supplyChainPermissionSettingsService: { getUserAccess: jest.fn() }, +})) + +import { revalidatePath } from 'next/cache' +import { requireSession } from '@/lib/server-session' +import { AppError, ErrorCode } from '@/server/core/errors' +import { dropship1688SourcingService } from '@/server/services/dropship-1688-sourcing.service' +import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service' +import { + claimDropship1688Sourcing, + revokeDropship1688SourcingTask, + updateDropship1688SourcingTask, +} from './sourcing.actions' + +const input = { barcode: 'DF-ONE', dateFrom: '2026-09-01', dateTo: '2026-09-10' } + +describe('claimDropship1688Sourcing', () => { + beforeEach(() => { + jest.clearAllMocks() + jest.mocked(requireSession).mockResolvedValue({ + authUser: { + id: 'buyer-1', email: 'buyer@example.com', name: '采购甲', role: 'USER', + status: 'ACTIVE', businessRoles: ['PURCHASING'], + }, + } as never) + jest.mocked(supplyChainPermissionSettingsService.getUserAccess).mockResolvedValue({ + view: true, edit: true, download: true, + }) + jest.mocked(dropship1688SourcingService.claim).mockResolvedValue({} as never) + jest.mocked(dropship1688SourcingService.update).mockResolvedValue({ id: 'task-1' } as never) + jest.mocked(dropship1688SourcingService.revoke).mockResolvedValue({ id: 'task-1' } as never) + }) + + it('claims as the authenticated user and refreshes the workspace', async () => { + await expect(claimDropship1688Sourcing(input)).resolves.toEqual({ ok: true }) + expect(dropship1688SourcingService.claim).toHaveBeenCalledWith( + input, + expect.objectContaining({ id: 'buyer-1', name: '采购甲' }), + ) + expect(revalidatePath).toHaveBeenCalledWith('/supply-chain/new-products/1688-dropship-data') + }) + + it.each(['workspace', 'newProduct1688DropshipData'])('denies missing %s view access', async (deniedTarget) => { + jest.mocked(supplyChainPermissionSettingsService.getUserAccess).mockImplementation(async (_user, target) => ({ + view: target !== deniedTarget, edit: false, download: false, + })) + await expect(claimDropship1688Sourcing(input)).resolves.toEqual({ + ok: false, message: '当前账号没有1688代发数据查看权限', + }) + expect(dropship1688SourcingService.claim).not.toHaveBeenCalled() + }) + + it.each([ + ['claim', () => claimDropship1688Sourcing(input), dropship1688SourcingService.claim], + ['update', () => updateDropship1688SourcingTask({ taskId: 'task-1' }), dropship1688SourcingService.update], + ['revoke', () => revokeDropship1688SourcingTask({ taskId: 'task-1' }), dropship1688SourcingService.revoke], + ])('denies %s without the page operation permission', async (_name, action, serviceMethod) => { + jest.mocked(supplyChainPermissionSettingsService.getUserAccess).mockImplementation(async (_user, target) => ({ + view: true, + edit: target === 'workspace', + download: target === 'workspace', + })) + + await expect(action()).resolves.toEqual({ + ok: false, message: '当前账号没有1688代发数据操作权限', + }) + expect(serviceMethod).not.toHaveBeenCalled() + expect(revalidatePath).not.toHaveBeenCalled() + }) + + it('returns a safe domain error without refreshing', async () => { + jest.mocked(dropship1688SourcingService.claim).mockRejectedValue( + new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '只有采购或管理员可以承接寻源任务'), + ) + await expect(claimDropship1688Sourcing(input)).resolves.toEqual({ + ok: false, message: '只有采购或管理员可以承接寻源任务', + }) + expect(revalidatePath).not.toHaveBeenCalled() + }) + + it('does not leak unexpected infrastructure errors', async () => { + jest.mocked(dropship1688SourcingService.claim).mockRejectedValue(new Error('database-secret')) + await expect(claimDropship1688Sourcing(input)).resolves.toEqual({ + ok: false, message: '承接失败,请稍后重试', + }) + }) + + it('updates as the authenticated user and refreshes the workspace', async () => { + const update = { taskId: 'task-1', supplierName: '供应商甲' } + await expect(updateDropship1688SourcingTask(update)).resolves.toEqual({ + ok: true, task: { id: 'task-1' }, + }) + expect(dropship1688SourcingService.update).toHaveBeenCalledWith( + update, + expect.objectContaining({ id: 'buyer-1' }), + ) + expect(revalidatePath).toHaveBeenCalledWith('/supply-chain/new-products/1688-dropship-data') + }) + + it('returns update permission errors and hides unexpected failures', async () => { + jest.mocked(dropship1688SourcingService.update).mockRejectedValueOnce( + new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '只能修改本人承接的寻源任务'), + ) + await expect(updateDropship1688SourcingTask({ taskId: 'task-2' })).resolves.toEqual({ + ok: false, message: '只能修改本人承接的寻源任务', + }) + jest.mocked(dropship1688SourcingService.update).mockRejectedValueOnce(new Error('database-secret')) + await expect(updateDropship1688SourcingTask({ taskId: 'task-1' })).resolves.toEqual({ + ok: false, message: '保存失败,请稍后重试', + }) + }) + + it('revokes as the authenticated user and refreshes the workspace', async () => { + await expect(revokeDropship1688SourcingTask({ taskId: 'task-1' })).resolves.toEqual({ ok: true }) + expect(dropship1688SourcingService.revoke).toHaveBeenCalledWith( + { taskId: 'task-1' }, + expect.objectContaining({ id: 'buyer-1' }), + ) + expect(revalidatePath).toHaveBeenCalledWith('/supply-chain/new-products/1688-dropship-data') + }) + + it.each(['workspace', 'newProduct1688DropshipData'])('denies revoke without %s view access', async (deniedTarget) => { + jest.mocked(supplyChainPermissionSettingsService.getUserAccess).mockImplementation(async (_user, target) => ({ + view: target !== deniedTarget, edit: false, download: false, + })) + await expect(revokeDropship1688SourcingTask({ taskId: 'task-1' })).resolves.toEqual({ + ok: false, message: '当前账号没有1688代发数据查看权限', + }) + expect(dropship1688SourcingService.revoke).not.toHaveBeenCalled() + }) + + it('returns revoke domain errors without refreshing and hides infrastructure failures', async () => { + jest.mocked(dropship1688SourcingService.revoke).mockRejectedValueOnce( + new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '只能撤销本人承接的寻源任务'), + ) + await expect(revokeDropship1688SourcingTask({ taskId: 'task-1' })).resolves.toEqual({ + ok: false, message: '只能撤销本人承接的寻源任务', + }) + jest.mocked(dropship1688SourcingService.revoke).mockRejectedValueOnce( + new AppError(ErrorCode.VALIDATION_FAILED, '该寻源任务已填写简尚条码,不能撤销'), + ) + await expect(revokeDropship1688SourcingTask({ taskId: 'task-1' })).resolves.toEqual({ + ok: false, message: '该寻源任务已填写简尚条码,不能撤销', + }) + expect(revalidatePath).not.toHaveBeenCalled() + + jest.mocked(dropship1688SourcingService.revoke).mockRejectedValueOnce(new Error('database-secret')) + await expect(revokeDropship1688SourcingTask({ taskId: 'task-1' })).resolves.toEqual({ + ok: false, message: '撤销失败,请稍后重试', + }) + }) +}) diff --git a/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/sourcing.actions.ts b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/sourcing.actions.ts new file mode 100644 index 00000000..0f5f43ee --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/new-products/1688-dropship-data/sourcing.actions.ts @@ -0,0 +1,81 @@ +'use server' + +import { revalidatePath } from 'next/cache' +import { requireSession } from '@/lib/server-session' +import { AppError, ErrorCode, isAppError } from '@/server/core/errors' +import type { AuthUser } from '@/server/core/types' +import { dropship1688SourcingService } from '@/server/services/dropship-1688-sourcing.service' +import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service' + +const PAGE_PATH = '/supply-chain/new-products/1688-dropship-data' + +async function assertDropshipWorkspaceAccess(authUser: AuthUser): Promise { + const [workspaceAccess, pageAccess] = await Promise.all([ + supplyChainPermissionSettingsService.getUserAccess(authUser, 'workspace'), + supplyChainPermissionSettingsService.getUserAccess(authUser, 'newProduct1688DropshipData'), + ]) + if (!workspaceAccess.view || !pageAccess.view) { + throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有1688代发数据查看权限') + } + if (!pageAccess.edit) { + throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有1688代发数据操作权限') + } +} + +export async function claimDropship1688Sourcing(input: unknown): Promise< + { ok: true } | { ok: false; message: string } +> { + const { authUser } = await requireSession('/login') + + try { + await assertDropshipWorkspaceAccess(authUser) + + await dropship1688SourcingService.claim(input, authUser) + revalidatePath(PAGE_PATH) + return { ok: true } + } catch (error) { + return { + ok: false, + message: isAppError(error) ? error.message : '承接失败,请稍后重试', + } + } +} + +export async function updateDropship1688SourcingTask(input: unknown): Promise< + | { ok: true; task: Awaited> } + | { ok: false; message: string } +> { + const { authUser } = await requireSession('/login') + + try { + await assertDropshipWorkspaceAccess(authUser) + + const task = await dropship1688SourcingService.update(input, authUser) + revalidatePath(PAGE_PATH) + return { ok: true, task } + } catch (error) { + return { + ok: false, + message: isAppError(error) ? error.message : '保存失败,请稍后重试', + } + } +} + +export async function revokeDropship1688SourcingTask( + input: unknown, +): Promise<{ ok: true } | { ok: false; message: string }> { + const { authUser } = await requireSession('/login') + + try { + await assertDropshipWorkspaceAccess(authUser) + + await dropship1688SourcingService.revoke(input, authUser) + revalidatePath(PAGE_PATH) + return { ok: true } + } catch (error) { + return { + ok: false, + message: isAppError(error) ? error.message : '撤销失败,请稍后重试', + } + } +} diff --git a/furniture-3d-system/src/app/supply-chain/purchase/supplier-recommended-products/SupplierRecommendedProductsClient.tsx b/furniture-3d-system/src/app/supply-chain/purchase/supplier-recommended-products/SupplierRecommendedProductsClient.tsx index efc11ce3..65a37147 100644 --- a/furniture-3d-system/src/app/supply-chain/purchase/supplier-recommended-products/SupplierRecommendedProductsClient.tsx +++ b/furniture-3d-system/src/app/supply-chain/purchase/supplier-recommended-products/SupplierRecommendedProductsClient.tsx @@ -40,7 +40,7 @@ function openDatePicker(event: React.MouseEvent) { export function SupplierRecommendedProductsClient({ initialData, canEdit, canDownload, canSelect, canViewDashboard, currentUser }: { initialData: SupplierRecommendedProductPage; canEdit: boolean; canDownload: boolean; canSelect: boolean; canViewDashboard: boolean; currentUser: { id: string; name: string } }) { const [data, setData] = useState(initialData) const [filters, setFilters] = useState({ ...EMPTY_SUPPLIER_RECOMMENDED_PRODUCT_FILTERS }) - const [pageView, setPageView] = useState<'list' | 'dashboard'>(canViewDashboard ? 'dashboard' : 'list') + const [pageView, setPageView] = useState<'list' | 'dashboard'>('list') const [editor, setEditor] = useState(null) const [logs, setLogs] = useState(null) const [preview, setPreview] = useState(null) diff --git a/furniture-3d-system/src/components/3d/ModelViewer.tsx b/furniture-3d-system/src/components/3d/ModelViewer.tsx index 13e706f4..eb66e6ed 100644 --- a/furniture-3d-system/src/components/3d/ModelViewer.tsx +++ b/furniture-3d-system/src/components/3d/ModelViewer.tsx @@ -2387,6 +2387,9 @@ function ModelViewerComponent({ signature ); }); + const removedNodeNames = Array.from( + appliedMaterialSignatureRef.current.keys(), + ).filter((nodeName) => !assignmentByNode.has(nodeName)); const unresolvedNodeNames = new Set(); const applyMaterialToNode = ( @@ -2399,6 +2402,10 @@ function ModelViewerComponent({ return engineRef.current.applyMaterialToMesh(nodeName, material); }; + removedNodeNames.forEach((nodeName) => { + engineRef.current?.restoreOriginalMaterial(nodeName); + }); + if (changedAssignments.length === 0) { const unresolvedNodeNames = materialAssignments .filter((assignment) => !appliedMaterialSignatureRef.current.has(assignment.nodeName)) diff --git a/furniture-3d-system/src/components/ui/Select.tsx b/furniture-3d-system/src/components/ui/Select.tsx index b768f881..0ead461c 100644 --- a/furniture-3d-system/src/components/ui/Select.tsx +++ b/furniture-3d-system/src/components/ui/Select.tsx @@ -75,7 +75,7 @@ export const Select = React.forwardRef( disabled, value, onChange, - children, + children: _children, // onClick/onKeyDown 由组件内部的触发按钮接管,不透传(其 select 元素 // 事件签名与 button 不兼容,且外部场景不应覆盖交互实现)。 onClick: _ignoredOnClick, @@ -259,8 +259,12 @@ export const Select = React.forwardRef( role="combobox" aria-expanded={open} aria-haspopup="listbox" - aria-label={label} - {...(props as unknown as React.ComponentProps<'button'>)} + id={props.id} + name={props.name} + title={props.title} + autoFocus={props.autoFocus} + aria-label={props['aria-label'] ?? label} + aria-describedby={props['aria-describedby']} > ({ + GLTFLoader: class { + setDRACOLoader(): void {} + }, +})); + +jest.mock("three/examples/jsm/loaders/OBJLoader.js", () => ({ + OBJLoader: class {}, +})); + +jest.mock("three/examples/jsm/loaders/DRACOLoader.js", () => ({ + DRACOLoader: class { + setDecoderPath(): void {} + }, +})); + +jest.mock("three/examples/jsm/controls/OrbitControls.js", () => ({ + OrbitControls: class { + target = new THREE.Vector3(); + update(): void {} + dispose(): void {} + }, +})); + +jest.mock("three/examples/jsm/utils/BufferGeometryUtils.js", () => ({ + toCreasedNormals: (geometry: THREE.BufferGeometry) => geometry, +})); + +jest.mock("../engine-core", () => ({ + createDefaultSceneLights: jest.fn(), + setupRoomEnvironment: jest.fn(() => null), +})); + +jest.mock("../engine-events", () => ({ + bindEngineEvents: jest.fn(), + unbindEngineEvents: jest.fn(), +})); + +jest.mock("../engine-render-loop", () => ({ + startRenderLoop: jest.fn(() => 1), + stopRenderLoop: jest.fn(), +})); + +const { ThreeDEngine } = require("../engine") as { + ThreeDEngine: typeof import("../engine").ThreeDEngine; +}; +type ThreeDEngineInstance = InstanceType; + +function createMaterialTestEngine(meshCount: number) { + const scene = new THREE.Scene(); + const modelRoot = new THREE.Group(); + scene.add(modelRoot); + const meshes = Array.from({ length: meshCount }, (_, index) => { + const mesh = new THREE.Mesh( + new THREE.BoxGeometry(1, 1, 1), + new THREE.MeshStandardMaterial({ color: 0x777777 + index }), + ); + mesh.name = `Mesh_${index + 1}`; + modelRoot.add(mesh); + return mesh; + }); + + const engine = Object.create(ThreeDEngine.prototype) as ThreeDEngineInstance; + (engine as unknown as { scene: THREE.Scene }).scene = scene; + (engine as unknown as { modelRoot: THREE.Group }).modelRoot = modelRoot; + ( + engine as unknown as { + runtimePreferredObjectUuidByNormalizedName: Map; + } + ).runtimePreferredObjectUuidByNormalizedName = new Map(); + + return { engine, meshes }; +} + +describe("ThreeDEngine material restoration", () => { + it("restores the original material after a single-mesh fallback assignment", () => { + const { engine, meshes } = createMaterialTestEngine(1); + const mesh = meshes[0]; + const originalMaterial = mesh.material; + + expect( + engine.applyMaterialToMesh( + "unresolved-node-name", + new THREE.MeshStandardMaterial({ color: 0x336699 }), + ), + ).toBe(true); + expect(mesh.material).not.toBe(originalMaterial); + + expect(engine.restoreOriginalMaterial("unresolved-node-name")).toBe(true); + expect(mesh.material).toBe(originalMaterial); + expect(mesh.userData.installationBaseMaterial).toBeUndefined(); + }); + + it("does not guess a material restoration target in a multi-mesh model", () => { + const { engine, meshes } = createMaterialTestEngine(2); + meshes[0].userData.installationBaseMaterial = meshes[0].material; + + expect(engine.restoreOriginalMaterial("unresolved-node-name")).toBe(false); + expect(meshes[0].userData.installationBaseMaterial).toBeDefined(); + }); +}); diff --git a/furniture-3d-system/src/lib/3d/engine.ts b/furniture-3d-system/src/lib/3d/engine.ts index 1e12f4e5..0e27eb14 100644 --- a/furniture-3d-system/src/lib/3d/engine.ts +++ b/furniture-3d-system/src/lib/3d/engine.ts @@ -41,6 +41,7 @@ const SELECTION_DEBUG_ENABLED = process.env.NEXT_PUBLIC_3D_SELECTION_DEBUG === "1"; const SELECTION_NAME_MATCH_SCORE_THRESHOLD = 650; const DISPLAY_NORMAL_REPAIR_CREASE_ANGLE = Math.PI / 10; +const INSTALLATION_BASE_MATERIAL_KEY = "installationBaseMaterial"; // frameCameraToBounds 历史固定取景方向(相对目标的相机偏移方向基准)。 const CAMERA_BOUNDS_DEFAULT_DIRECTION = new THREE.Vector3(1.02, 0.74, 1.18); @@ -2614,6 +2615,10 @@ export class ThreeDEngine { const allMeshes = this.getAllMeshes(); if (allMeshes.length === 1) { const fallbackMesh = allMeshes[0].mesh; + if (!fallbackMesh.userData[INSTALLATION_BASE_MATERIAL_KEY]) { + fallbackMesh.userData[INSTALLATION_BASE_MATERIAL_KEY] = + fallbackMesh.material; + } const meshMaterial = material.clone(); this.cloneMaterialTextureMaps(meshMaterial); applyMaterialUvProjection(fallbackMesh, meshMaterial); @@ -2636,6 +2641,9 @@ export class ThreeDEngine { if (!(child as THREE.Mesh).isMesh) return; const mesh = child as THREE.Mesh; + if (!mesh.userData[INSTALLATION_BASE_MATERIAL_KEY]) { + mesh.userData[INSTALLATION_BASE_MATERIAL_KEY] = mesh.material; + } const meshMaterial = material.clone(); this.cloneMaterialTextureMaps(meshMaterial); applyMaterialUvProjection(mesh, meshMaterial); @@ -2653,6 +2661,44 @@ export class ThreeDEngine { return applied; } + restoreOriginalMaterial(meshName: string): boolean { + const restoreObject = (object: THREE.Object3D): boolean => { + let restored = false; + object.traverse((child) => { + if (!(child as THREE.Mesh).isMesh) return; + const mesh = child as THREE.Mesh; + const originalMaterial = mesh.userData[ + INSTALLATION_BASE_MATERIAL_KEY + ] as THREE.Material | THREE.Material[] | undefined; + if (!originalMaterial) return; + + mesh.material = originalMaterial; + const materials = Array.isArray(originalMaterial) + ? originalMaterial + : [originalMaterial]; + materials.forEach((entry) => { + entry.needsUpdate = true; + }); + delete mesh.userData[INSTALLATION_BASE_MATERIAL_KEY]; + restored = true; + }); + return restored; + }; + + const object = this.findObjectByNodeName(meshName); + if (object) { + return restoreObject(object); + } + + const allMeshes = this.getAllMeshes(); + if (allMeshes.length === 1) { + return restoreObject(allMeshes[0].mesh); + } + + console.warn(`[3D Engine] Mesh or group not found for material restore: ${meshName}`); + return false; + } + setNodeVisibility(nodeName: string, visible: boolean): boolean { const object = this.findObjectByNodeName(nodeName); if (!object) { diff --git a/furniture-3d-system/src/lib/dropship-1688-filters.ts b/furniture-3d-system/src/lib/dropship-1688-filters.ts index f091d713..8b010170 100644 --- a/furniture-3d-system/src/lib/dropship-1688-filters.ts +++ b/furniture-3d-system/src/lib/dropship-1688-filters.ts @@ -1,6 +1,7 @@ import { z } from 'zod' -export const FILTER_FIELDS = ['skuOperator', 'spu', 'sku', 'barcode'] as const +// purchaser 不是商品档案上的列,而是承接记录里的采购;仓储层会单独解析它。 +export const FILTER_FIELDS = ['skuOperator', 'purchaser', 'spu', 'sku', 'barcode'] as const export type Dropship1688FilterField = typeof FILTER_FIELDS[number] export const DROPSHIP1688_FILTER_MAX_BYTES = 900_000 @@ -11,6 +12,7 @@ const columnFilterSchema = z.object({ export const dropship1688FiltersSchema = z.object({ skuOperator: columnFilterSchema.optional(), + purchaser: columnFilterSchema.optional(), spu: columnFilterSchema.optional(), sku: columnFilterSchema.optional(), barcode: columnFilterSchema.optional(), diff --git a/furniture-3d-system/src/lib/dropship-1688-sourcing-workbook.test.ts b/furniture-3d-system/src/lib/dropship-1688-sourcing-workbook.test.ts new file mode 100644 index 00000000..e0bec40d --- /dev/null +++ b/furniture-3d-system/src/lib/dropship-1688-sourcing-workbook.test.ts @@ -0,0 +1,124 @@ +import ExcelJS from 'exceljs' +import JSZip from 'jszip' +import { + createDropship1688SourcingWorkbook, + parseDropship1688SourcingWorkbook, + validateDropship1688SourcingWorkbookZip, +} from './dropship-1688-sourcing-workbook' + +describe('dropship 1688 sourcing workbook', () => { + it('exports a round-trip template with the requested order and calculated comparison', async () => { + const bytes = await createDropship1688SourcingWorkbook([{ + sourceSpu: 'SPU-ONE', + sourceBarcode: 'DF-ONE', + sourceCostPrice: '34.2900', + quotedPriceTaxIncluded: '50.0000', + invoiceTaxPoint: '13.0000', + sourceSkuOperator: '运营甲', + purchaserName: '采购甲', + supplierName: '供应商甲', + sourcingMode: '代发', + jianshangBarcode: 'JS-001', + }]) + const workbook = new ExcelJS.Workbook() + await workbook.xlsx.load(bytes as ExcelJS.Buffer) + const sheet = workbook.getWorksheet('寻源明细')! + + expect(sheet.getRow(1).values).toEqual([ + undefined, '代发SPU', '代发条码', '代发成本价', '报价(含税)', '对比', + '发票税点', 'SKU运营', '采购', '供应商', '模式', '简尚条码', + ]) + expect(sheet.getCell('A2').value).toBe('SPU-ONE') + expect(sheet.getCell('B2').value).toBe('DF-ONE') + expect(sheet.getCell('E2').value).toEqual({ formula: 'IF(OR(D2="",C2=""),"",D2-C2)' }) + expect(sheet.getCell('J2').dataValidation).toMatchObject({ + type: 'list', formulae: ['"入库,代发"'], + }) + expect(sheet.views[0]).toMatchObject({ state: 'frozen', ySplit: 1 }) + }) + + it('parses editable values and keeps the barcode plus purchaser key', async () => { + const workbook = new ExcelJS.Workbook() + const sheet = workbook.addWorksheet('寻源明细') + sheet.addRow([ + '代发SPU', '代发条码', '代发成本价', '报价(含税)', '对比', + '发票税点', 'SKU运营', '采购', '供应商', '模式', '简尚条码', + ]) + sheet.addRow([ + 'SPU-ONE', 'DF-ONE', 34.29, 50, 15.71, + 0.13, '运营甲', '采购甲', '供应商甲', '代发', 'JS-001', + ]) + sheet.getCell('F2').numFmt = '0%' + const buffer = Buffer.from(await workbook.xlsx.writeBuffer()) + + await expect(parseDropship1688SourcingWorkbook(buffer)).resolves.toEqual([{ + rowNumber: 2, + sourceBarcode: 'DF-ONE', + purchaserName: '采购甲', + supplierName: '供应商甲', + quotedPriceTaxIncluded: '50', + invoiceTaxPoint: '13', + sourcingMode: '代发', + jianshangBarcode: 'JS-001', + }]) + }) + + it('rejects workbooks without the complete round-trip headers', async () => { + const workbook = new ExcelJS.Workbook() + workbook.addWorksheet('寻源明细').addRow(['代发条码', '采购', '报价(含税)']) + const buffer = Buffer.from(await workbook.xlsx.writeBuffer()) + + await expect(parseDropship1688SourcingWorkbook(buffer)).rejects.toThrow( + '导入文件缺少必要表头', + ) + }) + + it('rejects ZIP archives with too many entries before workbook parsing', async () => { + const zip = new JSZip() + zip.file('one.xml', '') + zip.file('two.xml', '') + const buffer = await zip.generateAsync({ type: 'nodebuffer' }) + + await expect(validateDropship1688SourcingWorkbookZip(buffer, { + maxEntries: 1, + })).rejects.toThrow('导入文件包含过多 ZIP 条目') + }) + + it('rejects a ZIP entry whose declared uncompressed size is too large', async () => { + const zip = new JSZip() + zip.file('large.xml', 'abc') + const buffer = await zip.generateAsync({ type: 'nodebuffer' }) + + await expect(validateDropship1688SourcingWorkbookZip(buffer, { + maxEntryUncompressedSize: 2, + })).rejects.toThrow('导入文件包含解压后过大的 ZIP 条目') + }) + + it('rejects ZIP archives whose aggregate uncompressed size is too large', async () => { + const zip = new JSZip() + zip.file('one.xml', 'abc') + zip.file('two.xml', 'def') + const buffer = await zip.generateAsync({ type: 'nodebuffer' }) + + await expect(validateDropship1688SourcingWorkbookZip(buffer, { + maxTotalUncompressedSize: 5, + })).rejects.toThrow('导入文件解压后的总大小过大') + }) + + it('rejects more than 50,000 data rows before iterating workbook contents', async () => { + const workbook = new ExcelJS.Workbook() + const sheet = workbook.addWorksheet('寻源明细') + sheet.addRow([ + '代发SPU', '代发条码', '代发成本价', '报价(含税)', '对比', + '发票税点', 'SKU运营', '采购', '供应商', '模式', '简尚条码', + ]) + for (let rowNumber = 2; rowNumber <= 50_002; rowNumber += 1) { + sheet.getCell(rowNumber, 1).value = 'overflow' + } + const buffer = Buffer.from(await workbook.xlsx.writeBuffer()) + + await expect(parseDropship1688SourcingWorkbook(buffer)).rejects.toThrow( + '导入文件最多允许50000行数据', + ) + }) +}) diff --git a/furniture-3d-system/src/lib/dropship-1688-sourcing-workbook.ts b/furniture-3d-system/src/lib/dropship-1688-sourcing-workbook.ts new file mode 100644 index 00000000..ccfb2f80 --- /dev/null +++ b/furniture-3d-system/src/lib/dropship-1688-sourcing-workbook.ts @@ -0,0 +1,282 @@ +import ExcelJS from 'exceljs' +import JSZip from 'jszip' + +export const DROPSHIP_1688_SOURCING_WORKBOOK_MIME = + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' + +export type Dropship1688SourcingWorkbookRow = { + sourceSpu: string + sourceBarcode: string + sourceCostPrice: string | null + quotedPriceTaxIncluded: string | null + invoiceTaxPoint: string | null + sourceSkuOperator: string + purchaserName: string + supplierName: string + sourcingMode: string + jianshangBarcode: string +} + +export type Dropship1688SourcingImportRow = { + rowNumber: number + sourceBarcode: string + purchaserName: string + supplierName: string + quotedPriceTaxIncluded: string + invoiceTaxPoint: string + sourcingMode: string + jianshangBarcode: string +} + +const COLUMNS = [ + { key: 'sourceSpu', label: '代发SPU', width: 22, editable: false }, + { key: 'sourceBarcode', label: '代发条码', width: 22, editable: false }, + { key: 'sourceCostPrice', label: '代发成本价', width: 15, editable: false }, + { key: 'quotedPriceTaxIncluded', label: '报价(含税)', width: 16, editable: true }, + { key: 'comparison', label: '对比', width: 15, editable: false }, + { key: 'invoiceTaxPoint', label: '发票税点', width: 14, editable: true }, + { key: 'sourceSkuOperator', label: 'SKU运营', width: 18, editable: false }, + { key: 'purchaserName', label: '采购', width: 16, editable: false }, + { key: 'supplierName', label: '供应商', width: 24, editable: true }, + { key: 'sourcingMode', label: '模式', width: 12, editable: true }, + { key: 'jianshangBarcode', label: '简尚条码', width: 22, editable: true }, +] as const + +const REQUIRED_HEADERS = [ + '代发条码', + '采购', + '报价(含税)', + '发票税点', + '供应商', + '模式', + '简尚条码', +] as const + +type WorkbookZipLimits = { + maxEntries: number + maxEntryUncompressedSize: number + maxTotalUncompressedSize: number +} + +const DEFAULT_WORKBOOK_ZIP_LIMITS: WorkbookZipLimits = { + maxEntries: 2_048, + maxEntryUncompressedSize: 96 * 1024 * 1024, + maxTotalUncompressedSize: 128 * 1024 * 1024, +} + +const MAX_WORKBOOK_ROW_COUNT = 50_001 + +type ZipEntryWithDeclaredSize = { + dir: boolean + _data?: { uncompressedSize?: unknown } +} + +export async function validateDropship1688SourcingWorkbookZip( + buffer: Buffer | Uint8Array | ArrayBuffer, + limitOverrides: Partial = {}, +): Promise { + const limits = { ...DEFAULT_WORKBOOK_ZIP_LIMITS, ...limitOverrides } + const zip = await JSZip.loadAsync(buffer) + const entries = Object.values(zip.files) as ZipEntryWithDeclaredSize[] + if (entries.length > limits.maxEntries) { + throw new Error(`导入文件包含过多 ZIP 条目(最多${limits.maxEntries}个)`) + } + + let totalUncompressedSize = 0 + for (const entry of entries) { + if (entry.dir) continue + const declaredSize = entry._data?.uncompressedSize + if (typeof declaredSize !== 'number' + || !Number.isSafeInteger(declaredSize) + || declaredSize < 0) { + throw new Error('导入文件包含无效的 ZIP 条目大小') + } + if (declaredSize > limits.maxEntryUncompressedSize) { + throw new Error('导入文件包含解压后过大的 ZIP 条目') + } + totalUncompressedSize += declaredSize + if (!Number.isSafeInteger(totalUncompressedSize) + || totalUncompressedSize > limits.maxTotalUncompressedSize) { + throw new Error('导入文件解压后的总大小过大') + } + } +} + +function decimalValue(value: string | null) { + if (!value) return null + const parsed = Number(value) + return Number.isFinite(parsed) ? parsed : null +} + +function applyHeaderStyle(cell: ExcelJS.Cell, editable: boolean) { + cell.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true } + cell.font = { name: 'Microsoft YaHei', size: 10, bold: true, color: { argb: 'FF27272A' } } + cell.fill = { + type: 'pattern', + pattern: 'solid', + fgColor: { argb: editable ? 'FFEFF6FF' : 'FFF4F4F5' }, + } + cell.border = { + top: { style: 'thin', color: { argb: 'FFD4D4D8' } }, + left: { style: 'thin', color: { argb: 'FFD4D4D8' } }, + bottom: { style: 'thin', color: { argb: 'FFD4D4D8' } }, + right: { style: 'thin', color: { argb: 'FFD4D4D8' } }, + } +} + +function applyBodyStyle(cell: ExcelJS.Cell, editable: boolean) { + cell.alignment = { vertical: 'middle', horizontal: 'left' } + cell.font = { name: 'Microsoft YaHei', size: 10, color: { argb: 'FF27272A' } } + cell.fill = { + type: 'pattern', + pattern: 'solid', + fgColor: { argb: editable ? 'FFFFFBEB' : 'FFFFFFFF' }, + } + cell.border = { + top: { style: 'thin', color: { argb: 'FFE4E4E7' } }, + left: { style: 'thin', color: { argb: 'FFE4E4E7' } }, + bottom: { style: 'thin', color: { argb: 'FFE4E4E7' } }, + right: { style: 'thin', color: { argb: 'FFE4E4E7' } }, + } +} + +export async function createDropship1688SourcingWorkbook( + rows: readonly Dropship1688SourcingWorkbookRow[], +): Promise { + const workbook = new ExcelJS.Workbook() + workbook.creator = '供应链中心' + workbook.created = new Date() + workbook.modified = new Date() + workbook.calcProperties.fullCalcOnLoad = true + + const sheet = workbook.addWorksheet('寻源明细') + sheet.properties.defaultRowHeight = 22 + sheet.views = [{ state: 'frozen', ySplit: 1 }] + sheet.columns = COLUMNS.map((column) => ({ + key: column.key, + header: column.label, + width: column.width, + })) + sheet.getRow(1).height = 28 + COLUMNS.forEach((column, index) => { + const cell = sheet.getCell(1, index + 1) + applyHeaderStyle(cell, column.editable) + cell.note = column.editable + ? '可填写;导入后覆盖对应“代发条码 + 采购”的寻源记录。' + : '识别或计算字段,请勿修改。' + }) + + rows.forEach((source, index) => { + const rowNumber = index + 2 + const row = sheet.addRow({ + sourceSpu: source.sourceSpu, + sourceBarcode: source.sourceBarcode, + sourceCostPrice: decimalValue(source.sourceCostPrice), + quotedPriceTaxIncluded: decimalValue(source.quotedPriceTaxIncluded), + invoiceTaxPoint: decimalValue(source.invoiceTaxPoint), + sourceSkuOperator: source.sourceSkuOperator, + purchaserName: source.purchaserName, + supplierName: source.supplierName, + sourcingMode: source.sourcingMode, + jianshangBarcode: source.jianshangBarcode, + }) + row.height = 24 + COLUMNS.forEach((column, columnIndex) => { + applyBodyStyle(row.getCell(columnIndex + 1), column.editable) + }) + row.getCell(5).value = { + formula: `IF(OR(D${rowNumber}="",C${rowNumber}=""),"",D${rowNumber}-C${rowNumber})`, + } + row.getCell(3).numFmt = '¥#,##0.00' + row.getCell(4).numFmt = '¥#,##0.00' + row.getCell(5).numFmt = '[Green]+¥#,##0.00;[Red]-¥#,##0.00;¥0.00' + row.getCell(6).numFmt = '0.####"%"' + row.getCell(10).dataValidation = { + type: 'list', + allowBlank: true, + formulae: ['"入库,代发"'], + showErrorMessage: true, + errorTitle: '模式不正确', + error: '模式只能选择“入库”或“代发”。', + } + }) + + sheet.autoFilter = { + from: { row: 1, column: 1 }, + to: { row: Math.max(1, rows.length + 1), column: COLUMNS.length }, + } + const output = await workbook.xlsx.writeBuffer() + return new Uint8Array(output) +} + +function cellText(cell: ExcelJS.Cell) { + return cell.text.trim() +} + +function decimalCellText(cell: ExcelJS.Cell, percent: boolean) { + if (cell.value === null || cell.value === undefined || cell.value === '') return '' + if (typeof cell.value === 'number') { + const calculatedPercent = (cell.numFmt ?? '').replace(/"[^"]*"/g, '').includes('%') + const value = percent && calculatedPercent ? cell.value * 100 : cell.value + return String(value) + } + const text = cellText(cell).replace(/,/g, '') + if (!text) return '' + return percent && text.endsWith('%') ? text.slice(0, -1).trim() : text +} + +export async function parseDropship1688SourcingWorkbook( + buffer: Buffer | Uint8Array | ArrayBuffer, +): Promise { + await validateDropship1688SourcingWorkbookZip(buffer) + const workbook = new ExcelJS.Workbook() + await workbook.xlsx.load(buffer as ExcelJS.Buffer) + const sheet = workbook.getWorksheet('寻源明细') ?? workbook.worksheets[0] + if (!sheet) throw new Error('导入文件没有工作表') + if (sheet.actualRowCount > MAX_WORKBOOK_ROW_COUNT) { + throw new Error('导入文件最多允许50000行数据') + } + + const headerByLabel = new Map() + sheet.getRow(1).eachCell({ includeEmpty: false }, (cell, columnNumber) => { + headerByLabel.set(cellText(cell), columnNumber) + }) + const missing = REQUIRED_HEADERS.filter((header) => !headerByLabel.has(header)) + if (missing.length > 0) { + throw new Error(`导入文件缺少必要表头:${missing.join('、')}`) + } + + const column = (label: typeof REQUIRED_HEADERS[number]) => headerByLabel.get(label)! + const rows: Dropship1688SourcingImportRow[] = [] + for (let rowNumber = 2; rowNumber <= sheet.actualRowCount; rowNumber += 1) { + const row = sheet.getRow(rowNumber) + const sourceBarcode = cellText(row.getCell(column('代发条码'))) + const purchaserName = cellText(row.getCell(column('采购'))) + const supplierName = cellText(row.getCell(column('供应商'))) + const quotedPriceTaxIncluded = decimalCellText(row.getCell(column('报价(含税)')), false) + const invoiceTaxPoint = decimalCellText(row.getCell(column('发票税点')), true) + const sourcingMode = cellText(row.getCell(column('模式'))) + const jianshangBarcode = cellText(row.getCell(column('简尚条码'))) + const hasAnyValue = [ + sourceBarcode, + purchaserName, + supplierName, + quotedPriceTaxIncluded, + invoiceTaxPoint, + sourcingMode, + jianshangBarcode, + ].some(Boolean) + if (!hasAnyValue) continue + rows.push({ + rowNumber, + sourceBarcode, + purchaserName, + supplierName, + quotedPriceTaxIncluded, + invoiceTaxPoint, + sourcingMode, + jianshangBarcode, + }) + } + return rows +} diff --git a/furniture-3d-system/src/lib/dropship-1688-sourcing.ts b/furniture-3d-system/src/lib/dropship-1688-sourcing.ts new file mode 100644 index 00000000..72f0f20a --- /dev/null +++ b/furniture-3d-system/src/lib/dropship-1688-sourcing.ts @@ -0,0 +1,15 @@ +export const DROPSHIP_1688_MAX_PURCHASERS = 3 +export const DROPSHIP_1688_SOURCING_PAGE_SIZE = 50 +export const DROPSHIP_1688_SOURCING_EXPORT_LIMIT = 50_000 + +export type Dropship1688SourcingFilters = { + purchaserNames: string[] + sourceSpus: string[] + sourceSkuOperators: string[] +} + +export const EMPTY_DROPSHIP_1688_SOURCING_FILTERS: Dropship1688SourcingFilters = { + purchaserNames: [], + sourceSpus: [], + sourceSkuOperators: [], +} diff --git a/furniture-3d-system/src/lib/open-product/platform-api.ts b/furniture-3d-system/src/lib/open-product/platform-api.ts index 2c5c5f78..08e3aabe 100644 --- a/furniture-3d-system/src/lib/open-product/platform-api.ts +++ b/furniture-3d-system/src/lib/open-product/platform-api.ts @@ -1064,6 +1064,29 @@ export async function createInstallationDemoShareLink( return data.share } +export async function fetchInstallationDemoShareLink( + drawingId: string, +): Promise { + const data = await requestPlatform<{ share: InstallationDemoShareLinkDTO | null }>( + `/api/installation-demo-workbench/share?drawingId=${encodeURIComponent(drawingId)}`, + ) + return data.share +} + +export async function syncInstallationDemoShareLink( + input: CreateInstallationDemoShareInput, + token: string, +): Promise { + const data = await requestPlatform<{ share: InstallationDemoShareLinkDTO }>( + '/api/installation-demo-workbench/share/sync', + { + method: 'POST', + body: JSON.stringify({ ...input, token }), + }, + ) + return data.share +} + export async function syncInstallationDemoQrShare( input: CreateInstallationDemoShareInput, ): Promise { diff --git a/furniture-3d-system/src/lib/role-scope.test.ts b/furniture-3d-system/src/lib/role-scope.test.ts index fc8e40c2..84ec1d97 100644 --- a/furniture-3d-system/src/lib/role-scope.test.ts +++ b/furniture-3d-system/src/lib/role-scope.test.ts @@ -1,5 +1,8 @@ import { + canDeleteBarcodePrintImports, canCreateContent, + canEditBarcodePrintImports, + canImportBarcodePrintRecords, canOperateDesignWorkspace, hasBusinessRole, isReadOnlyUser, @@ -81,4 +84,26 @@ describe('role-scope business roles', () => { it('保留无部门旧设计账号的设计工作区兜底权限', () => { expect(canOperateDesignWorkspace({ role: 'USER', businessRoles: ['DESIGN'] })).toBe(true) }) + + it.each(['PURCHASING', 'WAREHOUSE'])( + '%s 可以导入和删除条码导入记录,但不能批量修改', + (businessRole) => { + const user = { role: 'USER', businessRoles: [businessRole] } + + expect(canImportBarcodePrintRecords(user)).toBe(true) + expect(canDeleteBarcodePrintImports(user)).toBe(true) + expect(canEditBarcodePrintImports(user)).toBe(false) + }, + ) + + it('设计师和管理员保留条码导入记录的完整维护权限', () => { + const designer = { role: 'USER', businessRoles: ['DESIGN'] } + const admin = { role: 'ADMIN', businessRoles: [] } + + for (const user of [designer, admin]) { + expect(canImportBarcodePrintRecords(user)).toBe(true) + expect(canDeleteBarcodePrintImports(user)).toBe(true) + expect(canEditBarcodePrintImports(user)).toBe(true) + } + }) }) diff --git a/furniture-3d-system/src/lib/role-scope.ts b/furniture-3d-system/src/lib/role-scope.ts index 5399f32a..35663eb6 100644 --- a/furniture-3d-system/src/lib/role-scope.ts +++ b/furniture-3d-system/src/lib/role-scope.ts @@ -78,7 +78,20 @@ export function isDesigner(user: ScopedRoleUser): boolean { return hasBusinessRole(user, 'DESIGN') } -export function canManageBarcodePrintImports(user: ScopedRoleUser): boolean { +export function canImportBarcodePrintRecords(user: ScopedRoleUser): boolean { + return ( + isAdmin(user) || + isDesigner(user) || + hasBusinessRole(user, 'PURCHASING') || + hasBusinessRole(user, 'WAREHOUSE') + ) +} + +export function canDeleteBarcodePrintImports(user: ScopedRoleUser): boolean { + return canImportBarcodePrintRecords(user) +} + +export function canEditBarcodePrintImports(user: ScopedRoleUser): boolean { return isAdmin(user) || isDesigner(user) } diff --git a/furniture-3d-system/src/lib/supply-chain-permission-settings.test.ts b/furniture-3d-system/src/lib/supply-chain-permission-settings.test.ts index 1612e60e..4e46842b 100644 --- a/furniture-3d-system/src/lib/supply-chain-permission-settings.test.ts +++ b/furniture-3d-system/src/lib/supply-chain-permission-settings.test.ts @@ -176,13 +176,19 @@ describe('supply chain permission settings', () => { ).toEqual({ targetKey: 'scriptMonitor', action: 'view' }) }) - it('assigns only the dedicated DF image endpoint to the 1688 module', () => { + it('assigns the dedicated image and sourcing workbook endpoints to the 1688 module', () => { expect(getSupplyChainApiPermissionRequirement('/api/supply-chain/1688-dropship-data/source-image', 'GET')) .toEqual({ targetKey: 'newProduct1688DropshipData', action: 'view' }) expect(getSupplyChainApiPermissionRequirement('/api/supply-chain/1688-dropship-data/source-image', 'POST')) .toEqual({ targetKey: 'newProduct1688DropshipData', action: 'edit' }) expect(getSupplyChainApiPermissionRequirement('/api/supply-chain/1688-dropship-data/source-image/other', 'GET')) .toBeUndefined() + expect(getSupplyChainApiPermissionRequirement('/api/supply-chain/1688-dropship-data/sourcing-list', 'GET')) + .toEqual({ targetKey: 'newProduct1688DropshipData', action: 'view' }) + expect(getSupplyChainApiPermissionRequirement('/api/supply-chain/1688-dropship-data/sourcing-export', 'POST')) + .toEqual({ targetKey: 'newProduct1688DropshipData', action: 'download' }) + expect(getSupplyChainApiPermissionRequirement('/api/supply-chain/1688-dropship-data/sourcing-import', 'POST')) + .toEqual({ targetKey: 'newProduct1688DropshipData', action: 'edit' }) expect(getSupplyChainApiPermissionRequirement('/api/supply-chain/product-archive/source-image', 'GET')) .toEqual({ targetKey: 'productArchive', action: 'view' }) }) diff --git a/furniture-3d-system/src/lib/supply-chain-permission-settings.ts b/furniture-3d-system/src/lib/supply-chain-permission-settings.ts index efec7cfb..a18d675c 100644 --- a/furniture-3d-system/src/lib/supply-chain-permission-settings.ts +++ b/furniture-3d-system/src/lib/supply-chain-permission-settings.ts @@ -356,6 +356,15 @@ export function getSupplyChainApiPermissionRequirement(pathname: string, method: if (pathname === '/api/supply-chain/1688-dropship-data/source-image') { return { targetKey: 'newProduct1688DropshipData' as const, action } } + if (pathname === '/api/supply-chain/1688-dropship-data/sourcing-list') { + return { targetKey: 'newProduct1688DropshipData' as const, action: 'view' as const } + } + if (pathname === '/api/supply-chain/1688-dropship-data/sourcing-export') { + return { targetKey: 'newProduct1688DropshipData' as const, action: 'download' as const } + } + if (pathname === '/api/supply-chain/1688-dropship-data/sourcing-import') { + return { targetKey: 'newProduct1688DropshipData' as const, action: 'edit' as const } + } if (pathname.startsWith('/api/supply-chain/new-products/dropship-issues')) { return { targetKey: 'newProductDropshipIssues' as const, action } } diff --git a/furniture-3d-system/src/lib/supply-chain-product-archive-values.ts b/furniture-3d-system/src/lib/supply-chain-product-archive-values.ts index 3ae3c02b..f5a79a1c 100644 --- a/furniture-3d-system/src/lib/supply-chain-product-archive-values.ts +++ b/furniture-3d-system/src/lib/supply-chain-product-archive-values.ts @@ -10,7 +10,19 @@ export const PRODUCT_ARCHIVE_STORAGE_TYPES = ['INBOUND', 'DROPSHIP'] as const export type ProductArchiveStorageType = (typeof PRODUCT_ARCHIVE_STORAGE_TYPES)[number] export function storageTypeLabel(value: string | null | undefined) { - if (value === 'INBOUND') return '入库' + if (value === 'INBOUND') return '入仓' if (value === 'DROPSHIP') return '代发' return '' } + +/** + * 产品定厂「发货方式」(`入仓` / `代发`)→ 档案「入库/代发」库值。 + * 无法识别的返回空串,调用方应保持原值不动(不要清空)。 + * 兼容「入库」写法,避免历史数据里出现这种填法时对不上。 + */ +export function storageTypeFromShippingMethodLabel(value: string | null | undefined) { + const keyword = String(value ?? '').trim() + if (keyword === '入仓' || keyword === '入库') return 'INBOUND' + if (keyword === '代发') return 'DROPSHIP' + return '' +} diff --git a/furniture-3d-system/src/lib/supply-chain-product-archive.ts b/furniture-3d-system/src/lib/supply-chain-product-archive.ts index eee42631..39f0552c 100644 --- a/furniture-3d-system/src/lib/supply-chain-product-archive.ts +++ b/furniture-3d-system/src/lib/supply-chain-product-archive.ts @@ -101,6 +101,39 @@ export type ProductArchiveSalesStatus = (typeof PRODUCT_ARCHIVE_SALES_STATUSES)[number] export type ProductArchiveStatusFilter = ProductArchiveSalesStatus | typeof PRODUCT_ARCHIVE_EMPTY_FILTER_VALUE +/** + * 「只看正常编码」与「排除以…开头」只对这几列开放。 + * 都是 NOT NULL 的文本列;nullable 列(image/weight/…)不开入口, + * 避免 NOT 条件在 SQL 里把 NULL 行一起判掉。 + */ +export const PRODUCT_ARCHIVE_TEXT_FILTER_KEYS = ['spu', 'sku', 'barcode', 'productName'] as const +export type ProductArchiveTextFilterKey = (typeof PRODUCT_ARCHIVE_TEXT_FILTER_KEYS)[number] + +/** + * 「正常编码」形态:字母前缀(2~6位) + 可选「-字母段(2~6位)」 + 数字编号(3~8位)。 + * 命中:XG0022 / DNZ0411 / GBSFY-SJ0380 / GBPM-YMJ0147 / CFZW0161 / CM20062362 + * 不命中:1036.00 / 110886Z15 / 1643A / 2247B / 含中文的商品名 / 32 位哈希 + * 服务端用同一个串拼 SQL 正则,避免两边口径漂移。 + */ +export const PRODUCT_ARCHIVE_NORMAL_CODE_PATTERN = '^[A-Z]{2,6}(-[A-Z]{2,6})?[0-9]{3,8}$' + +export function isNormalArchiveCode(value: string) { + return new RegExp(PRODUCT_ARCHIVE_NORMAL_CODE_PATTERN).test(String(value ?? '').trim().toUpperCase()) +} + +/** + * 「只看正常编码」当前只对 SPU 开放。 + * 其余文本列(条码是纯数字、商品名称是中文)不存在这个形态概念。 + * 要放开哪一列,改这里即可(服务端已支持任意文本列)。 + */ +export const PRODUCT_ARCHIVE_NORMAL_CODE_FIELDS = ['spu'] as const satisfies readonly ProductArchiveTextFilterKey[] + +/** 一条「排除以…开头」规则。可累加,多条之间取「且」。 */ +export type ProductArchiveExcludeRule = { + field: ProductArchiveTextFilterKey + startsWith: string +} + export type ProductArchiveFilters = { salesGranularity?: 'day' | 'month' | 'year' salesPeriod?: string @@ -190,6 +223,10 @@ export type ProductArchiveFilters = { createTimeTo?: string updateTimeFrom?: string updateTimeTo?: string + /** 只看「正常编码」(字母前缀+数字编号)。目前仅对 spu 开放。 */ + normalCodeOnly?: ProductArchiveTextFilterKey[] + /** 「排除以…开头」规则,可累加。与上面的勾选值「包含」是「且」的关系。 */ + excludeStartsWith?: ProductArchiveExcludeRule[] } export const PRODUCT_ARCHIVE_FILTER_OPTION_KEYS = [ diff --git a/furniture-3d-system/src/server/repositories/__tests__/dropship-1688-data.repository.test.ts b/furniture-3d-system/src/server/repositories/__tests__/dropship-1688-data.repository.test.ts index 0cc4f634..7ddde815 100644 --- a/furniture-3d-system/src/server/repositories/__tests__/dropship-1688-data.repository.test.ts +++ b/furniture-3d-system/src/server/repositories/__tests__/dropship-1688-data.repository.test.ts @@ -8,6 +8,9 @@ jest.mock('@/lib/prisma', () => ({ groupBy: jest.fn(), findMany: jest.fn(), }, + dropship1688SourcingTask: { + findMany: jest.fn(), + }, }, })) @@ -20,6 +23,7 @@ const archiveFindMany = prisma.supplyChainProductArchive.findMany as jest.Mock const dailyAggregate = prisma.supplyChainProductArchiveSalesPerformanceDaily.aggregate as jest.Mock const dailyGroupBy = prisma.supplyChainProductArchiveSalesPerformanceDaily.groupBy as jest.Mock const dailyFindMany = prisma.supplyChainProductArchiveSalesPerformanceDaily.findMany as jest.Mock +const taskFindMany = prisma.dropship1688SourcingTask.findMany as jest.Mock function archive(id: string, barcode: string) { return { @@ -32,12 +36,12 @@ function archive(id: string, barcode: string) { } } -function performance(barcode: string, realPerformance: string) { +function performance(barcode: string, realPerformance: string, salesAmount = '0') { return { barcode, _sum: { shipQty: 0n, - salesAmount: new Prisma.Decimal(0), + salesAmount: new Prisma.Decimal(salesAmount), realPerformance: new Prisma.Decimal(realPerformance), clearSalesCost: new Prisma.Decimal(0), sendFreight: new Prisma.Decimal(0), @@ -54,6 +58,7 @@ describe('dropship1688DataRepository', () => { _sum: { shipQty: 0n, shipAmount: new Prisma.Decimal(0), realPerformance: new Prisma.Decimal(0) }, }) dailyFindMany.mockResolvedValue([]) + taskFindMany.mockResolvedValue([]) }) it('sorts the complete result by filtered real performance before pagination', async () => { @@ -154,6 +159,33 @@ describe('dropship1688DataRepository', () => { expect(result.summary._sum.realPerformance.toString()).toBe('90') }) + it('counts only products whose fully backfilled displayed sales amount is positive', async () => { + const candidates = [ + archive('positive', 'DF-POSITIVE'), + archive('zero', 'DF-ZERO'), + archive('negative', 'DF-NEGATIVE'), + archive('legacy', 'DF-LEGACY'), + ] + archiveFindMany.mockImplementation(({ where }) => Promise.resolve( + where.id ? candidates.filter((candidate) => where.id.in.includes(candidate.id)) : candidates, + )) + const legacy = performance('DF-LEGACY', '40', '999') + legacy._count = { _all: 2, salesAmount: 1 } + dailyGroupBy.mockResolvedValue([ + performance('DF-POSITIVE', '100', '120'), + performance('DF-ZERO', '80', '0'), + performance('DF-NEGATIVE', '60', '-1'), + legacy, + ]) + + const result = await dropship1688DataRepository.listPage({ + keyword: '', dateFrom: new Date('2026-09-01'), dateTo: new Date('2026-09-07'), skip: 0, take: 50, + }) + + expect(result.summary.productsWithSalesAmount).toBe(1) + expect(result.summary._sum.shipAmount).toBeNull() + }) + it('matches ider-backed operators within the selected date range', async () => { archiveFindMany.mockImplementation(({ where }) => Promise.resolve(where.id ? [archive('a', 'DF-A')] @@ -257,6 +289,64 @@ describe('dropship1688DataRepository', () => { expect(result.summary._sum.realPerformance.toString()).toBe(total) }) + it('keeps filtered sales and calculated-profit summaries stable across pages', async () => { + const candidates = [ + archive('a', 'DF-A'), + archive('b', 'DF-B'), + archive('c', 'DF-C'), + ] + archiveFindMany.mockImplementation(({ where }) => Promise.resolve( + where.id ? candidates.filter((candidate) => where.id.in.includes(candidate.id)) : candidates, + )) + const first = performance('DF-A', '100', '20') + first._sum.clearSalesCost = new Prisma.Decimal('20') + first._sum.sendFreight = new Prisma.Decimal('5') + first._sum.afterSaleAmount = new Prisma.Decimal('0.0001') + const second = performance('DF-B', '50', '10') + second._sum.clearSalesCost = new Prisma.Decimal('10') + second._sum.sendFreight = new Prisma.Decimal('2') + second._sum.afterSaleAmount = new Prisma.Decimal('0.0002') + const excluded = performance('DF-C', '10000', '9000') + excluded._sum.clearSalesCost = new Prisma.Decimal('500') + excluded._sum.sendFreight = new Prisma.Decimal('100') + excluded._sum.afterSaleAmount = new Prisma.Decimal('1000') + dailyGroupBy.mockResolvedValue([first, second, excluded]) + const input = { + keyword: '', + dateFrom: new Date('2026-09-01'), + dateTo: new Date('2026-09-07'), + filters: { sku: { mode: 'include' as const, values: ['SKU-a', 'SKU-b'] } }, + take: 1, + } + + for (const [skip, barcode] of [[0, 'DF-A'], [1, 'DF-B']] as const) { + const result = await dropship1688DataRepository.listPage({ ...input, skip }) + expect(result.archives.map((record) => record.barcode)).toEqual([barcode]) + expect(result.total).toBe(2) + expect(result.summary.productsWithSalesAmount).toBe(2) + expect(result.summary._sum.shipAmount?.toString()).toBe('30') + expect(result.summary._sum.realPerformance.toString()).toBe('150') + expect(result.summary._sum.grossProfit.toString()).toBe('113') + expect(result.summary._sum.afterSaleAmount.toFixed(4)).toBe('0.0003') + } + expect(dailyGroupBy).toHaveBeenCalledWith(expect.objectContaining({ + where: { + barcode: { startsWith: 'DF-' }, + statDate: { gte: input.dateFrom, lte: input.dateTo }, + }, + _sum: expect.objectContaining({ + salesAmount: true, + realPerformance: true, + clearSalesCost: true, + sendFreight: true, + afterSaleAmount: true, + }), + })) + const aggregateSelection = dailyGroupBy.mock.calls[0][0]._sum + expect(aggregateSelection).not.toHaveProperty('grossProfit') + expect(dailyGroupBy.mock.calls[0][0].where).not.toHaveProperty('archive') + }) + it('filters by the latest trimmed non-empty operator in the selected period, not historical matches', async () => { const candidates = [archive('a', 'DF-A'), archive('b', 'DF-B'), archive('empty', 'DF-EMPTY')] archiveFindMany.mockImplementation(({ where }) => Promise.resolve( @@ -289,6 +379,122 @@ describe('dropship1688DataRepository', () => { expect(historical.archives.map((record) => record.barcode)).toEqual(['DF-B']) }) + it('matches a product when any accepting purchaser is selected', async () => { + const candidates = [archive('a', 'DF-A'), archive('b', 'DF-B')] + archiveFindMany.mockImplementation(({ where }) => Promise.resolve( + where.id ? candidates.filter((candidate) => where.id.in.includes(candidate.id)) : candidates, + )) + dailyGroupBy.mockResolvedValue([]) + taskFindMany.mockResolvedValue([{ sourceBarcode: 'DF-A' }]) + const input = { + keyword: '', dateFrom: new Date('2026-09-01'), dateTo: new Date('2026-09-07'), skip: 0, take: 50, + } + + const included = await dropship1688DataRepository.listPage({ + ...input, filters: { purchaser: { mode: 'include', values: ['采购乙'] } }, + }) + expect(included.archives.map((record) => record.barcode)).toEqual(['DF-A']) + + const excluded = await dropship1688DataRepository.listPage({ + ...input, filters: { purchaser: { mode: 'exclude', values: ['采购甲'] } }, + }) + expect(excluded.archives.map((record) => record.barcode)).toEqual(['DF-B']) + expect(taskFindMany).toHaveBeenNthCalledWith(1, { + where: { purchaserName: { in: ['采购乙'] } }, + distinct: ['sourceBarcode'], + select: { sourceBarcode: true }, + }) + expect(taskFindMany).toHaveBeenNthCalledWith(2, { + where: { purchaserName: { in: ['采购甲'] } }, + distinct: ['sourceBarcode'], + select: { sourceBarcode: true }, + }) + }) + + it('keeps purchaser-filtered totals and summaries stable across pages', async () => { + const candidates = [archive('a', 'DF-A'), archive('b', 'DF-B'), archive('c', 'DF-C')] + archiveFindMany.mockImplementation(({ where }) => Promise.resolve( + where.id ? candidates.filter((candidate) => where.id.in.includes(candidate.id)) : candidates, + )) + taskFindMany.mockResolvedValue([{ sourceBarcode: 'DF-A' }, { sourceBarcode: 'DF-B' }]) + dailyGroupBy.mockResolvedValue([ + performance('DF-A', '10'), performance('DF-B', '20'), performance('DF-C', '999'), + ]) + const filters = { purchaser: { mode: 'include' as const, values: ['采购甲'] } } + + for (const [skip, barcode] of [[0, 'DF-B'], [1, 'DF-A']] as const) { + const result = await dropship1688DataRepository.listPage({ + keyword: '', dateFrom: new Date('2026-09-01'), dateTo: new Date('2026-09-07'), + skip, take: 1, filters, + }) + expect(result.archives.map((record) => record.barcode)).toEqual([barcode]) + expect(result.total).toBe(2) + expect(result.summary._sum.realPerformance.toString()).toBe('30') + } + expect(taskFindMany).toHaveBeenCalledTimes(2) + expect(taskFindMany).toHaveBeenLastCalledWith({ + where: { purchaserName: { in: ['采购甲'] } }, + distinct: ['sourceBarcode'], + select: { sourceBarcode: true }, + }) + }) + + it('offers searchable purchaser options from the remaining candidate products', async () => { + archiveFindMany.mockResolvedValue([ + archive('a', 'DF-A'), + archive('b', 'DF-B'), + archive('c', 'DF-C'), + ]) + taskFindMany.mockImplementation(({ where }) => { + if (where.purchaserName) return Promise.resolve([{ sourceBarcode: 'DF-A' }]) + const requested = new Set(where.sourceBarcode.in) + return Promise.resolve([ + ...(requested.has('DF-A') ? [{ purchaserName: '采购乙' }, { purchaserName: '采购甲' }] : []), + ...(requested.has('DF-B') ? [{ purchaserName: ' 采购甲 ' }] : []), + ...(requested.has('DF-C') ? [{ purchaserName: '采购丁' }] : []), + ]) + }) + const input = { + field: 'purchaser' as const, + keyword: '', + dateFrom: new Date('2026-09-01'), + dateTo: new Date('2026-09-07'), + } + + const all = await dropship1688DataRepository.listFilterOptions({ ...input, filters: {} }) + expect(all.values).toEqual(['采购丁', '采购甲', '采购乙']) + + const searched = await dropship1688DataRepository.listFilterOptions({ + ...input, + optionQuery: '乙', + filters: { spu: { mode: 'include', values: ['SPU-a', 'SPU-b'] } }, + }) + expect(searched.values).toEqual(['采购乙']) + + const purchaserConstrainedSpus = await dropship1688DataRepository.listFilterOptions({ + ...input, + field: 'spu', + optionQuery: 'a', + filters: { purchaser: { mode: 'include', values: ['采购乙'] } }, + }) + expect(purchaserConstrainedSpus.values).toEqual(['SPU-a']) + expect(taskFindMany).toHaveBeenNthCalledWith(1, { + where: { sourceBarcode: { in: ['DF-A', 'DF-B', 'DF-C'] } }, + distinct: ['purchaserName'], + select: { purchaserName: true }, + }) + expect(taskFindMany).toHaveBeenNthCalledWith(2, { + where: { sourceBarcode: { in: ['DF-A', 'DF-B'] } }, + distinct: ['purchaserName'], + select: { purchaserName: true }, + }) + expect(taskFindMany).toHaveBeenNthCalledWith(3, { + where: { purchaserName: { in: ['采购乙'] } }, + distinct: ['sourceBarcode'], + select: { sourceBarcode: true }, + }) + }) + it('lists all unique options with other column filters applied and its own filter omitted', async () => { archiveFindMany.mockResolvedValue([ { ...archive('a', 'DF-A'), spu: 'SHARED' }, diff --git a/furniture-3d-system/src/server/repositories/__tests__/dropship-1688-sourcing.repository.test.ts b/furniture-3d-system/src/server/repositories/__tests__/dropship-1688-sourcing.repository.test.ts new file mode 100644 index 00000000..ba45ab4f --- /dev/null +++ b/furniture-3d-system/src/server/repositories/__tests__/dropship-1688-sourcing.repository.test.ts @@ -0,0 +1,446 @@ +jest.mock('@/lib/prisma', () => ({ + prisma: { + supplyChainProductArchive: { + findUnique: jest.fn(), + findMany: jest.fn(), + }, + supplyChainProductArchiveSalesPerformanceDaily: { + findMany: jest.fn(), + }, + $transaction: jest.fn(), + dropship1688SourcingTask: { + findUnique: jest.fn(), + findMany: jest.fn(), + count: jest.fn(), + update: jest.fn(), + deleteMany: jest.fn(), + }, + }, +})) + +import { Prisma } from '@prisma/client' +import { prisma } from '@/lib/prisma' +import { ErrorCode } from '@/server/core/errors' +import { dropship1688SourcingRepository } from '../dropship-1688-sourcing.repository' + +const archiveFindUnique = prisma.supplyChainProductArchive.findUnique as jest.Mock +const archiveFindMany = prisma.supplyChainProductArchive.findMany as jest.Mock +const dailyFindMany = prisma.supplyChainProductArchiveSalesPerformanceDaily.findMany as jest.Mock +const taskFindMany = prisma.dropship1688SourcingTask.findMany as jest.Mock +const taskCount = prisma.dropship1688SourcingTask.count as jest.Mock +const taskFindUnique = prisma.dropship1688SourcingTask.findUnique as jest.Mock +const taskUpdate = prisma.dropship1688SourcingTask.update as jest.Mock +const taskDeleteMany = prisma.dropship1688SourcingTask.deleteMany as jest.Mock +const transactionQueryRaw = jest.fn() +const transactionFindUnique = jest.fn() +const transactionCount = jest.fn() +const transactionCreate = jest.fn() +const transaction = { + $queryRaw: transactionQueryRaw, + dropship1688SourcingTask: { + findUnique: transactionFindUnique, + count: transactionCount, + create: transactionCreate, + }, +} + +const dateFrom = new Date('2026-09-01T00:00:00.000Z') +const dateTo = new Date('2026-09-10T00:00:00.000Z') + +function task(overrides: Record = {}) { + return { + id: 'task-1', + sourceArchiveId: 'archive-1', + sourceSpu: 'SPU-ONE', + sourceBarcode: 'DF-ONE', + sourceCostPrice: new Prisma.Decimal('70'), + sourceSkuOperator: '子美', + sourceDateFrom: dateFrom, + sourceDateTo: dateTo, + purchaserUserId: 'buyer-1', + purchaserName: '采购甲', + supplierName: '', + quotedPriceTaxIncluded: null, + invoiceTaxPoint: null, + sourcingMode: '', + jianshangBarcode: '', + acceptedAt: new Date('2026-09-16T01:00:00.000Z'), + updatedAt: new Date('2026-09-16T01:00:00.000Z'), + ...overrides, + } +} + +describe('dropship1688SourcingRepository', () => { + beforeEach(() => { + jest.clearAllMocks() + archiveFindUnique.mockResolvedValue(null) + archiveFindMany.mockResolvedValue([]) + dailyFindMany.mockResolvedValue([]) + taskFindMany.mockResolvedValue([]) + taskCount.mockResolvedValue(0) + taskFindUnique.mockResolvedValue(null) + taskUpdate.mockResolvedValue(task()) + taskDeleteMany.mockResolvedValue({ count: 1 }) + transactionQueryRaw.mockResolvedValue([{ + expected_count: 1, + matched_count: 1, + updated_count: 1, + }]) + transactionFindUnique.mockResolvedValue(null) + transactionCount.mockResolvedValue(0) + transactionCreate.mockResolvedValue(task()) + jest.mocked(prisma.$transaction).mockImplementation(async (input) => ( + Array.isArray(input) + ? Promise.all(input) + : input(transaction as never) + ) as never) + }) + + it('loads and updates the editable sourcing fields with the shared task projection', async () => { + taskFindUnique.mockResolvedValue(task()) + taskUpdate.mockResolvedValue(task({ + supplierName: '供应商甲', + quotedPriceTaxIncluded: new Prisma.Decimal('68.5'), + invoiceTaxPoint: new Prisma.Decimal('13'), + sourcingMode: '代发', + jianshangBarcode: 'JS-001', + })) + + await expect(dropship1688SourcingRepository.findTaskById('task-1')).resolves.toEqual(task()) + expect(taskFindUnique).toHaveBeenCalledWith({ where: { id: 'task-1' }, select: expect.any(Object) }) + + const update = { + id: 'task-1', + supplierName: '供应商甲', + quotedPriceTaxIncluded: new Prisma.Decimal('68.5'), + invoiceTaxPoint: new Prisma.Decimal('13'), + sourcingMode: '代发', + jianshangBarcode: 'JS-001', + } + await expect(dropship1688SourcingRepository.updateTask(update)).resolves.toMatchObject({ + supplierName: '供应商甲', sourcingMode: '代发', + }) + expect(taskUpdate).toHaveBeenCalledWith({ + where: { id: 'task-1' }, + data: { + supplierName: '供应商甲', + quotedPriceTaxIncluded: update.quotedPriceTaxIncluded, + invoiceTaxPoint: update.invoiceTaxPoint, + sourcingMode: '代发', + jianshangBarcode: 'JS-001', + }, + select: expect.any(Object), + }) + }) + + it('atomically deletes only an own sourcing task whose jianshang barcode is empty', async () => { + await expect(dropship1688SourcingRepository.deleteTaskIfRevocable({ + id: 'task-1', + purchaserUserId: 'buyer-1', + })).resolves.toBe(true) + expect(taskDeleteMany).toHaveBeenCalledTimes(1) + expect(taskDeleteMany).toHaveBeenCalledWith({ + where: { + id: 'task-1', + purchaserUserId: 'buyer-1', + jianshangBarcode: '', + }, + }) + }) + + it('reports when the atomic revoke predicate no longer matches', async () => { + taskDeleteMany.mockResolvedValue({ count: 0 }) + await expect(dropship1688SourcingRepository.deleteTaskIfRevocable({ + id: 'task-1', + purchaserUserId: 'buyer-1', + })).resolves.toBe(false) + }) + + it('recomputes the latest non-empty cost and operator independently inside the selected range', async () => { + archiveFindUnique.mockResolvedValue({ id: 'archive-1', barcode: 'DF-ONE', spu: ' SPU-ONE ' }) + dailyFindMany.mockResolvedValue([ + { unitCost: new Prisma.Decimal('72.5'), skuOperator: ' ' }, + { unitCost: null, skuOperator: ' 子美 ' }, + { unitCost: new Prisma.Decimal('65'), skuOperator: '旧运营' }, + ]) + + await expect(dropship1688SourcingRepository.findClaimSource({ + barcode: 'DF-ONE', dateFrom, dateTo, + })).resolves.toEqual({ + archiveId: 'archive-1', + spu: 'SPU-ONE', + barcode: 'DF-ONE', + costPrice: new Prisma.Decimal('72.5'), + skuOperator: '子美', + }) + expect(dailyFindMany).toHaveBeenCalledWith({ + where: { barcode: 'DF-ONE', statDate: { gte: dateFrom, lte: dateTo } }, + select: { skuOperator: true, unitCost: true }, + orderBy: { statDate: 'desc' }, + }) + }) + + it('does not read daily facts when the archive barcode does not exist', async () => { + await expect(dropship1688SourcingRepository.findClaimSource({ + barcode: 'DF-MISSING', dateFrom, dateTo, + })).resolves.toBeNull() + expect(dailyFindMany).not.toHaveBeenCalled() + }) + + it('returns the existing task for a repeated purchaser without consuming another slot', async () => { + transactionFindUnique.mockResolvedValue(task()) + const source = { + archiveId: 'archive-1', + spu: 'SPU-ONE', + barcode: 'DF-ONE', + costPrice: new Prisma.Decimal('70'), + skuOperator: '子美', + } + + await expect(dropship1688SourcingRepository.claim({ + source, + dateFrom, + dateTo, + purchaser: { id: 'buyer-1', name: '采购甲' }, + })).resolves.toEqual({ status: 'already-accepted', task: task() }) + + expect(transactionFindUnique).toHaveBeenCalledWith({ + where: { + sourceBarcode_purchaserUserId: { + sourceBarcode: 'DF-ONE', + purchaserUserId: 'buyer-1', + }, + }, + select: expect.any(Object), + }) + expect(transactionCount).not.toHaveBeenCalled() + expect(transactionCreate).not.toHaveBeenCalled() + }) + + it('serializes claims by barcode and allows the third purchaser', async () => { + transactionCount.mockResolvedValue(2) + transactionCreate.mockResolvedValue(task({ + id: 'task-3', purchaserUserId: 'buyer-3', purchaserName: '采购丙', + })) + const source = { + archiveId: 'archive-1', + spu: 'SPU-ONE', + barcode: 'DF-ONE', + costPrice: new Prisma.Decimal('70'), + skuOperator: '子美', + } + + await expect(dropship1688SourcingRepository.claim({ + source, + dateFrom, + dateTo, + purchaser: { id: 'buyer-3', name: '采购丙' }, + })).resolves.toEqual({ + status: 'claimed', + task: task({ id: 'task-3', purchaserUserId: 'buyer-3', purchaserName: '采购丙' }), + }) + + expect(transactionQueryRaw).toHaveBeenCalledTimes(1) + expect(transactionQueryRaw.mock.calls[0][0].join(' ')).toContain( + 'pg_advisory_xact_lock(hashtextextended(', + ) + expect(transactionQueryRaw.mock.calls[0][0].join(' ')).toContain('::text AS lock_result') + expect(transactionQueryRaw.mock.calls[0][1]).toBe('DF-ONE') + expect(transactionCount).toHaveBeenCalledWith({ where: { sourceBarcode: 'DF-ONE' } }) + expect(transactionCreate).toHaveBeenCalledWith({ + data: { + sourceArchiveId: 'archive-1', + sourceSpu: 'SPU-ONE', + sourceBarcode: 'DF-ONE', + sourceCostPrice: source.costPrice, + sourceSkuOperator: '子美', + sourceDateFrom: dateFrom, + sourceDateTo: dateTo, + purchaserUserId: 'buyer-3', + purchaserName: '采购丙', + }, + select: expect.any(Object), + }) + }) + + it('rejects a fourth purchaser without creating a task', async () => { + transactionCount.mockResolvedValue(3) + + await expect(dropship1688SourcingRepository.claim({ + source: { + archiveId: 'archive-1', + spu: 'SPU-ONE', + barcode: 'DF-ONE', + costPrice: new Prisma.Decimal('70'), + skuOperator: '子美', + }, + dateFrom, + dateTo, + purchaser: { id: 'buyer-4', name: '采购丁' }, + })).resolves.toEqual({ status: 'full' }) + + expect(transactionQueryRaw).toHaveBeenCalledTimes(1) + expect(transactionCount).toHaveBeenCalledWith({ where: { sourceBarcode: 'DF-ONE' } }) + expect(transactionCreate).not.toHaveBeenCalled() + }) + + it('keeps the accepted SPU snapshot while enriching current SKU and image data', async () => { + taskFindMany.mockResolvedValue([ + task(), + task({ id: 'task-2', sourceSpu: 'SPU-TWO', sourceBarcode: 'DF-TWO', purchaserUserId: 'buyer-2' }), + ]) + archiveFindMany.mockResolvedValue([ + { barcode: 'DF-ONE', sku: ' SKU-ONE ', image: ' https://example.com/one.jpg ' }, + ]) + + const result = await dropship1688SourcingRepository.listTasks() + + expect(taskFindMany).toHaveBeenCalledWith(expect.objectContaining({ + orderBy: [{ acceptedAt: 'desc' }, { id: 'asc' }], + })) + expect(archiveFindMany).toHaveBeenCalledWith({ + where: { barcode: { in: ['DF-ONE', 'DF-TWO'] } }, + select: { barcode: true, sku: true, image: true }, + }) + expect(result).toEqual([ + expect.objectContaining({ sourceBarcode: 'DF-ONE', sourceSpu: 'SPU-ONE', sku: 'SKU-ONE', hasImage: true }), + expect.objectContaining({ sourceBarcode: 'DF-TWO', sourceSpu: 'SPU-TWO', sku: '', hasImage: false }), + ]) + }) + + it('counts filtered tasks before loading and enriching only the requested page', async () => { + const filters = { + purchaserNames: ['采购甲'], + sourceSpus: ['SPU-ONE'], + sourceSkuOperators: ['子美'], + } + const where = { + purchaserName: { in: ['采购甲'] }, + sourceSpu: { in: ['SPU-ONE'] }, + sourceSkuOperator: { in: ['子美'] }, + } + taskCount.mockResolvedValue(61) + taskFindMany.mockResolvedValue([task()]) + archiveFindMany.mockResolvedValue([ + { barcode: 'DF-ONE', sku: ' SKU-ONE ', image: ' https://example.com/one.jpg ' }, + ]) + + await expect(dropship1688SourcingRepository.countTasks(filters)).resolves.toBe(61) + await expect(dropship1688SourcingRepository.listTasksPage({ + filters, skip: 50, take: 50, + })).resolves.toEqual([ + expect.objectContaining({ id: 'task-1', sku: 'SKU-ONE', hasImage: true }), + ]) + + expect(taskCount).toHaveBeenCalledWith({ where }) + expect(taskFindMany).toHaveBeenCalledWith(expect.objectContaining({ + where, + skip: 50, + take: 50, + orderBy: [{ acceptedAt: 'desc' }, { id: 'asc' }], + })) + expect(archiveFindMany).toHaveBeenCalledWith({ + where: { barcode: { in: ['DF-ONE'] } }, + select: { barcode: true, sku: true, image: true }, + }) + }) + + it('loads all accepting purchasers for the requested barcodes', async () => { + const records = [ + { sourceBarcode: 'DF-ONE', purchaserUserId: 'buyer-1', purchaserName: '采购甲', acceptedAt: new Date() }, + { sourceBarcode: 'DF-ONE', purchaserUserId: 'buyer-2', purchaserName: '采购乙', acceptedAt: new Date() }, + ] + taskFindMany.mockResolvedValue(records) + + await expect( + dropship1688SourcingRepository.listPurchasersByBarcodes(['DF-ONE', 'DF-TWO']), + ).resolves.toBe(records) + expect(taskFindMany).toHaveBeenCalledWith(expect.objectContaining({ + where: { sourceBarcode: { in: ['DF-ONE', 'DF-TWO'] } }, + orderBy: [{ sourceBarcode: 'asc' }, { acceptedAt: 'asc' }, { id: 'asc' }], + })) + }) + + it('loads import candidates by barcode and updates them with one set-based statement', async () => { + taskFindMany.mockResolvedValue([task()]) + await expect( + dropship1688SourcingRepository.listTasksByBarcodes(['DF-ONE']), + ).resolves.toEqual([task()]) + expect(taskFindMany).toHaveBeenCalledWith({ + where: { sourceBarcode: { in: ['DF-ONE'] } }, + select: expect.any(Object), + orderBy: [{ sourceBarcode: 'asc' }, { purchaserName: 'asc' }, { id: 'asc' }], + }) + + const update = { + id: 'task-1', supplierName: '供应商甲', + quotedPriceTaxIncluded: new Prisma.Decimal('50'), + invoiceTaxPoint: new Prisma.Decimal('13'), sourcingMode: '代发', + jianshangBarcode: 'JS-001', + } + await dropship1688SourcingRepository.updateTasks([update]) + expect(prisma.$transaction).toHaveBeenCalledTimes(1) + expect(transactionQueryRaw).toHaveBeenCalledTimes(1) + expect(transactionQueryRaw.mock.calls[0][0].join(' ')).toContain('jsonb_to_recordset') + expect(JSON.parse(transactionQueryRaw.mock.calls[0][1])).toEqual([{ + id: 'task-1', + supplier_name: '供应商甲', + quoted_price_tax_included: '50', + invoice_tax_point: '13', + sourcing_mode: '代发', + jianshang_barcode: 'JS-001', + }]) + expect(taskUpdate).not.toHaveBeenCalled() + }) + + it('uses one set-based write for a 50,000-row import', async () => { + const updates = Array.from({ length: 50_000 }, (_, index) => ({ + id: `task-${index + 1}`, + supplierName: `供应商${index + 1}`, + quotedPriceTaxIncluded: new Prisma.Decimal('50'), + invoiceTaxPoint: new Prisma.Decimal('13'), + sourcingMode: '代发', + jianshangBarcode: `JS-${index + 1}`, + })) + transactionQueryRaw.mockResolvedValueOnce([{ + expected_count: updates.length, + matched_count: updates.length, + updated_count: updates.length, + }]) + + await dropship1688SourcingRepository.updateTasks(updates) + + expect(prisma.$transaction).toHaveBeenCalledTimes(1) + expect(jest.mocked(prisma.$transaction).mock.calls[0][1]).toEqual({ + maxWait: 10_000, + timeout: 120_000, + }) + expect(transactionQueryRaw).toHaveBeenCalledTimes(1) + expect(JSON.parse(transactionQueryRaw.mock.calls[0][1])).toHaveLength(50_000) + expect(taskUpdate).not.toHaveBeenCalled() + }) + + it('aborts the transaction when the full payload does not match update targets', async () => { + transactionQueryRaw.mockResolvedValueOnce([{ + expected_count: 2, + matched_count: 1, + updated_count: 0, + }]) + const updates = ['task-1', 'task-missing'].map((id) => ({ + id, + supplierName: '供应商甲', + quotedPriceTaxIncluded: null, + invoiceTaxPoint: null, + sourcingMode: '代发', + jianshangBarcode: '', + })) + + await expect(dropship1688SourcingRepository.updateTasks(updates)).rejects.toMatchObject({ + code: ErrorCode.VALIDATION_FAILED, + message: '寻源任务状态已变化,导入未执行任何更新', + }) + expect(prisma.$transaction).toHaveBeenCalledTimes(1) + expect(transactionQueryRaw).toHaveBeenCalledTimes(1) + expect(taskUpdate).not.toHaveBeenCalled() + }) +}) diff --git a/furniture-3d-system/src/server/repositories/__tests__/product-archive-sales-performance-source.repository.test.ts b/furniture-3d-system/src/server/repositories/__tests__/product-archive-sales-performance-source.repository.test.ts index 161c8b6e..6a576a50 100644 --- a/furniture-3d-system/src/server/repositories/__tests__/product-archive-sales-performance-source.repository.test.ts +++ b/furniture-3d-system/src/server/repositories/__tests__/product-archive-sales-performance-source.repository.test.ts @@ -56,14 +56,16 @@ describe('daily sales source contract', () => { expect(text).not.toContain('SupplyChainProductArchive') }) - it('selects daily DF unit cost by single-unit priority, frequency and deterministic tie-break', async () => { + it('selects quantity-one daily cost and average freight', async () => { const text = await dailySql() - expect(text).toContain('CAST(goods_cost AS decimal(38,4)) / NULLIF(CAST(goods_count AS decimal(38,4)), 0)') + expect(text).toContain('CAST(goods_cost AS decimal(38,4)) / NULLIF(CAST(goods_count AS decimal(38,4)), 0) AS decimal(24,4)') expect(text).toContain('CASE WHEN goods_count = 1 THEN 1 ELSE 0 END AS isSingleUnit') - expect(text).toContain('AND goods_count > 0 AND goods_cost > 0') + expect(text).toContain('AND goods_count = 1 AND goods_cost > 0') expect(text).toContain('GROUP BY barcode, statDate, unitCost') expect(text).toContain('PARTITION BY barcode, statDate ORDER BY CASE WHEN singleUnitRows > 0 THEN 0 ELSE 1 END, singleUnitRows DESC, observationCount DESC, unitCost DESC') expect(text).toContain('AND ranked_costs.statDate = performance.statDate AND ranked_costs.costRank = 1') + expect(text).toContain('AVG(CAST(COALESCE(send_freight, 0) AS decimal(38,4)))') + expect(text).toContain('freight_averages.estimatedFreight') }) it('deduplicates ider within barcode/day and joins operators in stable order', async () => { @@ -73,20 +75,20 @@ describe('daily sales source contract', () => { expect(text).toContain("STRING_AGG(CAST(skuOperator AS nvarchar(max)), N' / ') WITHIN GROUP (ORDER BY skuOperator)") expect(text).toContain("COALESCE(operators.skuOperator, N'') AS skuOperator") expect(text).toContain('AND operators.statDate = performance.statDate') - expect(text.match(/LIKE N'DF-%'/g)).toHaveLength(2) + expect(text.match(/LIKE N'DF-%'/g)).toHaveLength(3) }) it('preserves enrichment fields and normalizes the source row count', async () => { query.mockResolvedValue({ recordset: [{ barcode: 'DF-EXAMPLE', statDate: '2026-09-01', sourceRowCount: '2', - skuOperator: 'Operator A / Operator B', unitCost: '70.0000', + skuOperator: 'Operator A / Operator B', unitCost: '70.0000', estimatedFreight: '5.5000', salesAmount: '180.0000', shipAmount: '150.0000', }] }) expect(await repository.listDailyAggregates({ periodStart: new Date('2026-09-01'), periodEnd: new Date('2026-09-07'), })).toEqual([{ barcode: 'DF-EXAMPLE', statDate: '2026-09-01', sourceRowCount: 2, - skuOperator: 'Operator A / Operator B', unitCost: '70.0000', + skuOperator: 'Operator A / Operator B', unitCost: '70.0000', estimatedFreight: '5.5000', salesAmount: '180.0000', shipAmount: '150.0000', }]) }) diff --git a/furniture-3d-system/src/server/repositories/__tests__/supply-chain-product-archive-sales-performance-daily.repository.test.ts b/furniture-3d-system/src/server/repositories/__tests__/supply-chain-product-archive-sales-performance-daily.repository.test.ts index a254798e..eab78734 100644 --- a/furniture-3d-system/src/server/repositories/__tests__/supply-chain-product-archive-sales-performance-daily.repository.test.ts +++ b/furniture-3d-system/src/server/repositories/__tests__/supply-chain-product-archive-sales-performance-daily.repository.test.ts @@ -9,7 +9,7 @@ import type { ProductArchiveSalesPerformanceDailyAggregate } from '../product-ar const row: ProductArchiveSalesPerformanceDailyAggregate = { barcode: 'DF-EXAMPLE', statDate: '2026-09-01', sourceRowCount: 2, - skuOperator: 'Operator A / Operator B', unitCost: '70.0000', salesAmount: '180.0000', + skuOperator: 'Operator A / Operator B', unitCost: '70.0000', estimatedFreight: '5.5000', salesAmount: '180.0000', shipAmount: '150.0000', returnAmount: '0', realPerformance: '160.0000', shipQty: '2', returnQty: '0', clearSalesCost: '140.0000', sendFreight: '5', platformCommission: '0', xyCost: '0', afterSaleAmount: '0', pushFeeTotal: '0', @@ -43,9 +43,10 @@ describe('daily sales staged publication', () => { expect(JSON.parse(stage[1]![0] as string)).toEqual([row]) expect(stage[0]).toContain('"skuOperator" text') expect(stage[0]).toContain('"unitCost" numeric(24,4)') + expect(stage[0]).toContain('"estimatedFreight" numeric(24,4)') expect(stage[0]).toContain('"salesAmount" numeric(24,4)') const publish = calls.find(([text]) => text.startsWith('INSERT INTO "SupplyChainProductArchiveSalesPerformanceDaily"'))! - expect(publish[0]).toContain('"skuOperator", "unitCost", "salesAmount", "shipAmount"') + expect(publish[0]).toContain('"skuOperator", "unitCost", "estimatedFreight", "salesAmount", "shipAmount"') const statements = calls.map(([text]) => text) expect(statements).toContain('CREATE UNIQUE INDEX ON archive_sales_stage ("barcode", "statDate")') expect(statements.indexOf('BEGIN')).toBeLessThan(statements.indexOf(publish[0])) @@ -77,6 +78,7 @@ describe('daily sales staged publication', () => { describe('daily sales enrichment migration', () => { it('only adds nullable enrichment to the existing all-barcode table, without rewriting historical facts', () => { const sql = readFileSync(join(process.cwd(), 'prisma/migrations/20260912120000_add_daily_sales_dropship_fields/migration.sql'), 'utf8') + .replace(/\r\n/g, '\n') .replace(/^--.*$/gm, '').trim() expect(sql).toBe([ 'ALTER TABLE "SupplyChainProductArchiveSalesPerformanceDaily"', @@ -86,4 +88,15 @@ describe('daily sales enrichment migration', () => { ].join('\n')) expect(sql).not.toMatch(/\b(?:CREATE|DROP|DELETE|UPDATE|TRUNCATE|REFERENCES)\b/) }) + + it('adds the nullable quantity-one freight estimate without rewriting facts', () => { + const sql = readFileSync(join(process.cwd(), 'prisma/migrations/20260918180000_add_dropship_estimated_freight/migration.sql'), 'utf8') + .replace(/\r\n/g, '\n') + .replace(/^--.*$/gm, '').trim() + expect(sql).toBe([ + 'ALTER TABLE "SupplyChainProductArchiveSalesPerformanceDaily"', + ' ADD COLUMN "estimatedFreight" DECIMAL(24,4);', + ].join('\n')) + expect(sql).not.toMatch(/\b(?:CREATE|DROP|DELETE|UPDATE|TRUNCATE|REFERENCES)\b/) + }) }) diff --git a/furniture-3d-system/src/server/repositories/__tests__/supply-chain-product-archive-text-rules.test.ts b/furniture-3d-system/src/server/repositories/__tests__/supply-chain-product-archive-text-rules.test.ts new file mode 100644 index 00000000..749eea3f --- /dev/null +++ b/furniture-3d-system/src/server/repositories/__tests__/supply-chain-product-archive-text-rules.test.ts @@ -0,0 +1,155 @@ +import { parseProductArchiveFilters } from '@/server/services/supply-chain-product-archive-query' +import { + PRODUCT_ARCHIVE_NORMAL_CODE_PATTERN, + isNormalArchiveCode, +} from '@/lib/supply-chain-product-archive' +import { + buildProductArchiveWhere, + buildProductArchiveWhereWithTextRules, + clearNormalCodeValueCache, +} from '../supply-chain-product-archive-filters' + +jest.mock('@/lib/prisma', () => ({ + prisma: { $queryRaw: jest.fn() }, +})) + +const mockedQueryRaw = (jest.requireMock('@/lib/prisma') as { + prisma: { $queryRaw: jest.Mock } +}).prisma.$queryRaw + +beforeEach(() => { + clearNormalCodeValueCache() + mockedQueryRaw.mockReset() + mockedQueryRaw.mockResolvedValue([{ value: 'DNZ0411' }, { value: 'XG0022' }]) +}) + +describe('normal archive code pattern', () => { + it('matches the codes the user wants to keep', () => { + for (const code of ['XG0022', 'DNZ0411', 'GBSFY-SJ0380', 'GBPM-YMJ0147', 'CFZW0161', 'CM20062362']) { + expect(isNormalArchiveCode(code)).toBe(true) + } + }) + + it('rejects the junk codes the user reported', () => { + for (const code of ['1036.00', '110886Z15', '1643A', '2247B', '0', '723E32B019A9337FA83B59A5AE754975', 'A31-344软包折叠椅45中古黑色黑皮【8188】']) { + expect(isNormalArchiveCode(code)).toBe(false) + } + }) + + it('rejects a long digit run (the MKHDNZ style codes are filtered by the rule, not by prefix)', () => { + expect(isNormalArchiveCode('MKHDNZ1234567890123')).toBe(false) + }) + + it('keeps the SQL and JS rules on the same pattern string', () => { + expect(PRODUCT_ARCHIVE_NORMAL_CODE_PATTERN).toBe('^[A-Z]{2,6}(-[A-Z]{2,6})?[0-9]{3,8}$') + }) +}) + +describe('product archive text rule parsing', () => { + it('accepts the new text rule fields', () => { + expect(parseProductArchiveFilters(JSON.stringify({ + normalCodeOnly: ['spu'], + excludeStartsWith: [{ field: 'spu', startsWith: 'WM-' }], + }))).toEqual({ + success: true, + data: { + normalCodeOnly: ['spu'], + excludeStartsWith: [{ field: 'spu', startsWith: 'WM-' }], + }, + }) + }) + + it('rejects non-text columns and empty keywords', () => { + expect(parseProductArchiveFilters(JSON.stringify({ normalCodeOnly: ['categoryL1'] }))).toEqual({ success: false }) + expect(parseProductArchiveFilters(JSON.stringify({ excludeStartsWith: [{ field: 'weight', startsWith: 'W' }] }))) + .toEqual({ success: false }) + expect(parseProductArchiveFilters(JSON.stringify({ excludeStartsWith: [{ field: 'spu', startsWith: ' ' }] }))) + .toEqual({ success: false }) + }) + + it('caps how many exclude rules can be sent', () => { + const rules = Array.from({ length: 21 }, (_, index) => ({ field: 'spu', startsWith: `R${index}` })) + expect(parseProductArchiveFilters(JSON.stringify({ excludeStartsWith: rules }))).toEqual({ success: false }) + }) +}) + +describe('buildProductArchiveWhere exclude rules', () => { + it('emits a NOT startsWith clause per rule', () => { + const where = buildProductArchiveWhere({ + excludeStartsWith: [ + { field: 'spu', startsWith: 'WM-' }, + { field: 'spu', startsWith: 'DF-' }, + ], + }) as { AND?: Array> } + + expect(where.AND).toEqual([ + { NOT: { spu: { startsWith: 'WM-', mode: 'insensitive' } } }, + { NOT: { spu: { startsWith: 'DF-', mode: 'insensitive' } } }, + ]) + }) + + it('drops empty keywords and de-duplicates case-insensitively', () => { + const where = buildProductArchiveWhere({ + excludeStartsWith: [ + { field: 'spu', startsWith: 'DF-' }, + { field: 'spu', startsWith: 'df-' }, + { field: 'spu', startsWith: ' DF- ' }, + { field: 'spu', startsWith: ' ' }, + ], + }) as { AND?: Array> } + + expect(where.AND).toHaveLength(1) + expect(where.AND?.[0]).toEqual({ NOT: { spu: { startsWith: 'DF-', mode: 'insensitive' } } }) + }) + + it('ignores rules aimed at a column that is not a text filter target', () => { + const where = buildProductArchiveWhere({ + excludeStartsWith: [{ field: 'weight' as never, startsWith: 'W' }], + }) + expect(where).toEqual({}) + }) + + it('leaves the legacy shape untouched when no text rules are set', () => { + expect(buildProductArchiveWhere({ categoryL1: ['桌类'] })).toEqual({ + AND: [{ categoryL1: { in: ['桌类'] } }], + }) + }) +}) + +describe('buildProductArchiveWhereWithTextRules normal code', () => { + it('resolves the normal-code values into an IN clause', async () => { + const where = await buildProductArchiveWhereWithTextRules({ normalCodeOnly: ['spu'] }) as { + AND?: unknown[] + } + + expect(mockedQueryRaw).toHaveBeenCalledTimes(1) + expect(where.AND).toEqual([ + {}, + { spu: { in: ['DNZ0411', 'XG0022'] } }, + ]) + }) + + it('merges exclude rules into the same AND group', async () => { + const where = await buildProductArchiveWhereWithTextRules({ + normalCodeOnly: ['spu'], + excludeStartsWith: [{ field: 'spu', startsWith: 'WM-' }], + }) as { AND?: unknown[] } + + expect(where.AND).toEqual([ + { AND: [{ NOT: { spu: { startsWith: 'WM-', mode: 'insensitive' } } }] }, + { spu: { in: ['DNZ0411', 'XG0022'] } }, + ]) + }) + + it('caches the resolved values across calls', async () => { + await buildProductArchiveWhereWithTextRules({ normalCodeOnly: ['spu'] }) + await buildProductArchiveWhereWithTextRules({ normalCodeOnly: ['spu'] }) + expect(mockedQueryRaw).toHaveBeenCalledTimes(1) + }) + + it('returns the plain where when there are no text rules', async () => { + const where = await buildProductArchiveWhereWithTextRules({ categoryL1: ['桌类'] }) + expect(where).toEqual({ AND: [{ categoryL1: { in: ['桌类'] } }] }) + expect(mockedQueryRaw).not.toHaveBeenCalled() + }) +}) diff --git a/furniture-3d-system/src/server/repositories/__tests__/supply-chain-product-archive-warehouse-config-fill.test.ts b/furniture-3d-system/src/server/repositories/__tests__/supply-chain-product-archive-warehouse-config-fill.test.ts new file mode 100644 index 00000000..f3878bba --- /dev/null +++ b/furniture-3d-system/src/server/repositories/__tests__/supply-chain-product-archive-warehouse-config-fill.test.ts @@ -0,0 +1,106 @@ +/** + * 仓库配置来源的「入库/代发」只填空值,不覆盖产品定厂带回的值 + * (产品定厂的「发货方式」由产品开发同步直接带入,仓库配置只是兜底) + */ +jest.mock('@/lib/prisma', () => ({ + prisma: { $transaction: jest.fn() }, +})) + +import { prisma } from '@/lib/prisma' +import { SupplyChainProductArchiveEnrichmentSyncRepositoryClass } from '../supply-chain-product-archive-enrichment-sync.repository' + +const mockPrisma = prisma as unknown as { $transaction: jest.Mock } + +const WAREHOUSE_CONFIG_SOURCE = { + sourceCode: 'WAREHOUSE_CONFIG', + sourceSystem: '供应链中心', + sourceSchema: 'public', + sourceObject: 'SupplyChainProductArchiveWarehouseConfig', + sourceRecordId: 'config-1', + sourceColumns: { + warehouseHead: 'warehouseHead', + storageType: 'storageType', + }, + fillEmptyOnly: true, +} as const + +function createTransaction(input: { storageType?: string; existingSource?: { id: string } | null }) { + return { + supplyChainProductArchive: { + findUniqueOrThrow: jest.fn().mockResolvedValue({ + id: 'archive-1', + barcode: 'BAR-001', + spu: 'SPU-001', + fieldSourceMap: {}, + storageType: input.storageType ?? '', + warehouseHead: '', + }), + update: jest.fn().mockResolvedValue({}), + }, + supplyChainProductArchiveSource: { + findUnique: jest.fn().mockResolvedValue(input.existingSource ?? null), + upsert: jest.fn().mockResolvedValue({}), + }, + } +} + +const repository = new SupplyChainProductArchiveEnrichmentSyncRepositoryClass() + +describe('仓库配置来源的入库/代发只填空值', () => { + beforeEach(() => jest.clearAllMocks()) + + it('档案已有值(产品定厂带回)时不覆盖,仓库负责人照常更新', async () => { + const tx = createTransaction({ storageType: 'INBOUND' }) + mockPrisma.$transaction.mockImplementation(async (callback) => callback(tx)) + const repository = new SupplyChainProductArchiveEnrichmentSyncRepositoryClass() + + const result = await repository.applyPatch({ + archiveId: 'archive-1', + patch: { warehouseHead: '新负责人', storageType: 'DROPSHIP' }, + source: WAREHOUSE_CONFIG_SOURCE, + }) + + expect(result.changes.map((change) => change.field)).toEqual(['warehouseHead']) + expect(tx.supplyChainProductArchive.update).toHaveBeenCalledWith( + expect.objectContaining({ + where: { id: 'archive-1' }, + data: expect.objectContaining({ warehouseHead: '新负责人' }), + }), + ) + expect(tx.supplyChainProductArchive.update.mock.calls[0][0].data).not.toHaveProperty('storageType') + }) + + it('档案为空时才填入仓库配置的入库/代发', async () => { + const tx = createTransaction({ storageType: '' }) + mockPrisma.$transaction.mockImplementation(async (callback) => callback(tx)) + const repository = new SupplyChainProductArchiveEnrichmentSyncRepositoryClass() + + const result = await repository.applyPatch({ + archiveId: 'archive-1', + patch: { warehouseHead: '新负责人', storageType: 'DROPSHIP' }, + source: WAREHOUSE_CONFIG_SOURCE, + }) + + expect(result.changes.map((change) => change.field)).toEqual(['warehouseHead', 'storageType']) + expect(tx.supplyChainProductArchive.update).toHaveBeenCalledWith( + expect.objectContaining({ + where: { id: 'archive-1' }, + data: expect.objectContaining({ warehouseHead: '新负责人', storageType: 'DROPSHIP' }), + }), + ) + }) + + it('该来源已经初始化过的条码不再重复应用(fillEmptyOnly 的早返回)', async () => { + const tx = createTransaction({ storageType: '' , existingSource: { id: 'source-1' } }) + mockPrisma.$transaction.mockImplementation(async (callback) => callback(tx)) + const repository = new SupplyChainProductArchiveEnrichmentSyncRepositoryClass() + + await expect(repository.applyPatch({ + archiveId: 'archive-1', + patch: { warehouseHead: '再改', storageType: 'DROPSHIP' }, + source: WAREHOUSE_CONFIG_SOURCE, + })).resolves.toEqual({ changes: [], sourceInitialized: false }) + + expect(tx.supplyChainProductArchive.update).not.toHaveBeenCalled() + }) +}) diff --git a/furniture-3d-system/src/server/repositories/bom-costing-agent.repository.ts b/furniture-3d-system/src/server/repositories/bom-costing-agent.repository.ts index 9cdd9c46..b879e254 100644 --- a/furniture-3d-system/src/server/repositories/bom-costing-agent.repository.ts +++ b/furniture-3d-system/src/server/repositories/bom-costing-agent.repository.ts @@ -59,6 +59,62 @@ export class BomCostingAgentRepository { return sku?.id ?? null } + async listSkusForCase(caseId: string) { + return prisma.bomCostingSku.findMany({ + where: { caseId }, + orderBy: { sortOrder: 'asc' }, + select: { + id: true, + externalSkuId: true, + name: true, + lengthMm: true, + widthMm: true, + heightMm: true, + sortOrder: true, + }, + }) + } + + async findCachedSkuEstimate(skuId: string, engineVersion: string) { + return prisma.bomCostingAgentSkuEstimate.findUnique({ + where: { skuId_engineVersion: { skuId, engineVersion } }, + }) + } + + async listCachedSkuEstimates(caseId: string, engineVersion: string) { + return prisma.bomCostingAgentSkuEstimate.findMany({ + where: { caseId, engineVersion }, + }) + } + + async upsertCachedSkuEstimate(input: { + caseId: string + skuId: string + externalSkuId: string + engineVersion: string + status: string + estimate: unknown + usage: unknown + }) { + return prisma.bomCostingAgentSkuEstimate.upsert({ + where: { skuId_engineVersion: { skuId: input.skuId, engineVersion: input.engineVersion } }, + create: { + caseId: input.caseId, + skuId: input.skuId, + externalSkuId: input.externalSkuId, + engineVersion: input.engineVersion, + status: input.status, + estimate: input.estimate as Prisma.InputJsonValue, + usage: input.usage as Prisma.InputJsonValue, + }, + update: { + status: input.status, + estimate: input.estimate as Prisma.InputJsonValue, + usage: input.usage as Prisma.InputJsonValue, + }, + }) + } + async listArchivedAssetsForCase(caseId: string) { const sourceCase = await prisma.bomCostingCase.findUnique({ where: { id: caseId }, diff --git a/furniture-3d-system/src/server/repositories/dropship-1688-data.repository.ts b/furniture-3d-system/src/server/repositories/dropship-1688-data.repository.ts index 48329a39..edaa8f28 100644 --- a/furniture-3d-system/src/server/repositories/dropship-1688-data.repository.ts +++ b/furniture-3d-system/src/server/repositories/dropship-1688-data.repository.ts @@ -23,6 +23,7 @@ const ARCHIVE_RANK_SELECT = { } satisfies Prisma.SupplyChainProductArchiveSelect const ZERO_DECIMAL = new Prisma.Decimal(0) +const PURCHASER_QUERY_CHUNK_SIZE = 5_000 // Preserve the database's Decimal(24, 4) amounts when summing filtered groups. const SummaryDecimal = Prisma.Decimal.clone({ precision: 40 }) @@ -41,18 +42,36 @@ type FilterInput = { filters?: Dropship1688Filters } +type FilterContext = { + operators: Map + purchaserBarcodes: Set +} + +function normalizedBarcode(value: string) { + return value.trim().toUpperCase() +} + +function uniqueTextOptions(values: readonly string[]) { + return [...new Set(values.map((value) => value.trim()).filter(Boolean))] + .sort((left, right) => left.localeCompare(right, 'zh-CN')) +} + function filterCandidates( candidates: ArchiveCandidate[], filters: Dropship1688Filters, - operators: Map, + context: FilterContext, ) { const predicates = FILTER_FIELDS.flatMap((field) => { const filter = filters[field] if (!filter) return [] const values = new Set(filter.values) return [(candidate: ArchiveCandidate) => { + if (field === 'purchaser') { + const matched = context.purchaserBarcodes.has(normalizedBarcode(candidate.barcode)) + return matched === (filter.mode === 'include') + } const value = field === 'skuOperator' - ? operators.get(candidate.barcode) ?? '' + ? context.operators.get(candidate.barcode) ?? '' : candidate[field] return values.has(value) === (filter.mode === 'include') }] @@ -110,18 +129,66 @@ class Dropship1688DataRepository { return new Map([...latest].map(([barcode, record]) => [barcode, record.value])) } - async listFilterOptions(input: FilterInput & { field: Dropship1688FilterField }) { + private async purchaserBarcodesForNames(names: readonly string[]) { + const barcodes = new Set() + for (let offset = 0; offset < names.length; offset += PURCHASER_QUERY_CHUNK_SIZE) { + const chunk = names.slice(offset, offset + PURCHASER_QUERY_CHUNK_SIZE) + const tasks = await prisma.dropship1688SourcingTask.findMany({ + where: { purchaserName: { in: [...chunk] } }, + distinct: ['sourceBarcode'], + select: { sourceBarcode: true }, + }) + tasks.forEach((task) => { + const barcode = normalizedBarcode(task.sourceBarcode) + if (barcode) barcodes.add(barcode) + }) + } + return barcodes + } + + private async purchaserNamesForBarcodes(barcodes: readonly string[]) { + const names: string[] = [] + for (let offset = 0; offset < barcodes.length; offset += PURCHASER_QUERY_CHUNK_SIZE) { + const chunk = barcodes.slice(offset, offset + PURCHASER_QUERY_CHUNK_SIZE) + const tasks = await prisma.dropship1688SourcingTask.findMany({ + where: { sourceBarcode: { in: [...chunk] } }, + distinct: ['purchaserName'], + select: { purchaserName: true }, + }) + names.push(...tasks.map((task) => task.purchaserName)) + } + return names + } + + async listFilterOptions(input: FilterInput & { + field: Dropship1688FilterField + optionQuery?: string + }) { const filters = { ...input.filters } delete filters[input.field] - const [candidates, operators] = await Promise.all([ + const [candidates, operators, purchaserBarcodes] = await Promise.all([ this.candidates(input), input.field === 'skuOperator' || filters.skuOperator ? this.latestOperators(input) : Promise.resolve(new Map()), + filters.purchaser + ? this.purchaserBarcodesForNames(filters.purchaser.values) + : Promise.resolve(new Set()), ]) - const values = filterCandidates(candidates, filters, operators).map((candidate) => - input.field === 'skuOperator' ? operators.get(candidate.barcode) ?? '' : candidate[input.field], - ) + const remainingCandidates = filterCandidates(candidates, filters, { operators, purchaserBarcodes }) + const optionQuery = input.optionQuery?.trim().toLocaleLowerCase('zh-CN') ?? '' + const matchesOptionQuery = (value: string) => !optionQuery + || (value || '(空值)').toLocaleLowerCase('zh-CN').includes(optionQuery) + if (input.field === 'purchaser') { + const names = await this.purchaserNamesForBarcodes( + remainingCandidates.map((candidate) => normalizedBarcode(candidate.barcode)), + ) + return { values: uniqueTextOptions(names.filter(matchesOptionQuery)) } + } + const values = remainingCandidates + .map((candidate) => input.field === 'skuOperator' + ? operators.get(candidate.barcode) ?? '' : candidate[input.field]) + .filter(matchesOptionQuery) return { values: [...new Set(values)].sort((left, right) => left.localeCompare(right, 'zh-CN')) } } @@ -142,7 +209,7 @@ class Dropship1688DataRepository { barcode: { startsWith: 'DF-' }, } satisfies Prisma.SupplyChainProductArchiveSalesPerformanceDailyWhereInput - const [candidates, dailyPerformance, operators] = await Promise.all([ + const [candidates, dailyPerformance, operators, purchaserBarcodes] = await Promise.all([ this.candidates(input), prisma.supplyChainProductArchiveSalesPerformanceDaily.groupBy({ by: ['barcode'], @@ -160,6 +227,9 @@ class Dropship1688DataRepository { input.filters?.skuOperator ? this.latestOperators(input) : Promise.resolve(new Map()), + input.filters?.purchaser + ? this.purchaserBarcodesForNames(input.filters.purchaser.values) + : Promise.resolve(new Set()), ]) const allPerformance = dailyPerformance.map((record) => ({ @@ -177,8 +247,16 @@ class Dropship1688DataRepository { const performanceByBarcode = new Map( allPerformance.map((record) => [record.barcode, record] as const), ) - const rankCandidates = filterCandidates(candidates, input.filters ?? {}, operators) + const rankCandidates = filterCandidates( + candidates, + input.filters ?? {}, + { operators, purchaserBarcodes }, + ) const summary = { + productsWithSalesAmount: rankCandidates.reduce((count, candidate) => { + const displayedSalesAmount = performanceByBarcode.get(candidate.barcode)?._sum.shipAmount + return count + Number(displayedSalesAmount?.greaterThan(0) ?? false) + }, 0), _sum: rankCandidates.reduce((sum, candidate) => { const values = performanceByBarcode.get(candidate.barcode)?._sum return { @@ -186,11 +264,15 @@ class Dropship1688DataRepository { shipAmount: sum.shipAmount === null || (values && values.shipAmount === null) ? null : sum.shipAmount.plus(values?.shipAmount ?? ZERO_DECIMAL), realPerformance: sum.realPerformance.plus(values?.realPerformance ?? ZERO_DECIMAL), + grossProfit: sum.grossProfit.plus(values?.grossProfit ?? ZERO_DECIMAL), + afterSaleAmount: sum.afterSaleAmount.plus(values?.afterSaleAmount ?? ZERO_DECIMAL), } }, { shipQty: BigInt(0), shipAmount: new SummaryDecimal(0) as Prisma.Decimal | null, realPerformance: new SummaryDecimal(0), + grossProfit: new SummaryDecimal(0), + afterSaleAmount: new SummaryDecimal(0), }), } rankCandidates.sort((left, right) => { @@ -235,6 +317,7 @@ class Dropship1688DataRepository { realPerformance: true, skuOperator: true, unitCost: true, + estimatedFreight: true, }, orderBy: [{ barcode: 'asc' }, { statDate: 'asc' }], }), diff --git a/furniture-3d-system/src/server/repositories/dropship-1688-sourcing.repository.ts b/furniture-3d-system/src/server/repositories/dropship-1688-sourcing.repository.ts new file mode 100644 index 00000000..70178f25 --- /dev/null +++ b/furniture-3d-system/src/server/repositories/dropship-1688-sourcing.repository.ts @@ -0,0 +1,414 @@ +import { Prisma } from '@prisma/client' +import { prisma } from '@/lib/prisma' +import { + DROPSHIP_1688_MAX_PURCHASERS, + type Dropship1688SourcingFilters, +} from '@/lib/dropship-1688-sourcing' +import { AppError, ErrorCode } from '@/server/core/errors' + +const TASK_SELECT = { + id: true, + sourceArchiveId: true, + sourceSpu: true, + sourceBarcode: true, + sourceCostPrice: true, + sourceSkuOperator: true, + sourceDateFrom: true, + sourceDateTo: true, + purchaserUserId: true, + purchaserName: true, + supplierName: true, + quotedPriceTaxIncluded: true, + invoiceTaxPoint: true, + sourcingMode: true, + jianshangBarcode: true, + acceptedAt: true, + updatedAt: true, +} satisfies Prisma.Dropship1688SourcingTaskSelect + +const PURCHASER_SELECT = { + sourceBarcode: true, + purchaserUserId: true, + purchaserName: true, + acceptedAt: true, +} satisfies Prisma.Dropship1688SourcingTaskSelect + +export type Dropship1688SourcingTaskRecord = Prisma.Dropship1688SourcingTaskGetPayload<{ + select: typeof TASK_SELECT +}> + +export type Dropship1688SourcingPurchaserRecord = Prisma.Dropship1688SourcingTaskGetPayload<{ + select: typeof PURCHASER_SELECT +}> + +export type Dropship1688ClaimSource = { + archiveId: string + spu: string + barcode: string + costPrice: Prisma.Decimal | null + skuOperator: string +} + +export type Dropship1688SourcingTaskWithProduct = Dropship1688SourcingTaskRecord & { + sku: string + hasImage: boolean +} + +export type Dropship1688ClaimResult = + | { status: 'claimed' | 'already-accepted'; task: Dropship1688SourcingTaskRecord } + | { status: 'full' } + +export type Dropship1688SourcingFilterOptions = { + purchaserNames: string[] + sourceSpus: string[] + sourceSkuOperators: string[] +} + +function taskWhere(filters: Dropship1688SourcingFilters): Prisma.Dropship1688SourcingTaskWhereInput { + return { + ...(filters.purchaserNames.length > 0 + ? { purchaserName: { in: filters.purchaserNames } } + : {}), + ...(filters.sourceSpus.length > 0 + ? { sourceSpu: { in: filters.sourceSpus } } + : {}), + ...(filters.sourceSkuOperators.length > 0 + ? { sourceSkuOperator: { in: filters.sourceSkuOperators } } + : {}), + } +} + +function uniqueOptions(values: readonly string[]) { + return [...new Set(values.map((value) => value.trim()).filter(Boolean))] + .sort((left, right) => left.localeCompare(right, 'zh-CN')) +} + +class Dropship1688SourcingRepository { + private async enrichTasks( + tasks: Dropship1688SourcingTaskRecord[], + ): Promise { + const barcodes = [...new Set(tasks.map((task) => task.sourceBarcode))] + const archives = barcodes.length === 0 + ? [] + : await prisma.supplyChainProductArchive.findMany({ + where: { barcode: { in: barcodes } }, + select: { barcode: true, sku: true, image: true }, + }) + const archiveByBarcode = new Map(archives.map((archive) => [archive.barcode, archive] as const)) + + return tasks.map((task) => { + const archive = archiveByBarcode.get(task.sourceBarcode) + return { + ...task, + sku: archive?.sku.trim() ?? '', + hasImage: Boolean(archive?.image?.trim()), + } + }) + } + + async findTaskById(id: string): Promise { + return prisma.dropship1688SourcingTask.findUnique({ + where: { id }, + select: TASK_SELECT, + }) + } + + async updateTask(input: { + id: string + supplierName: string + quotedPriceTaxIncluded: Prisma.Decimal | null + invoiceTaxPoint: Prisma.Decimal | null + sourcingMode: string + jianshangBarcode: string + }): Promise { + return prisma.dropship1688SourcingTask.update({ + where: { id: input.id }, + data: { + supplierName: input.supplierName, + quotedPriceTaxIncluded: input.quotedPriceTaxIncluded, + invoiceTaxPoint: input.invoiceTaxPoint, + sourcingMode: input.sourcingMode, + jianshangBarcode: input.jianshangBarcode, + }, + select: TASK_SELECT, + }) + } + + async deleteTaskIfRevocable(input: { + id: string + purchaserUserId: string + }): Promise { + const deleted = await prisma.dropship1688SourcingTask.deleteMany({ + where: { + id: input.id, + purchaserUserId: input.purchaserUserId, + jianshangBarcode: '', + }, + }) + return deleted.count === 1 + } + + async listTasksByBarcodes( + barcodes: readonly string[], + ): Promise { + if (barcodes.length === 0) return [] + return prisma.dropship1688SourcingTask.findMany({ + where: { sourceBarcode: { in: [...barcodes] } }, + select: TASK_SELECT, + orderBy: [{ sourceBarcode: 'asc' }, { purchaserName: 'asc' }, { id: 'asc' }], + }) + } + + async updateTasks(input: Array<{ + id: string + supplierName: string + quotedPriceTaxIncluded: Prisma.Decimal | null + invoiceTaxPoint: Prisma.Decimal | null + sourcingMode: string + jianshangBarcode: string + }>): Promise { + if (input.length === 0) return + const payload = input.map((task) => ({ + id: task.id, + supplier_name: task.supplierName, + quoted_price_tax_included: task.quotedPriceTaxIncluded?.toString() ?? null, + invoice_tax_point: task.invoiceTaxPoint?.toString() ?? null, + sourcing_mode: task.sourcingMode, + jianshang_barcode: task.jianshangBarcode, + })) + + await prisma.$transaction(async (transaction) => { + const [result] = await transaction.$queryRaw>` + WITH payload AS ( + SELECT * + FROM jsonb_to_recordset(${JSON.stringify(payload)}::jsonb) AS input( + id text, + supplier_name text, + quoted_price_tax_included text, + invoice_tax_point text, + sourcing_mode text, + jianshang_barcode text + ) + ), + payload_stats AS ( + SELECT COUNT(*)::int AS total, COUNT(DISTINCT id)::int AS distinct_ids + FROM payload + ), + matched_stats AS ( + SELECT COUNT(*)::int AS total + FROM payload + INNER JOIN "Dropship1688SourcingTask" AS task ON task.id = payload.id + ), + updated AS ( + UPDATE "Dropship1688SourcingTask" AS task + SET + "supplierName" = payload.supplier_name, + "quoted_price_tax_included" = payload.quoted_price_tax_included::numeric(24, 4), + "invoiceTaxPoint" = payload.invoice_tax_point::numeric(8, 4), + "sourcingMode" = payload.sourcing_mode, + "jianshangBarcode" = payload.jianshang_barcode, + "updatedAt" = CURRENT_TIMESTAMP + FROM payload + WHERE task.id = payload.id + AND ( + SELECT payload_stats.total = payload_stats.distinct_ids + AND payload_stats.total = matched_stats.total + FROM payload_stats, matched_stats + ) + RETURNING task.id + ) + SELECT + payload_stats.total AS expected_count, + matched_stats.total AS matched_count, + (SELECT COUNT(*)::int FROM updated) AS updated_count + FROM payload_stats, matched_stats + ` + if (!result + || result.expected_count !== input.length + || result.matched_count !== input.length + || result.updated_count !== input.length) { + throw new AppError( + ErrorCode.VALIDATION_FAILED, + '寻源任务状态已变化,导入未执行任何更新', + ) + } + }, { maxWait: 10_000, timeout: 120_000 }) + } + + async findClaimSource(input: { + barcode: string + dateFrom: Date + dateTo: Date + }): Promise { + const archive = await prisma.supplyChainProductArchive.findUnique({ + where: { barcode: input.barcode }, + select: { id: true, barcode: true, spu: true }, + }) + if (!archive) return null + + const dailyRecords = await prisma.supplyChainProductArchiveSalesPerformanceDaily.findMany({ + where: { + barcode: archive.barcode, + statDate: { gte: input.dateFrom, lte: input.dateTo }, + }, + select: { skuOperator: true, unitCost: true }, + orderBy: { statDate: 'desc' }, + }) + + let costPrice: Prisma.Decimal | null = null + let skuOperator = '' + for (const record of dailyRecords) { + if (costPrice === null && record.unitCost !== null) { + costPrice = record.unitCost + } + const operator = record.skuOperator.trim() + if (!skuOperator && operator) { + skuOperator = operator + } + if (costPrice !== null && skuOperator) break + } + + return { + archiveId: archive.id, + spu: archive.spu.trim(), + barcode: archive.barcode, + costPrice, + skuOperator, + } + } + + async claim(input: { + source: Dropship1688ClaimSource + dateFrom: Date + dateTo: Date + purchaser: { id: string; name: string } + }): Promise { + return prisma.$transaction(async (transaction) => { + // Serialize claims per barcode so two simultaneous clicks cannot create a fourth purchaser. + await transaction.$queryRaw` + SELECT pg_advisory_xact_lock(hashtextextended(${input.source.barcode}, 0))::text AS lock_result + ` + + const existing = await transaction.dropship1688SourcingTask.findUnique({ + where: { + sourceBarcode_purchaserUserId: { + sourceBarcode: input.source.barcode, + purchaserUserId: input.purchaser.id, + }, + }, + select: TASK_SELECT, + }) + if (existing) return { status: 'already-accepted', task: existing } + + const purchaserCount = await transaction.dropship1688SourcingTask.count({ + where: { sourceBarcode: input.source.barcode }, + }) + if (purchaserCount >= DROPSHIP_1688_MAX_PURCHASERS) { + return { status: 'full' } + } + + const task = await transaction.dropship1688SourcingTask.create({ + data: { + sourceArchiveId: input.source.archiveId, + sourceSpu: input.source.spu, + sourceBarcode: input.source.barcode, + sourceCostPrice: input.source.costPrice, + sourceSkuOperator: input.source.skuOperator, + sourceDateFrom: input.dateFrom, + sourceDateTo: input.dateTo, + purchaserUserId: input.purchaser.id, + purchaserName: input.purchaser.name, + }, + select: TASK_SELECT, + }) + return { status: 'claimed', task } + }) + } + + async listTasks(): Promise { + const tasks = await prisma.dropship1688SourcingTask.findMany({ + select: TASK_SELECT, + orderBy: [{ acceptedAt: 'desc' }, { id: 'asc' }], + }) + return this.enrichTasks(tasks) + } + + async countTasks(filters: Dropship1688SourcingFilters): Promise { + return prisma.dropship1688SourcingTask.count({ where: taskWhere(filters) }) + } + + async listTasksPage(input: { + filters: Dropship1688SourcingFilters + skip: number + take: number + }): Promise { + const tasks = await prisma.dropship1688SourcingTask.findMany({ + where: taskWhere(input.filters), + select: TASK_SELECT, + orderBy: [{ acceptedAt: 'desc' }, { id: 'asc' }], + skip: input.skip, + take: input.take, + }) + return this.enrichTasks(tasks) + } + + async listFilterOptions( + filters: Dropship1688SourcingFilters, + ): Promise { + const [purchasers, spus, operators] = await Promise.all([ + prisma.dropship1688SourcingTask.findMany({ + where: taskWhere({ ...filters, purchaserNames: [] }), + distinct: ['purchaserName'], + select: { purchaserName: true }, + orderBy: { purchaserName: 'asc' }, + }), + prisma.dropship1688SourcingTask.findMany({ + where: taskWhere({ ...filters, sourceSpus: [] }), + distinct: ['sourceSpu'], + select: { sourceSpu: true }, + orderBy: { sourceSpu: 'asc' }, + }), + prisma.dropship1688SourcingTask.findMany({ + where: taskWhere({ ...filters, sourceSkuOperators: [] }), + distinct: ['sourceSkuOperator'], + select: { sourceSkuOperator: true }, + orderBy: { sourceSkuOperator: 'asc' }, + }), + ]) + return { + purchaserNames: uniqueOptions(purchasers.map((row) => row.purchaserName)), + sourceSpus: uniqueOptions(spus.map((row) => row.sourceSpu)), + sourceSkuOperators: uniqueOptions(operators.map((row) => row.sourceSkuOperator)), + } + } + + async listTasksForExport(input: { + filters: Dropship1688SourcingFilters + take: number + }): Promise { + return prisma.dropship1688SourcingTask.findMany({ + where: taskWhere(input.filters), + select: TASK_SELECT, + orderBy: [{ acceptedAt: 'desc' }, { id: 'asc' }], + take: input.take, + }) + } + + async listPurchasersByBarcodes( + barcodes: readonly string[], + ): Promise { + if (barcodes.length === 0) return [] + return prisma.dropship1688SourcingTask.findMany({ + where: { sourceBarcode: { in: [...barcodes] } }, + select: PURCHASER_SELECT, + orderBy: [{ sourceBarcode: 'asc' }, { acceptedAt: 'asc' }, { id: 'asc' }], + }) + } +} + +export const dropship1688SourcingRepository = new Dropship1688SourcingRepository() +export { Dropship1688SourcingRepository } diff --git a/furniture-3d-system/src/server/repositories/intake-non-integrated-product.repository.ts b/furniture-3d-system/src/server/repositories/intake-non-integrated-product.repository.ts index 78aa50a6..71cfb7c9 100644 --- a/furniture-3d-system/src/server/repositories/intake-non-integrated-product.repository.ts +++ b/furniture-3d-system/src/server/repositories/intake-non-integrated-product.repository.ts @@ -376,7 +376,10 @@ class IntakeNonIntegratedProductRepositoryClass extends BaseRepository< } if ('$transaction' in client) { - return client.$transaction((tx) => createRecord(tx)) + return client.$transaction((tx) => createRecord(tx), { + maxWait: 10_000, + timeout: 60_000, + }) } return createRecord(client) @@ -538,7 +541,7 @@ class IntakeNonIntegratedProductRepositoryClass extends BaseRepository< result: mutation.result, updatedAt: updatedRecord.updatedAt, } - }) + }, { maxWait: 10_000, timeout: 60_000 }) } async findByIdWithPayloadMutationLockInTransaction( @@ -956,7 +959,10 @@ class IntakeNonIntegratedProductRepositoryClass extends BaseRepository< } if ('$transaction' in client) { - return client.$transaction((tx) => updateRecord(tx)) + return client.$transaction((tx) => updateRecord(tx), { + maxWait: 10_000, + timeout: 60_000, + }) } return updateRecord(client) diff --git a/furniture-3d-system/src/server/repositories/jushuitan-fixed-virtual-inventory-task.repository.test.ts b/furniture-3d-system/src/server/repositories/jushuitan-fixed-virtual-inventory-task.repository.test.ts new file mode 100644 index 00000000..b2a24fe1 --- /dev/null +++ b/furniture-3d-system/src/server/repositories/jushuitan-fixed-virtual-inventory-task.repository.test.ts @@ -0,0 +1,85 @@ +/** @jest-environment node */ + +jest.mock("@/lib/prisma", () => ({ + prisma: { + intakeJushuitanFixedVirtualInventoryTask: { + updateMany: jest.fn(), + }, + }, +})); + +import { prisma } from "@/lib/prisma"; +import { JushuitanFixedVirtualInventoryTaskRepository } from "./jushuitan-fixed-virtual-inventory-task.repository"; + +const updateMany = prisma.intakeJushuitanFixedVirtualInventoryTask + .updateMany as jest.Mock; + +describe("JushuitanFixedVirtualInventoryTaskRepository", () => { + beforeEach(() => { + jest.clearAllMocks(); + updateMany.mockResolvedValue({ count: 2 }); + }); + + it("marks a successful external batch in one update", async () => { + const attemptedAt = new Date("2026-09-17T10:00:00.000Z"); + const repository = new JushuitanFixedVirtualInventoryTaskRepository(); + + await repository.markManySucceeded({ + ids: ["task-1", "task-2"], + attemptedAt, + requestId: "jst-request-1", + }); + + expect(updateMany).toHaveBeenCalledWith({ + where: { id: { in: ["task-1", "task-2"] } }, + data: { + status: "pushed", + pushedAt: attemptedAt, + lastAttemptAt: attemptedAt, + error: "", + requestId: "jst-request-1", + }, + }); + }); + + it("schedules every task in a failed batch in one update", async () => { + const attemptedAt = new Date("2026-09-17T10:00:00.000Z"); + const scheduledAt = new Date("2026-09-17T12:00:00.000Z"); + const repository = new JushuitanFixedVirtualInventoryTaskRepository(); + + await repository.scheduleManyRetry({ + ids: ["task-1", "task-2"], + attemptedAt, + scheduledAt, + error: "rate limited", + requestId: "local-request-1", + }); + + expect(updateMany).toHaveBeenCalledWith({ + where: { id: { in: ["task-1", "task-2"] } }, + data: { + status: "pending", + scheduledAt, + retryCount: { increment: 1 }, + lastAttemptAt: attemptedAt, + error: "rate limited", + requestId: "local-request-1", + }, + }); + }); + + it("does not issue an update for an empty batch", async () => { + const repository = new JushuitanFixedVirtualInventoryTaskRepository(); + const attemptedAt = new Date("2026-09-17T10:00:00.000Z"); + + await expect( + repository.markManySucceeded({ + ids: [], + attemptedAt, + requestId: "jst-request-1", + }), + ).resolves.toEqual({ count: 0 }); + + expect(updateMany).not.toHaveBeenCalled(); + }); +}); diff --git a/furniture-3d-system/src/server/repositories/jushuitan-fixed-virtual-inventory-task.repository.ts b/furniture-3d-system/src/server/repositories/jushuitan-fixed-virtual-inventory-task.repository.ts index f1a71ca0..2b173542 100644 --- a/furniture-3d-system/src/server/repositories/jushuitan-fixed-virtual-inventory-task.repository.ts +++ b/furniture-3d-system/src/server/repositories/jushuitan-fixed-virtual-inventory-task.repository.ts @@ -11,7 +11,7 @@ export type CreateFixedVirtualInventoryTaskInput = { }; export type FixedVirtualInventoryRetryInput = { - id: string; + ids: string[]; attemptedAt: Date; scheduledAt: Date; error: string; @@ -19,12 +19,12 @@ export type FixedVirtualInventoryRetryInput = { }; export type FixedVirtualInventorySuccessInput = { - id: string; + ids: string[]; attemptedAt: Date; requestId: string; }; -class JushuitanFixedVirtualInventoryTaskRepository { +export class JushuitanFixedVirtualInventoryTaskRepository { async createMissing(tasks: CreateFixedVirtualInventoryTaskInput[]) { if (tasks.length === 0) return 0; @@ -70,9 +70,11 @@ class JushuitanFixedVirtualInventoryTaskRepository { }); } - async markSucceeded(input: FixedVirtualInventorySuccessInput) { - return prisma.intakeJushuitanFixedVirtualInventoryTask.update({ - where: { id: input.id }, + async markManySucceeded(input: FixedVirtualInventorySuccessInput) { + if (input.ids.length === 0) return { count: 0 }; + + return prisma.intakeJushuitanFixedVirtualInventoryTask.updateMany({ + where: { id: { in: input.ids } }, data: { status: "pushed", pushedAt: input.attemptedAt, @@ -83,9 +85,11 @@ class JushuitanFixedVirtualInventoryTaskRepository { }); } - async scheduleRetry(input: FixedVirtualInventoryRetryInput) { - return prisma.intakeJushuitanFixedVirtualInventoryTask.update({ - where: { id: input.id }, + async scheduleManyRetry(input: FixedVirtualInventoryRetryInput) { + if (input.ids.length === 0) return { count: 0 }; + + return prisma.intakeJushuitanFixedVirtualInventoryTask.updateMany({ + where: { id: { in: input.ids } }, data: { status: "pending", scheduledAt: input.scheduledAt, @@ -105,8 +109,8 @@ export type JushuitanFixedVirtualInventoryTaskRepositoryContract = Pick< | "createMissing" | "findDue" | "findByProductId" - | "markSucceeded" - | "scheduleRetry" + | "markManySucceeded" + | "scheduleManyRetry" >; export const jushuitanFixedVirtualInventoryTaskRepository = diff --git a/furniture-3d-system/src/server/repositories/notification-delivery.repository.ts b/furniture-3d-system/src/server/repositories/notification-delivery.repository.ts index 207ea58f..c6bc0e3e 100644 --- a/furniture-3d-system/src/server/repositories/notification-delivery.repository.ts +++ b/furniture-3d-system/src/server/repositories/notification-delivery.repository.ts @@ -70,6 +70,22 @@ class NotificationDeliveryRepository { }) } + async findRecipientsByNames(names: string[]): Promise { + const normalized = [...new Set(names.map((name) => name.trim()).filter(Boolean))] + if (normalized.length === 0) return [] + return prisma.user.findMany({ + where: { name: { in: normalized } }, + select: { + id: true, + name: true, + email: true, + status: true, + businessRoles: true, + dingtalkUserId: true, + }, + }) + } + findByIdempotencyKey(idempotencyKey: string) { return prisma.notificationDeliveryLog.findUnique({ where: { idempotencyKey } }) } diff --git a/furniture-3d-system/src/server/repositories/product-archive-sales-performance-source.repository.ts b/furniture-3d-system/src/server/repositories/product-archive-sales-performance-source.repository.ts index 784d6687..27908c30 100644 --- a/furniture-3d-system/src/server/repositories/product-archive-sales-performance-source.repository.ts +++ b/furniture-3d-system/src/server/repositories/product-archive-sales-performance-source.repository.ts @@ -28,6 +28,7 @@ export type ProductArchiveSalesPerformanceDailyAggregate = // Operator and unit-cost enrichment is sourced for DF barcodes only. skuOperator: string unitCost: string | null + estimatedFreight: string | null } export interface ProductArchiveSalesPerformanceSourceRepository { @@ -210,7 +211,7 @@ class ProductArchiveSalesPerformanceSourceRepositoryClass FROM ${this.sourceObject()} WHERE stat_date >= @periodStart AND stat_date <= @periodEnd AND UPPER(LTRIM(RTRIM(CAST(skuoid AS nvarchar(100))))) LIKE N'DF-%' - AND goods_count > 0 + AND goods_count = 1 AND goods_cost > 0 ), cost_counts AS ( SELECT barcode, statDate, unitCost, @@ -241,15 +242,29 @@ class ProductArchiveSalesPerformanceSourceRepositoryClass WITHIN GROUP (ORDER BY skuOperator) AS skuOperator FROM operator_values GROUP BY barcode, statDate + ), freight_averages AS ( + SELECT + UPPER(LTRIM(RTRIM(CAST(skuoid AS nvarchar(100))))) AS barcode, + CONVERT(char(10), stat_date, 23) AS statDate, + CONVERT(varchar(64), CAST(AVG(CAST(COALESCE(send_freight, 0) AS decimal(38,4))) AS decimal(24,4))) AS estimatedFreight + FROM ${this.sourceObject()} + WHERE stat_date >= @periodStart AND stat_date <= @periodEnd + AND UPPER(LTRIM(RTRIM(CAST(skuoid AS nvarchar(100))))) LIKE N'DF-%' + AND goods_count = 1 + AND goods_cost > 0 + GROUP BY UPPER(LTRIM(RTRIM(CAST(skuoid AS nvarchar(100))))), stat_date ) SELECT performance.*, COALESCE(operators.skuOperator, N'') AS skuOperator, - CONVERT(varchar(64), ranked_costs.unitCost) AS unitCost + CONVERT(varchar(64), ranked_costs.unitCost) AS unitCost, + freight_averages.estimatedFreight FROM performance LEFT JOIN operators ON operators.barcode = performance.barcode AND operators.statDate = performance.statDate LEFT JOIN ranked_costs ON ranked_costs.barcode = performance.barcode AND ranked_costs.statDate = performance.statDate AND ranked_costs.costRank = 1 + LEFT JOIN freight_averages ON freight_averages.barcode = performance.barcode + AND freight_averages.statDate = performance.statDate ORDER BY performance.statDate, performance.barcode `) return result.recordset.map((row) => ({ diff --git a/furniture-3d-system/src/server/repositories/supply-chain-product-archive-filters.ts b/furniture-3d-system/src/server/repositories/supply-chain-product-archive-filters.ts index 8b2e8348..c8cb138e 100644 --- a/furniture-3d-system/src/server/repositories/supply-chain-product-archive-filters.ts +++ b/furniture-3d-system/src/server/repositories/supply-chain-product-archive-filters.ts @@ -1,5 +1,13 @@ import { Prisma } from '@prisma/client' -import { PRODUCT_ARCHIVE_EMPTY_FILTER_VALUE, type ProductArchiveFilters, type ProductArchiveFilterOptionKey } from '@/lib/supply-chain-product-archive' +import { prisma } from '@/lib/prisma' +import { + PRODUCT_ARCHIVE_EMPTY_FILTER_VALUE, + PRODUCT_ARCHIVE_NORMAL_CODE_PATTERN, + type ProductArchiveExcludeRule, + type ProductArchiveFilters, + type ProductArchiveFilterOptionKey, + type ProductArchiveTextFilterKey, +} from '@/lib/supply-chain-product-archive' function parseDateBoundary(value: string, endOfDay = false) { return new Date(`${value}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}`) @@ -24,6 +32,25 @@ function buildEmptyValueClause(databaseField: string): Prisma.SupplyChainProduct return { [databaseField]: '' } as Prisma.SupplyChainProductArchiveWhereInput } +/** + * 去掉空值与重复的「排除以…开头」规则,保证同一列同一条只出一遍。 + * 关键词按大写去重:SQL 侧是不区分大小写的 startsWith。 + */ +function normalizeExcludeRules(filters: ProductArchiveFilters): ProductArchiveExcludeRule[] { + const seen = new Set() + const rules: ProductArchiveExcludeRule[] = [] + for (const rule of filters.excludeStartsWith ?? []) { + const field = rule?.field + const startsWith = String(rule?.startsWith ?? '').trim() + if (!field || !startsWith || !(field in TEXT_FILTER_DATABASE_FIELDS)) continue + const dedupeKey = `${field}\u0000${startsWith.toUpperCase()}` + if (seen.has(dedupeKey)) continue + seen.add(dedupeKey) + rules.push({ field, startsWith }) + } + return rules +} + export function buildProductArchiveWhere( filters: ProductArchiveFilters = {}, omitFilter?: ProductArchiveFilterOptionKey, @@ -83,6 +110,19 @@ export function buildProductArchiveWhere( clauses.push({ salesPerformance: { is: condition } } as Prisma.SupplyChainProductArchiveWhereInput) } } + // 「排除以…开头」:纯 Prisma 条件,不需要查库。 + // 只作用在 NOT NULL 的文本列上,NOT 不会误伤 NULL 行。 + // + // 注意:这里**故意不看 omitFilter**。omit 的语义是「取候选值时忽略本列已勾选的值」, + // 而文本规则是「这列接受什么形态」,必须作用到候选值列表上——否则列表里会冒出 + // 已经被排除的取值,用户勾了却得到 0 行。 + for (const rule of normalizeExcludeRules(filters)) { + const databaseField = TEXT_FILTER_DATABASE_FIELDS[rule.field] + if (!databaseField) continue + clauses.push({ + NOT: { [databaseField]: { startsWith: rule.startsWith, mode: 'insensitive' } }, + } as Prisma.SupplyChainProductArchiveWhereInput) + } if (filters.createTimeFrom || filters.createTimeTo) { clauses.push({ businessCreatedAt: { @@ -181,3 +221,69 @@ export const FILTER_OPTION_PERFORMANCE_FIELDS = { feeRatio: 'feeRatio', operatingProfit: 'operatingProfit', } as const + +/** 「只看正常编码」「排除以…开头」允许作用的列 —— 全部是 NOT NULL 文本列。 */ +export const TEXT_FILTER_DATABASE_FIELDS = { + spu: 'spu', + sku: 'sku', + barcode: 'barcode', + productName: 'productName', +} as const satisfies Record + +/** + * 「正常编码」取值清单的缓存。 + * + * Prisma 7 的字符串过滤不支持正则(生成类型里没有 regex),所以只能先用原生 SQL + * 把符合形态的取值查出来,再拼成 `in` 条件。这些取值只在档案同步时才会变, + * 因此按列缓存几分钟,避免每次翻页都做一次全表正则扫描。 + */ +const NORMAL_CODE_CACHE_TTL_MS = 5 * 60 * 1000 +const normalCodeValueCache = new Map() + +async function listNormalCodeValues(databaseField: string): Promise { + const cached = normalCodeValueCache.get(databaseField) + if (cached && cached.expiresAt > Date.now()) return cached.values + + const column = Prisma.raw(`"${databaseField}"`) + const rows = await prisma.$queryRaw>(Prisma.sql` + SELECT DISTINCT ${column} AS value + FROM "SupplyChainProductArchive" + WHERE ${column} ~ ${PRODUCT_ARCHIVE_NORMAL_CODE_PATTERN} + `) + const values = rows.map((row) => row.value).filter((value): value is string => Boolean(value)) + normalCodeValueCache.set(databaseField, { values, expiresAt: Date.now() + NORMAL_CODE_CACHE_TTL_MS }) + return values +} + +/** 供测试与排查清缓存用。 */ +export function clearNormalCodeValueCache() { + normalCodeValueCache.clear() +} + +async function resolveNormalCodeClauses( + filters: ProductArchiveFilters, +): Promise { + const clauses: Prisma.SupplyChainProductArchiveWhereInput[] = [] + for (const key of new Set(filters.normalCodeOnly ?? [])) { + const databaseField = TEXT_FILTER_DATABASE_FIELDS[key] + if (!databaseField) continue + clauses.push({ [databaseField]: { in: await listNormalCodeValues(databaseField) } }) + } + return clauses +} + +/** + * 带「文本规则」的取数条件。 + * + * `buildProductArchiveWhere` 保持同步(只有纯 Prisma 条件,老调用点与老测试不受影响); + * 需要查库的「只看正常编码」在这里补齐,再与基础条件合并。 + * 档案的列表、候选项、导出、图片导出都经由 preparePeriodArchiveQuery 走这一个入口。 + */ +export async function buildProductArchiveWhereWithTextRules( + filters: ProductArchiveFilters = {}, + omitFilter?: ProductArchiveFilterOptionKey, +): Promise { + const base = buildProductArchiveWhere(filters, omitFilter) + const extra = await resolveNormalCodeClauses(filters) + return extra.length > 0 ? { AND: [base, ...extra] } : base +} diff --git a/furniture-3d-system/src/server/repositories/supply-chain-product-archive-sales-performance-daily.repository.ts b/furniture-3d-system/src/server/repositories/supply-chain-product-archive-sales-performance-daily.repository.ts index 1dd6daeb..74ad41b5 100644 --- a/furniture-3d-system/src/server/repositories/supply-chain-product-archive-sales-performance-daily.repository.ts +++ b/furniture-3d-system/src/server/repositories/supply-chain-product-archive-sales-performance-daily.repository.ts @@ -5,7 +5,7 @@ import type { ProductArchiveSalesPerformanceDailyAggregate } from './product-arc const TABLE = '"SupplyChainProductArchiveSalesPerformanceDaily"' const RUNS = '"SupplyChainProductArchiveSalesSyncRun"' -const columns = ['barcode', 'statDate', 'skuOperator', 'unitCost', 'salesAmount', 'shipAmount', 'returnAmount', 'realPerformance', 'shipQty', 'returnQty', +const columns = ['barcode', 'statDate', 'skuOperator', 'unitCost', 'estimatedFreight', 'salesAmount', 'shipAmount', 'returnAmount', 'realPerformance', 'shipQty', 'returnQty', 'clearSalesCost', 'sendFreight', 'platformCommission', 'xyCost', 'afterSaleAmount', 'pushFeeTotal', 'marketingFeeTotal', 'advertisementFeeTotal', 'sharedWarehousingSum', 'otherFee', 'operatingFee', 'sourceRowCount'] as const const quoted = columns.map((name) => '"' + name + '"').join(', ') diff --git a/furniture-3d-system/src/server/repositories/supply-chain-product-archive-sales-period.repository.ts b/furniture-3d-system/src/server/repositories/supply-chain-product-archive-sales-period.repository.ts index 8b015675..ac0f00ff 100644 --- a/furniture-3d-system/src/server/repositories/supply-chain-product-archive-sales-period.repository.ts +++ b/furniture-3d-system/src/server/repositories/supply-chain-product-archive-sales-period.repository.ts @@ -4,7 +4,7 @@ import { PRODUCT_ARCHIVE_EMPTY_FILTER_VALUE, type ProductArchiveFilterOptionKey, import { resolveSalesPeriod, type SalesCoverage } from '@/lib/product-archive-sales-period' import { calculateProductArchiveSalesPerformance } from '@/server/services/product-archive-sales-performance' import type { ProductArchiveSalesPerformanceAggregate } from './product-archive-sales-performance-source.repository' -import { buildProductArchiveWhere } from './supply-chain-product-archive-filters' +import { buildProductArchiveWhereWithTextRules } from './supply-chain-product-archive-filters' import type { ProductArchiveRecord } from './supply-chain-product-archive-select' export const PERFORMANCE_KEYS = [ @@ -90,7 +90,7 @@ export function overlayPerformance(records: ProductArchiveRecord[], dataset: Per return records.map((record) => ({ ...record, salesPerformance: findPerformance(dataset, record.barcode) })) } export async function preparePeriodArchiveQuery(filters: ProductArchiveFilters = {}, omit?: ProductArchiveFilterOptionKey, dataset?: PeriodDataset) { - const where = buildProductArchiveWhere(getArchiveMasterFilters(filters), omit) + const where = await buildProductArchiveWhereWithTextRules(getArchiveMasterFilters(filters), omit) if (!PERFORMANCE_KEYS.some((key) => key !== omit && filters[key]?.length)) return { where, ids: null } const resolved = dataset ?? await listPeriodPerformance(filters) const products = await prisma.supplyChainProductArchive.findMany({ diff --git a/furniture-3d-system/src/server/repositories/supply-chain-product-archive-sync.repository.ts b/furniture-3d-system/src/server/repositories/supply-chain-product-archive-sync.repository.ts index aa4b13fe..009597ef 100644 --- a/furniture-3d-system/src/server/repositories/supply-chain-product-archive-sync.repository.ts +++ b/furniture-3d-system/src/server/repositories/supply-chain-product-archive-sync.repository.ts @@ -51,6 +51,7 @@ export type ProductCatalogWideArchiveRecord = { package_set_count: string | number | Prisma.Decimal | null purchase_order_method: string | null factory_warehouse: string | null + shipping_method: string | null sku_image_url: string | null updated_at: Date | null } @@ -185,6 +186,7 @@ function buildArchiveUpdate( brand: archive.brand, orderType: archive.orderType, inOutWarehouse: archive.inOutWarehouse, + storageType: archive.storageType, isSeasonal: archive.isSeasonal, replaceCount: archive.replaceCount, supplierName: archive.supplierName, @@ -269,6 +271,7 @@ class SupplyChainProductArchiveSyncRepositoryClass package_set_count, purchase_order_method, factory_warehouse, + shipping_method, CASE WHEN NULLIF(btrim(COALESCE(archive_image, '')), '') IS NOT NULL THEN image_url ELSE NULL diff --git a/furniture-3d-system/src/server/services/__tests__/barcode-print.service.test.ts b/furniture-3d-system/src/server/services/__tests__/barcode-print.service.test.ts index ad09a2d1..b541c94c 100644 --- a/furniture-3d-system/src/server/services/__tests__/barcode-print.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/barcode-print.service.test.ts @@ -11,6 +11,7 @@ var mockQueryRaw = jest.fn() var mockListForBarcodePrint = jest.fn() var mockListForBarcodePrintPage = jest.fn() var mockListForBarcodePrintSkuCodes = jest.fn() +var mockOperationLogRecord = jest.fn() jest.mock('@/lib/prisma', () => ({ prisma: { @@ -32,6 +33,17 @@ jest.mock('../intake-non-integrated-product.service', () => ({ }, })) +jest.mock('../operation-log.service', () => ({ + OperationLogAction: { + INTAKE_PRODUCT_DELETE: 'INTAKE_PRODUCT_DELETE', + INTAKE_PRODUCT_WRITE: 'INTAKE_PRODUCT_WRITE', + }, + OperationLogStatus: { SUCCESS: 'SUCCESS' }, + operationLogService: { + record: (...args: unknown[]) => mockOperationLogRecord(...args), + }, +})) + import { barcodePrintService } from '../barcode-print.service' function buildUser(overrides: Partial = {}): AuthUser { @@ -145,6 +157,7 @@ beforeEach(() => { ) mockDeleteMany = jest.fn(() => Promise.resolve({ count: 0 })) mockQueryRaw = jest.fn(() => Promise.resolve([])) + mockOperationLogRecord = jest.fn(() => Promise.resolve()) }) describe('barcodePrintService', () => { @@ -514,7 +527,11 @@ describe('barcodePrintService', () => { const nonImportManagers = [ ['供应商', buildUser({ businessRoles: ['SUPPLIER'], supplierCode: 'N1280' })], ['主管', buildUser({ role: 'SUPERVISOR' })], + ] as const + + const purchasingAndWarehouseUsers = [ ['采购', buildUser({ businessRoles: ['PURCHASING'] })], + ['仓库', buildUser({ businessRoles: ['WAREHOUSE'] })], ] as const it.each(nonImportManagers)('%s不能导入条码数据', async (_label, user) => { @@ -539,6 +556,39 @@ describe('barcodePrintService', () => { expect(mockDeleteMany).not.toHaveBeenCalled() }) + it.each(purchasingAndWarehouseUsers)('%s可以导入条码数据', async (_label, user) => { + await barcodePrintService.saveImportRecords(user, [ + { + kind: 'barcode', + skuCode: 'CS000201A', + updates: { + skuCode: 'CS000201A', + barcode: '690000000009', + supplierName: '临沂美诗家居', + }, + }, + ]) + + expect(mockCreateMany).toHaveBeenCalled() + }) + + it.each(purchasingAndWarehouseUsers)('%s可以删除导入数据', async (_label, user) => { + await barcodePrintService.deleteImportRecords(user, ['record-1']) + + expect(mockDeleteMany).toHaveBeenCalledWith({ + where: { + id: { in: ['record-1'] }, + sourceSkuItemId: null, + }, + }) + }) + + it.each(purchasingAndWarehouseUsers)('%s不能批量修改导入数据', async (_label, user) => { + await expect( + barcodePrintService.updateImportRecords(user, ['record-1'], { barcode: 'NEW' }), + ).rejects.toMatchObject({ code: ErrorCode.AUTH_PERMISSION_DENIED }) + }) + it('设计师可以删除导入数据', async () => { await barcodePrintService.deleteImportRecords( buildUser({ businessRoles: ['DESIGN'] }), @@ -554,4 +604,30 @@ describe('barcodePrintService', () => { }, }) }) + + it('删除成功后写入条码打印操作日志', async () => { + mockDeleteMany.mockResolvedValueOnce({ count: 2 }) + + await barcodePrintService.deleteImportRecords( + buildUser({ + id: 'warehouse-user', + name: '仓库人员', + businessRoles: ['WAREHOUSE'], + }), + ['record-1', 'record-2'], + ) + + expect(mockOperationLogRecord).toHaveBeenCalledWith({ + action: 'INTAKE_PRODUCT_DELETE', + status: 'SUCCESS', + actorId: 'warehouse-user', + actorName: '仓库人员', + workspaceCategory: '条码打印', + message: '删除 2 条手动导入条码数据', + details: { + importRecordIds: ['record-1', 'record-2'], + deleted: 2, + }, + }) + }) }) diff --git a/furniture-3d-system/src/server/services/__tests__/dropship-1688-data.service.test.ts b/furniture-3d-system/src/server/services/__tests__/dropship-1688-data.service.test.ts index 11fdb328..bdae7b7c 100644 --- a/furniture-3d-system/src/server/services/__tests__/dropship-1688-data.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/dropship-1688-data.service.test.ts @@ -24,10 +24,13 @@ function pageResult(total = 1) { }], total, summary: { + productsWithSalesAmount: 1, _sum: { shipQty: 1n, shipAmount: new Prisma.Decimal('29'), realPerformance: new Prisma.Decimal('67.23'), + grossProfit: new Prisma.Decimal('38.23'), + afterSaleAmount: new Prisma.Decimal('6.70'), }, }, performance: [{ @@ -46,6 +49,7 @@ function pageResult(total = 1) { realPerformance: new Prisma.Decimal('67.23'), skuOperator: '九千七', unitCost: new Prisma.Decimal('29'), + estimatedFreight: new Prisma.Decimal('4.50'), }], } } @@ -82,6 +86,10 @@ describe('dropship1688DataService', () => { shipQty: '1', salesAmount: '29.0000', realPerformance: '67.2300', + grossProfit: '38.2300', + afterSaleCostRate: new Prisma.Decimal('6.70').dividedBy('67.23').toFixed(8), + totalProducts: '1', + productsWithSalesAmount: '1', }, }) expect(result.rows[0]).toMatchObject({ @@ -92,6 +100,8 @@ describe('dropship1688DataService', () => { realPerformance: '67.2300', afterSaleCostRate: new Prisma.Decimal('6.70').dividedBy('67.23').toFixed(8), costPrice: '29.0000', + estimatedFreight: '4.5000', + totalCost: '33.5000', grossProfit: '38.2300', grossMargin: new Prisma.Decimal('38.23').dividedBy('67.23').toFixed(8), skuOperator: '九千七', @@ -145,6 +155,44 @@ describe('dropship1688DataService', () => { expect(result.rows[0].realPerformance).toBe('67.2300') }) + it('uses totals for all filtered products for gross profit and after-sales cost rate on every page', async () => { + const source = pageResult(51) + source.summary._sum.realPerformance = new Prisma.Decimal('200') + source.summary._sum.grossProfit = new Prisma.Decimal('70') + source.summary._sum.afterSaleAmount = new Prisma.Decimal('20') + repository.listPage.mockResolvedValue(source as never) + const filters = { skuOperator: { mode: 'include' as const, values: ['九千七'] } } + + for (const page of [1, 2]) { + const result = await dropship1688DataService.listPage({ + dateFrom: '2026-09-01', dateTo: '2026-09-07', keyword: ' DF ', filters, page, + }) + expect(result.page).toBe(page) + expect(result.summary).toMatchObject({ + realPerformance: '200.0000', grossProfit: '70.0000', afterSaleCostRate: '0.10000000', + }) + expect(result.rows[0].grossProfit).toBe('38.2300') + expect(result.rows[0].afterSaleCostRate).not.toBe(result.summary.afterSaleCostRate) + expect(repository.listPage).toHaveBeenLastCalledWith({ + keyword: 'DF', dateFrom: new Date('2026-09-01'), dateTo: new Date('2026-09-07'), + filters, skip: (page - 1) * 50, take: 50, + }) + } + }) + + it('leaves the summary after-sales cost rate unknown when total real performance is zero', async () => { + const source = pageResult() + source.summary._sum.realPerformance = new Prisma.Decimal(0) + source.summary._sum.grossProfit = new Prisma.Decimal('-3.12') + repository.listPage.mockResolvedValue(source as never) + + const result = await dropship1688DataService.listPage({}) + + expect(result.summary).toMatchObject({ + realPerformance: '0.0000', grossProfit: '-3.1200', afterSaleCostRate: '', + }) + }) + it('uses the last non-empty ider value in the selected period', async () => { const resultWithOperatorHistory = pageResult() resultWithOperatorHistory.trends = [ @@ -154,6 +202,7 @@ describe('dropship1688DataService', () => { realPerformance: new Prisma.Decimal('32.00'), skuOperator: '旧运营', unitCost: new Prisma.Decimal('28'), + estimatedFreight: new Prisma.Decimal('4.50'), }, { barcode: 'DF-A1AD000205', @@ -161,6 +210,7 @@ describe('dropship1688DataService', () => { realPerformance: new Prisma.Decimal('67.23'), skuOperator: '新运营', unitCost: new Prisma.Decimal('29'), + estimatedFreight: new Prisma.Decimal('4.50'), }, ] repository.listPage.mockResolvedValue(resultWithOperatorHistory as never) @@ -169,8 +219,49 @@ describe('dropship1688DataService', () => { expect(result.rows[0]?.skuOperator).toBe('新运营') expect(result.rows[0]?.costPrice).toBe('29.0000') + expect(result.rows[0]?.estimatedFreight).toBe('4.5000') + expect(result.rows[0]?.totalCost).toBe('33.5000') }) + it.each([ + { + unitCost: null, + estimatedFreight: new Prisma.Decimal('4.50'), + expectedCost: '0', + expectedFreight: '4.5000', + expectedTotal: '4.5000', + }, + { + unitCost: new Prisma.Decimal('29'), + estimatedFreight: null, + expectedCost: '29.0000', + expectedFreight: '0', + expectedTotal: '29.0000', + }, + { + unitCost: null, + estimatedFreight: null, + expectedCost: '0', + expectedFreight: '0', + expectedTotal: '0.0000', + }, + ])( + 'treats a missing cost component as zero', + async ({ unitCost, estimatedFreight, expectedCost, expectedFreight, expectedTotal }) => { + const source = pageResult() + source.trends = [{ ...source.trends[0], unitCost, estimatedFreight }] + repository.listPage.mockResolvedValue(source as never) + + const result = await dropship1688DataService.listPage({ page: 1 }) + + expect(result.rows[0]).toMatchObject({ + costPrice: expectedCost, + estimatedFreight: expectedFreight, + totalCost: expectedTotal, + }) + }, + ) + it('retains an explicit empty selection and passes filters to both page and option queries', async () => { const filters = { sku: { mode: 'include' as const, values: [] } } repository.listFilterOptions.mockResolvedValue({ values: ['SKU-1'] }) @@ -181,11 +272,23 @@ describe('dropship1688DataService', () => { const options = await dropship1688DataService.listFilterOptions({ field: 'sku', filters }) expect(options.values).toEqual(['SKU-1']) expect(repository.listFilterOptions).toHaveBeenCalledWith({ - field: 'sku', keyword: '', filters, + field: 'sku', keyword: '', optionQuery: '', filters, dateFrom: new Date('2026-09-01'), dateTo: new Date('2026-09-09'), }) }) + it('keeps the product keyword and candidate query separate', async () => { + repository.listFilterOptions.mockResolvedValue({ values: ['采购甲'] }) + + await dropship1688DataService.listFilterOptions({ + field: 'purchaser', keyword: ' 卧室 ', optionQuery: ' 采购甲 ', + }) + + expect(repository.listFilterOptions).toHaveBeenCalledWith(expect.objectContaining({ + field: 'purchaser', keyword: '卧室', optionQuery: '采购甲', + })) + }) + it('retains filters when no daily data is available', async () => { repository.findAvailableDateRange.mockResolvedValue({ _min: { statDate: null }, _max: { statDate: null }, @@ -194,6 +297,10 @@ describe('dropship1688DataService', () => { const result = await dropship1688DataService.listPage({ filters }) expect(result.filters).toEqual(filters) expect(result.rows).toEqual([]) + expect(result.summary).toEqual({ + shipQty: '0', salesAmount: '0', realPerformance: '0', grossProfit: '0', afterSaleCostRate: '', + totalProducts: '0', productsWithSalesAmount: '0', + }) expect(await dropship1688DataService.listFilterOptions({ field: 'skuOperator', filters })).toEqual({ values: [] }) }) @@ -203,6 +310,7 @@ describe('dropship1688DataService', () => { { ...source.trends[0], statDate: new Date('2026-08-01'), skuOperator: '上月运营', unitCost: new Prisma.Decimal('88'), realPerformance: new Prisma.Decimal('9999'), + estimatedFreight: new Prisma.Decimal('4.50'), }, { ...source.trends[0], statDate: new Date('2026-08-31'), skuOperator: '上一周运营' }, { ...source.trends[0], statDate: new Date('2026-09-01'), skuOperator: ' 新运营 / 子美 ' }, @@ -226,6 +334,6 @@ describe('dropship1688DataService', () => { repository.listPage.mockResolvedValue(source as never) const result = await dropship1688DataService.listPage({ dateFrom: '2026-09-01', dateTo: '2026-09-07' }) - expect(result.rows[0]).toMatchObject({ trend: [], comparisonTrend: [], costPrice: '', skuOperator: '' }) + expect(result.rows[0]).toMatchObject({ trend: [], comparisonTrend: [], totalCost: '0', costPrice: '0', estimatedFreight: '0', skuOperator: '' }) }) }) diff --git a/furniture-3d-system/src/server/services/__tests__/dropship-1688-sourcing.service.test.ts b/furniture-3d-system/src/server/services/__tests__/dropship-1688-sourcing.service.test.ts new file mode 100644 index 00000000..bf804262 --- /dev/null +++ b/furniture-3d-system/src/server/services/__tests__/dropship-1688-sourcing.service.test.ts @@ -0,0 +1,595 @@ +jest.mock('@/server/repositories/dropship-1688-sourcing.repository', () => ({ + dropship1688SourcingRepository: { + findClaimSource: jest.fn(), + findTaskById: jest.fn(), + updateTask: jest.fn(), + deleteTaskIfRevocable: jest.fn(), + listTasksByBarcodes: jest.fn(), + updateTasks: jest.fn(), + claim: jest.fn(), + listTasks: jest.fn(), + countTasks: jest.fn(), + listTasksPage: jest.fn(), + listFilterOptions: jest.fn(), + listTasksForExport: jest.fn(), + listPurchasersByBarcodes: jest.fn(), + }, +})) + +import { Prisma } from '@prisma/client' +import type { AuthUser } from '@/server/core/types' +import { ErrorCode } from '@/server/core/errors' +import { dropship1688SourcingRepository } from '@/server/repositories/dropship-1688-sourcing.repository' +import { dropship1688SourcingService } from '../dropship-1688-sourcing.service' + +const repository = dropship1688SourcingRepository as unknown as { + findClaimSource: jest.Mock + findTaskById: jest.Mock + updateTask: jest.Mock + deleteTaskIfRevocable: jest.Mock + listTasksByBarcodes: jest.Mock + updateTasks: jest.Mock + claim: jest.Mock + listTasks: jest.Mock + countTasks: jest.Mock + listTasksPage: jest.Mock + listFilterOptions: jest.Mock + listTasksForExport: jest.Mock + listPurchasersByBarcodes: jest.Mock +} + +const dateFrom = new Date('2026-09-01T00:00:00.000Z') +const dateTo = new Date('2026-09-10T00:00:00.000Z') + +function user(overrides: Partial = {}): AuthUser { + return { + id: 'buyer-1', + email: 'buyer@example.com', + name: '采购甲', + role: 'USER', + status: 'ACTIVE', + businessRoles: ['PURCHASING'], + ...overrides, + } +} + +function task(overrides: Record = {}) { + return { + id: 'task-1', + sourceArchiveId: 'archive-1', + sourceSpu: 'SPU-ONE', + sourceBarcode: 'DF-ONE', + sourceCostPrice: new Prisma.Decimal('70'), + sourceSkuOperator: '子美', + sourceDateFrom: dateFrom, + sourceDateTo: dateTo, + purchaserUserId: 'buyer-1', + purchaserName: '采购甲', + supplierName: '', + quotedPriceTaxIncluded: null, + invoiceTaxPoint: null, + sourcingMode: '', + jianshangBarcode: '', + acceptedAt: new Date('2026-09-16T01:00:00.000Z'), + updatedAt: new Date('2026-09-16T01:00:00.000Z'), + ...overrides, + } +} + +describe('dropship1688SourcingService', () => { + beforeEach(() => { + jest.clearAllMocks() + repository.findClaimSource.mockResolvedValue({ + archiveId: 'archive-1', + spu: 'SPU-ONE', + barcode: 'DF-ONE', + costPrice: new Prisma.Decimal('70'), + skuOperator: '子美', + }) + repository.claim.mockResolvedValue({ status: 'claimed', task: task() }) + repository.findTaskById.mockResolvedValue(task()) + repository.updateTask.mockResolvedValue(task()) + repository.deleteTaskIfRevocable.mockResolvedValue(true) + repository.listTasksByBarcodes.mockResolvedValue([]) + repository.updateTasks.mockResolvedValue(undefined) + repository.listTasks.mockResolvedValue([]) + repository.countTasks.mockResolvedValue(0) + repository.listTasksPage.mockResolvedValue([]) + repository.listFilterOptions.mockResolvedValue({ + purchaserNames: [], sourceSpus: [], sourceSkuOperators: [], + }) + repository.listTasksForExport.mockResolvedValue([]) + repository.listPurchasersByBarcodes.mockResolvedValue([]) + }) + + it('allows purchasing users and derives the purchaser identity only from the server actor', async () => { + const result = await dropship1688SourcingService.claim({ + barcode: ' df-one ', + dateFrom: '2026-09-01', + dateTo: '2026-09-10', + }, user({ name: ' 采购甲 ' })) + + expect(repository.findClaimSource).toHaveBeenCalledWith({ + barcode: 'DF-ONE', dateFrom, dateTo, + }) + expect(repository.claim).toHaveBeenCalledWith(expect.objectContaining({ + dateFrom, + dateTo, + purchaser: { id: 'buyer-1', name: '采购甲' }, + })) + expect(result).toMatchObject({ + sourceBarcode: 'DF-ONE', + sourceSpu: 'SPU-ONE', + sourceCostPrice: '70.0000', + purchaserUserId: 'buyer-1', + purchaserName: '采购甲', + sourceDateFrom: '2026-09-01', + sourceDateTo: '2026-09-10', + }) + }) + + it('allows an administrator without the purchasing business role', async () => { + await expect(dropship1688SourcingService.claim({ + barcode: 'DF-ONE', dateFrom: '2026-09-01', dateTo: '2026-09-10', + }, user({ role: 'SUPER_ADMIN', businessRoles: [] }))).resolves.toBeDefined() + }) + + it('updates all editable fields for the purchaser who accepted the task', async () => { + repository.updateTask.mockResolvedValue(task({ + supplierName: '供应商甲', + quotedPriceTaxIncluded: new Prisma.Decimal('68.5'), + invoiceTaxPoint: new Prisma.Decimal('13'), + sourcingMode: '代发', + jianshangBarcode: 'JS-001', + })) + + const result = await dropship1688SourcingService.update({ + taskId: 'task-1', + supplierName: ' 供应商甲 ', + quotedPriceTaxIncluded: '68.5', + invoiceTaxPoint: '13', + sourcingMode: ' 代发 ', + jianshangBarcode: ' JS-001 ', + }, user()) + + expect(repository.findTaskById).toHaveBeenCalledWith('task-1') + expect(repository.updateTask).toHaveBeenCalledWith({ + id: 'task-1', + supplierName: '供应商甲', + quotedPriceTaxIncluded: new Prisma.Decimal('68.5'), + invoiceTaxPoint: new Prisma.Decimal('13'), + sourcingMode: '代发', + jianshangBarcode: 'JS-001', + }) + expect(result).toMatchObject({ + supplierName: '供应商甲', + quotedPriceTaxIncluded: '68.5000', + invoiceTaxPoint: '13.0000', + sourcingMode: '代发', + }) + }) + + it('allows administrators to update another purchaser task', async () => { + repository.findTaskById.mockResolvedValue(task({ purchaserUserId: 'buyer-2' })) + await expect(dropship1688SourcingService.update({ + taskId: 'task-1', supplierName: '', quotedPriceTaxIncluded: '', invoiceTaxPoint: '', + sourcingMode: '', jianshangBarcode: '', + }, user({ role: 'ADMIN', businessRoles: [] }))).resolves.toBeDefined() + expect(repository.updateTask).toHaveBeenCalled() + }) + + it('rejects another purchaser and non-purchasing users before writing', async () => { + repository.findTaskById.mockResolvedValue(task({ purchaserUserId: 'buyer-2' })) + const input = { + taskId: 'task-1', supplierName: '', quotedPriceTaxIncluded: '', invoiceTaxPoint: '', + sourcingMode: '', jianshangBarcode: '', + } + await expect(dropship1688SourcingService.update(input, user())).rejects.toMatchObject({ + code: ErrorCode.AUTH_PERMISSION_DENIED, + message: '只能修改本人承接的寻源任务', + }) + await expect(dropship1688SourcingService.update( + input, + user({ businessRoles: ['OPERATIONS'] }), + )).rejects.toMatchObject({ code: ErrorCode.AUTH_PERMISSION_DENIED }) + expect(repository.updateTask).not.toHaveBeenCalled() + }) + + it.each([ + { quotedPriceTaxIncluded: '-1', invoiceTaxPoint: '' }, + { quotedPriceTaxIncluded: '1.12345', invoiceTaxPoint: '' }, + { quotedPriceTaxIncluded: '', invoiceTaxPoint: '100.0001' }, + { quotedPriceTaxIncluded: '', invoiceTaxPoint: '101' }, + ])('rejects invalid sourcing decimals: %j', async (values) => { + await expect(dropship1688SourcingService.update({ + taskId: 'task-1', supplierName: '', sourcingMode: '', + jianshangBarcode: '', ...values, + }, user())).rejects.toMatchObject({ code: ErrorCode.VALIDATION_INVALID_FORMAT }) + expect(repository.findTaskById).not.toHaveBeenCalled() + }) + + it('rejects sourcing modes outside the two supported choices', async () => { + await expect(dropship1688SourcingService.update({ + taskId: 'task-1', supplierName: '', quotedPriceTaxIncluded: '', invoiceTaxPoint: '', + sourcingMode: '一件代发', jianshangBarcode: '', + }, user())).rejects.toMatchObject({ + code: ErrorCode.VALIDATION_INVALID_FORMAT, + message: '模式只能选择入库或代发', + }) + expect(repository.findTaskById).not.toHaveBeenCalled() + }) + + it('rejects a missing sourcing task without writing', async () => { + repository.findTaskById.mockResolvedValue(null) + await expect(dropship1688SourcingService.update({ + taskId: 'missing', supplierName: '', quotedPriceTaxIncluded: '', invoiceTaxPoint: '', + sourcingMode: '', jianshangBarcode: '', + }, user())).rejects.toMatchObject({ code: ErrorCode.PRODUCT_NOT_FOUND }) + expect(repository.updateTask).not.toHaveBeenCalled() + }) + + it('revokes the purchaser own acceptance and deletes exactly that task', async () => { + await expect(dropship1688SourcingService.revoke( + { taskId: 'task-1' }, + user(), + )).resolves.toEqual({ id: 'task-1' }) + expect(repository.findTaskById).toHaveBeenCalledWith('task-1') + expect(repository.deleteTaskIfRevocable).toHaveBeenCalledWith({ + id: 'task-1', purchaserUserId: 'buyer-1', + }) + }) + + it('does not let an administrator revoke another purchaser acceptance', async () => { + repository.findTaskById.mockResolvedValue( + task({ purchaserUserId: 'buyer-2', purchaserName: '采购乙' }), + ) + await expect(dropship1688SourcingService.revoke( + { taskId: 'task-1' }, + user({ role: 'ADMIN', businessRoles: [] }), + )).rejects.toMatchObject({ + code: ErrorCode.AUTH_PERMISSION_DENIED, + message: '只能撤销本人承接的寻源任务', + }) + expect(repository.deleteTaskIfRevocable).not.toHaveBeenCalled() + }) + + it('refuses to revoke an acceptance owned by another purchaser', async () => { + repository.findTaskById.mockResolvedValue( + task({ purchaserUserId: 'buyer-2', purchaserName: '采购乙' }), + ) + await expect(dropship1688SourcingService.revoke( + { taskId: 'task-1' }, + user(), + )).rejects.toMatchObject({ + code: ErrorCode.AUTH_PERMISSION_DENIED, + message: '只能撤销本人承接的寻源任务', + }) + expect(repository.deleteTaskIfRevocable).not.toHaveBeenCalled() + }) + + it('refuses to revoke an acceptance that already has a jianshang barcode', async () => { + repository.findTaskById.mockResolvedValue(task({ jianshangBarcode: ' JS-001 ' })) + await expect(dropship1688SourcingService.revoke( + { taskId: 'task-1' }, + user(), + )).rejects.toMatchObject({ + code: ErrorCode.VALIDATION_FAILED, + message: '该寻源任务已填写简尚条码,不能撤销', + }) + expect(repository.deleteTaskIfRevocable).not.toHaveBeenCalled() + }) + + it('applies the ownership rule before the jianshang barcode rule', async () => { + repository.findTaskById.mockResolvedValue(task({ + purchaserUserId: 'buyer-2', purchaserName: '采购乙', jianshangBarcode: 'JS-001', + })) + await expect(dropship1688SourcingService.revoke( + { taskId: 'task-1' }, + user(), + )).rejects.toMatchObject({ code: ErrorCode.AUTH_PERMISSION_DENIED }) + expect(repository.deleteTaskIfRevocable).not.toHaveBeenCalled() + }) + + it('refuses to revoke without the purchasing role before reading the task', async () => { + await expect(dropship1688SourcingService.revoke( + { taskId: 'task-1' }, + user({ businessRoles: ['OPERATIONS'] }), + )).rejects.toMatchObject({ code: ErrorCode.AUTH_PERMISSION_DENIED }) + expect(repository.findTaskById).not.toHaveBeenCalled() + expect(repository.deleteTaskIfRevocable).not.toHaveBeenCalled() + }) + + it('refuses to revoke a missing task', async () => { + repository.findTaskById.mockResolvedValue(null) + await expect(dropship1688SourcingService.revoke( + { taskId: 'missing' }, + user(), + )).rejects.toMatchObject({ code: ErrorCode.PRODUCT_NOT_FOUND }) + expect(repository.deleteTaskIfRevocable).not.toHaveBeenCalled() + }) + + it('maps an atomic revoke miss to a newly filled jianshang barcode', async () => { + repository.findTaskById + .mockResolvedValueOnce(task()) + .mockResolvedValueOnce(task({ jianshangBarcode: 'JS-001' })) + repository.deleteTaskIfRevocable.mockResolvedValue(false) + + await expect(dropship1688SourcingService.revoke( + { taskId: 'task-1' }, + user(), + )).rejects.toMatchObject({ + code: ErrorCode.VALIDATION_FAILED, + message: '该寻源任务已填写简尚条码,不能撤销', + }) + expect(repository.findTaskById).toHaveBeenCalledTimes(2) + }) + + it('maps an atomic revoke miss to a concurrently removed task', async () => { + repository.findTaskById + .mockResolvedValueOnce(task()) + .mockResolvedValueOnce(null) + repository.deleteTaskIfRevocable.mockResolvedValue(false) + + await expect(dropship1688SourcingService.revoke( + { taskId: 'task-1' }, + user(), + )).rejects.toMatchObject({ + code: ErrorCode.PRODUCT_NOT_FOUND, + message: '寻源任务不存在', + }) + }) + + it('maps an atomic revoke miss to an ownership mismatch', async () => { + repository.findTaskById + .mockResolvedValueOnce(task()) + .mockResolvedValueOnce(task({ purchaserUserId: 'buyer-2', purchaserName: '采购乙' })) + repository.deleteTaskIfRevocable.mockResolvedValue(false) + + await expect(dropship1688SourcingService.revoke( + { taskId: 'task-1' }, + user(), + )).rejects.toMatchObject({ + code: ErrorCode.AUTH_PERMISSION_DENIED, + message: '只能撤销本人承接的寻源任务', + }) + }) + + it('maps an unexplained atomic revoke miss to a refreshable state conflict', async () => { + repository.deleteTaskIfRevocable.mockResolvedValue(false) + + await expect(dropship1688SourcingService.revoke( + { taskId: 'task-1' }, + user(), + )).rejects.toMatchObject({ + code: ErrorCode.VALIDATION_FAILED, + message: '寻源任务状态已变化,请刷新页面后重试', + }) + expect(repository.findTaskById).toHaveBeenCalledTimes(2) + }) + + it.each([ + {}, + { taskId: '' }, + { taskId: ' ' }, + { taskId: 'task-1', purchaserName: '伪造采购' }, + ])('rejects invalid revoke input: %j', async (input) => { + await expect(dropship1688SourcingService.revoke(input, user())) + .rejects.toMatchObject({ code: ErrorCode.VALIDATION_INVALID_FORMAT }) + expect(repository.findTaskById).not.toHaveBeenCalled() + expect(repository.deleteTaskIfRevocable).not.toHaveBeenCalled() + }) + + it('rejects a fourth purchaser when all three slots are already filled', async () => { + repository.claim.mockResolvedValue({ status: 'full' }) + + await expect(dropship1688SourcingService.claim({ + barcode: 'DF-ONE', dateFrom: '2026-09-01', dateTo: '2026-09-10', + }, user())).rejects.toMatchObject({ + code: ErrorCode.VALIDATION_OUT_OF_RANGE, + message: '该商品最多由3名采购承接', + }) + }) + + it('rejects non-purchasing users before reading product data', async () => { + await expect(dropship1688SourcingService.claim({ + barcode: 'DF-ONE', dateFrom: '2026-09-01', dateTo: '2026-09-10', + }, user({ businessRoles: ['OPERATIONS'] }))).rejects.toMatchObject({ + code: ErrorCode.AUTH_PERMISSION_DENIED, + }) + expect(repository.findClaimSource).not.toHaveBeenCalled() + }) + + it.each([ + { barcode: 'SKU-ONE', dateFrom: '2026-09-01', dateTo: '2026-09-10' }, + { barcode: 'DF-ONE', dateFrom: '2026-02-31', dateTo: '2026-09-10' }, + { barcode: 'DF-ONE', dateFrom: '2026-09-11', dateTo: '2026-09-10' }, + { barcode: 'DF-ONE', dateFrom: '2026-09-01', dateTo: '2026-09-10', purchaserName: '伪造采购' }, + ])('rejects invalid claim input: %j', async (input) => { + await expect(dropship1688SourcingService.claim(input, user())).rejects.toMatchObject({ + code: ErrorCode.VALIDATION_INVALID_FORMAT, + }) + expect(repository.findClaimSource).not.toHaveBeenCalled() + }) + + it('rejects a missing or non-DF archive after the authoritative lookup', async () => { + repository.findClaimSource.mockResolvedValueOnce(null) + await expect(dropship1688SourcingService.claim({ + barcode: 'DF-MISSING', dateFrom: '2026-09-01', dateTo: '2026-09-10', + }, user())).rejects.toMatchObject({ code: ErrorCode.PRODUCT_NOT_FOUND }) + + repository.findClaimSource.mockResolvedValueOnce({ + archiveId: 'archive-legacy', spu: 'SPU-LEGACY', barcode: 'SKU-LEGACY', costPrice: null, skuOperator: '', + }) + await expect(dropship1688SourcingService.claim({ + barcode: 'DF-ONE', dateFrom: '2026-09-01', dateTo: '2026-09-10', + }, user())).rejects.toMatchObject({ code: ErrorCode.PRODUCT_NOT_FOUND }) + expect(repository.claim).not.toHaveBeenCalled() + }) + + it('formats the accepted SPU snapshot while preserving current SKU and image enrichment', async () => { + repository.listTasks.mockResolvedValue([ + task({ quotedPriceTaxIncluded: new Prisma.Decimal('62.3456'), invoiceTaxPoint: new Prisma.Decimal('13'), sku: 'SKU-ONE', hasImage: true }), + task({ + id: 'task-2', sourceSpu: '', sourceBarcode: 'DF-TWO', sourceCostPrice: null, + purchaserUserId: 'buyer-2', quotedPriceTaxIncluded: null, sku: '', hasImage: false, + }), + ]) + + await expect(dropship1688SourcingService.listTasks()).resolves.toEqual([ + expect.objectContaining({ + sourceBarcode: 'DF-ONE', sourceCostPrice: '70.0000', quotedPriceTaxIncluded: '62.3456', + invoiceTaxPoint: '13.0000', + sourceSpu: 'SPU-ONE', sku: 'SKU-ONE', hasImage: true, + }), + expect.objectContaining({ + sourceBarcode: 'DF-TWO', sourceCostPrice: null, quotedPriceTaxIncluded: null, + sourceSpu: '', sku: '', hasImage: false, + }), + ]) + }) + + it('clamps an out-of-range sourcing page to the last available page', async () => { + const filters = { + purchaserNames: ['采购甲'], + sourceSpus: [], + sourceSkuOperators: [], + } + repository.countTasks.mockResolvedValue(61) + repository.listTasksPage.mockResolvedValue([task({ id: 'task-last' })]) + repository.listFilterOptions.mockResolvedValue({ + purchaserNames: ['采购甲'], sourceSpus: ['SPU-ONE'], sourceSkuOperators: ['子美'], + }) + + const result = await dropship1688SourcingService.listPage({ + page: 9, pageSize: 50, filters, + }) + + expect(repository.countTasks).toHaveBeenCalledWith(filters) + expect(repository.listTasksPage).toHaveBeenCalledTimes(1) + expect(repository.listTasksPage).toHaveBeenCalledWith({ + filters, skip: 50, take: 50, + }) + expect(repository.listFilterOptions).toHaveBeenCalledTimes(1) + expect(result).toMatchObject({ + total: 61, + page: 2, + pageSize: 50, + totalPages: 2, + rows: [expect.objectContaining({ id: 'task-last' })], + }) + }) + + it('does not query a task page when the filtered count is zero', async () => { + const filters = { purchaserNames: [], sourceSpus: [], sourceSkuOperators: [] } + + const result = await dropship1688SourcingService.listPage({ + page: 1, pageSize: 50, filters, + }) + + expect(repository.countTasks).toHaveBeenCalledWith(filters) + expect(repository.listTasksPage).not.toHaveBeenCalled() + expect(result).toMatchObject({ total: 0, page: 1, totalPages: 1, rows: [] }) + }) + + it('imports editable fields by the exact barcode and purchaser pair in one write', async () => { + repository.listTasksByBarcodes.mockResolvedValue([ + task(), + task({ id: 'task-2', purchaserUserId: 'buyer-2', purchaserName: '采购乙' }), + ]) + + await expect(dropship1688SourcingService.importRows([ + { + rowNumber: 2, + sourceBarcode: 'df-one', + purchaserName: '采购甲', + supplierName: '供应商甲', + quotedPriceTaxIncluded: '88.5', + invoiceTaxPoint: '13', + sourcingMode: '代发', + jianshangBarcode: 'JS-001', + }, + ], user())).resolves.toEqual({ updated: 1 }) + + expect(repository.listTasksByBarcodes).toHaveBeenCalledWith(['DF-ONE']) + expect(repository.updateTasks).toHaveBeenCalledWith([{ + id: 'task-1', + supplierName: '供应商甲', + quotedPriceTaxIncluded: new Prisma.Decimal('88.5'), + invoiceTaxPoint: new Prisma.Decimal('13'), + sourcingMode: '代发', + jianshangBarcode: 'JS-001', + }]) + }) + + it('rejects duplicate workbook keys before reading or writing tasks', async () => { + const row = { + sourceBarcode: 'DF-ONE', purchaserName: '采购甲', supplierName: '', + quotedPriceTaxIncluded: '', invoiceTaxPoint: '', sourcingMode: '', jianshangBarcode: '', + } + await expect(dropship1688SourcingService.importRows([ + { rowNumber: 2, ...row }, + { rowNumber: 4, ...row }, + ], user())).rejects.toMatchObject({ + code: ErrorCode.VALIDATION_INVALID_FORMAT, + message: '第4行与第2行的代发条码和采购重复', + }) + expect(repository.listTasksByBarcodes).not.toHaveBeenCalled() + expect(repository.updateTasks).not.toHaveBeenCalled() + }) + + it('does not let a purchaser import another purchaser row', async () => { + repository.listTasksByBarcodes.mockResolvedValue([ + task({ id: 'task-2', purchaserUserId: 'buyer-2', purchaserName: '采购乙' }), + ]) + await expect(dropship1688SourcingService.importRows([{ + rowNumber: 2, sourceBarcode: 'DF-ONE', purchaserName: '采购乙', supplierName: '', + quotedPriceTaxIncluded: '', invoiceTaxPoint: '', sourcingMode: '', jianshangBarcode: '', + }], user())).rejects.toMatchObject({ + code: ErrorCode.AUTH_PERMISSION_DENIED, + message: '第2行:只能导入本人承接的寻源任务', + }) + expect(repository.updateTasks).not.toHaveBeenCalled() + }) + + it('validates every import row before writing any update', async () => { + repository.listTasksByBarcodes.mockResolvedValue([task()]) + + await expect(dropship1688SourcingService.importRows([ + { + rowNumber: 2, sourceBarcode: 'DF-ONE', purchaserName: '采购甲', supplierName: '供应商甲', + quotedPriceTaxIncluded: '88.5', invoiceTaxPoint: '13', sourcingMode: '代发', + jianshangBarcode: 'JS-001', + }, + { + rowNumber: 3, sourceBarcode: 'DF-TWO', purchaserName: '采购甲', supplierName: '供应商乙', + quotedPriceTaxIncluded: '66', invoiceTaxPoint: '13', sourcingMode: '入库', + jianshangBarcode: 'JS-002', + }, + ], user())).rejects.toMatchObject({ + code: ErrorCode.PRODUCT_NOT_FOUND, + message: '第3行:未找到代发条码 DF-TWO 与采购 采购甲 的承接记录', + }) + + expect(repository.updateTasks).not.toHaveBeenCalled() + }) + + it('normalizes requested barcodes and groups multiple accepting purchasers', async () => { + repository.listPurchasersByBarcodes.mockResolvedValue([ + { sourceBarcode: 'DF-ONE', purchaserUserId: 'buyer-1', purchaserName: '采购甲', acceptedAt: new Date('2026-09-16T01:00:00.000Z') }, + { sourceBarcode: 'DF-ONE', purchaserUserId: 'buyer-2', purchaserName: '采购乙', acceptedAt: new Date('2026-09-16T02:00:00.000Z') }, + ]) + + const result = await dropship1688SourcingService.listPurchasersByBarcodes([ + ' df-one ', 'DF-ONE', 'DF-TWO', 'SKU-IGNORED', + ]) + + expect(repository.listPurchasersByBarcodes).toHaveBeenCalledWith(['DF-ONE', 'DF-TWO']) + expect(result).toEqual({ + 'DF-ONE': [ + { userId: 'buyer-1', name: '采购甲', acceptedAt: '2026-09-16T01:00:00.000Z' }, + { userId: 'buyer-2', name: '采购乙', acceptedAt: '2026-09-16T02:00:00.000Z' }, + ], + 'DF-TWO': [], + }) + }) +}) diff --git a/furniture-3d-system/src/server/services/__tests__/operation-log-failure-notification.service.test.ts b/furniture-3d-system/src/server/services/__tests__/operation-log-failure-notification.service.test.ts new file mode 100644 index 00000000..b026f4e7 --- /dev/null +++ b/furniture-3d-system/src/server/services/__tests__/operation-log-failure-notification.service.test.ts @@ -0,0 +1,284 @@ +import { OperationLogAction, OperationLogStatus } from '@prisma/client' +import { + OperationLogFailureNotificationService, + buildOperationLogFailureMessage, + buildOperationLogFailureNotificationKey, + type OperationLogFailureNotificationDeps, + type OperationLogFailurePayload, +} from '@/server/services/operation-log-failure-notification.service' +import type { NotificationRecipient } from '@/server/repositories/notification-delivery.repository' + +// 北京时间 2026-09-17 14:40:14 +const FIXED_NOW = new Date('2026-09-17T06:40:14Z') + +type SentRecord = { key: string; title: string; content: string; recipientUserId: string; source: string } + +function activeRecipient(overrides: Partial = {}): NotificationRecipient { + return { + id: 'user-xu', + name: '徐霞客', + email: 'xu@example.com', + status: 'ACTIVE', + businessRoles: [], + dingtalkUserId: 'ding-xu', + ...overrides, + } as NotificationRecipient +} + +function baseDeps(options: { + recipient?: NotificationRecipient | null + sendFails?: boolean +} = {}) { + const sent: SentRecord[] = [] + const undeliverable: Array<{ code: string; recipientName: string }> = [] + const recordedKeys = new Set() + const recipient = options.recipient === undefined ? activeRecipient() : options.recipient + + const deps: OperationLogFailureNotificationDeps = { + findRecipientsByNames: async (names) => ( + recipient && names.includes(recipient.name) ? [recipient] : [] + ), + findByIdempotencyKey: async (key) => (recordedKeys.has(key) ? { id: `delivery-${key}` } : null), + sendToEmployee: async (input) => { + if (options.sendFails) throw new Error('通知中心连接失败') + recordedKeys.add(input.idempotencyKey) + sent.push({ + key: input.idempotencyKey, + title: input.title, + content: input.content, + recipientUserId: input.recipientUserId, + source: input.source ?? '', + }) + return { id: `delivery-${sent.length}` } + }, + recordUndeliverable: async (input) => { + recordedKeys.add(input.idempotencyKey) + undeliverable.push({ code: input.errorCode, recipientName: input.recipient.name }) + return null + }, + now: () => FIXED_NOW, + } + + return { deps, sent, undeliverable, recordedKeys } +} + +function serviceWith(deps: OperationLogFailureNotificationDeps) { + return new OperationLogFailureNotificationService(deps) +} + +function productWriteFailure(overrides: Partial = {}): OperationLogFailurePayload { + return { + action: OperationLogAction.INTAKE_PRODUCT_WRITE, + status: OperationLogStatus.FAILED, + source: 'USER', + actorName: '槐米', + productSpu: 'LRSF0095', + skuCode: null, + workspaceCategory: '样包测量', + errorCode: 'P2028', + message: '产品资料保存失败:Invalid `prisma.intakeNonIntegratedProduct.update()` invocation: Transaction API error', + requestId: 'req-1', + createdAt: FIXED_NOW, + ...overrides, + } +} + +function fixedVirtualInventoryFailure(skuCode: string, at: Date): OperationLogFailurePayload { + return { + action: OperationLogAction.JUSHUITAN_VIRTUAL_INVENTORY_PUSH, + status: OperationLogStatus.FAILED, + source: 'SYSTEM', + actorName: '聚水潭固定虚拟库存定时任务', + skuCode, + errorCode: 'JUSHUITAN_FIXED_VIRTUAL_INVENTORY_FAILED', + message: 'Jushuitan fixed virtual inventory push failed; retry at 2026-09-17T08:00:00.000Z: 调用太频繁', + createdAt: at, + } +} + +describe('OperationLogFailureNotificationService', () => { + afterEach(() => { + delete process.env.OPERATION_LOG_NOTIFIER_HOURLY_LIMIT + delete process.env.OPERATION_LOG_NOTIFIER_RECIPIENT + }) + + it('成功日志不推送', async () => { + const env = baseDeps() + const result = await serviceWith(env.deps).notify({ + ...productWriteFailure(), + status: OperationLogStatus.SUCCESS, + }) + + expect(result.outcome).toBe('ignored') + expect(env.sent).toHaveLength(0) + }) + + it('失败日志推送给徐霞客,且为纯文字(不带按钮字段)', async () => { + const env = baseDeps() + const result = await serviceWith(env.deps).notify(productWriteFailure()) + + expect(result.outcome).toBe('sent') + expect(result.recipientName).toBe('徐霞客') + expect(env.sent).toHaveLength(1) + expect(env.sent[0].recipientUserId).toBe('user-xu') + expect(env.sent[0].title).toBe('产品资料保存失败') + expect(env.sent[0].content).toBe([ + '动作:产品资料保存', + '时间:2026-09-17 14:40:14', + '人员:槐米(人工操作)', + '产品:LRSF0095 / 节点:样包测量', + '错误码:P2028', + '原因:Invalid `prisma.intakeNonIntegratedProduct.update()` invocation: Transaction API error', + ].join('\n\n')) + }) + + it('系统来源显示为系统任务,且原因剥离动作前缀', async () => { + const env = baseDeps() + await serviceWith(env.deps).notify(productWriteFailure({ source: 'SYSTEM', actorName: '定时任务' })) + + expect(env.sent[0].content).toContain('人员:定时任务(系统任务)') + expect(env.sent[0].content).toContain('原因:Invalid `prisma') + }) + + it('聚水潭定时任务在同一小时窗内把上千条失败折叠成一条', async () => { + const env = baseDeps() + const service = serviceWith(env.deps) + + const first = await service.notify(fixedVirtualInventoryFailure('CBG-001', FIXED_NOW)) + const second = await service.notify(fixedVirtualInventoryFailure('CBG-002', new Date(FIXED_NOW.getTime() + 60_000))) + const third = await service.notify(fixedVirtualInventoryFailure('CBG-003', new Date(FIXED_NOW.getTime() + 600_000))) + + expect(first.outcome).toBe('sent') + expect(second.outcome).toBe('skipped-duplicate') + expect(third.outcome).toBe('skipped-duplicate') + expect(env.sent).toHaveLength(1) + expect(env.sent[0].content).toContain('说明:该错误码在 60 分钟内多次出现时只通知一次') + }) + + it('折叠类幂等键不含业务对象,普通类含产品与 SKU', () => { + const folded = buildOperationLogFailureNotificationKey({ + action: OperationLogAction.JUSHUITAN_VIRTUAL_INVENTORY_PUSH, + errorCode: 'JUSHUITAN_FIXED_VIRTUAL_INVENTORY_FAILED', + productSpu: 'SPU-1', + skuCode: 'SKU-1', + now: FIXED_NOW, + }) + const scoped = buildOperationLogFailureNotificationKey({ + action: OperationLogAction.INTAKE_PRODUCT_WRITE, + errorCode: 'P2028', + productSpu: 'SPU-1', + skuCode: 'SKU-1', + now: FIXED_NOW, + }) + + expect(folded).toBe(`oplog-failure:folded:${Math.floor(FIXED_NOW.getTime() / 3_600_000)}:JUSHUITAN_VIRTUAL_INVENTORY_PUSH:JUSHUITAN_FIXED_VIRTUAL_INVENTORY_FAILED`) + expect(scoped).toContain('oplog-failure:scoped:') + expect(scoped).toContain('SPU-1:SKU-1') + }) + + it('不同产品的同类失败各自推送,同一产品重复失败只推一次', async () => { + const env = baseDeps() + const service = serviceWith(env.deps) + + expect((await service.notify(productWriteFailure({ productSpu: 'LRSF0095' }))).outcome).toBe('sent') + expect((await service.notify(productWriteFailure({ productSpu: 'LRSF0096' }))).outcome).toBe('sent') + expect((await service.notify(productWriteFailure({ productSpu: 'LRSF0095' }))).outcome).toBe('skipped-duplicate') + + expect(env.sent).toHaveLength(2) + }) + + it('超出时间窗后同一产品再次失败会重新推送', async () => { + const env = baseDeps() + let now = FIXED_NOW + const service = new OperationLogFailureNotificationService({ + ...env.deps, + now: () => now, + }) + + expect((await service.notify(productWriteFailure())).outcome).toBe('sent') + now = new Date(FIXED_NOW.getTime() + 11 * 60_000) + expect((await service.notify(productWriteFailure())).outcome).toBe('sent') + expect(env.sent).toHaveLength(2) + }) + + it('收件人未绑定钉钉时记录不可投递,不调用发送', async () => { + const env = baseDeps({ recipient: activeRecipient({ dingtalkUserId: null }) }) + const result = await serviceWith(env.deps).notify(productWriteFailure()) + + expect(result.outcome).toBe('undeliverable') + expect(env.sent).toHaveLength(0) + expect(env.undeliverable).toEqual([{ code: 'RECIPIENT_DINGTALK_UNBOUND', recipientName: '徐霞客' }]) + }) + + it('收件人不存在时记录不可投递', async () => { + const env = baseDeps({ recipient: null }) + const result = await serviceWith(env.deps).notify(productWriteFailure()) + + expect(result.outcome).toBe('undeliverable') + expect(env.undeliverable[0].code).toBe('RECIPIENT_NOT_FOUND') + }) + + it('通知中心调用失败时不抛出,返回 error 供调用方忽略', async () => { + const env = baseDeps({ sendFails: true }) + const result = await serviceWith(env.deps).notify(productWriteFailure()) + + expect(result.outcome).toBe('error') + expect(result.detail).toContain('通知中心连接失败') + }) + + it('每小时超过推送上限后熔断', async () => { + process.env.OPERATION_LOG_NOTIFIER_HOURLY_LIMIT = '2' + const env = baseDeps() + const service = serviceWith(env.deps) + + expect((await service.notify(productWriteFailure({ productSpu: 'SPU-1' }))).outcome).toBe('sent') + expect((await service.notify(productWriteFailure({ productSpu: 'SPU-2' }))).outcome).toBe('sent') + const third = await service.notify(productWriteFailure({ productSpu: 'SPU-3' })) + + expect(third.outcome).toBe('skipped-rate-limit') + expect(env.sent).toHaveLength(2) + }) + + it('收件人名称可通过环境变量覆盖', async () => { + process.env.OPERATION_LOG_NOTIFIER_RECIPIENT = '徐霞客' + const env = baseDeps() + const result = await serviceWith(env.deps).notify(productWriteFailure()) + expect(result.recipientName).toBe('徐霞客') + }) +}) + +describe('buildOperationLogFailureMessage', () => { + it('缺少产品、节点、错误码时不产生空行占位', () => { + const { content } = buildOperationLogFailureMessage({ + action: OperationLogAction.INTAKE_FILE_UPLOAD, + status: OperationLogStatus.RETRY, + source: 'USER', + actorName: '依依', + message: '文件上传失败:网络中断', + createdAt: FIXED_NOW, + }) + + expect(content.split('\n\n')).toEqual([ + '动作:文件上传', + '时间:2026-09-17 14:40:14', + '人员:依依(人工操作)', + '原因:网络中断', + ]) + }) + + it('超长原因按上限截断', () => { + const { content } = buildOperationLogFailureMessage({ + action: OperationLogAction.INTAKE_PRODUCT_WRITE, + status: OperationLogStatus.FAILED, + source: 'USER', + actorName: '槐米', + errorCode: 'P2028', + message: `产品资料保存失败:${'x'.repeat(600)}`, + createdAt: FIXED_NOW, + }) + + const reasonLine = content.split('\n\n').find((line) => line.startsWith('原因:')) ?? '' + expect(reasonLine.endsWith('…')).toBe(true) + expect(reasonLine.length).toBeLessThanOrEqual('原因:'.length + 401) + }) +}) diff --git a/furniture-3d-system/src/server/services/__tests__/operation-log.service.test.ts b/furniture-3d-system/src/server/services/__tests__/operation-log.service.test.ts new file mode 100644 index 00000000..1b949b67 --- /dev/null +++ b/furniture-3d-system/src/server/services/__tests__/operation-log.service.test.ts @@ -0,0 +1,107 @@ +import { OperationLogAction, OperationLogStatus } from '@prisma/client' + +const mockNotify = jest.fn() +const mockCreate = jest.fn() + +// jest.mock 的工厂会被提升到 import 之前执行,这里用惰性包装避免访问尚未初始化的变量。 +jest.mock('@/server/services/operation-log-failure-notification.service', () => ({ + operationLogFailureNotificationService: { + notify: (...args: unknown[]) => mockNotify(...args), + }, +})) + +jest.mock('@/server/repositories/operation-log.repository', () => ({ + operationLogRepository: { + create: (...args: unknown[]) => mockCreate(...args), + }, +})) + +import { operationLogService } from '@/server/services/operation-log.service' + +const ORIGINAL_NODE_ENV = process.env.NODE_ENV + +function flushBackgroundTasks() { + return new Promise((resolve) => setTimeout(resolve, 0)) +} + +describe('OperationLogService 失败日志通知挂载', () => { + beforeEach(() => { + mockNotify.mockReset().mockResolvedValue({ outcome: 'sent' }) + mockCreate.mockReset().mockResolvedValue({ id: 'log-1' }) + // 绕过测试环境静默守卫,验证挂载逻辑本身。 + ;(process.env as Record).NODE_ENV = 'development' + }) + + afterEach(() => { + ;(process.env as Record).NODE_ENV = ORIGINAL_NODE_ENV as string + }) + + const failureInput = { + action: OperationLogAction.INTAKE_PRODUCT_WRITE, + status: OperationLogStatus.FAILED, + actorName: '槐米', + productSpu: 'LRSF0095', + workspaceCategory: '样包测量', + errorCode: 'P2028', + message: '产品资料保存失败:Transaction API error', + requestId: 'req-1', + } + + it('失败日志写入后自动触发通知,参数与日志一致', async () => { + await operationLogService.record(failureInput) + await flushBackgroundTasks() + + expect(mockCreate).toHaveBeenCalledTimes(1) + expect(mockNotify).toHaveBeenCalledTimes(1) + expect(mockNotify).toHaveBeenCalledWith({ + action: OperationLogAction.INTAKE_PRODUCT_WRITE, + status: OperationLogStatus.FAILED, + source: undefined, + actorName: '槐米', + productSpu: 'LRSF0095', + skuCode: undefined, + workspaceCategory: '样包测量', + errorCode: 'P2028', + message: '产品资料保存失败:Transaction API error', + requestId: 'req-1', + }) + }) + + it('成功日志不触发通知', async () => { + await operationLogService.record({ + ...failureInput, + status: OperationLogStatus.SUCCESS, + }) + await flushBackgroundTasks() + + expect(mockNotify).not.toHaveBeenCalled() + }) + + it('RETRY 状态同样触发通知', async () => { + await operationLogService.record({ + ...failureInput, + status: OperationLogStatus.RETRY, + }) + await flushBackgroundTasks() + + expect(mockNotify).toHaveBeenCalledTimes(1) + }) + + it('日志写入失败时不抛错,也不触发通知', async () => { + mockCreate.mockRejectedValueOnce(new Error('database down')) + + await expect(operationLogService.record(failureInput)).resolves.toBeUndefined() + await flushBackgroundTasks() + + expect(mockNotify).not.toHaveBeenCalled() + }) + + it('通知本身抛错时 record 依然静默完成', async () => { + mockNotify.mockRejectedValueOnce(new Error('notification exploded')) + + await expect(operationLogService.record(failureInput)).resolves.toBeUndefined() + await flushBackgroundTasks() + + expect(mockNotify).toHaveBeenCalledTimes(1) + }) +}) diff --git a/furniture-3d-system/src/server/services/__tests__/supply-chain-product-archive-enrichment-sync.service.test.ts b/furniture-3d-system/src/server/services/__tests__/supply-chain-product-archive-enrichment-sync.service.test.ts index 4919a56b..7e3c1af4 100644 --- a/furniture-3d-system/src/server/services/__tests__/supply-chain-product-archive-enrichment-sync.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/supply-chain-product-archive-enrichment-sync.service.test.ts @@ -552,7 +552,23 @@ describe('supply-chain product archive enrichment sync', () => { expect.objectContaining({ scanned: 1, changed: 1 }), ) - expect(repository.applyPatch).toHaveBeenCalledTimes(8) + // 仓库配置拆成两条:负责人照常更新;入库/代发只填空值(产品定厂带回的值不被覆盖) + expect(repository.applyPatch).toHaveBeenCalledTimes(9) + expect(repository.applyPatch).toHaveBeenCalledWith( + expect.objectContaining({ + patch: expect.objectContaining({ warehouseHead: '负责人' }), + source: expect.objectContaining({ sourceObject: 'SupplyChainProductArchiveWarehouseConfig' }), + }), + ) + expect(repository.applyPatch).toHaveBeenCalledWith( + expect.objectContaining({ + patch: expect.objectContaining({ storageType: 'INBOUND' }), + source: expect.objectContaining({ + sourceObject: 'SupplyChainProductArchiveWarehouseConfig', + fillEmptyOnly: true, + }), + }), + ) expect(repository.applyPatch).toHaveBeenCalledWith( expect.objectContaining({ patch: expect.objectContaining({ stockJianshang: '60' }), diff --git a/furniture-3d-system/src/server/services/__tests__/supply-chain-product-archive-sync.service.test.ts b/furniture-3d-system/src/server/services/__tests__/supply-chain-product-archive-sync.service.test.ts index 39461de3..c05625a0 100644 --- a/furniture-3d-system/src/server/services/__tests__/supply-chain-product-archive-sync.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/supply-chain-product-archive-sync.service.test.ts @@ -49,6 +49,7 @@ function createSourceRecord() { package_set_count: '1', purchase_order_method: '非订单式', factory_warehouse: '成品仓', + shipping_method: '', sku_image_url: 'https://cp.jiansun.vip/api/storage/object?key=sku-1.jpeg', updated_at: new Date('2026-07-17T08:00:00.000Z'), } @@ -129,6 +130,51 @@ describe('supply-chain product archive wide-catalog sync', () => { ) }) + it('maps the factory shipping method into the archive storage type', () => { + for (const [shippingMethod, expected] of [ + ['入仓', 'INBOUND'], + ['入库', 'INBOUND'], + ['代发', 'DROPSHIP'], + ] as const) { + const mapped = mapProductCatalogWideArchiveSource({ + ...createSourceRecord(), + shipping_method: shippingMethod, + }) + + expect(mapped?.archive).toEqual( + expect.objectContaining({ storageType: expected }), + ) + const fieldSourceMap = mapped?.archive.fieldSourceMap as Record< + string, + { sourceCode: string; sourceColumn: string } + > + expect(fieldSourceMap.storageType).toEqual( + expect.objectContaining({ + sourceCode: PRODUCT_DEVELOPMENT_ARCHIVE_SOURCE_CODE, + sourceColumn: 'shipping_method', + }), + ) + } + }) + + it('keeps the storage type untouched when the factory row has no shipping method', () => { + const mapped = mapProductCatalogWideArchiveSource({ + ...createSourceRecord(), + shipping_method: null, + }) + + expect(mapped?.archive).not.toHaveProperty('storageType') + }) + + it('ignores unrecognized shipping method values instead of writing garbage', () => { + const mapped = mapProductCatalogWideArchiveSource({ + ...createSourceRecord(), + shipping_method: '海运', + }) + + expect(mapped?.archive).not.toHaveProperty('storageType') + }) + it('upserts eligible rows and removes stale product sources', async () => { const valid = createSourceRecord() const missingBarcode = { diff --git a/furniture-3d-system/src/server/services/barcode-print.service.ts b/furniture-3d-system/src/server/services/barcode-print.service.ts index 8209989e..3fe74db8 100644 --- a/furniture-3d-system/src/server/services/barcode-print.service.ts +++ b/furniture-3d-system/src/server/services/barcode-print.service.ts @@ -14,7 +14,11 @@ import { } from '@/app/intake/barcode-print/barcodePrintRows' import type { AuthUser } from '@/server/core/types' import { AppError, ErrorCode } from '@/server/core/errors' -import { canManageBarcodePrintImports } from '@/lib/role-scope' +import { + canDeleteBarcodePrintImports, + canEditBarcodePrintImports, + canImportBarcodePrintRecords, +} from '@/lib/role-scope' import { barcodePrintImportRepository, type BarcodePrintImportListFilters, @@ -446,10 +450,10 @@ class BarcodePrintService { } async saveImportRecords(user: AuthUser, records: SaveBarcodePrintImportRecordInput[]) { - if (!canManageBarcodePrintImports(user)) { + if (!canImportBarcodePrintRecords(user)) { throw new AppError( ErrorCode.AUTH_PERMISSION_DENIED, - '只有设计师和管理员可以导入条码与品牌货号。', + '只有设计师、采购、仓库和管理员可以导入条码与品牌货号。', ) } @@ -501,10 +505,10 @@ class BarcodePrintService { } async deleteImportRecords(user: AuthUser, ids: unknown[]) { - if (!canManageBarcodePrintImports(user)) { + if (!canDeleteBarcodePrintImports(user)) { throw new AppError( ErrorCode.AUTH_PERMISSION_DENIED, - '只有设计师和管理员可以删除导入数据。', + '只有设计师、采购、仓库和管理员可以删除导入数据。', ) } @@ -548,7 +552,7 @@ class BarcodePrintService { ids: unknown, rawFields: unknown, ) { - if (!canManageBarcodePrintImports(user)) { + if (!canEditBarcodePrintImports(user)) { throw new AppError( ErrorCode.AUTH_PERMISSION_DENIED, '只有设计师和管理员可以修改导入数据。', diff --git a/furniture-3d-system/src/server/services/bom-costing/agent/agent-estimate-card.test.ts b/furniture-3d-system/src/server/services/bom-costing/agent/agent-estimate-card.test.ts new file mode 100644 index 00000000..dc9f0e16 --- /dev/null +++ b/furniture-3d-system/src/server/services/bom-costing/agent/agent-estimate-card.test.ts @@ -0,0 +1,120 @@ +import { buildEstimateCard, selectFirstBatchSkus } from './agent-estimate-card' +import type { BomCostingAgentRunResult } from './agent-contracts' + +function skuInput(overrides: Partial[0][number]> = {}) { + return { + skuId: 's', + externalSkuId: 'SKU', + name: 'n', + lengthMm: null as number | null, + widthMm: null as number | null, + heightMm: null as number | null, + ...overrides, + } +} + +function runResult(overrides: { + total?: [number, number] + confidence?: number + question?: string + categoryTotals?: Record +}): BomCostingAgentRunResult { + const [min, max] = overrides.total ?? [100, 150] + return { + status: 'COMPLETED', + estimate: { + structureSummary: 's', + lines: [], + confidence: overrides.confidence ?? 0.6, + estimateRange: { min, max }, + openQuestions: overrides.question ? [overrides.question] : [], + }, + categoryTotals: { + BOARD: 80, + ACCESSORY: 20, + unresolvedLineCount: 0, + ...overrides.categoryTotals, + } as never, + warnings: [], + trace: [], + usage: { rounds: 2, modelCalls: 2, elapsedMs: 10 }, + } +} + +describe('selectFirstBatchSkus', () => { + it('单 SKU 与双 SKU 全部入选', () => { + const one = [skuInput({ skuId: 'a' })] + expect(selectFirstBatchSkus(one)).toHaveLength(1) + const two = [skuInput({ skuId: 'a' }), skuInput({ skuId: 'b' })] + expect(selectFirstBatchSkus(two)).toHaveLength(2) + }) + + it('五个 SKU 按最大外形轴取 最小/中位/最大,保持原顺序', () => { + const skus = [ + skuInput({ skuId: 'a', lengthMm: 900 }), + skuInput({ skuId: 'b', lengthMm: 1000 }), + skuInput({ skuId: 'c', lengthMm: 1330 }), + skuInput({ skuId: 'd', lengthMm: 1760 }), + skuInput({ skuId: 'e', lengthMm: 1960 }), + ] + const picked = selectFirstBatchSkus(skus) + expect(picked.map((sku) => sku.skuId)).toEqual(['a', 'c', 'e']) + }) + + it('尺寸全缺的 SKU 不参与代表选择,除非没有别的可选', () => { + const skus = [ + skuInput({ skuId: 'no-dim' }), + skuInput({ skuId: 'small', widthMm: 400 }), + skuInput({ skuId: 'mid', widthMm: 800 }), + skuInput({ skuId: 'large', widthMm: 1600 }), + ] + expect(selectFirstBatchSkus(skus).map((sku) => sku.skuId)).toEqual(['small', 'mid', 'large']) + expect(selectFirstBatchSkus([skuInput({ skuId: 'no-dim' })]).map((sku) => sku.skuId)) + .toEqual(['no-dim']) + }) +}) + +describe('buildEstimateCard', () => { + it('聚合五行构成、区间包络、最小置信度与不确定点并集', () => { + const skus = [skuInput({ skuId: 'a', externalSkuId: 'S-A' }), skuInput({ skuId: 'b', externalSkuId: 'S-B' }), skuInput({ skuId: 'c', externalSkuId: 'S-C' })] + const card = buildEstimateCard({ + caseId: 'case-1', + title: '测试衣柜', + skus, + firstBatchSkuIds: ['a', 'b', 'c'], + resultsBySkuId: new Map([ + ['a', { status: 'ESTIMATED' as const, runResult: runResult({ total: [200, 260], confidence: 0.7, question: '板厚未确认', categoryTotals: { BOARD: 180, ACCESSORY: 20 } }) }], + ['b', { status: 'ESTIMATED' as const, runResult: runResult({ total: [300, 380], confidence: 0.55, question: '铰链数量按两门推定', categoryTotals: { BOARD: 260, LABOR: 40 } }) }], + ['c', { status: 'PENDING' as const }], + ]), + usage: { rounds: 6, modelCalls: 6, elapsedMs: 1000 }, + }) + expect(card.estimatedSkuCount).toBe(2) + expect(card.pendingSkuCount).toBe(1) + expect(card.totalRange).toEqual({ min: 200, max: 380 }) + expect(card.confidence).toBe(0.55) + expect(card.openQuestions).toEqual(['板厚未确认', '铰链数量按两门推定']) + const board = card.breakdown.find((row) => row.category === 'BOARD') + expect(board?.total).toBe(440) + const labor = card.breakdown.find((row) => row.category === 'LABOR') + expect(labor?.total).toBe(40) + const packaging = card.breakdown.find((row) => row.category === 'PACKAGING') + expect(packaging?.total).toBeNull() + expect(card.skus.find((sku) => sku.skuId === 'c')?.status).toBe('PENDING') + }) + + it('全部未核算时区间为 null,FAILED 不计入已核算数', () => { + const card = buildEstimateCard({ + caseId: 'case-1', + title: 't', + skus: [skuInput({ skuId: 'a' }), skuInput({ skuId: 'b' })], + firstBatchSkuIds: ['a'], + resultsBySkuId: new Map([['a', { status: 'FAILED' as const }]]), + usage: { rounds: 0, modelCalls: 0, elapsedMs: 5 }, + }) + expect(card.totalRange).toBeNull() + expect(card.confidence).toBeNull() + expect(card.failedSkuCount).toBe(1) + expect(card.estimatedSkuCount).toBe(0) + }) +}) diff --git a/furniture-3d-system/src/server/services/bom-costing/agent/agent-estimate-card.ts b/furniture-3d-system/src/server/services/bom-costing/agent/agent-estimate-card.ts new file mode 100644 index 00000000..dc6119b1 --- /dev/null +++ b/furniture-3d-system/src/server/services/bom-costing/agent/agent-estimate-card.ts @@ -0,0 +1,168 @@ +import type { BomCostingAgentEstimate } from './agent-contracts' +import type { BomCostingAgentRunResult } from './agent-contracts' + +// EstimateCard 契约(设计文档 5.2):case 级预估卡的纯数据形状与聚合规则。 +// 聚合全部由代码完成:模型只产出单 SKU 的 estimate,这里负责五行构成、 +// 区间包络、置信度(取最小)与不确定点并集。 + +export const BOM_COSTING_AGENT_ENGINE_VERSION = 'bom-costing-agent-card/v1' + +export type BomEstimateSkuStatus = 'ESTIMATED' | 'PENDING' | 'FAILED' | 'RUNNING' + +export interface BomEstimateSkuEntry { + externalSkuId: string + name: string + status: BomEstimateSkuStatus + estimate?: BomCostingAgentEstimate + warnings?: string[] + cachedAt?: string +} + +export interface BomEstimateCardBreakdownRow { + category: 'BOARD' | 'STEEL' | 'ACCESSORY' | 'PACKAGING' | 'PROCESSING' | 'LABOR' + total: number | null +} + +export interface BomEstimateCard { + caseId: string + title: string + engineVersion: string + skus: Array + firstBatchSkuIds: string[] + breakdown: BomEstimateCardBreakdownRow[] + totalRange: { min: number; max: number } | null + confidence: number | null + openQuestions: string[] + estimatedSkuCount: number + pendingSkuCount: number + failedSkuCount: number + usage: { rounds: number; modelCalls: number; elapsedMs: number } +} + +export interface BomEstimateSkuInput { + skuId: string + externalSkuId: string + name: string + lengthMm: number | null + widthMm: number | null + heightMm: number | null +} + +// 首批代表 SKU 选择(跨度原则):按最大外形轴排序后取 最小/中位/最大 三个, +// 返回保持原清单顺序;尺寸全缺的 SKU 排在末位不参与代表选择(除非没有别的可选)。 +export function selectFirstBatchSkus( + skus: readonly T[], + limit = 3, +): T[] { + if (skus.length <= limit) return [...skus] + const metric = (sku: T) => { + const values = [sku.lengthMm, sku.widthMm, sku.heightMm] + .filter((value): value is number => value !== null && Number.isFinite(value) && value > 0) + return values.length > 0 ? Math.max(...values) : 0 + } + const ordered = [...skus] + .map((sku, index) => ({ sku, index, metric: metric(sku) })) + .sort((left, right) => left.metric - right.metric || left.index - right.index) + const withDimension = ordered.filter((item) => item.metric > 0) + const picks = new Set() + if (withDimension.length >= 3) { + picks.add(withDimension[0]!.index) + picks.add(withDimension[Math.floor((withDimension.length - 1) / 2)].index) + picks.add(withDimension[withDimension.length - 1]!.index) + } else { + for (const item of withDimension) picks.add(item.index) + } + if (picks.size < limit) { + for (const item of ordered) { + if (picks.size >= limit) break + picks.add(item.index) + } + } + return [...picks].sort((left, right) => left - right).map((index) => skus[index]!) +} + +function roundMoney(value: number) { + return Math.round(value * 100) / 100 +} + +const BREAKDOWN_CATEGORIES: BomEstimateCardBreakdownRow['category'][] = [ + 'BOARD', + 'STEEL', + 'ACCESSORY', + 'PACKAGING', + 'PROCESSING', + 'LABOR', +] + +export interface BomEstimateBuildInput { + caseId: string + title: string + skus: readonly BomEstimateSkuInput[] + firstBatchSkuIds: readonly string[] + resultsBySkuId: ReadonlyMap + usage: { rounds: number; modelCalls: number; elapsedMs: number } +} + +export function buildEstimateCard(input: BomEstimateBuildInput): BomEstimateCard { + const firstBatch = new Set(input.firstBatchSkuIds) + const totalsByCategory = new Map() + let rangeMin = Number.POSITIVE_INFINITY + let rangeMax = Number.NEGATIVE_INFINITY + let confidence: number | null = null + const openQuestions = new Set() + let estimatedSkuCount = 0 + let failedSkuCount = 0 + + const skus = input.skus.map((sku) => { + const result = input.resultsBySkuId.get(sku.skuId) + const status: BomEstimateSkuStatus = result?.status ?? 'PENDING' + if (status === 'ESTIMATED' && result?.runResult?.estimate) { + estimatedSkuCount += 1 + const estimate = result.runResult.estimate + for (const [category, total] of Object.entries(result.runResult.categoryTotals ?? {})) { + if (category === 'unresolvedLineCount' || typeof total !== 'number') continue + totalsByCategory.set(category, roundMoney((totalsByCategory.get(category) ?? 0) + total)) + } + if (estimate.estimateRange.min < rangeMin) rangeMin = estimate.estimateRange.min + if (estimate.estimateRange.max > rangeMax) rangeMax = estimate.estimateRange.max + if (confidence === null || estimate.confidence < confidence) confidence = estimate.confidence + for (const question of estimate.openQuestions) openQuestions.add(question) + } + if (status === 'FAILED') failedSkuCount += 1 + return { + skuId: sku.skuId, + externalSkuId: sku.externalSkuId, + name: sku.name, + status, + estimate: status === 'ESTIMATED' ? result?.runResult?.estimate ?? undefined : undefined, + warnings: status === 'ESTIMATED' ? result?.runResult?.warnings : undefined, + cachedAt: result?.cachedAt, + firstBatch: firstBatch.has(sku.skuId), + } + }) + + return { + caseId: input.caseId, + title: input.title, + engineVersion: BOM_COSTING_AGENT_ENGINE_VERSION, + skus, + firstBatchSkuIds: [...input.firstBatchSkuIds], + breakdown: BREAKDOWN_CATEGORIES.map((category) => ({ + category, + total: totalsByCategory.get(category) ?? null, + })), + totalRange: Number.isFinite(rangeMin) && Number.isFinite(rangeMax) + ? { min: roundMoney(rangeMin), max: roundMoney(rangeMax) } + : null, + confidence, + openQuestions: [...openQuestions], + estimatedSkuCount, + pendingSkuCount: input.skus.length - estimatedSkuCount - failedSkuCount, + failedSkuCount, + usage: input.usage, + } +} diff --git a/furniture-3d-system/src/server/services/bom-costing/agent/agent-tool-providers.test.ts b/furniture-3d-system/src/server/services/bom-costing/agent/agent-tool-providers.test.ts index 0d17dec2..30ab1a04 100644 --- a/furniture-3d-system/src/server/services/bom-costing/agent/agent-tool-providers.test.ts +++ b/furniture-3d-system/src/server/services/bom-costing/agent/agent-tool-providers.test.ts @@ -1,6 +1,8 @@ import { Prisma } from '@prisma/client' import { bomCostingAgentRepository } from '@/server/repositories/bom-costing-agent.repository' +import { bomCostingScenarioRepository } from '@/server/repositories/bom-costing-scenario.repository' import { bomCosting1688ImageSearchService } from '../bom-costing-1688-image-search' +import { buildCategoryProfileEstimate } from '../bom-costing-scenario.service' import { createDefaultBomCostingAgentToolDeps } from './agent-tool-providers' jest.mock('@/server/repositories/bom-costing-agent.repository', () => ({ @@ -11,14 +13,37 @@ jest.mock('@/server/repositories/bom-costing-agent.repository', () => ({ }, })) +jest.mock('@/server/repositories/bom-costing-scenario.repository', () => ({ + bomCostingScenarioRepository: { + findLatestSyncStatuses: jest.fn(), + findReferenceCandidates: jest.fn(), + findCategoryCohortCandidates: jest.fn(), + }, +})) + jest.mock('../bom-costing-1688-image-search', () => ({ bomCosting1688ImageSearchService: { findRealtimeQuote: jest.fn(), }, })) +jest.mock('../bom-costing-scenario.service', () => ({ + buildCategoryProfileEstimate: jest.fn(), +})) + const repositoryMock = jest.mocked(bomCostingAgentRepository) +const scenarioRepositoryMock = jest.mocked(bomCostingScenarioRepository) const realtimeMock = jest.mocked(bomCosting1688ImageSearchService) +const profileBuilderMock = jest.mocked(buildCategoryProfileEstimate) + +function latestSyncRun(id: string | null) { + scenarioRepositoryMock.findLatestSyncStatuses.mockResolvedValue({ + latestSuccessful: id === null ? null : { id } as never, + latestFailed: null, + mirrorState: id === null ? 'EMPTY' : 'READY', + mirrorRunIds: id === null ? [] : [id], + }) +} describe('createDefaultBomCostingAgentToolDeps', () => { beforeEach(() => { @@ -114,4 +139,145 @@ describe('createDefaultBomCostingAgentToolDeps', () => { }) expect(Object.keys(summary as Record)).not.toContain('warnings') }) + + it('searchMirrorCandidates 锁定最新成功批次并做尺寸感知检索映射', async () => { + latestSyncRun('run-1') + scenarioRepositoryMock.findReferenceCandidates.mockResolvedValue([ + { + id: 'c1', + sourceRowId: 'row-9', + sourceSku: 'SKU-Z', + bomVersionKey: 'v1', + category: '板材', + categoryCode: 'BOARD', + partNumber: '', + partName: '侧板', + materialName: '白蜡木拼板 18mm', + materialCode: '', + materialSpec: '1220x2440', + processName: '', + unit: '块', + quantity: new Prisma.Decimal('2'), + coefficient: null, + rawCoefficient: null, + lengthMm: new Prisma.Decimal('800'), + widthMm: new Prisma.Decimal('400'), + areaSqm: new Prisma.Decimal('0.64'), + edgeLengthM: null, + unitPrice: new Prisma.Decimal('33.30'), + amount: new Prisma.Decimal('66.60'), + sourceCreatedAt: new Date('2026-08-01'), + syncedAt: new Date('2026-08-02'), + }, + ] as never) + const deps = createDefaultBomCostingAgentToolDeps() + const candidates = await deps.searchMirrorCandidates({ + category: 'BOARD', + partName: '侧板', + materialKeywords: ['白蜡木', '拼板'], + lengthMm: 800, + widthMm: 400, + }, { caseId: 'c' }) + expect(scenarioRepositoryMock.findLatestSyncStatuses).toHaveBeenCalledTimes(1) + expect(scenarioRepositoryMock.findReferenceCandidates).toHaveBeenCalledWith(expect.objectContaining({ + syncRunId: 'run-1', + category: 'BOARD', + partName: '侧板', + materialName: '白蜡木 拼板', + lengthMm: 800, + widthMm: 400, + })) + expect(candidates).toEqual([{ + sourceRowId: 'row-9', + sourceSku: 'SKU-Z', + partName: '侧板', + materialName: '白蜡木拼板 18mm', + materialSpec: '1220x2440', + unit: '块', + unitPrice: 33.3, + amount: 66.6, + quantity: 2, + lengthMm: 800, + widthMm: 400, + areaSqm: 0.64, + }]) + }) + + it('searchMirrorCandidates 无成功同步批次时返回空而不抛错', async () => { + latestSyncRun(null) + const deps = createDefaultBomCostingAgentToolDeps() + const candidates = await deps.searchMirrorCandidates({ category: 'BOARD' }, { caseId: 'c' }) + expect(candidates).toEqual([]) + expect(scenarioRepositoryMock.findReferenceCandidates).not.toHaveBeenCalled() + }) + + it('getCategoryProfileEstimate 三级级联:同族命中即返回', async () => { + latestSyncRun('run-1') + const profile = { + basis: 'SKU_FAMILY' as const, + total: 268.5, + estimateRange: { min: 240, max: 300 }, + medianLineCount: 9, + medianLineAmount: 30, + medianPhysicalQuantity: 2.4, + physicalUnit: 'AREA_SQM' as const, + lossFactor: 1, + sampleCount: 12, + rawSampleCount: 14, + outlierCount: 2, + } + profileBuilderMock.mockReturnValueOnce(profile) + scenarioRepositoryMock.findCategoryCohortCandidates.mockResolvedValue([] as never) + + const deps = createDefaultBomCostingAgentToolDeps() + const result = await deps.getCategoryProfileEstimate({ + category: 'BOARD', + familyReferenceSkus: ['SKU-A'], + similarReferenceSkus: ['SKU-B'], + }, { caseId: 'c' }) + + expect(result).toEqual({ + basis: 'SKU_FAMILY', + total: 268.5, + estimateRange: { min: 240, max: 300 }, + medianLineCount: 9, + medianPhysicalQuantity: 2.4, + physicalUnit: 'AREA_SQM', + sampleCount: 12, + }) + expect(scenarioRepositoryMock.findCategoryCohortCandidates).toHaveBeenCalledTimes(1) + }) + + it('getCategoryProfileEstimate 同族与相似皆缺时回退同分类 cohort,全缺返回 NONE', async () => { + latestSyncRun('run-1') + profileBuilderMock.mockReturnValueOnce(null).mockReturnValueOnce(null).mockReturnValueOnce({ + basis: 'CATEGORY_COHORT', + total: 180, + estimateRange: { min: 150, max: 220 }, + medianLineCount: 7, + medianLineAmount: 26, + medianPhysicalQuantity: null, + physicalUnit: null, + lossFactor: 1, + sampleCount: 30, + rawSampleCount: 33, + outlierCount: 3, + }) + scenarioRepositoryMock.findCategoryCohortCandidates.mockResolvedValue([] as never) + const deps = createDefaultBomCostingAgentToolDeps() + + const result = await deps.getCategoryProfileEstimate({ + category: 'LABOR', + familyReferenceSkus: ['SKU-A'], + similarReferenceSkus: ['SKU-B'], + }, { caseId: 'c' }) + expect(result).toMatchObject({ basis: 'CATEGORY_COHORT', total: 180, sampleCount: 30 }) + expect(scenarioRepositoryMock.findCategoryCohortCandidates).toHaveBeenCalledTimes(3) + + profileBuilderMock.mockReset() + profileBuilderMock.mockReturnValue(null) + const none = await deps.getCategoryProfileEstimate({ category: 'LABOR' }, { caseId: 'c' }) + expect(none).toEqual({ basis: 'NONE' }) + expect(profileBuilderMock).toHaveBeenCalledTimes(1) + }) }) diff --git a/furniture-3d-system/src/server/services/bom-costing/agent/agent-tool-providers.ts b/furniture-3d-system/src/server/services/bom-costing/agent/agent-tool-providers.ts index 455459c1..63def8d3 100644 --- a/furniture-3d-system/src/server/services/bom-costing/agent/agent-tool-providers.ts +++ b/furniture-3d-system/src/server/services/bom-costing/agent/agent-tool-providers.ts @@ -1,11 +1,36 @@ import { bomCostingAgentRepository } from '@/server/repositories/bom-costing-agent.repository' +import { bomCostingScenarioRepository } from '@/server/repositories/bom-costing-scenario.repository' import { bomCosting1688ImageSearchService } from '../bom-costing-1688-image-search' +import { buildCategoryProfileEstimate, type CategoryProfileEstimate } from '../bom-costing-scenario.service' import type { BomCostingAgentToolDeps } from './agent-tools' +function candidateNumber(value: unknown): number | null { + if (value === null || value === undefined) return null + const parsed = Number(value) + return Number.isFinite(parsed) ? parsed : null +} + +function toProfileSummary(estimate: CategoryProfileEstimate) { + return { + basis: estimate.basis, + total: estimate.total, + estimateRange: estimate.estimateRange, + medianLineCount: estimate.medianLineCount, + medianPhysicalQuantity: estimate.medianPhysicalQuantity, + physicalUnit: estimate.physicalUnit, + sampleCount: estimate.sampleCount, + } +} + // 工具接线层:repository 只出原始行,这里负责映射成 agent 可消费的摘要。 // 实时行情工具刻意只透出状态/采购参考价/区间/可比数,warnings 与 offers // 留在服务端内部,避免进入 agent 转录后流向前端。 export function createDefaultBomCostingAgentToolDeps(): BomCostingAgentToolDeps { + // 价格工具共用的数据边界:只允许最新成功同步批次成为定价来源。 + async function latestSuccessfulSyncRunId() { + const { latestSuccessful } = await bomCostingScenarioRepository.findLatestSyncStatuses() + return latestSuccessful?.id ?? null + } return { listArchivedImages: async (context) => { const assets = await bomCostingAgentRepository.listArchivedAssetsForCase(context.caseId) @@ -32,6 +57,66 @@ export function createDefaultBomCostingAgentToolDeps(): BomCostingAgentToolDeps sourceRowId: row.sourceRowId, })) }, + searchMirrorCandidates: async (input) => { + const syncRunId = await latestSuccessfulSyncRunId() + if (!syncRunId) return [] + const candidates = await bomCostingScenarioRepository.findReferenceCandidates({ + syncRunId, + category: input.category, + partName: input.partName ?? null, + // nonEmptyTokens 会按空白分词并为每个关键词生成多形态 token, + // 因此多关键词以空格拼接传入即可。 + materialName: input.materialKeywords && input.materialKeywords.length > 0 + ? input.materialKeywords.join(' ') + : null, + lengthMm: input.lengthMm ?? null, + widthMm: input.widthMm ?? null, + referenceSkus: input.referenceSkus, + limit: input.limit, + }) + return candidates.map((candidate) => ({ + sourceRowId: candidate.sourceRowId, + sourceSku: candidate.sourceSku, + partName: candidate.partName, + materialName: candidate.materialName, + materialSpec: candidate.materialSpec, + unit: candidate.unit, + unitPrice: candidateNumber(candidate.unitPrice), + amount: candidateNumber(candidate.amount), + quantity: candidateNumber(candidate.quantity), + lengthMm: candidateNumber(candidate.lengthMm), + widthMm: candidateNumber(candidate.widthMm), + areaSqm: candidateNumber(candidate.areaSqm), + })) + }, + getCategoryProfileEstimate: async (input) => { + const syncRunId = await latestSuccessfulSyncRunId() + if (!syncRunId) return { basis: 'NONE' as const } + const cascade = async ( + basis: CategoryProfileEstimate['basis'], + referenceSkus: string[] | undefined, + ) => { + if (!referenceSkus || referenceSkus.length === 0) return null + const candidates = await bomCostingScenarioRepository.findCategoryCohortCandidates({ + syncRunId, + category: input.category, + referenceSkus, + limit: 500, + }) + return buildCategoryProfileEstimate(candidates, basis, input.category) + } + const family = await cascade('SKU_FAMILY', input.familyReferenceSkus) + if (family) return toProfileSummary(family) + const similar = await cascade('SIMILAR_HISTORY', input.similarReferenceSkus) + if (similar) return toProfileSummary(similar) + const cohortCandidates = await bomCostingScenarioRepository.findCategoryCohortCandidates({ + syncRunId, + category: input.category, + limit: 500, + }) + const cohort = buildCategoryProfileEstimate(cohortCandidates, 'CATEGORY_COHORT', input.category) + return cohort ? toProfileSummary(cohort) : { basis: 'NONE' as const } + }, listMaterialOptions: async () => { const options = await bomCostingAgentRepository.listEnabledMaterialOptions() return options.map((option) => ({ diff --git a/furniture-3d-system/src/server/services/bom-costing/agent/agent-tools.ts b/furniture-3d-system/src/server/services/bom-costing/agent/agent-tools.ts index c3260982..eb29bf3f 100644 --- a/furniture-3d-system/src/server/services/bom-costing/agent/agent-tools.ts +++ b/furniture-3d-system/src/server/services/bom-costing/agent/agent-tools.ts @@ -47,12 +47,53 @@ export interface BomCostingAgentRealtimeQuoteSummary { comparableOfferCount: number } +export interface BomCostingAgentMirrorCandidate { + sourceRowId: string + sourceSku: string + partName: string + materialName: string + materialSpec: string + unit: string + unitPrice: number | null + amount: number | null + quantity: number | null + lengthMm: number | null + widthMm: number | null + areaSqm: number | null +} + +export interface BomCostingAgentCategoryProfile { + basis: 'SKU_FAMILY' | 'SIMILAR_HISTORY' | 'CATEGORY_COHORT' + total: number + estimateRange: { min: number; max: number } + medianLineCount: number + medianPhysicalQuantity: number | null + physicalUnit: 'AREA_SQM' | null + sampleCount: number +} + export interface BomCostingAgentToolDeps { listArchivedImages: (context: BomCostingAgentToolContext) => Promise searchReferencePrices: ( input: { category?: string; materialKeywords?: string[]; limit?: number }, context: BomCostingAgentToolContext, ) => Promise + searchMirrorCandidates: ( + input: { + category: string + partName?: string + materialKeywords?: string[] + lengthMm?: number + widthMm?: number + referenceSkus?: string[] + limit?: number + }, + context: BomCostingAgentToolContext, + ) => Promise + getCategoryProfileEstimate: ( + input: { category: string; familyReferenceSkus?: string[]; similarReferenceSkus?: string[] }, + context: BomCostingAgentToolContext, + ) => Promise listMaterialOptions: (context: BomCostingAgentToolContext) => Promise searchRealtimeMarket: ( input: { imageUrl: string }, @@ -163,6 +204,55 @@ export function createBomCostingAgentTools(deps: BomCostingAgentToolDeps) { }, context) }, }, + { + name: 'search_mirror_candidates', + description: + '尺寸感知的公司历史 BOM 行级检索(定价首选)。输入 {category(BOARD|STEEL|ACCESSORY|PACKAGING|PROCESSING|LABOR), ' + + 'partName?, materialKeywords?, lengthMm?, widthMm?, referenceSkus?, limit?};' + + '板件长宽按 ±20% 尺寸带匹配(BOARD 尺寸无匹配时不做无尺寸兜底,防止以小充大);' + + '返回候选行的单价/金额/尺寸/来源 SKU,可直接作为该行定价依据。', + execute: (input: unknown, context: BomCostingAgentToolContext) => { + const record = typeof input === 'object' && input !== null ? input as Record : {} + if (typeof record.category !== 'string' || !record.category.trim()) { + return Promise.resolve({ error: '输入不合法:category 必填(BOARD|STEEL|ACCESSORY|PACKAGING|PROCESSING|LABOR)' }) + } + return deps.searchMirrorCandidates({ + category: record.category.trim(), + partName: typeof record.partName === 'string' ? record.partName : undefined, + materialKeywords: Array.isArray(record.materialKeywords) + ? record.materialKeywords.filter((item): item is string => typeof item === 'string' && item.trim() !== '') + : undefined, + lengthMm: typeof record.lengthMm === 'number' ? record.lengthMm : undefined, + widthMm: typeof record.widthMm === 'number' ? record.widthMm : undefined, + referenceSkus: Array.isArray(record.referenceSkus) + ? record.referenceSkus.filter((item): item is string => typeof item === 'string' && item.trim() !== '') + : undefined, + limit: typeof record.limit === 'number' ? record.limit : undefined, + }, context) + }, + }, + { + name: 'get_category_profile', + description: + '按分类获取公司历史整套 BOM 的中位总额(同名 SKU 族 → 相似整套 → 同分类三级回退)。' + + '输入 {category, familyReferenceSkus?, similarReferenceSkus?};' + + '返回中位总额/区间/中位行数/中位板件面积(BOARD)与样本数,用于整套级别兜底价或合理性校验。', + execute: (input: unknown, context: BomCostingAgentToolContext) => { + const record = typeof input === 'object' && input !== null ? input as Record : {} + if (typeof record.category !== 'string' || !record.category.trim()) { + return Promise.resolve({ error: '输入不合法:category 必填' }) + } + return deps.getCategoryProfileEstimate({ + category: record.category.trim(), + familyReferenceSkus: Array.isArray(record.familyReferenceSkus) + ? record.familyReferenceSkus.filter((item): item is string => typeof item === 'string' && item.trim() !== '') + : undefined, + similarReferenceSkus: Array.isArray(record.similarReferenceSkus) + ? record.similarReferenceSkus.filter((item): item is string => typeof item === 'string' && item.trim() !== '') + : undefined, + }, context) + }, + }, { name: 'list_material_options', description: '列出公司启用材质目录(材质身份的唯一来源,含别名)。', diff --git a/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-case-runner.test.ts b/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-case-runner.test.ts new file mode 100644 index 00000000..c0e77dd6 --- /dev/null +++ b/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-case-runner.test.ts @@ -0,0 +1,206 @@ +import { bomCostingAgentRepository } from '@/server/repositories/bom-costing-agent.repository' +import { runBomCostingAgentEstimateForCase, estimateSkuOnDemand } from './bom-costing-agent-case-runner' +import { runBomCostingAgentTrialForSku } from './bom-costing-agent-runner' +import type { BomCostingAgentRunResult } from './agent-contracts' + +jest.mock('@/server/repositories/bom-costing-agent.repository', () => ({ + bomCostingAgentRepository: { + findCaseForAgentTrial: jest.fn(), + listSkusForCase: jest.fn(), + listCachedSkuEstimates: jest.fn(), + findCachedSkuEstimate: jest.fn(), + upsertCachedSkuEstimate: jest.fn(), + findSkuForAgentTrial: jest.fn(), + listArchivedAssetsForCase: jest.fn(), + }, +})) + +jest.mock('./bom-costing-agent-runner', () => ({ + runBomCostingAgentTrialForSku: jest.fn(), +})) + +const repositoryMock = jest.mocked(bomCostingAgentRepository) +const trialMock = jest.mocked(runBomCostingAgentTrialForSku) + +function skuRow(id: string, externalSkuId: string, lengthMm: number | null) { + return { + id, + externalSkuId, + name: `n-${externalSkuId}`, + lengthMm, + widthMm: null, + heightMm: null, + sortOrder: 0, + } +} + +function completedResult(range: [number, number], confidence: number): BomCostingAgentRunResult { + return { + status: 'COMPLETED', + estimate: { + structureSummary: 's', + lines: [], + confidence, + estimateRange: { min: range[0], max: range[1] }, + openQuestions: ['板厚未确认'], + }, + categoryTotals: { BOARD: 100, unresolvedLineCount: 0 } as never, + warnings: [], + trace: [], + usage: { rounds: 3, modelCalls: 3, elapsedMs: 50 }, + } +} + +function cacheEntry(skuId: string, status: string) { + return { + id: `cache-${skuId}`, + caseId: 'case-1', + skuId, + externalSkuId: 'S', + engineVersion: 'bom-costing-agent-card/v1', + status, + estimate: completedResult([100, 120], 0.6), + usage: {}, + createdAt: new Date('2026-09-16T00:00:00Z'), + updatedAt: new Date('2026-09-16T01:00:00Z'), + } +} + +beforeEach(() => { + jest.clearAllMocks() + repositoryMock.findCaseForAgentTrial.mockResolvedValue({ + id: 'case-1', + title: '测试衣柜', + sourceHost: 'taobao.com', + status: 'READY' as never, + skillCode: 'WARDROBE', + }) + repositoryMock.listSkusForCase.mockResolvedValue([ + skuRow('s-small', 'S1', 900), + skuRow('s-mid', 'S2', 1300), + skuRow('s-large', 'S3', 1900), + skuRow('s-extra', 'S4', 2200), + ] as never) + repositoryMock.listCachedSkuEstimates.mockResolvedValue([] as never) + repositoryMock.upsertCachedSkuEstimate.mockResolvedValue({} as never) +}) + +describe('runBomCostingAgentEstimateForCase', () => { + it('首批只精算 3 个代表 SKU,其余保持 PENDING,卡片聚合正确', async () => { + trialMock.mockImplementation(async ({ skuId }) => ({ + caseId: 'case-1', + skuId: skuId!, + externalSkuId: 'S', + skillCode: null, + selectedImageCount: 8, + result: completedResult(skuId === 's-small' ? [200, 260] : [300, 380], 0.6), + })) + + const { card } = await runBomCostingAgentEstimateForCase({ caseId: 'case-1' }) + + expect(trialMock).toHaveBeenCalledTimes(3) + // 跨度原则:最小/中位/最大(s-extra 是最大外形轴) + expect(card.firstBatchSkuIds).toEqual(['s-small', 's-mid', 's-extra']) + expect(card.estimatedSkuCount).toBe(3) + expect(card.pendingSkuCount).toBe(1) + expect(card.totalRange).toEqual({ min: 200, max: 380 }) + expect(card.title).toBe('测试衣柜') + const extra = card.skus.find((sku) => sku.skuId === 's-large') + expect(extra?.status).toBe('PENDING') + expect(extra?.firstBatch).toBe(false) + expect(repositoryMock.upsertCachedSkuEstimate).toHaveBeenCalledTimes(3) + }) + + it('缓存命中跳过模型调用;失败缓存不作为有效结果', async () => { + repositoryMock.listCachedSkuEstimates.mockResolvedValue([ + cacheEntry('s-small', 'COMPLETED'), + cacheEntry('s-mid', 'FAILED'), + ] as never) + trialMock.mockImplementation(async ({ skuId }) => ({ + caseId: 'case-1', + skuId: skuId!, + externalSkuId: 'S', + skillCode: null, + selectedImageCount: 4, + result: completedResult([280, 340], 0.5), + })) + + const { card } = await runBomCostingAgentEstimateForCase({ caseId: 'case-1' }) + + // s-small 缓存命中不重跑;s-mid 是 FAILED 缓存 → 重算;s-extra 首批新算 + expect(trialMock).toHaveBeenCalledTimes(2) + expect(card.estimatedSkuCount).toBe(3) + expect(repositoryMock.upsertCachedSkuEstimate).toHaveBeenCalledTimes(2) + }) + + it('首批单个 SKU 失败不拖垮整卡', async () => { + trialMock.mockImplementation(async ({ skuId }) => { + if (skuId === 's-mid') throw new Error('模型调用失败') + return { + caseId: 'case-1', + skuId: skuId!, + externalSkuId: 'S', + skillCode: null, + selectedImageCount: 4, + result: completedResult([240, 300], 0.5), + } + }) + + const { card } = await runBomCostingAgentEstimateForCase({ caseId: 'case-1' }) + + expect(card.failedSkuCount).toBe(1) + expect(card.estimatedSkuCount).toBe(2) + expect(card.totalRange).toEqual({ min: 240, max: 300 }) + }) +}) + +describe('estimateSkuOnDemand', () => { + it('有效缓存直接返回,不再调用模型', async () => { + repositoryMock.findCachedSkuEstimate.mockResolvedValue(cacheEntry('s-extra', 'COMPLETED') as never) + const entry = await estimateSkuOnDemand({ caseId: 'case-1', skuId: 's-extra' }) + expect(entry.status).toBe('ESTIMATED') + expect(entry.cachedAt).toBe('2026-09-16T01:00:00.000Z') + expect(trialMock).not.toHaveBeenCalled() + }) + + it('无缓存时运行并落缓存', async () => { + repositoryMock.findCachedSkuEstimate.mockResolvedValue(null) + repositoryMock.findSkuForAgentTrial.mockResolvedValue({ + id: 's-extra', + caseId: 'case-1', + externalSkuId: 'S4', + name: 'n-S4', + lengthMm: null, + widthMm: null, + heightMm: null, + weightKg: null, + packageWeightKg: null, + sortOrder: 3, + } as never) + trialMock.mockResolvedValue({ + caseId: 'case-1', + skuId: 's-extra', + externalSkuId: 'S4', + skillCode: null, + selectedImageCount: 6, + result: completedResult([260, 320], 0.55), + }) + + const entry = await estimateSkuOnDemand({ caseId: 'case-1', skuId: 's-extra' }) + expect(entry.status).toBe('ESTIMATED') + expect(trialMock).toHaveBeenCalledTimes(1) + expect(repositoryMock.upsertCachedSkuEstimate).toHaveBeenCalledWith(expect.objectContaining({ + caseId: 'case-1', + skuId: 's-extra', + engineVersion: 'bom-costing-agent-card/v1', + status: 'ESTIMATED', + })) + }) + + it('SKU 不属于该案例时抛错', async () => { + repositoryMock.findCachedSkuEstimate.mockResolvedValue(null) + repositoryMock.findSkuForAgentTrial.mockResolvedValue(null) + await expect(estimateSkuOnDemand({ caseId: 'case-1', skuId: 'other' })) + .rejects.toThrow('SKU 不属于该案例') + }) +}) diff --git a/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-case-runner.ts b/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-case-runner.ts new file mode 100644 index 00000000..967d1102 --- /dev/null +++ b/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-case-runner.ts @@ -0,0 +1,212 @@ +import { bomCostingAgentRepository } from '@/server/repositories/bom-costing-agent.repository' +import type { BomCostingAgentRunResult } from './agent-contracts' +import { + BOM_COSTING_AGENT_ENGINE_VERSION, + buildEstimateCard, + selectFirstBatchSkus, + type BomEstimateCard, + type BomEstimateSkuStatus, +} from './agent-estimate-card' +import { runBomCostingAgentTrialForSku } from './bom-costing-agent-runner' + +// case 级旁路编排(设计文档 5.1):首批自动精算 + 其余按需点算。 +// 只读案例数据、只写 agent 缓存表,不进处理管线。 + +export interface BomCostingCaseEstimateResult { + card: BomEstimateCard +} + +type SkuResultEntry = { + status: BomEstimateSkuStatus + runResult?: BomCostingAgentRunResult + cachedAt?: string +} + +export interface BomCostingCaseEstimateOptions { + firstBatchLimit?: number + maxImages?: number + signal?: AbortSignal +} + +function runResultStatusToSkuStatus(status: BomCostingAgentRunResult['status']): BomEstimateSkuStatus { + // PARTIAL(结构有行但全未定价)也是合法产物:出结果、区间放宽、不确定点说明。 + return status === 'FAILED' ? 'FAILED' : 'ESTIMATED' +} + +// 缓存行是写入时的原始状态;读取时归一化为卡片状态口径(容错历史 COMPLETED/PARTIAL)。 +function cachedStatusToSkuStatus(status: string): BomEstimateSkuStatus { + return status === 'COMPLETED' || status === 'PARTIAL' ? 'ESTIMATED' : status === 'FAILED' ? 'FAILED' : 'PENDING' +} + +async function estimateSingleSku(input: { + caseId: string + skuId: string + externalSkuId: string + maxImages?: number + signal?: AbortSignal +}): Promise { + const trial = await runBomCostingAgentTrialForSku({ + caseId: input.caseId, + skuId: input.skuId, + maxImages: input.maxImages, + signal: input.signal, + }) + const status = runResultStatusToSkuStatus(trial.result.status) + await bomCostingAgentRepository.upsertCachedSkuEstimate({ + caseId: input.caseId, + skuId: input.skuId, + externalSkuId: input.externalSkuId, + engineVersion: BOM_COSTING_AGENT_ENGINE_VERSION, + status, + estimate: trial.result, + usage: trial.result.usage, + }) + return { + status, + runResult: trial.result, + cachedAt: new Date().toISOString(), + } +} + +export async function runBomCostingAgentEstimateForCase(input: { + caseId: string + options?: BomCostingCaseEstimateOptions +}): Promise { + const options = input.options ?? {} + const startedAt = Date.now() + const brief = await bomCostingAgentRepository.findCaseForAgentTrial(input.caseId) + if (!brief) throw new Error(`案例不存在或已删除:${input.caseId}`) + const skus = await bomCostingAgentRepository.listSkusForCase(input.caseId) + if (skus.length === 0) throw new Error(`案例没有 SKU:${input.caseId}`) + + const cache = await bomCostingAgentRepository.listCachedSkuEstimates( + input.caseId, + BOM_COSTING_AGENT_ENGINE_VERSION, + ) + const resultsBySkuId = new Map() + + for (const entry of cache) { + if (entry.status === 'FAILED') continue + resultsBySkuId.set(entry.skuId, { + status: cachedStatusToSkuStatus(entry.status), + runResult: entry.estimate as unknown as BomCostingAgentRunResult, + cachedAt: entry.updatedAt.toISOString(), + }) + } + + const firstBatch = selectFirstBatchSkus( + skus.map((sku) => ({ + skuId: sku.id, + externalSkuId: sku.externalSkuId, + name: sku.name, + lengthMm: sku.lengthMm === null ? null : Number(sku.lengthMm), + widthMm: sku.widthMm === null ? null : Number(sku.widthMm), + heightMm: sku.heightMm === null ? null : Number(sku.heightMm), + })), + options.firstBatchLimit ?? 3, + ) + const firstBatchSkuIds = firstBatch.map((sku) => sku.skuId) + + for (const sku of firstBatch) { + if (resultsBySkuId.has(sku.skuId)) continue + try { + resultsBySkuId.set(sku.skuId, await estimateSingleSku({ + caseId: input.caseId, + skuId: sku.skuId, + externalSkuId: sku.externalSkuId, + maxImages: options.maxImages, + signal: options.signal, + })) + } catch (error) { + console.warn(`[BOM agent] 首批 SKU 估算失败 sku=${sku.externalSkuId}:`, + error instanceof Error ? error.message : error) + resultsBySkuId.set(sku.skuId, { status: 'FAILED' }) + } + } + + const card = buildEstimateCard({ + caseId: input.caseId, + title: brief.title, + skus: skus.map((sku) => ({ + skuId: sku.id, + externalSkuId: sku.externalSkuId, + name: sku.name, + lengthMm: sku.lengthMm === null ? null : Number(sku.lengthMm), + widthMm: sku.widthMm === null ? null : Number(sku.widthMm), + heightMm: sku.heightMm === null ? null : Number(sku.heightMm), + })), + firstBatchSkuIds, + resultsBySkuId, + usage: { + rounds: 0, + modelCalls: 0, + elapsedMs: Date.now() - startedAt, + }, + }) + return { card } +} + +// 只读卡片:仅从缓存表聚合,不发起任何模型调用(GET / 前端刷新用)。 +export async function getAgentEstimateCard(caseId: string): Promise { + const brief = await bomCostingAgentRepository.findCaseForAgentTrial(caseId) + if (!brief) return null + const skus = await bomCostingAgentRepository.listSkusForCase(caseId) + const cache = await bomCostingAgentRepository.listCachedSkuEstimates( + caseId, + BOM_COSTING_AGENT_ENGINE_VERSION, + ) + const resultsBySkuId = new Map() + for (const entry of cache) { + if (entry.status === 'FAILED') continue + resultsBySkuId.set(entry.skuId, { + status: cachedStatusToSkuStatus(entry.status), + runResult: entry.estimate as unknown as BomCostingAgentRunResult, + cachedAt: entry.updatedAt.toISOString(), + }) + } + return buildEstimateCard({ + caseId, + title: brief.title, + skus: skus.map((sku) => ({ + skuId: sku.id, + externalSkuId: sku.externalSkuId, + name: sku.name, + lengthMm: sku.lengthMm === null ? null : Number(sku.lengthMm), + widthMm: sku.widthMm === null ? null : Number(sku.widthMm), + heightMm: sku.heightMm === null ? null : Number(sku.heightMm), + })), + firstBatchSkuIds: [], + resultsBySkuId, + usage: { rounds: 0, modelCalls: 0, elapsedMs: 0 }, + }) +} + +export async function estimateSkuOnDemand(input: { + caseId: string + skuId: string + options?: Pick +}): Promise { + const cached = await bomCostingAgentRepository.findCachedSkuEstimate( + input.skuId, + BOM_COSTING_AGENT_ENGINE_VERSION, + ) + if (cached && cached.status !== 'FAILED') { + return { + status: cachedStatusToSkuStatus(cached.status), + runResult: cached.estimate as unknown as BomCostingAgentRunResult, + cachedAt: cached.updatedAt.toISOString(), + } + } + const sku = await bomCostingAgentRepository.findSkuForAgentTrial(input.skuId) + if (!sku || sku.caseId !== input.caseId) { + throw new Error(`SKU 不属于该案例:${input.skuId}`) + } + const entry = await estimateSingleSku({ + caseId: input.caseId, + skuId: input.skuId, + externalSkuId: sku.externalSkuId, + maxImages: input.options?.maxImages, + signal: input.options?.signal, + }) + return entry +} diff --git a/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-loop.test.ts b/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-loop.test.ts index 8768def7..b4a83e0a 100644 --- a/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-loop.test.ts +++ b/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-loop.test.ts @@ -144,6 +144,8 @@ describe('runBomCostingAgentLoop', () => { sourceRowId: 'row-1', }] }, + searchMirrorCandidates: async () => [], + getCategoryProfileEstimate: async () => ({ basis: 'NONE' as const }), listMaterialOptions: async () => [], searchRealtimeMarket: async () => ({ status: 'NOT_CONFIGURED' as const, diff --git a/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-loop.ts b/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-loop.ts index 7128f2a0..82b2f200 100644 --- a/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-loop.ts +++ b/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-loop.ts @@ -21,6 +21,7 @@ const MODEL_CALL_RETRY_DELAY_MS = 3_000 export interface BomCostingAgentMission { userContent: BomCostingMultimodalUserContent + skillKnowledge?: string toolContext?: BomCostingAgentToolContext budget?: Partial signal?: AbortSignal @@ -147,7 +148,10 @@ export async function runBomCostingAgentLoop(input: { attempt += 1 try { const result = await input.callModel({ - systemPrompt: buildBomCostingAgentSystemPrompt({ toolRuntimes: input.toolRuntimes }), + systemPrompt: buildBomCostingAgentSystemPrompt({ + toolRuntimes: input.toolRuntimes, + skillKnowledge: input.mission.skillKnowledge, + }), userContent: renderTranscript(input.mission.userContent, observations), }) content = result.content diff --git a/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-runner.ts b/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-runner.ts index bfaf3b4c..b76144b9 100644 --- a/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-runner.ts +++ b/furniture-3d-system/src/server/services/bom-costing/agent/bom-costing-agent-runner.ts @@ -120,6 +120,7 @@ export async function runBomCostingAgentTrialForSku(input: { const result = await runBomCostingAgentLoop({ mission: { userContent, + skillKnowledge: skillKnowledge ?? undefined, toolContext: { caseId: input.caseId, skuId: input.skuId }, budget: input.budget, signal: input.signal, diff --git a/furniture-3d-system/src/server/services/bom-costing/bom-costing-scenario.service.ts b/furniture-3d-system/src/server/services/bom-costing/bom-costing-scenario.service.ts index c68c169a..834783b4 100644 --- a/furniture-3d-system/src/server/services/bom-costing/bom-costing-scenario.service.ts +++ b/furniture-3d-system/src/server/services/bom-costing/bom-costing-scenario.service.ts @@ -1361,7 +1361,7 @@ async function resolveCohortQuote(input: { return quoteFromCohortCandidates(cohortCandidates, input.line, 'CATEGORY_COHORT') } -type CategoryProfileEstimate = { +export type CategoryProfileEstimate = { basis: Extract total: number estimateRange: { min: number; max: number } @@ -1539,7 +1539,7 @@ async function applyHistoricalLossFactorFallbacks(input: { } } -function buildCategoryProfileEstimate( +export function buildCategoryProfileEstimate( candidates: BomCostingScenarioReferenceCandidate[], basis: CategoryProfileEstimate['basis'], category: string, diff --git a/furniture-3d-system/src/server/services/dropship-1688-data.service.ts b/furniture-3d-system/src/server/services/dropship-1688-data.service.ts index d5e8e4a2..4b92486c 100644 --- a/furniture-3d-system/src/server/services/dropship-1688-data.service.ts +++ b/furniture-3d-system/src/server/services/dropship-1688-data.service.ts @@ -40,7 +40,9 @@ export type Dropship1688DataRow = { image: string color: string skuOperator: string + totalCost: string costPrice: string + estimatedFreight: string shipQty: string salesAmount: string afterSaleAmount: string @@ -61,7 +63,9 @@ function archiveRow(archive: Dropship1688ArchiveRecord): Dropship1688DataRow { image: archive.image?.trim() ?? '', color: archive.color, skuOperator: '', - costPrice: '', + totalCost: '0', + costPrice: '0', + estimatedFreight: '0', shipQty: '', salesAmount: '', afterSaleAmount: '', @@ -95,7 +99,15 @@ class Dropship1688DataService { page: 1, pageSize: PAGE_SIZE, totalPages: 1, - summary: { shipQty: '0', salesAmount: '0', realPerformance: '0' }, + summary: { + shipQty: '0', + salesAmount: '0', + realPerformance: '0', + grossProfit: '0', + afterSaleCostRate: '', + totalProducts: '0', + productsWithSalesAmount: '0', + }, dataUpdatedThrough: '', filters: input.filters ?? {}, } @@ -134,6 +146,7 @@ class Dropship1688DataService { const comparisonTrendsByBarcode = new Map() const operatorByBarcode = new Map() const costPriceByBarcode = new Map() + const estimatedFreightByBarcode = new Map() result.trends.forEach((record) => { const comparisonTrend = comparisonTrendsByBarcode.get(record.barcode) ?? [] comparisonTrend.push({ date: dateText(record.statDate), value: record.realPerformance.toFixed(4) }) @@ -148,6 +161,9 @@ class Dropship1688DataService { if (record.unitCost !== null) { costPriceByBarcode.set(record.barcode, record.unitCost.toFixed(4)) } + if (record.estimatedFreight !== null) { + estimatedFreightByBarcode.set(record.barcode, record.estimatedFreight.toFixed(4)) + } }) const rows = result.archives.map((archive) => { const row = archiveRow(archive) @@ -157,9 +173,14 @@ class Dropship1688DataService { const grossProfit = performance._sum.grossProfit ?? new Prisma.Decimal(0) const salesAmount = performance._sum.shipAmount const afterSaleAmount = performance._sum.afterSaleAmount ?? new Prisma.Decimal(0) + const costPrice = costPriceByBarcode.get(archive.barcode) ?? '0' + const estimatedFreight = estimatedFreightByBarcode.get(archive.barcode) ?? '0' + const totalCost = new Prisma.Decimal(costPrice).plus(estimatedFreight).toFixed(4) return { ...row, - costPrice: costPriceByBarcode.get(archive.barcode) ?? '', + totalCost, + costPrice, + estimatedFreight, shipQty: performance._sum.shipQty?.toString() ?? '0', salesAmount: decimalText(salesAmount), afterSaleAmount: decimalText(afterSaleAmount), @@ -186,6 +207,13 @@ class Dropship1688DataService { shipQty: result.summary._sum.shipQty?.toString() ?? '0', salesAmount: decimalText(result.summary._sum.shipAmount), realPerformance: decimalText(result.summary._sum.realPerformance) || '0', + grossProfit: decimalText(result.summary._sum.grossProfit) || '0', + afterSaleCostRate: percentageText( + result.summary._sum.afterSaleAmount, + result.summary._sum.realPerformance, + ), + totalProducts: String(result.total), + productsWithSalesAmount: String(result.summary.productsWithSalesAmount), }, dataUpdatedThrough: dateText(availableTo), filters: input.filters ?? {}, @@ -195,6 +223,7 @@ class Dropship1688DataService { async listFilterOptions(input: { field: Dropship1688FilterField keyword?: string + optionQuery?: string dateFrom?: string dateTo?: string filters?: Dropship1688Filters @@ -209,6 +238,7 @@ class Dropship1688DataService { return dropship1688DataRepository.listFilterOptions({ field: input.field, keyword: input.keyword?.trim() ?? '', + optionQuery: input.optionQuery?.trim() ?? '', dateFrom, dateTo, filters: input.filters, diff --git a/furniture-3d-system/src/server/services/dropship-1688-sourcing.service.ts b/furniture-3d-system/src/server/services/dropship-1688-sourcing.service.ts new file mode 100644 index 00000000..2a00f18c --- /dev/null +++ b/furniture-3d-system/src/server/services/dropship-1688-sourcing.service.ts @@ -0,0 +1,446 @@ +import { Prisma } from '@prisma/client' +import { z } from 'zod' +import { + DROPSHIP_1688_MAX_PURCHASERS, + DROPSHIP_1688_SOURCING_EXPORT_LIMIT, + type Dropship1688SourcingFilters, +} from '@/lib/dropship-1688-sourcing' +import { hasBusinessRole, isAdmin } from '@/lib/role-scope' +import { AppError, ErrorCode } from '@/server/core/errors' +import type { AuthUser } from '@/server/core/types' +import { + dropship1688SourcingRepository, + type Dropship1688SourcingPurchaserRecord, + type Dropship1688SourcingRepository, + type Dropship1688SourcingTaskRecord, + type Dropship1688SourcingTaskWithProduct, +} from '@/server/repositories/dropship-1688-sourcing.repository' + +const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/ + +const dateSchema = z.string().regex(DATE_PATTERN).refine((value) => { + const date = new Date(`${value}T00:00:00.000Z`) + return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value +}) + +const claimSchema = z.object({ + barcode: z.string().trim().min(4).max(100).regex(/^DF-.+/i).transform((value) => value.toUpperCase()), + dateFrom: dateSchema, + dateTo: dateSchema, +}).strict().refine((value) => value.dateFrom <= value.dateTo, { + message: '开始日期不能晚于结束日期', + path: ['dateFrom'], +}) + +const priceSchema = z.string().trim().refine( + (value) => value === '' || /^(?:0|[1-9]\d{0,19})(?:\.\d{1,4})?$/.test(value), + '报价必须是非负数,且最多保留4位小数', +) + +const taxPointSchema = z.string().trim().refine((value) => { + if (value === '' || !/^(?:0|[1-9]\d{0,2})(?:\.\d{1,4})?$/.test(value)) return value === '' + return new Prisma.Decimal(value).lte(100) +}, '发票税点必须是0到100之间的数字,且最多保留4位小数') + +const updateSchema = z.object({ + taskId: z.string().trim().min(1).max(100), + supplierName: z.string().trim().max(200, '供应商不能超过200个字符'), + quotedPriceTaxIncluded: priceSchema, + invoiceTaxPoint: taxPointSchema, + sourcingMode: z.string().trim().pipe( + z.enum(['', '入库', '代发'], { message: '模式只能选择入库或代发' }), + ), + jianshangBarcode: z.string().trim().max(100, '简尚条码不能超过100个字符'), +}).strict() + +const revokeSchema = z.object({ + taskId: z.string().trim().min(1).max(100), +}).strict() + +const importRowSchema = z.object({ + rowNumber: z.number().int().min(2), + sourceBarcode: z.string().trim().min(1, '代发条码不能为空').max(100) + .regex(/^DF-.+/i, '代发条码格式不正确') + .transform((value) => value.toUpperCase()), + purchaserName: z.string().trim().min(1, '采购不能为空').max(200), + supplierName: z.string().trim().max(200, '供应商不能超过200个字符'), + quotedPriceTaxIncluded: priceSchema, + invoiceTaxPoint: taxPointSchema, + sourcingMode: z.string().trim().pipe( + z.enum(['', '入库', '代发'], { message: '模式只能选择入库或代发' }), + ), + jianshangBarcode: z.string().trim().max(100, '简尚条码不能超过100个字符'), +}).strict() + +const sourcingFilterSchema = z.object({ + purchaserNames: z.array(z.string().trim().min(1).max(200)).max(100).default([]), + sourceSpus: z.array(z.string().trim().min(1).max(200)).max(100).default([]), + sourceSkuOperators: z.array(z.string().trim().min(1).max(200)).max(100).default([]), +}).strict().transform((filters) => ({ + purchaserNames: [...new Set(filters.purchaserNames)], + sourceSpus: [...new Set(filters.sourceSpus)], + sourceSkuOperators: [...new Set(filters.sourceSkuOperators)], +})) + +function utcDate(value: string) { + return new Date(`${value}T00:00:00.000Z`) +} + +function dateText(value: Date) { + return value.toISOString().slice(0, 10) +} + +function toTaskDto( + record: Dropship1688SourcingTaskRecord & Partial>, +) { + return { + id: record.id, + sourceArchiveId: record.sourceArchiveId, + sourceSpu: record.sourceSpu, + sourceBarcode: record.sourceBarcode, + sourceCostPrice: record.sourceCostPrice?.toFixed(4) ?? null, + sourceSkuOperator: record.sourceSkuOperator, + sourceDateFrom: dateText(record.sourceDateFrom), + sourceDateTo: dateText(record.sourceDateTo), + purchaserUserId: record.purchaserUserId, + purchaserName: record.purchaserName, + supplierName: record.supplierName, + quotedPriceTaxIncluded: record.quotedPriceTaxIncluded?.toFixed(4) ?? null, + invoiceTaxPoint: record.invoiceTaxPoint?.toFixed(4) ?? null, + sourcingMode: record.sourcingMode, + jianshangBarcode: record.jianshangBarcode, + acceptedAt: record.acceptedAt.toISOString(), + updatedAt: record.updatedAt.toISOString(), + sku: record.sku ?? '', + hasImage: record.hasImage ?? false, + } +} + +export type Dropship1688SourcingTaskDto = ReturnType +export type Dropship1688SourcingPageDto = { + rows: Dropship1688SourcingTaskDto[] + total: number + page: number + pageSize: number + totalPages: number + filterOptions: { + purchaserNames: string[] + sourceSpus: string[] + sourceSkuOperators: string[] + } +} +export type Dropship1688SourcingPurchaserDto = { + userId: string + name: string + acceptedAt: string +} + +function appendPurchaser( + grouped: Record, + record: Dropship1688SourcingPurchaserRecord, +) { + const purchasers = grouped[record.sourceBarcode] + if (!purchasers) return + purchasers.push({ + userId: record.purchaserUserId, + name: record.purchaserName, + acceptedAt: record.acceptedAt.toISOString(), + }) +} + +class Dropship1688SourcingService { + constructor( + private readonly repository: Dropship1688SourcingRepository = dropship1688SourcingRepository, + ) {} + + async claim(input: unknown, actor: AuthUser): Promise { + if (!isAdmin(actor) && !hasBusinessRole(actor, 'PURCHASING')) { + throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '只有采购或管理员可以承接寻源任务') + } + + const parsed = claimSchema.safeParse(input) + if (!parsed.success) { + throw new AppError( + ErrorCode.VALIDATION_INVALID_FORMAT, + parsed.error.issues[0]?.message ?? '承接参数不正确', + ) + } + + const dateFrom = utcDate(parsed.data.dateFrom) + const dateTo = utcDate(parsed.data.dateTo) + const source = await this.repository.findClaimSource({ + barcode: parsed.data.barcode, + dateFrom, + dateTo, + }) + if (!source || !source.barcode.toUpperCase().startsWith('DF-')) { + throw new AppError(ErrorCode.PRODUCT_NOT_FOUND, '1688代发商品不存在') + } + + const result = await this.repository.claim({ + source, + dateFrom, + dateTo, + purchaser: { id: actor.id, name: actor.name.trim() }, + }) + if (result.status === 'full') { + throw new AppError( + ErrorCode.VALIDATION_OUT_OF_RANGE, + `该商品最多由${DROPSHIP_1688_MAX_PURCHASERS}名采购承接`, + ) + } + return toTaskDto({ ...result.task, sku: '', hasImage: false }) + } + + async listTasks(): Promise { + const tasks = await this.repository.listTasks() + return tasks.map(toTaskDto) + } + + async listPage(input: { + page: number + pageSize: number + filters: Dropship1688SourcingFilters + }): Promise { + const [total, filterOptions] = await Promise.all([ + this.repository.countTasks(input.filters), + this.repository.listFilterOptions(input.filters), + ]) + const totalPages = Math.max(1, Math.ceil(total / input.pageSize)) + const page = Math.min(input.page, totalPages) + const tasks = total === 0 + ? [] + : await this.repository.listTasksPage({ + filters: input.filters, + skip: (page - 1) * input.pageSize, + take: input.pageSize, + }) + return { + rows: tasks.map(toTaskDto), + total, + page, + pageSize: input.pageSize, + totalPages, + filterOptions, + } + } + + async listTasksForExport(input: unknown): Promise { + const parsed = z.object({ filters: sourcingFilterSchema }).strict().safeParse(input) + if (!parsed.success) { + throw new AppError(ErrorCode.VALIDATION_INVALID_FORMAT, '寻源导出筛选条件不正确') + } + const tasks = await this.repository.listTasksForExport({ + filters: parsed.data.filters, + take: DROPSHIP_1688_SOURCING_EXPORT_LIMIT + 1, + }) + if (tasks.length > DROPSHIP_1688_SOURCING_EXPORT_LIMIT) { + throw new AppError( + ErrorCode.VALIDATION_OUT_OF_RANGE, + `单次最多导出${DROPSHIP_1688_SOURCING_EXPORT_LIMIT}条寻源数据,请缩小筛选范围`, + ) + } + if (tasks.length === 0) { + throw new AppError(ErrorCode.PRODUCT_NOT_FOUND, '当前筛选条件下没有寻源数据') + } + return tasks.map(toTaskDto) + } + + async importRows(input: unknown, actor: AuthUser): Promise<{ updated: number }> { + if (!isAdmin(actor) && !hasBusinessRole(actor, 'PURCHASING')) { + throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '只有采购或管理员可以导入寻源明细') + } + + const parsed = z.array(importRowSchema) + .min(1, '导入文件没有可用数据') + .max(50_000, '单次最多导入50000行') + .safeParse(input) + if (!parsed.success) { + const issue = parsed.error.issues[0] + const rowIndex = typeof issue?.path[0] === 'number' ? issue.path[0] : null + const originalRow = rowIndex === null || !Array.isArray(input) + ? null + : input[rowIndex] + const rowNumber = originalRow && typeof originalRow === 'object' && 'rowNumber' in originalRow + ? (originalRow as { rowNumber?: unknown }).rowNumber + : null + throw new AppError( + ErrorCode.VALIDATION_INVALID_FORMAT, + `${typeof rowNumber === 'number' ? `第${rowNumber}行:` : ''}${issue?.message ?? '导入数据格式不正确'}`, + ) + } + + const rows = parsed.data + const duplicateKeys = new Map() + rows.forEach((row) => { + const key = `${row.sourceBarcode}\u0000${row.purchaserName}` + const firstRowNumber = duplicateKeys.get(key) + if (firstRowNumber !== undefined) { + throw new AppError( + ErrorCode.VALIDATION_INVALID_FORMAT, + `第${row.rowNumber}行与第${firstRowNumber}行的代发条码和采购重复`, + ) + } + duplicateKeys.set(key, row.rowNumber) + }) + + const records = await this.repository.listTasksByBarcodes([ + ...new Set(rows.map((row) => row.sourceBarcode)), + ]) + const recordsByKey = new Map() + records.forEach((record) => { + const key = `${record.sourceBarcode.toUpperCase()}\u0000${record.purchaserName.trim()}` + recordsByKey.set(key, [ + ...(recordsByKey.get(key) ?? []), + { ...record, sku: '', hasImage: false }, + ]) + }) + + const updates = rows.map((row) => { + const matches = recordsByKey.get(`${row.sourceBarcode}\u0000${row.purchaserName}`) ?? [] + if (matches.length === 0) { + throw new AppError( + ErrorCode.PRODUCT_NOT_FOUND, + `第${row.rowNumber}行:未找到代发条码 ${row.sourceBarcode} 与采购 ${row.purchaserName} 的承接记录`, + ) + } + if (matches.length > 1) { + throw new AppError( + ErrorCode.VALIDATION_INVALID_FORMAT, + `第${row.rowNumber}行:代发条码 ${row.sourceBarcode} 与采购 ${row.purchaserName} 对应多条记录,无法确定覆盖目标`, + ) + } + const task = matches[0] + if (!isAdmin(actor) && task.purchaserUserId !== actor.id) { + throw new AppError( + ErrorCode.AUTH_PERMISSION_DENIED, + `第${row.rowNumber}行:只能导入本人承接的寻源任务`, + ) + } + return { + id: task.id, + supplierName: row.supplierName, + quotedPriceTaxIncluded: row.quotedPriceTaxIncluded + ? new Prisma.Decimal(row.quotedPriceTaxIncluded) + : null, + invoiceTaxPoint: row.invoiceTaxPoint + ? new Prisma.Decimal(row.invoiceTaxPoint) + : null, + sourcingMode: row.sourcingMode, + jianshangBarcode: row.jianshangBarcode, + } + }) + + await this.repository.updateTasks(updates) + return { updated: updates.length } + } + + async update(input: unknown, actor: AuthUser): Promise { + if (!isAdmin(actor) && !hasBusinessRole(actor, 'PURCHASING')) { + throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '只有采购或管理员可以填写寻源明细') + } + + const parsed = updateSchema.safeParse(input) + if (!parsed.success) { + throw new AppError( + ErrorCode.VALIDATION_INVALID_FORMAT, + parsed.error.issues[0]?.message ?? '寻源明细参数不正确', + ) + } + + const existing = await this.repository.findTaskById(parsed.data.taskId) + if (!existing) { + throw new AppError(ErrorCode.PRODUCT_NOT_FOUND, '寻源任务不存在') + } + if (!isAdmin(actor) && existing.purchaserUserId !== actor.id) { + throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '只能修改本人承接的寻源任务') + } + + const updated = await this.repository.updateTask({ + id: parsed.data.taskId, + supplierName: parsed.data.supplierName, + quotedPriceTaxIncluded: parsed.data.quotedPriceTaxIncluded + ? new Prisma.Decimal(parsed.data.quotedPriceTaxIncluded) + : null, + invoiceTaxPoint: parsed.data.invoiceTaxPoint + ? new Prisma.Decimal(parsed.data.invoiceTaxPoint) + : null, + sourcingMode: parsed.data.sourcingMode, + jianshangBarcode: parsed.data.jianshangBarcode, + }) + return toTaskDto({ ...updated, sku: '', hasImage: false }) + } + + /** + * 撤销承接。 + * 限制一:简尚条码已填写的寻源任务不能撤销(说明寻源已完成,不能回退)。 + * 限制二:只能撤销本人承接的寻源任务,管理员也不能代替其他采购撤销。 + */ + async revoke(input: unknown, actor: AuthUser): Promise<{ id: string }> { + if (!isAdmin(actor) && !hasBusinessRole(actor, 'PURCHASING')) { + throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '只有采购或管理员可以撤销寻源任务') + } + + const parsed = revokeSchema.safeParse(input) + if (!parsed.success) { + throw new AppError(ErrorCode.VALIDATION_INVALID_FORMAT, '撤销参数不正确') + } + + const existing = await this.repository.findTaskById(parsed.data.taskId) + if (!existing) { + throw new AppError(ErrorCode.PRODUCT_NOT_FOUND, '寻源任务不存在') + } + if (existing.purchaserUserId !== actor.id) { + throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '只能撤销本人承接的寻源任务') + } + if (existing.jianshangBarcode.trim().length > 0) { + throw new AppError( + ErrorCode.VALIDATION_FAILED, + '该寻源任务已填写简尚条码,不能撤销', + ) + } + + const deleted = await this.repository.deleteTaskIfRevocable({ + id: existing.id, + purchaserUserId: actor.id, + }) + if (!deleted) { + const latest = await this.repository.findTaskById(existing.id) + if (!latest) { + throw new AppError(ErrorCode.PRODUCT_NOT_FOUND, '寻源任务不存在') + } + if (latest.purchaserUserId !== actor.id) { + throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '只能撤销本人承接的寻源任务') + } + if (latest.jianshangBarcode.trim().length > 0) { + throw new AppError( + ErrorCode.VALIDATION_FAILED, + '该寻源任务已填写简尚条码,不能撤销', + ) + } + throw new AppError(ErrorCode.VALIDATION_FAILED, '寻源任务状态已变化,请刷新页面后重试') + } + return { id: existing.id } + } + + async listPurchasersByBarcodes( + barcodes: readonly string[], + ): Promise> { + const normalizedBarcodes = [...new Set( + barcodes + .map((barcode) => barcode.trim().toUpperCase()) + .filter((barcode) => barcode.length <= 100 && /^DF-.+/.test(barcode)), + )] + const grouped = Object.fromEntries( + normalizedBarcodes.map((barcode) => [barcode, [] as Dropship1688SourcingPurchaserDto[]]), + ) + if (normalizedBarcodes.length === 0) return grouped + + const records = await this.repository.listPurchasersByBarcodes(normalizedBarcodes) + records.forEach((record) => appendPurchaser(grouped, record)) + return grouped + } +} + +export const dropship1688SourcingService = new Dropship1688SourcingService() +export { Dropship1688SourcingService } diff --git a/furniture-3d-system/src/server/services/installation-demo/installation-demo-share.service.test.ts b/furniture-3d-system/src/server/services/installation-demo/installation-demo-share.service.test.ts index d94de98a..fbea16a1 100644 --- a/furniture-3d-system/src/server/services/installation-demo/installation-demo-share.service.test.ts +++ b/furniture-3d-system/src/server/services/installation-demo/installation-demo-share.service.test.ts @@ -128,6 +128,79 @@ describe("InstallationDemoShareService", () => { ); }); + it("reuses the same permanent link when the owner updates one drawing", async () => { + const service = new InstallationDemoShareService(); + const first = await service.create(user, createInput()); + const updatedInput = createInput(); + updatedInput.modelUrl = "/api/storage/object?key=models%2Fcabinet-v2.glb"; + + mockedConfigService.get.mockReset(); + mockedConfigService.get + .mockResolvedValueOnce({ token: first.token }) + .mockResolvedValueOnce(first); + + const updated = await service.create(user, updatedInput); + + expect(updated.token).toBe(first.token); + expect(updated.createdAt).toBe(first.createdAt); + expect(updated.expiresAt).toBe(first.expiresAt); + expect(updated.modelUrl).toBe(updatedInput.modelUrl); + }); + + it("restores only the current user's existing link for a drawing", async () => { + const service = new InstallationDemoShareService(); + const snapshot = await service.createSnapshot(user, createInput(), { + token: "a".repeat(32), + expiresAt: null, + }); + mockedConfigService.get + .mockResolvedValueOnce({ token: snapshot.token }) + .mockResolvedValueOnce(snapshot); + + await expect(service.getOwned(user, "drawing-1")).resolves.toEqual(snapshot); + + mockedConfigService.get + .mockResolvedValueOnce({ token: snapshot.token }) + .mockResolvedValueOnce(snapshot); + await expect( + service.getOwned({ ...user, id: "user-2" }, "drawing-1"), + ).resolves.toBeNull(); + }); + + it("syncs content without changing token or creation metadata", async () => { + const service = new InstallationDemoShareService(); + const snapshot = await service.createSnapshot(user, createInput(), { + token: "b".repeat(32), + expiresAt: null, + }); + const updatedInput = createInput(); + updatedInput.modelUrl = "/api/storage/object?key=models%2Fcabinet-v3.glb"; + mockedConfigService.get.mockResolvedValueOnce(snapshot); + + const updated = await service.sync(user, updatedInput, snapshot.token); + + expect(updated).toMatchObject({ + token: snapshot.token, + createdAt: snapshot.createdAt, + expiresAt: snapshot.expiresAt, + createdBy: snapshot.createdBy, + modelUrl: updatedInput.modelUrl, + }); + }); + + it("refuses to sync a link created by another user", async () => { + const service = new InstallationDemoShareService(); + const snapshot = await service.createSnapshot(user, createInput(), { + token: "c".repeat(32), + expiresAt: null, + }); + mockedConfigService.get.mockResolvedValueOnce(snapshot); + + await expect( + service.sync({ ...user, id: "user-2" }, createInput(), snapshot.token), + ).rejects.toThrow("不能更新其他用户创建的分享链接"); + }); + it('revokes cached permanent snapshots and refuses new shares for a deleted manual drawing', async () => { const service = new InstallationDemoShareService(); const input = createInput(); diff --git a/furniture-3d-system/src/server/services/installation-demo/installation-demo-share.service.ts b/furniture-3d-system/src/server/services/installation-demo/installation-demo-share.service.ts index c8a6df74..56361f82 100644 --- a/furniture-3d-system/src/server/services/installation-demo/installation-demo-share.service.ts +++ b/furniture-3d-system/src/server/services/installation-demo/installation-demo-share.service.ts @@ -19,12 +19,17 @@ import { systemConfigService } from "../system-config.service"; import { installationDemoAccessService } from "./installation-demo-access.service"; const SHARE_CONFIG_KEY_PREFIX = "installation-demo-workbench:share:"; +const SHARE_OWNER_CONFIG_KEY_PREFIX = `${SHARE_CONFIG_KEY_PREFIX}owner:`; const SHARE_TOKEN_LENGTH = 32; function buildShareConfigKey(token: string) { return `${SHARE_CONFIG_KEY_PREFIX}${token}`; } +function buildShareOwnerConfigKey(userId: string, drawingId: string) { + return `${SHARE_OWNER_CONFIG_KEY_PREFIX}${encodeURIComponent(userId)}:${encodeURIComponent(drawingId)}`; +} + function isRecord(value: unknown): value is Record { return Boolean(value) && typeof value === "object" && !Array.isArray(value); } @@ -488,6 +493,56 @@ export function normalizeStoredInstallationDemoShareSnapshot( } export class InstallationDemoShareService { + private async findOwnedSnapshot( + user: AuthUser, + drawingId: string, + ): Promise { + const ownerEntry = await systemConfigService.get( + buildShareOwnerConfigKey(user.id, drawingId), + ); + if (!isRecord(ownerEntry) || typeof ownerEntry.token !== "string") { + return null; + } + + let token: string; + try { + token = normalizeInstallationDemoShareToken(ownerEntry.token); + } catch { + return null; + } + const snapshot = normalizeStoredInstallationDemoShareSnapshot( + await systemConfigService.get(buildShareConfigKey(token)), + ); + if ( + !snapshot || + snapshot.createdBy.id !== user.id || + snapshot.drawing.id !== drawingId + ) { + return null; + } + return snapshot; + } + + private async persistOwnedSnapshot( + snapshot: InstallationDemoShareSnapshot, + ): Promise { + await systemConfigService.set( + buildShareConfigKey(snapshot.token), + snapshot, + `Installation demo permanent share ${snapshot.drawing.code}`, + ); + await systemConfigService.set( + buildShareOwnerConfigKey(snapshot.createdBy.id, snapshot.drawing.id), + { + version: 1, + token: snapshot.token, + drawing: { id: snapshot.drawing.id }, + createdBy: { id: snapshot.createdBy.id }, + }, + `Installation demo share owner ${snapshot.drawing.code}`, + ); + } + async createSnapshot( user: AuthUser, rawInput: unknown, @@ -531,18 +586,75 @@ export class InstallationDemoShareService { user: AuthUser, rawInput: unknown, ): Promise { - const token = nanoid(SHARE_TOKEN_LENGTH); + await assertCanShare(user); + const input = normalizeCreateInput(rawInput); + const existing = await this.findOwnedSnapshot(user, input.drawing.id); + const snapshot = await this.createSnapshot(user, input, { + token: existing?.token ?? nanoid(SHARE_TOKEN_LENGTH), + expiresAt: existing?.expiresAt ?? null, + }); + if (existing) { + snapshot.createdAt = existing.createdAt; + snapshot.createdBy = existing.createdBy; + } + + await this.persistOwnedSnapshot(snapshot); + + return snapshot; + } + + async getOwned( + user: AuthUser, + rawDrawingId: unknown, + ): Promise { + await assertCanShare(user); + const drawingId = normalizeText(rawDrawingId, "图纸 ID"); + const snapshot = await this.findOwnedSnapshot(user, drawingId); + if (!snapshot) return null; + if ( + snapshot.drawing.id.startsWith("manual-") && + !(await installationDemoCatalogRepository.exists(snapshot.drawing.id)) + ) { + return null; + } + return snapshot; + } + + async sync( + user: AuthUser, + rawInput: unknown, + rawToken: unknown, + ): Promise { + const token = normalizeInstallationDemoShareToken(rawToken); + const existing = normalizeStoredInstallationDemoShareSnapshot( + await systemConfigService.get(buildShareConfigKey(token)), + ); + if (!existing) { + throw new AppError( + ErrorCode.SHARE_LINK_NOT_FOUND, + "安装演示链接不存在", + ); + } + if (existing.createdBy.id !== user.id) { + throw new AppError( + ErrorCode.AUTH_PERMISSION_DENIED, + "不能更新其他用户创建的分享链接", + ); + } + const snapshot = await this.createSnapshot(user, rawInput, { token, - expiresAt: null, + expiresAt: existing.expiresAt, }); - - await systemConfigService.set( - buildShareConfigKey(token), - snapshot, - `Installation demo permanent share ${snapshot.drawing.code}`, - ); - + if (snapshot.drawing.id !== existing.drawing.id) { + throw new AppError( + ErrorCode.VALIDATION_INVALID_FORMAT, + "分享链接与当前图纸不匹配", + ); + } + snapshot.createdAt = existing.createdAt; + snapshot.createdBy = existing.createdBy; + await this.persistOwnedSnapshot(snapshot); return snapshot; } diff --git a/furniture-3d-system/src/server/services/intake-non-integrated-product.service.ts b/furniture-3d-system/src/server/services/intake-non-integrated-product.service.ts index 88dcad3a..3e9eba84 100644 --- a/furniture-3d-system/src/server/services/intake-non-integrated-product.service.ts +++ b/furniture-3d-system/src/server/services/intake-non-integrated-product.service.ts @@ -7301,7 +7301,10 @@ class IntakeNonIntegratedProductService { created: true, restored: false, } - }) + // 200+ SKU 的大产品保存要在事务内重建全部子表数据(skuItems/factoryRows/ + // pricingRows/sampleMeasurementRows 近千行),Prisma 默认 5s 事务超时不够, + // LRSF0095 已实际触发 P2028 回滚导致"保存成功但刷新丢失",放宽到 60s。 + }, { maxWait: 10_000, timeout: 60_000 }) const savedProduct = await this.getById(saveResult.productId, user) if (!savedProduct) { diff --git a/furniture-3d-system/src/server/services/jushuitan-fixed-virtual-inventory.helpers.ts b/furniture-3d-system/src/server/services/jushuitan-fixed-virtual-inventory.helpers.ts new file mode 100644 index 00000000..7ea1f5a4 --- /dev/null +++ b/furniture-3d-system/src/server/services/jushuitan-fixed-virtual-inventory.helpers.ts @@ -0,0 +1,48 @@ +export const JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH = + "/open/webapi/itemapi/iteminventory/batchupdatewmsvirtualqtys"; +export const JUSHUITAN_FIXED_VIRTUAL_INVENTORY_WMS_CO_ID = 15994660; +export const JUSHUITAN_FIXED_VIRTUAL_INVENTORY_QTY = 100000; +export const FIXED_VIRTUAL_INVENTORY_RETRY_DELAY_MS = 2 * 60 * 60 * 1000; +export const FIXED_VIRTUAL_INVENTORY_BATCH_SIZE = 100; +export const DEFAULT_FIXED_VIRTUAL_INVENTORY_REQUEST_INTERVAL_MS = 3000; + +export function readFixedVirtualInventoryRequestId(raw: unknown) { + if (!raw || typeof raw !== "object") return ""; + const record = raw as Record; + const data = record.data; + const dataRecord = + data && typeof data === "object" ? (data as Record) : null; + + for (const value of [ + record.request_id, + record.requestId, + dataRecord?.request_id, + dataRecord?.requestId, + ]) { + if (typeof value === "string" && value.trim()) return value.trim(); + } + + return ""; +} + +export function normalizeFixedVirtualInventoryError(error: unknown) { + return error instanceof Error + ? error.message + : "Jushuitan fixed virtual inventory push failed"; +} + +export function isFixedVirtualInventoryRateLimited(error: unknown) { + return /code\s*=\s*(?:199|200)\b|调用(?:太|过于)频繁|请求(?:太|过于)频繁|too many requests|rate.?limit|\b429\b/i.test( + normalizeFixedVirtualInventoryError(error), + ); +} + +export function buildFixedVirtualInventoryPayload(barcodes: string[]) { + return { + wms_co_id: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_WMS_CO_ID, + sku_and_qty: barcodes.map((barcode) => ({ + sku_id: barcode, + qty: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_QTY, + })), + }; +} diff --git a/furniture-3d-system/src/server/services/jushuitan-fixed-virtual-inventory.service.test.ts b/furniture-3d-system/src/server/services/jushuitan-fixed-virtual-inventory.service.test.ts index a9535740..f9acad98 100644 --- a/furniture-3d-system/src/server/services/jushuitan-fixed-virtual-inventory.service.test.ts +++ b/furniture-3d-system/src/server/services/jushuitan-fixed-virtual-inventory.service.test.ts @@ -17,15 +17,16 @@ import { } from "./jushuitan-fixed-virtual-inventory.service"; function createTask( + index = 1, overrides: Partial = {}, ): JushuitanFixedVirtualInventoryTaskRecord { return { - id: "task-1", + id: `task-${index}`, productId: "product-1", productSpu: "SPU-1", - skuItemId: "sku-1", - skuCode: "SKU-1", - barcode: "BARCODE-1", + skuItemId: `sku-${index}`, + skuCode: `SKU-${index}`, + barcode: `BARCODE-${index}`, status: "pending", scheduledAt: new Date("2026-08-10T00:00:00.000Z"), retryCount: 0, @@ -39,13 +40,16 @@ function createTask( }; } -function createRepository(tasks: JushuitanFixedVirtualInventoryTaskRecord[]) { +function createRepository( + batches: JushuitanFixedVirtualInventoryTaskRecord[][], +) { + const pendingBatches = [...batches]; return { createMissing: jest.fn(async () => 1), - findDue: jest.fn(async () => tasks), + findDue: jest.fn(async () => pendingBatches.shift() ?? []), findByProductId: jest.fn(async () => []), - markSucceeded: jest.fn(async () => undefined), - scheduleRetry: jest.fn(async () => undefined), + markManySucceeded: jest.fn(async () => ({ count: 0 })), + scheduleManyRetry: jest.fn(async () => ({ count: 0 })), } satisfies JushuitanFixedVirtualInventoryTaskRepositoryContract; } @@ -58,16 +62,41 @@ const actor = { businessRoles: [], } as AuthUser; +const runInput = { + actor, + source: "SYSTEM" as const, + requestId: "local-request-1", + now: new Date("2026-08-10T00:00:00.000Z"), +}; + +function successfulResponse(requestId: string) { + return { + path: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH, + code: 0, + message: "ok", + raw: { code: 0, data: { request_id: requestId } }, + }; +} + describe("Jushuitan fixed virtual inventory service", () => { + beforeEach(() => { + jest + .spyOn(operationLogService, "record") + .mockResolvedValue(undefined); + }); + afterEach(() => { jest.restoreAllMocks(); }); - it("builds the fixed warehouse and quantity payload from a barcode", () => { - expect(buildFixedVirtualInventoryPayload("BARCODE-1")).toEqual({ + it("builds one fixed warehouse payload for multiple barcodes", () => { + expect( + buildFixedVirtualInventoryPayload(["BARCODE-1", "BARCODE-2"]), + ).toEqual({ wms_co_id: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_WMS_CO_ID, sku_and_qty: [ { sku_id: "BARCODE-1", qty: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_QTY }, + { sku_id: "BARCODE-2", qty: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_QTY }, ], }); }); @@ -97,102 +126,212 @@ describe("Jushuitan fixed virtual inventory service", () => { ]); }); - it("pushes a due task and records the external request id", async () => { - const repository = createRepository([createTask()]); - const post = jest.fn(async () => ({ - path: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH, - code: 0, - message: "ok", - raw: { code: 0, data: { request_id: "jst-request-1" } }, - })); - const record = jest - .spyOn(operationLogService, "record") - .mockResolvedValue(undefined); + it("pushes a due batch and records the external request id", async () => { + const repository = createRepository([[createTask()]]); + const post = jest.fn(async () => successfulResponse("jst-request-1")); const service = new JushuitanFixedVirtualInventoryService(repository, post); - const result = await service.processDue({ - actor, - source: "SYSTEM", - requestId: "local-request-1", - now: new Date("2026-08-10T00:00:00.000Z"), - }); + const result = await service.processDue(runInput); expect(result).toEqual({ processed: 1, pushed: 1, failed: 0 }); expect(post).toHaveBeenCalledWith( JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH, - buildFixedVirtualInventoryPayload("BARCODE-1"), + buildFixedVirtualInventoryPayload(["BARCODE-1"]), ); - expect(repository.markSucceeded).toHaveBeenCalledWith({ - id: "task-1", - attemptedAt: new Date("2026-08-10T00:00:00.000Z"), + expect(repository.markManySucceeded).toHaveBeenCalledWith({ + ids: ["task-1"], + attemptedAt: runInput.now, requestId: "jst-request-1", }); - expect(record).toHaveBeenCalledWith( + expect(operationLogService.record).toHaveBeenCalledWith( expect.objectContaining({ status: OperationLogStatus.SUCCESS }), ); }); - it("retries a code-zero response without an external request id", async () => { - const repository = createRepository([createTask()]); + it("shares one active run when the scheduler is triggered twice", async () => { + const repository = createRepository([]); + const task = createTask(); + let releaseFindDue: + | ((tasks: JushuitanFixedVirtualInventoryTaskRecord[]) => void) + | undefined; + repository.findDue.mockImplementationOnce( + () => + new Promise((resolve) => { + releaseFindDue = resolve; + }), + ); + const post = jest.fn(async () => successfulResponse("jst-request-1")); + const service = new JushuitanFixedVirtualInventoryService(repository, post); + + const firstRun = service.processDue(runInput); + const secondRun = service.processDue(runInput); + expect(repository.findDue).toHaveBeenCalledTimes(1); + releaseFindDue?.([task]); + + await expect(Promise.all([firstRun, secondRun])).resolves.toEqual([ + { processed: 1, pushed: 1, failed: 0 }, + { processed: 1, pushed: 1, failed: 0 }, + ]); + expect(post).toHaveBeenCalledTimes(1); + }); + + it("sends 224 tasks as serial batches of 100, 100, and 24", async () => { + const tasks = Array.from({ length: 224 }, (_, index) => + createTask(index + 1), + ); + const repository = createRepository([ + tasks.slice(0, 100), + tasks.slice(100, 200), + tasks.slice(200), + ]); + const post = jest + .fn() + .mockResolvedValueOnce(successfulResponse("jst-request-1")) + .mockResolvedValueOnce(successfulResponse("jst-request-2")) + .mockResolvedValueOnce(successfulResponse("jst-request-3")); + const sleep = jest.fn(async () => undefined); + const service = new JushuitanFixedVirtualInventoryService( + repository, + post, + { requestIntervalMs: 3000, sleep }, + ); + + await expect(service.processDue(runInput)).resolves.toEqual({ + processed: 224, + pushed: 224, + failed: 0, + }); + + expect(post).toHaveBeenCalledTimes(3); + expect(sleep).toHaveBeenCalledTimes(2); + expect( + post.mock.calls.map(([, payload]) => + (payload.sku_and_qty as unknown[]).length, + ), + ).toEqual([100, 100, 24]); + expect(repository.markManySucceeded).toHaveBeenNthCalledWith( + 3, + expect.objectContaining({ + ids: tasks.slice(200).map((task) => task.id), + requestId: "jst-request-3", + }), + ); + }); + + it.each(["199", "200"])( + "stops after a code %s rate-limited batch and leaves later tasks untouched", + async (code) => { + const tasks = Array.from({ length: 224 }, (_, index) => + createTask(index + 1), + ); + const repository = createRepository([ + tasks.slice(0, 100), + tasks.slice(100, 200), + tasks.slice(200), + ]); + const post = jest + .fn() + .mockResolvedValueOnce(successfulResponse("jst-request-1")) + .mockRejectedValueOnce( + new Error(`聚水潭接口失败:code=${code},调用太频繁,请稍后再试`), + ); + const service = new JushuitanFixedVirtualInventoryService( + repository, + post, + { requestIntervalMs: 0 }, + ); + + await expect(service.processDue(runInput)).resolves.toEqual({ + processed: 200, + pushed: 100, + failed: 100, + }); + + expect(post).toHaveBeenCalledTimes(2); + expect(repository.findDue).toHaveBeenCalledTimes(2); + expect(repository.scheduleManyRetry).toHaveBeenCalledWith( + expect.objectContaining({ + ids: tasks.slice(100, 200).map((task) => task.id), + }), + ); + expect(repository.markManySucceeded).not.toHaveBeenCalledWith( + expect.objectContaining({ + ids: tasks.slice(200).map((task) => task.id), + }), + ); + }, + ); + + it("retries empty barcodes without including them in the batch request", async () => { + const emptyTask = createTask(1, { barcode: " " }); + const validTask = createTask(2); + const repository = createRepository([[emptyTask, validTask]]); + const post = jest.fn(async () => successfulResponse("jst-request-1")); + const service = new JushuitanFixedVirtualInventoryService(repository, post); + + await expect(service.processDue(runInput)).resolves.toEqual({ + processed: 2, + pushed: 1, + failed: 1, + }); + expect(post).toHaveBeenCalledWith( + JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH, + buildFixedVirtualInventoryPayload([validTask.barcode]), + ); + expect(repository.scheduleManyRetry).toHaveBeenCalledWith( + expect.objectContaining({ + ids: [emptyTask.id], + error: "SKU barcode is empty", + }), + ); + }); + + it("retries a code-zero batch response without an external request id", async () => { + const tasks = [createTask(1), createTask(2)]; + const repository = createRepository([tasks]); const post = jest.fn(async () => ({ path: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH, code: 0, message: "ok", raw: { code: 0, data: {} }, })); - jest.spyOn(operationLogService, "record").mockResolvedValue(undefined); const service = new JushuitanFixedVirtualInventoryService(repository, post); - const now = new Date("2026-08-10T00:00:00.000Z"); - const result = await service.processDue({ - actor, - source: "SYSTEM", - requestId: "local-request-1", - now, - }); + const result = await service.processDue(runInput); - expect(result).toEqual({ processed: 1, pushed: 0, failed: 1 }); - expect(repository.markSucceeded).not.toHaveBeenCalled(); - expect(repository.scheduleRetry).toHaveBeenCalledWith( + expect(result).toEqual({ processed: 2, pushed: 0, failed: 2 }); + expect(repository.markManySucceeded).not.toHaveBeenCalled(); + expect(repository.scheduleManyRetry).toHaveBeenCalledWith( expect.objectContaining({ - id: "task-1", - attemptedAt: now, + ids: tasks.map((task) => task.id), + attemptedAt: runInput.now, error: "Jushuitan fixed virtual inventory response is missing request_id", }), ); }); it("schedules every failed task exactly two hours later", async () => { - const repository = createRepository([createTask()]); + const tasks = [createTask(1), createTask(2)]; + const repository = createRepository([tasks]); const post = jest.fn(async () => { throw new Error("Jushuitan rejected the request"); }); - const record = jest - .spyOn(operationLogService, "record") - .mockResolvedValue(undefined); const service = new JushuitanFixedVirtualInventoryService(repository, post); - const now = new Date("2026-08-10T00:00:00.000Z"); - const result = await service.processDue({ - actor, - source: "SYSTEM", - requestId: "local-request-1", - now, - }); + const result = await service.processDue(runInput); - expect(result).toEqual({ processed: 1, pushed: 0, failed: 1 }); - expect(repository.scheduleRetry).toHaveBeenCalledWith({ - id: "task-1", - attemptedAt: now, + expect(result).toEqual({ processed: 2, pushed: 0, failed: 2 }); + expect(repository.scheduleManyRetry).toHaveBeenCalledWith({ + ids: tasks.map((task) => task.id), + attemptedAt: runInput.now, scheduledAt: new Date( - now.getTime() + FIXED_VIRTUAL_INVENTORY_RETRY_DELAY_MS, + runInput.now.getTime() + FIXED_VIRTUAL_INVENTORY_RETRY_DELAY_MS, ), error: "Jushuitan rejected the request", requestId: "local-request-1", }); - expect(record).toHaveBeenCalledWith( + expect(operationLogService.record).toHaveBeenCalledWith( expect.objectContaining({ status: OperationLogStatus.FAILED }), ); }); - }); diff --git a/furniture-3d-system/src/server/services/jushuitan-fixed-virtual-inventory.service.ts b/furniture-3d-system/src/server/services/jushuitan-fixed-virtual-inventory.service.ts index 89d1ab0d..a45b1b2c 100644 --- a/furniture-3d-system/src/server/services/jushuitan-fixed-virtual-inventory.service.ts +++ b/furniture-3d-system/src/server/services/jushuitan-fixed-virtual-inventory.service.ts @@ -14,13 +14,19 @@ import { type JushuitanFixedVirtualInventoryTaskRepositoryContract, type JushuitanFixedVirtualInventoryTaskRecord, } from "@/server/repositories/jushuitan-fixed-virtual-inventory-task.repository"; +import { + buildFixedVirtualInventoryPayload, + DEFAULT_FIXED_VIRTUAL_INVENTORY_REQUEST_INTERVAL_MS, + FIXED_VIRTUAL_INVENTORY_BATCH_SIZE, + FIXED_VIRTUAL_INVENTORY_RETRY_DELAY_MS, + isFixedVirtualInventoryRateLimited, + JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH, + JUSHUITAN_FIXED_VIRTUAL_INVENTORY_QTY, + JUSHUITAN_FIXED_VIRTUAL_INVENTORY_WMS_CO_ID, + normalizeFixedVirtualInventoryError, + readFixedVirtualInventoryRequestId, +} from "./jushuitan-fixed-virtual-inventory.helpers"; -export const JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH = - "/open/webapi/itemapi/iteminventory/batchupdatewmsvirtualqtys"; -export const JUSHUITAN_FIXED_VIRTUAL_INVENTORY_WMS_CO_ID = 15994660; -export const JUSHUITAN_FIXED_VIRTUAL_INVENTORY_QTY = 100000; -export const FIXED_VIRTUAL_INVENTORY_RETRY_DELAY_MS = 2 * 60 * 60 * 1000; -const FIXED_VIRTUAL_INVENTORY_BATCH_SIZE = 100; const MAX_FIXED_VIRTUAL_INVENTORY_TASKS_PER_RUN = 5000; type FixedVirtualInventoryProduct = { @@ -28,7 +34,6 @@ type FixedVirtualInventoryProduct = { spu: string; skuItems: NonIntegratedSkuItem[]; }; - type FixedVirtualInventoryRunInput = { actor: AuthUser; source: "USER" | "SYSTEM"; @@ -36,53 +41,28 @@ type FixedVirtualInventoryRunInput = { requestId: string; now?: Date; }; - type FixedVirtualInventoryApi = ( path: string, biz: Record, ) => Promise; +type FixedVirtualInventoryRunResult = { + processed: number; + pushed: number; + failed: number; +}; +type FixedVirtualInventoryServiceOptions = { + requestIntervalMs?: number; + sleep?: (milliseconds: number) => Promise; +}; -function readRequestId(raw: unknown) { - if (!raw || typeof raw !== "object") return ""; - const record = raw as Record; - const data = record.data; - const dataRecord = - data && typeof data === "object" ? (data as Record) : null; +export class JushuitanFixedVirtualInventoryService { + private activeRun: Promise | null = null; + private lastRequestAt = 0; - for (const value of [ - record.request_id, - record.requestId, - dataRecord?.request_id, - dataRecord?.requestId, - ]) { - if (typeof value === "string" && value.trim()) return value.trim(); - } - - return ""; -} - -function normalizeError(error: unknown) { - return error instanceof Error - ? error.message - : "Jushuitan fixed virtual inventory push failed"; -} - -function buildFixedVirtualInventoryPayload(barcode: string) { - return { - wms_co_id: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_WMS_CO_ID, - sku_and_qty: [ - { - sku_id: barcode, - qty: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_QTY, - }, - ], - }; -} - -class JushuitanFixedVirtualInventoryService { constructor( private readonly repository: JushuitanFixedVirtualInventoryTaskRepositoryContract = jushuitanFixedVirtualInventoryTaskRepository, private readonly post: FixedVirtualInventoryApi = postJushuitanWithDefaultCredentials, + private readonly options: FixedVirtualInventoryServiceOptions = {}, ) {} async enqueueForProduct( @@ -106,6 +86,20 @@ class JushuitanFixedVirtualInventoryService { } async processDue(input: FixedVirtualInventoryRunInput) { + if (this.activeRun) return this.activeRun; + + const run = this.processDueInternal(input); + this.activeRun = run; + try { + return await run; + } finally { + if (this.activeRun === run) this.activeRun = null; + } + } + + private async processDueInternal( + input: FixedVirtualInventoryRunInput, + ): Promise { const now = input.now ?? new Date(); const result = { processed: 0, pushed: 0, failed: 0 }; @@ -117,13 +111,13 @@ class JushuitanFixedVirtualInventoryService { const tasks = await this.repository.findDue(now, take); if (tasks.length === 0) break; - for (const task of tasks) { - result.processed += 1; - if (await this.processOne(task, input)) { - result.pushed += 1; - } else { - result.failed += 1; - } + const batchResult = await this.processBatch(tasks, input); + result.processed += tasks.length; + result.pushed += batchResult.pushed; + result.failed += batchResult.failed; + + if (batchResult.rateLimited) { + break; } if (tasks.length < take) break; @@ -132,71 +126,99 @@ class JushuitanFixedVirtualInventoryService { return result; } - private async processOne( - task: JushuitanFixedVirtualInventoryTaskRecord, + private async processBatch( + tasks: JushuitanFixedVirtualInventoryTaskRecord[], input: FixedVirtualInventoryRunInput, ) { const attemptedAt = input.now ?? new Date(); - const barcode = task.barcode.trim(); - if (!barcode) { - return this.scheduleRetry( - task, + const missingBarcodeTasks = tasks.filter((task) => !task.barcode.trim()); + const pushableTasks = tasks.filter((task) => task.barcode.trim()); + + if (missingBarcodeTasks.length > 0) { + await this.scheduleRetry( + missingBarcodeTasks, input, attemptedAt, "SKU barcode is empty", ); } - const payload = buildFixedVirtualInventoryPayload(barcode); + + if (pushableTasks.length === 0) { + return { + pushed: 0, + failed: missingBarcodeTasks.length, + rateLimited: false, + }; + } + + const payload = buildFixedVirtualInventoryPayload( + pushableTasks.map((task) => task.barcode.trim()), + ); try { + await this.waitForRequestTurn(); const response = await this.post( JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH, payload, ); - const requestId = readRequestId(response.raw); + const requestId = readFixedVirtualInventoryRequestId(response.raw); if (!requestId) { throw new Error( "Jushuitan fixed virtual inventory response is missing request_id", ); } - await this.repository.markSucceeded({ - id: task.id, + await this.repository.markManySucceeded({ + ids: pushableTasks.map((task) => task.id), attemptedAt, requestId, }); - await operationLogService.record({ - action: OperationLogAction.JUSHUITAN_VIRTUAL_INVENTORY_PUSH, - status: OperationLogStatus.SUCCESS, - source: input.source, - actorId: input.actorId, - actorName: input.actor.name, - productId: task.productId, - productSpu: task.productSpu, - skuId: task.skuItemId, - skuCode: task.skuCode, - message: "Jushuitan fixed virtual inventory request accepted", - requestId, - details: { - flow: "fixed-wms-virtual-inventory", - path: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH, - wmsCoId: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_WMS_CO_ID, - qty: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_QTY, - barcode: task.barcode, - }, - }); - return true; + await Promise.allSettled( + pushableTasks.map((task) => + operationLogService.record({ + action: OperationLogAction.JUSHUITAN_VIRTUAL_INVENTORY_PUSH, + status: OperationLogStatus.SUCCESS, + source: input.source, + actorId: input.actorId, + actorName: input.actor.name, + productId: task.productId, + productSpu: task.productSpu, + skuId: task.skuItemId, + skuCode: task.skuCode, + message: "Jushuitan fixed virtual inventory request accepted", + requestId, + details: { + flow: "fixed-wms-virtual-inventory", + path: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH, + wmsCoId: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_WMS_CO_ID, + qty: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_QTY, + barcode: task.barcode, + batchSize: pushableTasks.length, + }, + }), + ), + ); + return { + pushed: pushableTasks.length, + failed: missingBarcodeTasks.length, + rateLimited: false, + }; } catch (error) { - return this.scheduleRetry( - task, + await this.scheduleRetry( + pushableTasks, input, attemptedAt, - normalizeError(error), + normalizeFixedVirtualInventoryError(error), ); + return { + pushed: 0, + failed: tasks.length, + rateLimited: isFixedVirtualInventoryRateLimited(error), + }; } } private async scheduleRetry( - task: JushuitanFixedVirtualInventoryTaskRecord, + tasks: JushuitanFixedVirtualInventoryTaskRecord[], input: FixedVirtualInventoryRunInput, attemptedAt: Date, reason: string, @@ -204,44 +226,74 @@ class JushuitanFixedVirtualInventoryService { const scheduledAt = new Date( attemptedAt.getTime() + FIXED_VIRTUAL_INVENTORY_RETRY_DELAY_MS, ); - await this.repository.scheduleRetry({ - id: task.id, + await this.repository.scheduleManyRetry({ + ids: tasks.map((task) => task.id), attemptedAt, scheduledAt, error: reason, requestId: input.requestId, }); - await operationLogService.record({ - action: OperationLogAction.JUSHUITAN_VIRTUAL_INVENTORY_PUSH, - status: OperationLogStatus.FAILED, - source: input.source, - actorId: input.actorId, - actorName: input.actor.name, - productId: task.productId, - productSpu: task.productSpu, - skuId: task.skuItemId, - skuCode: task.skuCode, - errorCode: "JUSHUITAN_FIXED_VIRTUAL_INVENTORY_FAILED", - message: `Jushuitan fixed virtual inventory push failed; retry at ${scheduledAt.toISOString()}: ${reason}`, - requestId: input.requestId, - details: { - flow: "fixed-wms-virtual-inventory", - path: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH, - wmsCoId: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_WMS_CO_ID, - qty: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_QTY, - barcode: task.barcode, - scheduledAt: scheduledAt.toISOString(), - reason, - }, - }); - return false; + await Promise.allSettled( + tasks.map((task) => + operationLogService.record({ + action: OperationLogAction.JUSHUITAN_VIRTUAL_INVENTORY_PUSH, + status: OperationLogStatus.FAILED, + source: input.source, + actorId: input.actorId, + actorName: input.actor.name, + productId: task.productId, + productSpu: task.productSpu, + skuId: task.skuItemId, + skuCode: task.skuCode, + errorCode: "JUSHUITAN_FIXED_VIRTUAL_INVENTORY_FAILED", + message: `Jushuitan fixed virtual inventory push failed; retry at ${scheduledAt.toISOString()}: ${reason}`, + requestId: input.requestId, + details: { + flow: "fixed-wms-virtual-inventory", + path: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_PATH, + wmsCoId: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_WMS_CO_ID, + qty: JUSHUITAN_FIXED_VIRTUAL_INVENTORY_QTY, + barcode: task.barcode, + batchSize: tasks.length, + scheduledAt: scheduledAt.toISOString(), + reason, + }, + }), + ), + ); + } + + private async waitForRequestTurn() { + const intervalMs = this.getRequestIntervalMs(); + const waitMs = Math.max( + 0, + this.lastRequestAt + intervalMs - Date.now(), + ); + if (waitMs > 0) { + const sleep = + this.options.sleep ?? + ((milliseconds: number) => + new Promise((resolve) => setTimeout(resolve, milliseconds))); + await sleep(waitMs); + } + this.lastRequestAt = Date.now(); + } + + private getRequestIntervalMs() { + if (this.options.requestIntervalMs !== undefined) { + return Math.max(0, this.options.requestIntervalMs); + } + const configured = Number.parseInt( + process.env.JST_FIXED_VIRTUAL_INVENTORY_REQUEST_INTERVAL_MS?.trim() ?? "", + 10, + ); + return Number.isFinite(configured) && configured >= 0 + ? configured + : DEFAULT_FIXED_VIRTUAL_INVENTORY_REQUEST_INTERVAL_MS; } } export const jushuitanFixedVirtualInventoryService = new JushuitanFixedVirtualInventoryService(); -export { - JushuitanFixedVirtualInventoryService, - buildFixedVirtualInventoryPayload, -}; +export * from "./jushuitan-fixed-virtual-inventory.helpers"; diff --git a/furniture-3d-system/src/server/services/jushuitan-product-pricing-push.service.test.ts b/furniture-3d-system/src/server/services/jushuitan-product-pricing-push.service.test.ts index 8677f615..042d56c9 100644 --- a/furniture-3d-system/src/server/services/jushuitan-product-pricing-push.service.test.ts +++ b/furniture-3d-system/src/server/services/jushuitan-product-pricing-push.service.test.ts @@ -260,6 +260,39 @@ describe('JushuitanProductPricingPushService', () => { expect(combineSkuBody.get('access_token')).toBe('combine-access-token') }) + it('超过聚水潭单次 200 上限的大产品按批次推送普通商品资料', async () => { + const fetchMock = createSuccessFetchMock() + global.fetch = fetchMock as unknown as typeof fetch + + // LRSF0095 实际场景:224 个 SKU 一次推送被聚水潭拒绝(code=130,items 最多 200 个) + const skus = Array.from({ length: 250 }, (_, index) => + createSku({ + id: `bulk-sku-${index + 1}`, + skuSequence: index + 1, + skuCode: `GBGJ-CS${String(index + 1).padStart(6, '0')}`, + barcode: `GBGJ-CS${String(index + 1).padStart(6, '0')}N1280V01`, + }), + ) + const result = await new JushuitanProductPricingPushService().pushProductPricing({ + product: createProduct(skus), + targetSkuIds: skus.map((sku) => sku.id), + }) + + const itemSkuCalls = fetchMock.mock.calls.filter((call) => + String(call[0]).includes('/open/jushuitan/itemsku/upload'), + ) + expect(itemSkuCalls.length).toBe(3) + + const batchSizes = itemSkuCalls.map((call) => { + const body = call[1]?.body as URLSearchParams + const biz = JSON.parse(body.get('biz') ?? '{}') as { items?: unknown[] } + return (biz.items ?? []).length + }) + expect(batchSizes).toEqual([100, 100, 50]) + expect(batchSizes.reduce((sum, size) => sum + size, 0)).toBe(250) + expect(new Set(result.pushedSkuIds).size).toBe(250) + }) + it('套件量等于 1 时只推普通商品资料', async () => { const fetchMock = createSuccessFetchMock() global.fetch = fetchMock as unknown as typeof fetch diff --git a/furniture-3d-system/src/server/services/jushuitan-product-pricing-push.service.ts b/furniture-3d-system/src/server/services/jushuitan-product-pricing-push.service.ts index b2360de7..efb10c3e 100644 --- a/furniture-3d-system/src/server/services/jushuitan-product-pricing-push.service.ts +++ b/furniture-3d-system/src/server/services/jushuitan-product-pricing-push.service.ts @@ -159,6 +159,17 @@ const VIRTUAL_INVENTORY_MAIN_WAREHOUSE = 1 const DEFAULT_VIRTUAL_INVENTORY_REQUEST_INTERVAL_MS = 3000 const WAREHOUSE_INFO_TABLE = 'jst_warehouseInfo' const DEFAULT_JUSHUITAN_SALES_STATUS = '销售' +// 聚水潭 /open/jushuitan/itemsku/upload 单次最多 200 个 items(超限返回 code=130, +// 实际案例:LRSF0095 一次推 224 个被拒),留余量按 100 一批分批推送。 +const JUSHUITAN_ITEMS_MAX_BATCH_SIZE = 100 + +function chunkWithLimit(items: T[], size: number): T[][] { + const batches: T[][] = [] + for (let i = 0; i < items.length; i += size) { + batches.push(items.slice(i, i + size)) + } + return batches +} const JUSHUITAN_PACKAGE_TYPE_BY_SET_COUNT: Record = { '1': '非双包', '2': '双包', @@ -1439,33 +1450,70 @@ class JushuitanProductPricingPushService { const externallySucceededSkuIds = new Set() if (normalItems.length > 0) { - results.push( - await postJushuitan(credentials, ITEMSKU_UPLOAD_PATH, { - items: normalItems, - }), + const normalBatches = chunkWithLimit( + normalItems, + JUSHUITAN_ITEMS_MAX_BATCH_SIZE, ) - normalRows.forEach((row) => externallySucceededSkuIds.add(row.sku.id)) + let normalCursor = 0 + for (const batch of normalBatches) { + const batchRows = normalRows.slice( + normalCursor, + normalCursor + batch.length, + ) + normalCursor += batch.length + try { + results.push( + await postJushuitan(credentials, ITEMSKU_UPLOAD_PATH, { + items: batch, + }), + ) + batchRows.forEach((row) => externallySucceededSkuIds.add(row.sku.id)) + } catch (error) { + const succeededSkuIds = Array.from(externallySucceededSkuIds) + if (succeededSkuIds.length > 0) { + throw new JushuitanProductPricingPushPartialFailureError( + '聚水潭部分商品已推送成功,后续批次推送失败;已成功 SKU 将锁定,请勿重复操作并人工核对', + error, + succeededSkuIds, + 'normal-item-upload', + ) + } + throw error + } + } } if (combineItems.length > 0) { - try { - results.push( - await postJushuitan(combineCredentials, COMBINESKU_UPLOAD_PATH, { - items: combineItems, - }), + const combineBatches = chunkWithLimit( + combineItems, + JUSHUITAN_ITEMS_MAX_BATCH_SIZE, + ) + let combineCursor = 0 + for (const batch of combineBatches) { + const batchRows = combineRows.slice( + combineCursor, + combineCursor + batch.length, ) - combineRows.forEach((row) => externallySucceededSkuIds.add(row.sku.id)) - } catch (error) { - const succeededSkuIds = Array.from(externallySucceededSkuIds) - if (succeededSkuIds.length > 0) { - throw new JushuitanProductPricingPushPartialFailureError( - '聚水潭部分商品已推送成功,后续组合商品推送失败;已成功 SKU 将锁定,请勿重复操作并人工核对', - error, - succeededSkuIds, - 'combine-item-upload', + combineCursor += batch.length + try { + results.push( + await postJushuitan(combineCredentials, COMBINESKU_UPLOAD_PATH, { + items: batch, + }), ) + batchRows.forEach((row) => externallySucceededSkuIds.add(row.sku.id)) + } catch (error) { + const succeededSkuIds = Array.from(externallySucceededSkuIds) + if (succeededSkuIds.length > 0) { + throw new JushuitanProductPricingPushPartialFailureError( + '聚水潭部分商品已推送成功,后续组合商品推送失败;已成功 SKU 将锁定,请勿重复操作并人工核对', + error, + succeededSkuIds, + 'combine-item-upload', + ) + } + throw error } - throw error } } diff --git a/furniture-3d-system/src/server/services/operation-log-failure-notification.service.ts b/furniture-3d-system/src/server/services/operation-log-failure-notification.service.ts new file mode 100644 index 00000000..6244043e --- /dev/null +++ b/furniture-3d-system/src/server/services/operation-log-failure-notification.service.ts @@ -0,0 +1,358 @@ +import 'server-only' + +import { OperationLogAction, OperationLogStatus } from '@prisma/client' +import { + notificationDeliveryRepository, + type NotificationRecipient, +} from '@/server/repositories/notification-delivery.repository' +import { + notificationDeliveryService, + type RecordUndeliverableNotificationInput, + type SendEmployeeNotificationInput, +} from './notification-delivery.service' + +export const OPERATION_LOG_FAILURE_BUSINESS_EVENT = 'operation_log_failure' + +const FAILURE_STATUSES = new Set([ + OperationLogStatus.FAILED, + OperationLogStatus.RETRY, +]) + +/** + * 定时任务批量写入的错误码:一次运行会产生上千条失败日志, + * 按长窗口折叠成一条通知;其余错误码按业务对象在短窗口内合并。 + */ +const FOLDED_ERROR_CODES = new Set(['JUSHUITAN_FIXED_VIRTUAL_INVENTORY_FAILED']) +const FOLDED_WINDOW_MINUTES = 60 +const DEFAULT_WINDOW_MINUTES = 10 +const DEFAULT_RECIPIENT_NAME = '徐霞客' +const DEFAULT_HOURLY_LIMIT = 30 +const RECIPIENT_CACHE_TTL_MS = 10 * 60 * 1000 +const REASON_MAX_LENGTH = 400 +const SHANGHAI_OFFSET_MS = 8 * 60 * 60 * 1000 + +const ACTION_LABELS: Record = { + INTAKE_PRODUCT_CREATE: '新建产品开发明细', + INTAKE_PRODUCT_WRITE: '产品资料保存', + INTAKE_PRODUCT_DELETE: '删除产品开发明细', + INTAKE_FILE_UPLOAD: '文件上传', + INTAKE_WORKSPACE_CONFIRMATION: '节点确认', + JUSHUITAN_PRODUCT_PUSH: '聚水潭商品推送', + JUSHUITAN_VIRTUAL_INVENTORY_PUSH: '聚水潭虚拟库存推送', + SUPPLY_CHAIN_DROPSHIP_ISSUE_WRITE: '代发问题单写入', +} + +export type OperationLogFailurePayload = { + action: OperationLogAction + status: OperationLogStatus + source?: 'USER' | 'SYSTEM' | null + actorName: string + productSpu?: string | null + skuCode?: string | null + workspaceCategory?: string | null + errorCode?: string | null + message: string + requestId?: string | null + createdAt?: Date | null +} + +export type OperationLogFailureNotificationOutcome = + | 'sent' + | 'ignored' + | 'skipped-duplicate' + | 'skipped-rate-limit' + | 'undeliverable' + | 'error' + +export type OperationLogFailureNotificationResult = { + outcome: OperationLogFailureNotificationOutcome + idempotencyKey: string | null + recipientName: string | null + detail: string | null +} + +export type OperationLogFailureNotificationDeps = { + findRecipientsByNames(names: string[]): Promise + findByIdempotencyKey(idempotencyKey: string): Promise<{ id: string } | null> + sendToEmployee(input: SendEmployeeNotificationInput): Promise + recordUndeliverable(input: RecordUndeliverableNotificationInput): Promise + now(): Date +} + +function resolveRecipientName() { + return (process.env.OPERATION_LOG_NOTIFIER_RECIPIENT || DEFAULT_RECIPIENT_NAME).trim() +} + +function pad(value: number) { + return String(value).padStart(2, '0') +} + +/** 统一按北京时间展示,不依赖服务器时区。 */ +export function formatShanghaiTimestamp(date: Date) { + const shifted = new Date(date.getTime() + SHANGHAI_OFFSET_MS) + return [ + `${shifted.getUTCFullYear()}-${pad(shifted.getUTCMonth() + 1)}-${pad(shifted.getUTCDate())}`, + `${pad(shifted.getUTCHours())}:${pad(shifted.getUTCMinutes())}:${pad(shifted.getUTCSeconds())}`, + ].join(' ') +} + +function collapseWhitespace(value: string) { + return value.replace(/\s+/g, ' ').trim() +} + +function truncate(value: string, maxLength: number) { + const normalized = collapseWhitespace(value) + return normalized.length <= maxLength ? normalized : `${normalized.slice(0, maxLength)}…` +} + +function stripActionPrefix(message: string, actionLabel: string) { + const normalized = message.trim() + const prefix = `${actionLabel}失败:` + return normalized.startsWith(prefix) ? normalized.slice(prefix.length).trim() : normalized +} + +export function isFoldedOperationLogError(errorCode: string | null | undefined) { + return Boolean(errorCode && FOLDED_ERROR_CODES.has(errorCode)) +} + +export function describeOperationLogAction(action: OperationLogAction) { + return ACTION_LABELS[action] ?? action +} + +/** + * 通知与幂等键对同一窗口必须保持稳定:折叠类不含业务对象, + * 因此一次定时任务的上千条失败只会命中同一个幂等键。 + */ +export function buildOperationLogFailureNotificationKey(input: { + action: OperationLogAction + errorCode?: string | null + productSpu?: string | null + skuCode?: string | null + now: Date +}) { + const folded = isFoldedOperationLogError(input.errorCode) + const windowMs = (folded ? FOLDED_WINDOW_MINUTES : DEFAULT_WINDOW_MINUTES) * 60 * 1000 + const bucket = Math.floor(input.now.getTime() / windowMs) + const parts = [ + 'oplog-failure', + folded ? 'folded' : 'scoped', + String(bucket), + input.action, + input.errorCode?.trim() || 'UNKNOWN', + ] + if (!folded) { + parts.push(input.productSpu?.trim() || '-', input.skuCode?.trim() || '-') + } + return parts.join(':') +} + +export function buildOperationLogFailureMessage(input: OperationLogFailurePayload) { + const actionLabel = describeOperationLogAction(input.action) + const title = `${actionLabel}失败` + const folded = isFoldedOperationLogError(input.errorCode) + const sourceLabel = (input.source ?? 'USER') === 'SYSTEM' ? '系统任务' : '人工操作' + + const identity = [ + input.productSpu?.trim() ? `产品:${input.productSpu.trim()}` : null, + input.skuCode?.trim() ? `SKU:${input.skuCode.trim()}` : null, + input.workspaceCategory?.trim() ? `节点:${input.workspaceCategory.trim()}` : null, + ].filter((line): line is string => Boolean(line)) + + const lines = [ + `动作:${actionLabel}`, + `时间:${formatShanghaiTimestamp(input.createdAt ?? new Date())}`, + `人员:${input.actorName.trim() || '未知'}(${sourceLabel})`, + ...(identity.length > 0 ? [identity.join(' / ')] : []), + ...(input.errorCode?.trim() ? [`错误码:${input.errorCode.trim()}`] : []), + `原因:${truncate(stripActionPrefix(input.message, actionLabel), REASON_MAX_LENGTH)}`, + ] + + if (folded) { + lines.push(`说明:该错误码在 ${FOLDED_WINDOW_MINUTES} 分钟内多次出现时只通知一次`) + } + + // 钉钉按 Markdown 渲染:单个 \n 会被合并成空格,必须用空行分段才能每条独立成行。 + return { title, content: lines.join('\n\n') } +} + +export class OperationLogFailureNotificationService { + private recipientCache: { name: string; recipient: NotificationRecipient; at: number } | null = null + private readonly hourlyCounters = new Map() + + constructor( + private readonly deps: OperationLogFailureNotificationDeps = { + findRecipientsByNames: (names) => notificationDeliveryRepository.findRecipientsByNames(names), + findByIdempotencyKey: (key) => notificationDeliveryRepository.findByIdempotencyKey(key), + sendToEmployee: (input) => notificationDeliveryService.sendToEmployee(input), + recordUndeliverable: (input) => notificationDeliveryService.recordUndeliverable(input), + now: () => new Date(), + }, + ) {} + + /** + * 失败日志通知的唯一入口。调用方必须 fire-and-forget,本方法自身绝不抛错。 + */ + async notify(input: OperationLogFailurePayload): Promise { + try { + return await this.dispatch(input) + } catch (error) { + console.error('[OperationLogFailureNotify] 推送失败日志通知时发生异常', error) + return { + outcome: 'error', + idempotencyKey: null, + recipientName: null, + detail: error instanceof Error ? error.message : String(error), + } + } + } + + private async dispatch( + input: OperationLogFailurePayload, + ): Promise { + if (!FAILURE_STATUSES.has(input.status)) { + return { outcome: 'ignored', idempotencyKey: null, recipientName: null, detail: '非失败状态' } + } + + const now = this.deps.now() + const idempotencyKey = buildOperationLogFailureNotificationKey({ + action: input.action, + errorCode: input.errorCode, + productSpu: input.productSpu, + skuCode: input.skuCode, + now, + }) + + const existing = await this.deps.findByIdempotencyKey(idempotencyKey) + if (existing) { + return { + outcome: 'skipped-duplicate', + idempotencyKey, + recipientName: null, + detail: '同一时间窗内已通知过', + } + } + + if (!this.consumeRateLimit(now)) { + console.warn(`[OperationLogFailureNotify] 超过每小时推送上限,已跳过:${idempotencyKey}`) + return { + outcome: 'skipped-rate-limit', + idempotencyKey, + recipientName: null, + detail: '超过每小时推送上限', + } + } + + const { title, content } = buildOperationLogFailureMessage(input) + const recipient = await this.resolveRecipient(now) + + if (!recipient || !recipient.dingtalkUserId?.trim()) { + const name = resolveRecipientName() + const errorCode = recipient ? 'RECIPIENT_DINGTALK_UNBOUND' : 'RECIPIENT_NOT_FOUND' + const errorMessage = recipient + ? `收件人 ${recipient.name} 尚未绑定钉钉账号` + : `未找到系统用户:${name}` + await this.deps.recordUndeliverable({ + idempotencyKey, + businessEvent: OPERATION_LOG_FAILURE_BUSINESS_EVENT, + businessRecordId: input.requestId?.trim() || undefined, + source: 'SYSTEM', + recipient: recipient + ? { + id: recipient.id, + name: recipient.name, + email: recipient.email, + dingtalkUserId: recipient.dingtalkUserId ?? '', + } + : { + id: name, + name, + email: '', + dingtalkUserId: '', + }, + title, + content, + errorCode, + errorMessage, + }) + return { outcome: 'undeliverable', idempotencyKey, recipientName: recipient?.name ?? null, detail: errorCode } + } + + await this.deps.sendToEmployee({ + idempotencyKey, + businessEvent: OPERATION_LOG_FAILURE_BUSINESS_EVENT, + businessRecordId: input.requestId?.trim() || undefined, + source: 'SYSTEM', + recipientUserId: recipient.id, + title, + content, + retryExisting: false, + }) + + return { outcome: 'sent', idempotencyKey, recipientName: recipient.name, detail: null } + } + + private async resolveRecipient(now: Date): Promise { + const name = resolveRecipientName() + const cached = this.recipientCache + if (cached && cached.name === name && now.getTime() - cached.at < RECIPIENT_CACHE_TTL_MS) { + return cached.recipient + } + + const users = await this.deps.findRecipientsByNames([name]) + const recipient = users.find((user) => user.name === name) ?? null + if (recipient) this.recipientCache = { name, recipient, at: now.getTime() } + return recipient + } + + /** 逐小时熔断:只在确认要真正发送时计数,被幂等键挡下的重复不计入。 */ + private consumeRateLimit(now: Date) { + const configured = Number(process.env.OPERATION_LOG_NOTIFIER_HOURLY_LIMIT) + const limit = Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_HOURLY_LIMIT + const bucket = String(Math.floor(now.getTime() / 3_600_000)) + + for (const key of [...this.hourlyCounters.keys()]) { + if (key !== bucket) this.hourlyCounters.delete(key) + } + + const used = this.hourlyCounters.get(bucket) ?? 0 + if (used >= limit) return false + this.hourlyCounters.set(bucket, used + 1) + return true + } + + /** 手动测试入口:绕过幂等键,直接给收件人发一条测试通知。 */ + async sendTestNotification() { + const now = this.deps.now() + const recipient = await this.resolveRecipient(now) + if (!recipient) { + throw new Error(`未找到系统用户:${resolveRecipientName()}`) + } + + const { title, content } = buildOperationLogFailureMessage({ + action: OperationLogAction.INTAKE_PRODUCT_WRITE, + status: OperationLogStatus.FAILED, + source: 'USER', + actorName: recipient.name, + productSpu: 'TEST-SPU', + workspaceCategory: '样包测量', + errorCode: 'P2028', + message: '产品资料保存失败:链路测试消息,收到即代表失败日志通知已接通', + createdAt: now, + }) + + const idempotencyKey = `oplog-failure-test:${now.getTime()}` + await this.deps.sendToEmployee({ + idempotencyKey, + businessEvent: `${OPERATION_LOG_FAILURE_BUSINESS_EVENT}_test`, + source: 'SYSTEM', + recipientUserId: recipient.id, + title: `(测试)${title}`, + content, + retryExisting: false, + }) + + return { idempotencyKey, recipientName: recipient.name, title, content } + } +} + +export const operationLogFailureNotificationService = new OperationLogFailureNotificationService() diff --git a/furniture-3d-system/src/server/services/operation-log.service.ts b/furniture-3d-system/src/server/services/operation-log.service.ts index 67760867..e00aed05 100644 --- a/furniture-3d-system/src/server/services/operation-log.service.ts +++ b/furniture-3d-system/src/server/services/operation-log.service.ts @@ -9,6 +9,7 @@ import { type OperationLogFilter, type OperationLogWithActor, } from '@/server/repositories/operation-log.repository' +import { operationLogFailureNotificationService } from './operation-log-failure-notification.service' export { OperationLogAction, OperationLogStatus } export type OperationLogInput = CreateOperationLogInput @@ -40,12 +41,40 @@ class OperationLogService { async record(input: OperationLogInput): Promise { try { await operationLogRepository.create(input) + this.notifyFailureInBackground(input) } catch (error) { // Logging must never prevent the business operation from completing. console.error('[OperationLog] Failed to record operation', error) } } + /** + * 失败日志通知是旁路能力:不 await、不抛错。 + * 既不拖慢保存等业务响应,也不影响日志写入本身。 + */ + private notifyFailureInBackground(input: OperationLogInput) { + if (input.status === OperationLogStatus.SUCCESS) return + // 单测环境保持静默,避免自动化测试真的发出外部通知。 + if (process.env.NODE_ENV === 'test') return + + void operationLogFailureNotificationService + .notify({ + action: input.action, + status: input.status, + source: input.source, + actorName: input.actorName, + productSpu: input.productSpu, + skuCode: input.skuCode, + workspaceCategory: input.workspaceCategory, + errorCode: input.errorCode, + message: input.message, + requestId: input.requestId, + }) + .catch((error) => { + console.error('[OperationLog] Failed to notify failure log', error) + }) + } + async list(options: OperationLogListOptions = {}) { const page = Math.max(1, options.page ?? 1) const pageSize = Math.min(200, Math.max(1, options.pageSize ?? 50)) diff --git a/furniture-3d-system/src/server/services/supply-chain-product-archive-enrichment-sync.mapper.ts b/furniture-3d-system/src/server/services/supply-chain-product-archive-enrichment-sync.mapper.ts index 67bc4f79..523e2ff1 100644 --- a/furniture-3d-system/src/server/services/supply-chain-product-archive-enrichment-sync.mapper.ts +++ b/furniture-3d-system/src/server/services/supply-chain-product-archive-enrichment-sync.mapper.ts @@ -324,20 +324,33 @@ export function buildProductArchiveEnrichmentUpdates( { warehouseType: 'remark2' }, ), }, - ...(warehouseConfig ? [{ - patch: { - warehouseHead: warehouseConfig.warehouseHead, - storageType: warehouseConfig.storageType, + ...(warehouseConfig ? [ + { + patch: { warehouseHead: warehouseConfig.warehouseHead }, + source: source( + WAREHOUSE_CONFIG_ARCHIVE_SOURCE_CODE, + CONFIG_SOURCE_SYSTEM, + PUBLIC_SOURCE_SCHEMA, + 'SupplyChainProductArchiveWarehouseConfig', + warehouseConfig.id, + { warehouseHead: 'warehouseHead' }, + ), }, - source: source( - WAREHOUSE_CONFIG_ARCHIVE_SOURCE_CODE, - CONFIG_SOURCE_SYSTEM, - PUBLIC_SOURCE_SCHEMA, - 'SupplyChainProductArchiveWarehouseConfig', - warehouseConfig.id, - { warehouseHead: 'warehouseHead', storageType: 'storageType' }, - ), - }] : []), + { + // 入库/代发只填空值:产品定厂的「发货方式」是采购在定厂时的明确决策, + // 档案里已有值(定厂带回)不能被仓库配置覆盖;没填过的才由仓库配置兜底。 + patch: { storageType: warehouseConfig.storageType }, + source: source( + WAREHOUSE_CONFIG_ARCHIVE_SOURCE_CODE, + CONFIG_SOURCE_SYSTEM, + PUBLIC_SOURCE_SCHEMA, + 'SupplyChainProductArchiveWarehouseConfig', + warehouseConfig.id, + { storageType: 'storageType' }, + { fillEmptyOnly: true }, + ), + }, + ] : []), ...(isDropshipSku ? [ { diff --git a/furniture-3d-system/src/server/services/supply-chain-product-archive-query.ts b/furniture-3d-system/src/server/services/supply-chain-product-archive-query.ts index 2705a9f6..9c3c82a5 100644 --- a/furniture-3d-system/src/server/services/supply-chain-product-archive-query.ts +++ b/furniture-3d-system/src/server/services/supply-chain-product-archive-query.ts @@ -3,6 +3,7 @@ import { validSalesSelection } from '@/lib/product-archive-sales-period' import { PRODUCT_ARCHIVE_EMPTY_FILTER_VALUE, PRODUCT_ARCHIVE_SALES_STATUSES, + PRODUCT_ARCHIVE_TEXT_FILTER_KEYS, type ProductArchiveFilters, } from '@/lib/supply-chain-product-archive' @@ -13,6 +14,12 @@ const archiveSalesPeriodSchema = z.string().regex(/^(\d{4}-\d{2}-\d{2}|\d{4}-\d{ // candidate list (e.g. thousands of SPUs) — such payloads arrive via POST body // once they outgrow the query string. const archiveValueArraySchema = z.array(z.string().trim().max(200)).max(20000) +// 「只看正常编码」与「排除以…开头」只开放给 NOT NULL 的文本列。 +const archiveTextFilterKeySchema = z.enum(PRODUCT_ARCHIVE_TEXT_FILTER_KEYS) +const archiveExcludeRuleSchema = z.object({ + field: archiveTextFilterKeySchema, + startsWith: z.string().trim().min(1).max(64), +}).strict() const productArchiveFiltersSchema = z.object({ salesGranularity: archiveSalesGranularitySchema.optional(), @@ -110,6 +117,8 @@ const productArchiveFiltersSchema = z.object({ createTimeTo: archiveDateSchema.optional(), updateTimeFrom: archiveDateSchema.optional(), updateTimeTo: archiveDateSchema.optional(), + normalCodeOnly: z.array(archiveTextFilterKeySchema).max(PRODUCT_ARCHIVE_TEXT_FILTER_KEYS.length).optional(), + excludeStartsWith: z.array(archiveExcludeRuleSchema).max(20).optional(), }).strict().refine(validSalesSelection, { message: '销售统计周期不正确', path: ['salesPeriod'] }) export function parseProductArchiveFilters(raw: string | null) { diff --git a/furniture-3d-system/src/server/services/supply-chain-product-archive-sales-performance-daily-sync.service.test.ts b/furniture-3d-system/src/server/services/supply-chain-product-archive-sales-performance-daily-sync.service.test.ts index 3f79d9da..d08af842 100644 --- a/furniture-3d-system/src/server/services/supply-chain-product-archive-sales-performance-daily-sync.service.test.ts +++ b/furniture-3d-system/src/server/services/supply-chain-product-archive-sales-performance-daily-sync.service.test.ts @@ -7,7 +7,7 @@ import type { SalesSyncSession } from '@/server/repositories/supply-chain-produc function setup(latest: string | null = '2026-09-01') { const row = (statDate: string): ProductArchiveSalesPerformanceDailyAggregate => ({ barcode: 'BAR', statDate, sourceRowCount: 1, shipAmount: '10', returnAmount: '0', - salesAmount: '25', skuOperator: '', unitCost: null, + salesAmount: '25', skuOperator: '', unitCost: null, estimatedFreight: null, realPerformance: '20', shipQty: '1', returnQty: '0', clearSalesCost: '5', sendFreight: '2', platformCommission: '1', xyCost: '0', afterSaleAmount: '0', pushFeeTotal: '0', marketingFeeTotal: '0', advertisementFeeTotal: '0', sharedWarehousingSum: '0', otherFee: '0', operatingFee: '0', diff --git a/furniture-3d-system/src/server/services/supply-chain-product-archive-sync.service.ts b/furniture-3d-system/src/server/services/supply-chain-product-archive-sync.service.ts index bdc95c03..67beab87 100644 --- a/furniture-3d-system/src/server/services/supply-chain-product-archive-sync.service.ts +++ b/furniture-3d-system/src/server/services/supply-chain-product-archive-sync.service.ts @@ -5,7 +5,7 @@ import { toProductArchiveFieldSourceJson, } from '@/lib/supply-chain-product-archive-field-source' import { calculateProductArchiveVolumeDecimal } from '@/lib/supply-chain-product-archive-volume' -import { normalizeProductArchiveOrderType } from '@/lib/supply-chain-product-archive-values' +import { normalizeProductArchiveOrderType, storageTypeFromShippingMethodLabel } from '@/lib/supply-chain-product-archive-values' import { PRODUCT_DEVELOPMENT_ARCHIVE_SOURCE, supplyChainProductArchiveSyncRepository, @@ -120,8 +120,13 @@ export function mapProductCatalogWideArchiveSource( const height = numericText(record.package_height_cm) const skuImage = text(record.archive_image) const skuImageUrl = skuImage ? text(record.sku_image_url) || skuImage : '' + // 产品定厂「发货方式」(入仓/代发)→ 档案「入库/代发」库值;定厂没填就不写,交给仓库配置兜底 + const shippingStorageType = storageTypeFromShippingMethodLabel(record.shipping_method) + const fieldColumns = shippingStorageType + ? { ...PRODUCT_DEVELOPMENT_ARCHIVE_FIELD_COLUMNS, storageType: 'shipping_method' } + : PRODUCT_DEVELOPMENT_ARCHIVE_FIELD_COLUMNS const fieldSourceMap = createProductArchiveFieldSourceMap({ - fields: PRODUCT_DEVELOPMENT_ARCHIVE_FIELD_COLUMNS, + fields: fieldColumns, sourceCode: PRODUCT_DEVELOPMENT_ARCHIVE_SOURCE_CODE, sourceSystem: PRODUCT_DEVELOPMENT_ARCHIVE_SOURCE.sourceSystem, sourceSchema: PRODUCT_DEVELOPMENT_ARCHIVE_SOURCE.sourceSchema, @@ -159,6 +164,7 @@ export function mapProductCatalogWideArchiveSource( inOutWarehouse: text(record.factory_warehouse), isSeasonal: '', replaceCount: '', + ...(shippingStorageType ? { storageType: shippingStorageType } : {}), supplierName: text(record.archive_supplier_name), purchaseOwner: text(record.archive_purchase_owner), minimumOrderQuantity: text(record.archive_minimum_order_quantity), diff --git a/furniture-3d-system/src/server/services/supply-chain-product-archive.service.ts b/furniture-3d-system/src/server/services/supply-chain-product-archive.service.ts index 55f405a8..b35a3c7d 100644 --- a/furniture-3d-system/src/server/services/supply-chain-product-archive.service.ts +++ b/furniture-3d-system/src/server/services/supply-chain-product-archive.service.ts @@ -36,7 +36,7 @@ export function resolveProductArchiveWarehouseFields(input: { ), warehouseHead: configured?.warehouseHead ?? input.currentWarehouseHead, storageType: configured?.storageType - ? configured.storageType === 'INBOUND' ? '入库' : '代发' + ? configured.storageType === 'INBOUND' ? '入仓' : '代发' : input.currentStorageType, } }