Merge remote-tracking branch 'origin/codex/xuxiake-mainline' into codex/xuxiake-mainline

This commit is contained in:
居居 2026-09-21 14:25:22 +08:00
commit e9cb61e18c
134 changed files with 12899 additions and 623 deletions

View File

@ -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.

View File

@ -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 实测,不影响 ①② 开发)。

View File

@ -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",

View File

@ -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");

View File

@ -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");

View File

@ -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);

View File

@ -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])
}

View File

@ -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=<id> 指定 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<T>(operation: () => Promise<T>, attempts = 8): Promise<T> {
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<LineProbe> {
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<string, { priced: number; total: number }>()
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<Record<string, unknown>> = []
let totalLines = 0
let totalCandidatesHit = 0
let totalProfileFallback = 0
let totalV1Priced = 0
const categoryStats = new Map<string, { lines: number; candidatesHit: number; profileFallback: number; v1Priced: number }>()
// 只探测前 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<string, unknown> | 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)
})

View File

@ -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=<SKU记录ID>] [--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> 指定案例 ID(与 --latest 二选一)',
' --sku=<id> 指定 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(

View File

@ -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 },
)
}

View File

@ -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,

View File

@ -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 },
)
}

View File

@ -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 },
)
}

View File

@ -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 })

View File

@ -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),

View File

@ -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('采购甲')
})
})

View File

@ -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 })
}

View File

@ -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()
})
})

View File

@ -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 })
}

View File

@ -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()
})
})

View File

@ -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 })
}

View File

@ -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<string, string> = {
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<Phase>('idle')
const [errorMessage, setErrorMessage] = useState('')
const [caseId, setCaseId] = useState<string | null>(null)
const [card, setCard] = useState<BomEstimateCard | null>(null)
const [images, setImages] = useState<PreviewImage[]>([])
const [imageTab, setImageTab] = useState<PreviewImage['kind'] | 'ALL'>('ALL')
const [selectedImageId, setSelectedImageId] = useState<string | null>(null)
const [pendingSkuId, setPendingSkuId] = useState<string | null>(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 (
<div className="mx-auto w-full max-w-6xl px-4 py-6">
<ToastContainer toasts={toasts} onClose={removeToast} position="top" />
<header className="mb-4">
<h1 className="text-base font-bold text-[#2f3a3d]">BOM 成本预估</h1>
<p className="mt-0.5 text-xs text-[#6a7a7d]">粘贴竞品链接,先出代表 SKU 的成本预估,其余 SKU 点击逐个核算(v2 预览)。</p>
</header>
<div className="flex items-center gap-2 rounded-[8px] bg-white p-3 ring-1 ring-black/[0.06]">
<Input
value={sourceUrl}
onChange={(event) => setSourceUrl(event.target.value)}
placeholder="粘贴竞品商品链接(淘宝/天猫/1688/京东/抖音)"
disabled={busy}
className="h-9 flex-1 text-xs"
/>
<Button size="small" onClick={handleEstimate} disabled={busy || !sourceUrl.trim()} className="h-9">
{busy ? '预估中…' : '开始预估'}
</Button>
</div>
{busy && (
<div className="mt-4 flex items-center gap-3 rounded-[8px] bg-white px-4 py-3 text-xs text-[#4a5a5d] ring-1 ring-black/[0.06]">
<span className="h-3 w-3 animate-spin rounded-full border-2 border-[#47646b] border-t-transparent" />
{phase === 'creating' ? '正在读取竞品资料与归档图片…' : 'AI 正在看图拆结构、检索公司历史价格…(约 2-3 分钟,请保持页面打开)'}
</div>
)}
{phase === 'error' && (
<div className="mt-4 rounded-[8px] bg-red-500/[0.06] px-4 py-3 text-xs text-red-600 ring-1 ring-red-500/20">
{errorMessage}
</div>
)}
{card && phase === 'ready' && (
<div className="mt-4 space-y-4">
<section className="rounded-[10px] bg-white p-5 ring-1 ring-black/[0.06]">
<h2 className="text-sm font-bold text-[#2f3a3d]">{card.title || '竞品成本预估'}</h2>
<div className="mt-2 flex flex-wrap items-baseline gap-x-3 gap-y-1">
<span className="text-2xl font-black tracking-tight text-[#2f3a3d]">
{card.totalRange ? `¥${card.totalRange.min} – ${card.totalRange.max}` : '暂未形成区间'}
</span>
<span className="rounded-[4px] bg-[#47646b]/10 px-1.5 py-0.5 text-[10px] font-bold text-[#47646b]">
置信度 {confidenceLabel(card.confidence)}{card.confidence !== null ? ` ${Math.round(card.confidence * 100)}%` : ''}
</span>
<span className="text-[10px] text-[#8a9799]">已核算 {card.estimatedSkuCount}/{card.skus.length} 个 SKU</span>
</div>
<div className="mt-3 flex flex-wrap gap-x-4 gap-y-1 text-xs text-[#4a5a5d]">
{card.breakdown.map((row) => (
<span key={row.category}>
{BREAKDOWN_LABELS[row.category] ?? row.category}
<span className="ml-1 font-bold text-[#2f3a3d]">{row.total === null ? '待补' : `¥${row.total}`}</span>
</span>
))}
</div>
{card.openQuestions.length > 0 && (
<p className="mt-3 rounded-[6px] bg-amber-500/[0.06] px-3 py-2 text-[11px] leading-4 text-[#8a5f3f]">
不确定:{card.openQuestions.slice(0, 4).join(';')}
</p>
)}
</section>
<section className="rounded-[10px] bg-white p-4 ring-1 ring-black/[0.06]">
<h3 className="text-xs font-bold text-[#2f3a3d]">SKU 列表</h3>
<ul className="mt-2 divide-y divide-black/[0.04]">
{card.skus.map((sku) => (
<li key={sku.skuId} className="flex items-center justify-between gap-3 py-2 text-xs">
<div className="min-w-0 flex-1">
<span className="font-bold text-[#2f3a3d]">{sku.externalSkuId}</span>
<span className="ml-2 truncate text-[#6a7a7d]">{sku.name}</span>
{sku.firstBatch && (
<span className="ml-2 rounded-[3px] bg-[#47646b]/10 px-1 py-px text-[9px] font-bold text-[#47646b]">首批</span>
)}
</div>
{sku.status === 'ESTIMATED' && sku.estimate ? (
<span className="shrink-0 font-bold text-[#2f3a3d]">
¥{sku.estimate.estimateRange.min} – {sku.estimate.estimateRange.max}
</span>
) : sku.status === 'FAILED' ? (
<Button size="small" variant="gray" className="h-7 text-[10px]" onClick={() => handleEstimateSku(sku.skuId)} disabled={pendingSkuId !== null}>
{pendingSkuId === sku.skuId ? '核算中…' : '重新核算'}
</Button>
) : (
<Button size="small" variant="gray" className="h-7 text-[10px]" onClick={() => handleEstimateSku(sku.skuId)} disabled={pendingSkuId !== null}>
{pendingSkuId === sku.skuId ? '核算中…' : '点击核算'}
</Button>
)}
</li>
))}
</ul>
</section>
{images.length > 0 && (
<section className="rounded-[10px] bg-white p-4 ring-1 ring-black/[0.06]">
<div className="flex items-center justify-between">
<h3 className="text-xs font-bold text-[#2f3a3d]">商品图片</h3>
<div className="flex gap-1">
{IMAGE_TABS.map((tab) => (
<button
key={tab.key}
onClick={() => { setImageTab(tab.key); setSelectedImageId(null) }}
className={cn(
'rounded-[5px] px-2 py-1 text-[10px] font-bold transition',
imageTab === tab.key ? 'bg-[#47646b] text-white' : 'bg-black/[0.04] text-[#6a7a7d] hover:bg-black/[0.07]',
)}
>
{tab.label}
</button>
))}
</div>
</div>
{selectedImage && (
/* eslint-disable-next-line @next/next/no-img-element */
<img src={selectedImage.url} alt="竞品图片" className="mt-3 max-h-[420px] w-full rounded-[8px] object-contain" />
)}
<div className="mt-3 flex gap-2 overflow-x-auto pb-1">
{visibleImages.map((image) => (
<button
key={image.assetId}
onClick={() => setSelectedImageId(image.assetId)}
className={cn(
'h-16 w-16 shrink-0 overflow-hidden rounded-[6px] ring-1 transition',
selectedImage?.assetId === image.assetId ? 'ring-2 ring-[#47646b]' : 'ring-black/[0.08] hover:ring-black/20',
)}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={image.url} alt={`${image.kind} 图片`} className="h-full w-full object-cover" />
</button>
))}
</div>
</section>
)}
</div>
)}
</div>
)
}

View File

@ -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 <EstimateClient />
}

View File

@ -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<string | null>(null);
const [shareExpiresAt, setShareExpiresAt] = useState<string | null>(null);
const [shareLoading, setShareLoading] = useState(false);
const [shareMessage, setShareMessage] = useState<string | null>(null);
const [shareCopied, setShareCopied] = useState(false);
const [qrShareUrl, setQrShareUrl] = useState<string | null>(null);
const [qrShareLoading, setQrShareLoading] = useState(false);
const [qrShareMessage, setQrShareMessage] = useState<string | null>(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 (
<div className="asset-center-obsidian flex h-full min-h-0 flex-col overflow-hidden bg-[#f8f9fa] text-[#2d3335] lg:flex-row">
<div className="asset-center-obsidian flex h-[calc(100dvh-56px)] min-h-[calc(100dvh-56px)] flex-col overflow-hidden bg-[#f8f9fa] text-[#2d3335] lg:h-[calc(100dvh-64px)] lg:min-h-[calc(100dvh-64px)] lg:flex-row">
<InstallationPreviewStage
drawing={catalog.selectedDrawing}
modelUrl={modelUrl}

View File

@ -60,7 +60,12 @@ interface InstallationDetailsPanelProps {
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

View File

@ -52,21 +52,19 @@ export function InstallationDrawingToolSelection({
{tools.map((tool) => {
const selected = selectedToolIdSet.has(tool.id)
return (
<label
<button
key={tool.id}
type="button"
role="checkbox"
aria-checked={selected}
disabled={!canEdit}
onClick={() => onToggleTool(tool.id)}
className={[
'flex cursor-pointer items-center gap-3 rounded-[8px] border px-3 py-2.5 transition',
'relative flex w-full cursor-pointer items-center gap-3 rounded-[8px] border px-3 py-2.5 text-left transition',
selected ? 'border-[#2d3335]/30 bg-[#f5f7f8]' : 'border-black/[0.06] hover:bg-black/[0.02]',
!canEdit ? 'cursor-default' : '',
].join(' ')}
>
<input
type="checkbox"
checked={selected}
disabled={!canEdit}
onChange={() => onToggleTool(tool.id)}
className="sr-only"
/>
<span
className={[
'flex h-5 w-5 shrink-0 items-center justify-center rounded-[5px] border',
@ -79,7 +77,7 @@ export function InstallationDrawingToolSelection({
<span className="block truncate text-[12px] font-black text-[#2d3335]">{tool.name}</span>
<span className="mt-0.5 block truncate text-[10px] font-semibold text-[#8b9092]">{tool.toolCode} · {tool.fileName}</span>
</span>
</label>
</button>
)
})}
</div>

View File

@ -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

View File

@ -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 ? <RefreshCw size={14} strokeWidth={1.8} /> : <Link2 size={14} strokeWidth={1.8} />}
{loading ? '生成中' : shareUrl ? '重新生成' : '生成链接'}
{loading ? '处理中' : shareUrl ? '更新链接内容' : '生成链接'}
</button>
{shareUrl ? (
<button

View File

@ -20,6 +20,7 @@ interface HardwareCompositeCandidateSummary {
partId: string
groupCount: number
nodeCount: number
composite: boolean
}
interface PartCatalogSectionProps {
@ -495,7 +496,9 @@ export function PartCatalogSection({
{compositeCandidate ? (
<>
<span className="text-[11px] font-black text-[#2d3335]">
找到 {compositeCandidate.groupCount} 组同型候选 · {compositeCandidate.nodeCount} 个模型
{compositeCandidate.composite
? `找到 ${compositeCandidate.groupCount} 组同型候选 · ${compositeCandidate.nodeCount} 个模型`
: `找到 ${compositeCandidate.nodeCount} 个同型候选`}
</span>
<button
type="button"

View File

@ -54,7 +54,7 @@ export function useInstallationDrawingConfirmation({
}
const share = await syncInstallationDemoQrShare(shareInput);
onQrShareSynced(share);
setMessage("图纸样式已确认,永久二维码已同步;分享链接请重新生成");
setMessage("图纸样式已确认,永久二维码已同步;已有分享链接会自动更新");
return true;
} catch (error) {
const detail =

View File

@ -0,0 +1,85 @@
import { act, renderHook, waitFor } from '@testing-library/react'
import {
fetchInstallationDemoNumberingConfig,
saveInstallationDemoNumberingConfig,
} from '@/lib/open-product/platform-api'
import { getHardwareCompositeGroups } from '../lib/installationHardwareComposite'
import { useInstallationNumberingCatalog } from './useInstallationNumberingCatalog'
jest.mock('@/lib/open-product/platform-api', () => ({
fetchInstallationDemoNumberingConfig: jest.fn(),
saveInstallationDemoNumberingConfig: jest.fn(),
}))
const mockedFetchConfig = jest.mocked(fetchInstallationDemoNumberingConfig)
const mockedSaveConfig = jest.mocked(saveInstallationDemoNumberingConfig)
describe('useInstallationNumberingCatalog peer assignment', () => {
beforeEach(() => {
window.localStorage.clear()
jest.clearAllMocks()
mockedFetchConfig.mockResolvedValue(null)
mockedSaveConfig.mockResolvedValue({} as never)
})
it('adds six peers to two existing normal nodes as eight individual pieces', async () => {
const { result } = renderHook(() =>
useInstallationNumberingCatalog('drawing-normal', true),
)
await waitFor(() => expect(mockedFetchConfig).toHaveBeenCalled())
act(() => result.current.createPartFromNodes(['node-1', 'node-2'], 'hardware'))
await waitFor(() => expect(result.current.parts).toHaveLength(1))
const partId = result.current.parts[0].id
act(() =>
result.current.assignNodesToPart(partId, [
'node-3',
'node-4',
'node-5',
'node-6',
'node-7',
'node-8',
]),
)
await waitFor(() => expect(result.current.parts[0].nodeNames).toHaveLength(8))
expect(result.current.parts[0]).toMatchObject({ quantity: 8 })
expect(getHardwareCompositeGroups(result.current.parts[0])).toEqual([])
})
it('keeps explicitly defined composite hardware grouped when peers are appended', async () => {
const { result } = renderHook(() =>
useInstallationNumberingCatalog('drawing-composite', true),
)
await waitFor(() => expect(mockedFetchConfig).toHaveBeenCalled())
act(() => result.current.createPartFromNodes(['seat-1', 'bolt-1'], 'hardware'))
await waitFor(() => expect(result.current.parts).toHaveLength(1))
const partId = result.current.parts[0].id
act(() =>
result.current.defineHardwareCompositeGroup({
partId,
nodeNames: ['seat-1', 'bolt-1'],
template: { nodeSignatures: ['seat', 'bolt'] },
}),
)
await waitFor(() =>
expect(getHardwareCompositeGroups(result.current.parts[0])).toHaveLength(1),
)
act(() =>
result.current.appendHardwareCompositeGroups(partId, [
['seat-2', 'bolt-2'],
['seat-3', 'bolt-3'],
]),
)
await waitFor(() =>
expect(getHardwareCompositeGroups(result.current.parts[0])).toHaveLength(3),
)
expect(result.current.parts[0]).toMatchObject({ quantity: 3 })
expect(result.current.parts[0].nodeNames).toHaveLength(6)
})
})

View File

@ -0,0 +1,225 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import type {
CreateInstallationDemoShareInput,
InstallationDemoShareLinkDTO,
} from "@/lib/installation-demo-share-types";
import {
createInstallationDemoShareLink,
fetchInstallationDemoShareLink,
syncInstallationDemoShareLink,
} from "@/lib/open-product/platform-api";
import type { InstallationDrawingImageMode } from "../lib/installationDrawingCaptureTypes";
import type { InstallationNumberingSnapshotBatch } from "../lib/installationNumberingSnapshotStorage";
interface UseInstallationShareLinkOptions {
drawingId: string | null;
canShare: boolean;
disabledReason: string | null;
contentRevision: string;
materialDirty: boolean;
confirmedAt: string | null;
confirmedImageMode: InstallationDrawingImageMode | null;
prepareNumberingSnapshotBatch: (
imageMode: InstallationDrawingImageMode,
) => Promise<InstallationNumberingSnapshotBatch | null>;
buildShareInput: (
batch: InstallationNumberingSnapshotBatch,
includeDrawing: boolean,
imageMode: InstallationDrawingImageMode | null,
) => CreateInstallationDemoShareInput | null;
}
export function useInstallationShareLink({
drawingId,
canShare,
disabledReason,
contentRevision,
materialDirty,
confirmedAt,
confirmedImageMode,
prepareNumberingSnapshotBatch,
buildShareInput,
}: UseInstallationShareLinkOptions) {
const [token, setToken] = useState<string | null>(null);
const [url, setUrl] = useState<string | null>(null);
const [expiresAt, setExpiresAt] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const prepareBatchRef = useRef(prepareNumberingSnapshotBatch);
const buildInputRef = useRef(buildShareInput);
const autoSyncSequenceRef = useRef(0);
const applyShare = useCallback((share: InstallationDemoShareLinkDTO) => {
setToken(share.token);
setUrl(share.url);
setExpiresAt(share.expiresAt);
}, []);
useEffect(() => {
prepareBatchRef.current = prepareNumberingSnapshotBatch;
buildInputRef.current = buildShareInput;
}, [buildShareInput, prepareNumberingSnapshotBatch]);
useEffect(() => {
let cancelled = false;
queueMicrotask(() => {
if (cancelled) return;
setToken(null);
setUrl(null);
setExpiresAt(null);
setLoading(false);
setCopied(false);
setMessage(null);
});
if (!drawingId || !canShare) {
return () => {
cancelled = true;
};
}
void fetchInstallationDemoShareLink(drawingId)
.then((share) => {
if (cancelled || !share) return;
setToken(share.token);
setUrl(share.url);
setExpiresAt(share.expiresAt);
})
.catch((error) => {
if (!cancelled) {
setMessage(error instanceof Error ? error.message : "分享链接读取失败");
}
});
return () => {
cancelled = true;
};
}, [canShare, drawingId]);
useEffect(() => {
if (!token || !drawingId || disabledReason || materialDirty) return;
const sequence = ++autoSyncSequenceRef.current;
const timer = window.setTimeout(() => {
void (async () => {
try {
const includeDrawing = Boolean(confirmedAt);
const imageMode = includeDrawing
? (confirmedImageMode ?? "line-art")
: "original";
const batch = await prepareBatchRef.current(imageMode);
if (!batch || autoSyncSequenceRef.current !== sequence) return;
const input = buildInputRef.current(
batch,
includeDrawing,
confirmedImageMode,
);
if (!input) return;
const share = await syncInstallationDemoShareLink(input, token);
if (autoSyncSequenceRef.current !== sequence) return;
applyShare(share);
setMessage("最新改动已同步,分享链接地址保持不变");
} catch (error) {
if (autoSyncSequenceRef.current !== sequence) return;
setMessage(
error instanceof Error
? `分享链接自动同步失败:${error.message}`
: "分享链接自动同步失败",
);
}
})();
}, 1200);
return () => {
window.clearTimeout(timer);
if (autoSyncSequenceRef.current === sequence) {
autoSyncSequenceRef.current += 1;
}
};
}, [
applyShare,
confirmedAt,
confirmedImageMode,
contentRevision,
disabledReason,
drawingId,
materialDirty,
token,
]);
const update = useCallback(async () => {
if (disabledReason) {
setMessage(disabledReason ?? "当前演示还不能分享");
return;
}
setLoading(true);
setMessage(null);
setCopied(false);
try {
const updatingExistingLink = Boolean(token);
const includeDrawing = Boolean(confirmedAt);
const imageMode = includeDrawing
? (confirmedImageMode ?? "line-art")
: "original";
const batch = await prepareNumberingSnapshotBatch(imageMode);
if (!batch) {
throw new Error(
includeDrawing
? "已确认图纸当前模式的部件或工具图读取失败,请重新确认图纸"
: "部件或工具图读取失败,请先保存部件编号图",
);
}
const input = buildShareInput(batch, includeDrawing, confirmedImageMode);
if (!input) throw new Error("当前演示还不能分享");
const share = await createInstallationDemoShareLink(input);
applyShare(share);
setMessage(
updatingExistingLink
? "分享内容已更新,链接地址保持不变"
: input.drawingDocument
? "分享链接已生成,永久有效;后续保存会自动同步"
: "分享链接已生成;后续保存会自动同步当前安装动画",
);
} catch (error) {
setMessage(error instanceof Error ? error.message : "分享链接生成失败");
} finally {
setLoading(false);
}
}, [
buildShareInput,
applyShare,
confirmedAt,
confirmedImageMode,
disabledReason,
prepareNumberingSnapshotBatch,
token,
]);
const copy = useCallback(() => {
if (!url) return;
void navigator.clipboard
.writeText(url)
.then(() => {
setCopied(true);
window.setTimeout(() => setCopied(false), 1600);
})
.catch(() => {
setMessage("复制失败,可以手动选中链接复制");
});
}, [url]);
return {
token,
url,
expiresAt,
loading,
message,
copied,
setMessage,
update,
copy,
};
}

View File

@ -0,0 +1,79 @@
import { act, renderHook } from '@testing-library/react'
import type { ThreeDEngine } from '@/lib/3d/engine'
import type { InstallationStepDraft } from '../types'
import { useInstallationStepActionCommands } from './useInstallationStepActionCommands'
if (typeof globalThis.structuredClone !== 'function') {
globalThis.structuredClone = ((value: unknown) =>
JSON.parse(JSON.stringify(value))) as typeof structuredClone
}
function createStep(): InstallationStepDraft {
return {
id: 'step-1',
order: 1,
title: '安装侧板',
fixedNodeNames: [],
installNodeNames: ['panel-1'],
hardwareNodeNames: [],
direction: 'right',
cameraPreset: 'medium',
durationMs: 1000,
note: '',
workflowVersion: 2,
transformSpace: 'local',
scopeNodeNames: ['panel-1'],
assembledTransforms: undefined,
actions: [],
}
}
describe('useInstallationStepActionCommands state saving', () => {
it('saves the first assembled state with transforms and camera view', () => {
let currentStep = createStep()
const updateStepWith = jest.fn(
(_stepId: string, updater: (step: InstallationStepDraft) => InstallationStepDraft) => {
currentStep = updater(currentStep)
},
)
const engine = {
resolveObjectByNodeName: jest.fn(() => ({
position: { x: 1, y: 2, z: 3 },
quaternion: { x: 0, y: 0, z: 0, w: 1 },
})),
getCamera: jest.fn(() => ({ position: { x: 7, y: 8, z: 9 } })),
getControls: jest.fn(() => ({ target: { x: 4, y: 5, z: 6 } })),
} as unknown as ThreeDEngine
const { result } = renderHook(() =>
useInstallationStepActionCommands({
activeStep: currentStep,
steps: [currentStep],
parts: [],
numberingParts: [],
scopeNodeNames: ['panel-1'],
selectedNodeNames: ['panel-1'],
engine,
canEdit: true,
editTarget: 'posture',
activeActionId: null,
updateStepWith,
}),
)
let saved = false
act(() => {
saved = result.current.saveCurrentCameraView()
})
expect(saved).toBe(true)
expect(currentStep.assembledTransforms?.['panel-1']).toMatchObject({
position: [1, 2, 3],
rotation: [0, 0, 0, 1],
})
expect(currentStep.assembledCameraView).toEqual({
position: [7, 8, 9],
target: [4, 5, 6],
})
})
})

View File

@ -518,9 +518,7 @@ export function useInstallationStepActionWorkspace({
mode === 'edit' &&
isInstallationStepActionWorkflow(activeStep) &&
(editTarget === 'posture' || editTarget === 'expanded') &&
(editScene === 'assembled'
? hasCompleteSceneTransforms(activeStep?.assembledTransforms)
: scopeNodeNames.length > 0),
scopeNodeNames.length > 0,
canAddSelectedAction:
editTarget === 'action' &&
!activeActionId &&

View File

@ -3,11 +3,15 @@ import { BarcodePrintHeader } from "./BarcodePrintHeader";
import { EMPTY_FILTERS } from "./barcodePrintFiltering";
function renderHeader({
canManageImports,
canImportRecords,
canDeleteImports = canImportRecords,
canEditImports = canImportRecords,
canExport = false,
onExport = jest.fn(),
}: {
canManageImports: boolean;
canImportRecords: boolean;
canDeleteImports?: boolean;
canEditImports?: boolean;
canExport?: boolean;
onExport?: () => void;
}) {
@ -17,7 +21,9 @@ function renderHeader({
productCategoryOptions={[]}
salesCategoryOptions={[]}
statusMessage=""
canManageImports={canManageImports}
canImportRecords={canImportRecords}
canDeleteImports={canDeleteImports}
canEditImports={canEditImports}
canExport={canExport}
onBarcodeImport={jest.fn()}
onBrandSkuImport={jest.fn()}
@ -34,7 +40,7 @@ function renderHeader({
describe("BarcodePrintHeader", () => {
it("hides all import controls for users without import permission", () => {
renderHeader({ canManageImports: false });
renderHeader({ canImportRecords: false });
expect(screen.queryByRole("button", { name: "条码导入" })).not.toBeInTheDocument();
expect(
@ -55,7 +61,7 @@ describe("BarcodePrintHeader", () => {
});
it("shows all import controls for designers and administrators", () => {
renderHeader({ canManageImports: true });
renderHeader({ canImportRecords: true });
expect(screen.getByRole("button", { name: "条码导入" })).toBeInTheDocument();
expect(
@ -71,7 +77,7 @@ describe("BarcodePrintHeader", () => {
});
it("places bulk delete and edit actions after the import template actions", () => {
renderHeader({ canManageImports: true });
renderHeader({ canImportRecords: true });
const brandSkuTemplate = screen.getByRole("button", {
name: "品牌货号导入模板下载",
@ -91,10 +97,23 @@ describe("BarcodePrintHeader", () => {
it("shows the export action for administrators", () => {
const onExport = jest.fn();
renderHeader({ canManageImports: true, canExport: true, onExport });
renderHeader({ canImportRecords: true, canExport: true, onExport });
fireEvent.click(screen.getByRole("button", { name: "导出数据" }));
expect(onExport).toHaveBeenCalledTimes(1);
});
it("allows purchasing and warehouse users to import and delete without bulk edit", () => {
renderHeader({
canImportRecords: true,
canDeleteImports: true,
canEditImports: false,
});
expect(screen.getByRole("button", { name: "条码导入" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "品牌货号导入" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "删除选中" })).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "修改选中" })).not.toBeInTheDocument();
});
});

View File

@ -29,7 +29,9 @@ export function BarcodePrintHeader({
productCategoryOptions,
salesCategoryOptions,
statusMessage,
canManageImports,
canImportRecords,
canDeleteImports,
canEditImports,
canExport,
selectedRowCount = 0,
exporting = false,
@ -48,7 +50,9 @@ export function BarcodePrintHeader({
productCategoryOptions: string[];
salesCategoryOptions: string[];
statusMessage: string;
canManageImports: boolean;
canImportRecords: boolean;
canDeleteImports: boolean;
canEditImports: boolean;
canExport: boolean;
selectedRowCount?: number;
exporting?: boolean;
@ -68,7 +72,7 @@ export function BarcodePrintHeader({
}) {
return (
<div className="shrink-0 border-b border-[var(--obs-shell-border)] bg-[var(--obs-shell-header-bg)] px-3 py-2.5">
{canManageImports || canExport ? (
{canImportRecords || canDeleteImports || canEditImports || canExport ? (
<div className="flex flex-wrap items-center justify-end gap-2">
{canExport ? (
<BarcodePrintActionButton
@ -80,7 +84,7 @@ export function BarcodePrintHeader({
<span>{exporting ? "正在导出" : "导出数据"}</span>
</BarcodePrintActionButton>
) : null}
{canManageImports ? (
{canImportRecords ? (
<>
<BarcodePrintActionButton disabled={actionDisabled} onClick={onBarcodeImport}>
<Upload className="h-3.5 w-3.5" aria-hidden="true" />
@ -98,29 +102,33 @@ export function BarcodePrintHeader({
<Download className="h-3.5 w-3.5" aria-hidden="true" />
<span>品牌货号导入模板下载</span>
</BarcodePrintActionButton>
<BarcodePrintActionButton
disabled={actionDisabled || selectedRowCount === 0}
intent="danger"
onClick={onDeleteSelected}
>
<Trash2 className="h-3.5 w-3.5" aria-hidden="true" />
<span>删除选中{selectedRowCount ? `(${selectedRowCount} 行)` : ""}</span>
</BarcodePrintActionButton>
<BarcodePrintActionButton
disabled={actionDisabled || selectedRowCount === 0}
onClick={onEditSelected}
>
<Pencil className="h-3.5 w-3.5" aria-hidden="true" />
<span>修改选中{selectedRowCount ? `(${selectedRowCount} 行)` : ""}</span>
</BarcodePrintActionButton>
</>
) : null}
{canDeleteImports ? (
<BarcodePrintActionButton
disabled={actionDisabled || selectedRowCount === 0}
intent="danger"
onClick={onDeleteSelected}
>
<Trash2 className="h-3.5 w-3.5" aria-hidden="true" />
<span>删除选中{selectedRowCount ? `(${selectedRowCount} 行)` : ""}</span>
</BarcodePrintActionButton>
) : null}
{canEditImports ? (
<BarcodePrintActionButton
disabled={actionDisabled || selectedRowCount === 0}
onClick={onEditSelected}
>
<Pencil className="h-3.5 w-3.5" aria-hidden="true" />
<span>修改选中{selectedRowCount ? `(${selectedRowCount} 行)` : ""}</span>
</BarcodePrintActionButton>
) : null}
</div>
) : null}
<div
className={`flex flex-wrap items-center gap-x-3 gap-y-2 ${
canManageImports || canExport ? "mt-3" : ""
canImportRecords || canDeleteImports || canEditImports || canExport ? "mt-3" : ""
}`}
>
<BarcodePrintInput

View File

@ -35,7 +35,7 @@ export function BarcodePrintTable({
onStartDataColumnResize,
onBarcodePrint,
onCertificatePrint,
canManageImports,
canDeleteImports,
isSupplier = false,
onDeleteImportedData,
}: {
@ -59,7 +59,7 @@ export function BarcodePrintTable({
) => void;
onBarcodePrint: (row: BarcodePrintRow) => void;
onCertificatePrint: (row: BarcodePrintRow) => void;
canManageImports: boolean;
canDeleteImports: boolean;
isSupplier?: boolean;
onDeleteImportedData: (importRecordIds: string[] | undefined) => void;
}) {
@ -91,7 +91,7 @@ export function BarcodePrintTable({
aria-label="选择当前筛选结果"
checked={allVisibleSelected}
onChange={onToggleVisibleRows}
disabled={selectableRows.length === 0}
disabled={!canDeleteImports || selectableRows.length === 0}
className="h-3.5 w-3.5"
/>
</th>
@ -173,7 +173,7 @@ export function BarcodePrintTable({
}行`}
checked={selectedRowIds.has(row.id)}
onChange={() => onToggleRow(row.id)}
disabled={!row.importRecordIds?.length}
disabled={!canDeleteImports || !row.importRecordIds?.length}
className="h-3.5 w-3.5"
/>
</td>
@ -227,7 +227,7 @@ export function BarcodePrintTable({
>
<FileText className="h-3.5 w-3.5" aria-hidden="true" />
</button>
{canManageImports && row.importRecordIds?.length ? (
{canDeleteImports && row.importRecordIds?.length ? (
<button
type="button"
aria-label="删除导入数据"

View File

@ -9,7 +9,12 @@ import {
type MouseEvent as ReactMouseEvent,
} from "react";
import type { NonIntegratedProductRecord } from "@/app/intake/non-integrated/nonIntegratedStorage";
import { canManageBarcodePrintImports, isAdmin } from "@/lib/role-scope";
import {
canDeleteBarcodePrintImports,
canEditBarcodePrintImports,
canImportBarcodePrintRecords,
isAdmin,
} from "@/lib/role-scope";
import {
BARCODE_PRINT_IMPORT_ACCEPT,
downloadBarcodePrintImportTemplate,
@ -120,7 +125,11 @@ function buildAppliedFilters(filters: BarcodePrintFilterState) {
const UNBOUND_SUPPLIER_MESSAGE =
"当前供应商账号未绑定供应商名称或编码,请联系管理员绑定后查看条码打印数据。";
const IMPORT_PERMISSION_DENIED_MESSAGE =
"只有设计师和管理员可以导入或删除条码数据。";
"当前账号没有条码导入权限。";
const DELETE_PERMISSION_DENIED_MESSAGE =
"当前账号没有删除条码导入数据的权限。";
const EDIT_PERMISSION_DENIED_MESSAGE =
"当前账号没有修改条码导入数据的权限。";
export function BarcodePrintWorkspace({
products: _products,
@ -135,7 +144,9 @@ export function BarcodePrintWorkspace({
const supplierCode = user.supplierCode?.trim().toUpperCase() ?? "";
const supplierName = user.supplierName?.trim() ?? "";
const isUnboundSupplier = isSupplierUser && !supplierName && !supplierCode;
const canManageImports = canManageBarcodePrintImports(user);
const canImportRecords = canImportBarcodePrintRecords(user);
const canDeleteImports = canDeleteBarcodePrintImports(user);
const canEditImports = canEditBarcodePrintImports(user);
const canExport = isAdmin(user);
const [rows, setRows] = useState<BarcodePrintRow[]>([]);
const [totalRowCount, setTotalRowCount] = useState(0);
@ -380,7 +391,7 @@ export function BarcodePrintWorkspace({
async function handleImportFile(kind: BarcodePrintImportKind, file: File | null) {
if (!file) return;
if (!canManageImports) {
if (!canImportRecords) {
setStatusMessage(IMPORT_PERMISSION_DENIED_MESSAGE);
return;
}
@ -456,7 +467,7 @@ export function BarcodePrintWorkspace({
}
async function handleDownloadTemplate(kind: BarcodePrintImportKind) {
if (!canManageImports) {
if (!canImportRecords) {
setStatusMessage(IMPORT_PERMISSION_DENIED_MESSAGE);
return;
}
@ -497,8 +508,8 @@ export function BarcodePrintWorkspace({
async function deleteImportedData(importRecordIds: string[] | undefined) {
if (!importRecordIds?.length) return;
if (!canManageImports) {
setStatusMessage(IMPORT_PERMISSION_DENIED_MESSAGE);
if (!canDeleteImports) {
setStatusMessage(DELETE_PERMISSION_DENIED_MESSAGE);
return;
}
@ -519,6 +530,10 @@ export function BarcodePrintWorkspace({
async function deleteSelectedData() {
if (selectedImportRecordIds.length === 0) return;
if (!canDeleteImports) {
setStatusMessage(DELETE_PERMISSION_DENIED_MESSAGE);
return;
}
if (
!window.confirm(
`确认删除选中的 ${selectedImportRecordIds.length} 条导入数据吗?`,
@ -545,11 +560,19 @@ export function BarcodePrintWorkspace({
function openBulkEdit() {
if (selectedImportRecordIds.length === 0) return;
if (!canEditImports) {
setStatusMessage(EDIT_PERMISSION_DENIED_MESSAGE);
return;
}
setBulkEditOpen(true);
}
async function submitBulkEdit({ fields }: BarcodePrintBulkEditSubmit) {
if (selectedImportRecordIds.length === 0) return;
if (!canEditImports) {
setStatusMessage(EDIT_PERMISSION_DENIED_MESSAGE);
return;
}
setBulkEditSaving(true);
try {
@ -759,7 +782,7 @@ export function BarcodePrintWorkspace({
return (
<section className="flex h-full min-h-0 flex-col overflow-hidden rounded-[8px] border border-[var(--obs-shell-border)] bg-[var(--obs-shell-panel-bg)] text-[var(--obs-shell-title)] shadow-[0_1px_2px_rgba(17,19,21,0.04)]">
{canManageImports ? (
{canImportRecords ? (
<>
<input
ref={barcodeImportInputRef}
@ -790,7 +813,9 @@ export function BarcodePrintWorkspace({
productCategoryOptions={productCategoryOptions}
salesCategoryOptions={salesCategoryOptions}
statusMessage={isUnboundSupplier ? UNBOUND_SUPPLIER_MESSAGE : statusMessage}
canManageImports={canManageImports}
canImportRecords={canImportRecords}
canDeleteImports={canDeleteImports}
canEditImports={canEditImports}
canExport={canExport}
selectedRowCount={selectedRows.length}
exporting={exporting}
@ -843,7 +868,7 @@ export function BarcodePrintWorkspace({
onStartDataColumnResize={startDataColumnResize}
onBarcodePrint={(row) => void handleBarcodePrint(row.id)}
onCertificatePrint={(row) => handleCertificatePrint(row.id)}
canManageImports={canManageImports}
canDeleteImports={canDeleteImports}
isSupplier={isSupplierUser}
onDeleteImportedData={(ids) => void deleteImportedData(ids)}
/>

View File

@ -0,0 +1,63 @@
import {
createEmptyNonIntegratedOpeningReference,
createEmptyNonIntegratedPatentApplication,
createEmptyNonIntegratedProjectReview,
} from "./core/nonIntegratedStorage";
import { createFactoryRow } from "./NonIntegratedDetailClient.testFixtures";
import { buildProductPayload } from "./nonIntegratedProductPayload";
import { createFormValuesFromProduct } from "./workspaces/basic-info/productFormValueHelpers";
import { EMPTY_DOCUMENT_WORKSPACE_NOTES } from "./workspaces/documents/documentWorkspaceHelpers";
describe("buildProductPayload", () => {
it("keeps a factory supplier that exists only in the live supplier directory", () => {
const payload = buildProductPayload(
"product-1",
createFormValuesFromProduct(null),
[],
{},
{},
[],
{ rows: [] },
[
createFactoryRow({
supplierName: "木际",
supplierCode: "",
}),
],
[],
[],
[],
[],
[],
[],
[],
EMPTY_DOCUMENT_WORKSPACE_NOTES,
{},
{},
{},
{},
createEmptyNonIntegratedOpeningReference(),
createEmptyNonIntegratedPatentApplication(),
createEmptyNonIntegratedProjectReview(),
"draft",
1,
{},
{},
{},
undefined,
undefined,
undefined,
undefined,
undefined,
"product",
"",
undefined,
new Map([["木际", "N3580"]]),
);
expect(payload.factoryRows[0]).toMatchObject({
supplierName: "木际",
supplierCode: "N3580",
});
});
});

View File

@ -85,6 +85,7 @@ export function buildProductPayload(
productDevelopmentKind: ProductDevelopmentKind = "product",
productTag = "",
metadata?: Record<string, unknown>,
supplierCodeByName?: ReadonlyMap<string, string>,
): NonIntegratedProductRecord {
const now = new Date().toISOString();
const derivedSkuItems = skuItems.map((item, index) => {
@ -116,7 +117,7 @@ export function buildProductPayload(
factoryRows: factoryRowsForPayload,
} = normalizeNonIntegratedPackageSetCounts(
derivedSkuItems,
normalizeFactoryRowsForPayload(factoryRows),
normalizeFactoryRowsForPayload(factoryRows, supplierCodeByName),
);
const normalizedStyleDetails = Object.entries(styleDetails)
.filter(([styleKey]) => Boolean(styleKey))

View File

@ -103,6 +103,7 @@ export type UseNonIntegratedSaveControllerParams = {
SetStateAction<NonIntegratedProductRecord["metadata"]>
>;
};
supplierCodeByName: ReadonlyMap<string, string>;
workflow: ProductWorkflowState;
};

View File

@ -123,6 +123,7 @@ export function useNonIntegratedDetailDomainControllers(
projectState,
refreshSpuEstimate: spuEstimate.refreshSpuEstimate,
skuState,
supplierCodeByName: directoryOptions.supplierCodeByName,
workflowRows: workflow.workflowRows,
workflowState,
});

View File

@ -23,6 +23,7 @@ describe("useNonIntegratedPersistenceCoordinator", () => {
const setSaveMessage = jest.fn();
const setSaveMessageType = jest.fn();
const onProductSavedRef = { current: jest.fn() };
const supplierCodeByName = new Map([["木际", "N3580"]]);
jest.mocked(useNonIntegratedAssetStorageNormalizer).mockReturnValue({
normalizeProductAssetsForStorage,
@ -115,6 +116,7 @@ describe("useNonIntegratedPersistenceCoordinator", () => {
skuBatchFlowNos: {},
skuItems: [],
},
supplierCodeByName,
workflowRows: {
displayedProductFactoryRows: productFactoryRows,
productFactoryRows,
@ -149,6 +151,7 @@ describe("useNonIntegratedPersistenceCoordinator", () => {
normalizeProductAssetsForStorage,
onProductSavedRef,
}),
supplierCodeByName,
workflow: expect.objectContaining({ productFactoryRows }),
}),
);

View File

@ -46,6 +46,7 @@ type PersistenceCoordinatorProps = Pick<
typeof useSpuEstimateRefreshToken
>["refreshSpuEstimate"];
skuState: ReturnType<typeof useNonIntegratedSkuState>;
supplierCodeByName: ReadonlyMap<string, string>;
workflowRows: WorkflowDerivedState["workflowRows"];
workflowState: ReturnType<typeof useNonIntegratedWorkflowState>;
};
@ -66,6 +67,7 @@ export function useNonIntegratedPersistenceCoordinator({
projectState,
refreshSpuEstimate,
skuState,
supplierCodeByName,
workflowRows,
workflowState,
}: PersistenceCoordinatorProps) {
@ -143,6 +145,7 @@ export function useNonIntegratedPersistenceCoordinator({
setOpeningReferenceAndRef: projectState.setOpeningReferenceAndRef,
setProductMetadata: workflowState.setProductMetadata,
},
supplierCodeByName,
workflow: {
displayedProductFactoryRows: workflowRows.displayedProductFactoryRows,
planningLayoutRows: workflowState.planningLayoutRows,

View File

@ -64,6 +64,7 @@ export function useNonIntegratedSaveController({
persistence,
state,
stateActions,
supplierCodeByName,
workflow,
}: UseNonIntegratedSaveControllerParams) {
const lastPersistErrorMessageRef = useRef("");
@ -219,6 +220,7 @@ export function useNonIntegratedSaveController({
identity.effectiveProductDevelopmentKind,
identity.productTag,
nextProductMetadata,
supplierCodeByName,
),
);
@ -346,6 +348,7 @@ export function useNonIntegratedSaveController({
documents.skuBatchWorkflowConfirmations,
state.skuItems,
state.styleDetails,
supplierCodeByName,
documents.uploadFiles,
persistence.compactStoredProducts,
],

View File

@ -91,8 +91,8 @@ describe('supply chain menu', () => {
expect(items.map((item) => item.label)).toEqual([
'新品经营总览',
'1688代发数据明细',
'新品终止任务反馈',
'1688代发数据明细',
'1688代发异常事项',
])
})

View File

@ -56,8 +56,8 @@ export const SUPPLY_CHAIN_MENU: SupplyChainMenuModule[] = [
{
items: [
{ label: '新品经营总览', route: '/supply-chain/new-products/overview', targetKey: 'newProductOverview' },
{ label: '1688代发数据明细', route: '/supply-chain/new-products/1688-dropship-data', targetKey: 'newProduct1688DropshipData' },
{ label: '新品终止任务反馈', route: '/supply-chain/new-products/termination-feedback', targetKey: 'newProductTerminationFeedback' },
{ label: '1688代发数据明细', route: '/supply-chain/new-products/1688-dropship-data', targetKey: 'newProduct1688DropshipData' },
{ label: '1688代发异常事项', route: '/supply-chain/new-products/dropship-issues', targetKey: 'newProductDropshipIssues' },
],
},

View File

@ -1,10 +1,13 @@
'use client'
import { useEffect, useRef, useState } from 'react'
import { Filter } from 'lucide-react'
import type {
ProductArchiveFilterOptionKey,
ProductArchiveFilters,
import { useEffect, useRef, useState, type CSSProperties } from 'react'
import { Filter, X } from 'lucide-react'
import {
PRODUCT_ARCHIVE_NORMAL_CODE_FIELDS,
PRODUCT_ARCHIVE_TEXT_FILTER_KEYS,
type ProductArchiveFilters,
type ProductArchiveFilterOptionKey,
type ProductArchiveTextFilterKey,
} from '@/lib/supply-chain-product-archive'
import { ProductArchiveFilterOptionList } from './ProductArchiveFilterOptionList'
@ -34,6 +37,74 @@ const FILTER_CONTROLS: Record<string, FilterControl | undefined> = {
updateTime: { kind: 'dateRange', filterKey: 'updateTime' },
}
// 文本列带「形态 + 排除规则」,用双排;其余列保持原来的单列窄弹层。
const POPOVER_WIDTH = 300
const POPOVER_TEXT_WIDTH = 520
const POPOVER_MARGIN = 12
// 低于这个高度就没法同时放下规则和候选值了,宁可让它溢出去靠页面滚动。
const POPOVER_MIN_HEIGHT = 200
const TEXT_FILTER_KEY_SET: ReadonlySet<string> = new Set(PRODUCT_ARCHIVE_TEXT_FILTER_KEYS)
const NORMAL_CODE_FIELD_SET: ReadonlySet<string> = new Set(PRODUCT_ARCHIVE_NORMAL_CODE_FIELDS)
function isTextFilterKey(key: string): key is ProductArchiveTextFilterKey {
return TEXT_FILTER_KEY_SET.has(key)
}
/** 本列是否已勾「只看正常编码」。 */
function normalCodeEnabled(filters: ProductArchiveFilters, key: string) {
return NORMAL_CODE_FIELD_SET.has(key)
&& Boolean(filters.normalCodeOnly?.includes(key as ProductArchiveTextFilterKey))
}
/** 本列当前的「排除以…开头」关键词。 */
function excludeKeywords(filters: ProductArchiveFilters, key: string) {
if (!isTextFilterKey(key)) return []
return (filters.excludeStartsWith ?? [])
.filter((rule) => rule.field === key)
.map((rule) => rule.startsWith)
}
/** 去空、按大写去重,保持输入顺序。 */
function normalizeExcludeInputs(values: string[]) {
const seen = new Set<string>()
const normalized: string[] = []
for (const value of values) {
const keyword = value.trim()
if (!keyword) continue
const dedupeKey = keyword.toUpperCase()
if (seen.has(dedupeKey)) continue
seen.add(dedupeKey)
normalized.push(keyword)
}
return normalized
}
/**
* 弹层往右下展开,靠右的列会顶出屏幕、靠近屏幕底部的表头会把弹层截断。
* 打开前先按已知宽度和视口算好横向偏移与最大高度,避免「先渲染再挪」的闪动。
*/
function resolvePopoverLayout(trigger: HTMLElement | null, width: number) {
const fallback = { shift: 0, maxHeight: 520, above: false }
if (!trigger || typeof window === 'undefined') return fallback
const rect = trigger.getBoundingClientRect()
let shift = 0
if (rect.left + width > window.innerWidth - POPOVER_MARGIN) {
shift = window.innerWidth - POPOVER_MARGIN - (rect.left + width)
}
if (rect.left + shift < POPOVER_MARGIN) shift = POPOVER_MARGIN - rect.left
const below = window.innerHeight - (rect.bottom + 7) - POPOVER_MARGIN
const above = rect.top - 7 - POPOVER_MARGIN
// 下方放不下时向上翻;两边都不够就用较大的一边并允许内部滚动。
const useAbove = below < POPOVER_MIN_HEIGHT && above > below
const available = useAbove ? above : below
const maxHeight = Math.max(POPOVER_MIN_HEIGHT, Math.min(520, available))
return { shift: Math.round(shift), maxHeight: Math.round(maxHeight), above: useAbove }
}
function getSelectedValues(control: FilterControl, filters: ProductArchiveFilters) {
if (control.kind === 'dateRange') return []
return filters[control.filterKey] ?? []
@ -70,6 +141,9 @@ export function ProductArchiveHeaderFilter({
const [selectedValues, setSelectedValues] = useState<string[]>([])
const [dateFrom, setDateFrom] = useState('')
const [dateTo, setDateTo] = useState('')
const [normalCodeOn, setNormalCodeOn] = useState(false)
const [excludeInputs, setExcludeInputs] = useState<string[]>([])
const [popoverLayout, setPopoverLayout] = useState({ shift: 0, maxHeight: 520, above: false })
useEffect(() => {
if (!open) return
@ -82,18 +156,47 @@ export function ProductArchiveHeaderFilter({
if (!control) return null
const clear = () => {
const next = { ...filters } as ProductArchiveFilters
if (control.kind === 'dateRange') {
delete next[`${control.filterKey}From` as 'createTimeFrom' | 'updateTimeFrom']
delete next[`${control.filterKey}To` as 'createTimeFrom' | 'updateTimeTo']
} else {
delete next[control.filterKey]
const textFilterKey = control.kind === 'options' && isTextFilterKey(control.filterKey)
? control.filterKey
: null
const supportsNormalCode = Boolean(textFilterKey && NORMAL_CODE_FIELD_SET.has(textFilterKey))
/**
* 把本列的两类文本规则写回 filters。
* 只动本列那几条,其他列的规则原样保留(规则是跨列共存的)。
*/
const writeTextRules = (next: ProductArchiveFilters, keywordList: string[], normalCode: boolean) => {
if (!textFilterKey) return
const otherRules = (filters.excludeStartsWith ?? []).filter((rule) => rule.field !== textFilterKey)
const mergedRules = [
...otherRules,
...keywordList.map((startsWith) => ({ field: textFilterKey, startsWith })),
]
if (mergedRules.length) next.excludeStartsWith = mergedRules
else delete next.excludeStartsWith
const otherFields = (filters.normalCodeOnly ?? []).filter((key) => key !== textFilterKey)
const mergedFields = normalCode && supportsNormalCode ? [...otherFields, textFilterKey] : otherFields
if (mergedFields.length) next.normalCodeOnly = mergedFields
else delete next.normalCodeOnly
}
const clear = () => {
const next = { ...filters } as ProductArchiveFilters
if (control.kind === 'dateRange') {
delete next[`${control.filterKey}From` as 'createTimeFrom' | 'updateTimeFrom']
delete next[`${control.filterKey}To` as 'createTimeFrom' | 'updateTimeTo']
} else {
delete next[control.filterKey]
writeTextRules(next, [], false)
}
onChange(next)
setSelectedValues([])
setExcludeInputs([])
setNormalCodeOn(false)
setOpen(false)
}
onChange(next)
setSelectedValues([])
setOpen(false)
}
const apply = () => {
const next = { ...filters } as ProductArchiveFilters
@ -106,6 +209,7 @@ const clear = () => {
}
}
else delete next[control.filterKey]
writeTextRules(next, normalizeExcludeInputs(excludeInputs), normalCodeOn)
} else {
const fromKey = `${control.filterKey}From` as 'createTimeFrom' | 'updateTimeFrom'
const toKey = `${control.filterKey}To` as 'createTimeTo' | 'updateTimeTo'
@ -126,7 +230,24 @@ const clear = () => {
)
}
const active = controlHasFilter(control, filters)
const activeRuleCount = control.kind === 'options'
? excludeKeywords(filters, control.filterKey).length
+ (normalCodeEnabled(filters, control.filterKey) ? 1 : 0)
: 0
const active = controlHasFilter(control, filters) || activeRuleCount > 0
const optionList = control.kind === 'options' ? (
<ProductArchiveFilterOptionList
field={control.filterKey}
placeholder={control.placeholder}
filters={filters}
selectedValues={selectedValues}
onToggle={toggleOption}
onSelectAll={(values) => {
setSelectedValues((current) => [...new Set([...current, ...values])])
}}
/>
) : null
return (
<span className="archive-header-filter" ref={rootRef}>
@ -138,11 +259,19 @@ const clear = () => {
aria-expanded={open}
onClick={(event) => {
event.stopPropagation()
if (control.kind === 'options') setSelectedValues(getSelectedValues(control, filters))
if (control.kind === 'options') {
setSelectedValues(getSelectedValues(control, filters))
setExcludeInputs(excludeKeywords(filters, control.filterKey))
setNormalCodeOn(normalCodeEnabled(filters, control.filterKey))
}
if (control.kind === 'dateRange') {
setDateFrom(filters[`${control.filterKey}From` as 'createTimeFrom' | 'updateTimeFrom'] ?? '')
setDateTo(filters[`${control.filterKey}To` as 'createTimeTo' | 'updateTimeTo'] ?? '')
}
if (!open) {
const width = textFilterKey ? POPOVER_TEXT_WIDTH : POPOVER_WIDTH
setPopoverLayout(resolvePopoverLayout(event.currentTarget, width))
}
setOpen((current) => !current)
}}
>
@ -151,41 +280,92 @@ const clear = () => {
{open && (
<form
className="archive-header-filter-popover"
className={[
'archive-header-filter-popover',
textFilterKey ? 'is-text' : '',
popoverLayout.above ? 'is-above' : '',
].filter(Boolean).join(' ')}
style={{
'--popover-shift': `${popoverLayout.shift}px`,
'--popover-max-height': `${popoverLayout.maxHeight}px`,
} as CSSProperties}
onSubmit={(event) => {
event.preventDefault()
apply()
}}
>
{control.kind === 'options' && (
<ProductArchiveFilterOptionList
field={control.filterKey}
placeholder={control.placeholder}
filters={filters}
selectedValues={selectedValues}
onToggle={toggleOption}
onSelectAll={(values) => {
setSelectedValues((current) => [...new Set([...current, ...values])])
}}
/>
)}
{textFilterKey ? (
<div className="archive-header-filter-body">
<div className="archive-header-filter-rules">
{supportsNormalCode && (
<label className="archive-header-filter-normalcode">
<input
type="checkbox"
checked={normalCodeOn}
onChange={(event) => setNormalCodeOn(event.target.checked)}
/>
<span>只看正常编码</span>
</label>
)}
{control.kind === 'dateRange' && (
<div className="archive-header-filter-dates">
<input
type="date"
aria-label={`${label}开始日期`}
value={dateFrom}
onChange={(event) => setDateFrom(event.target.value)}
/>
<span>至</span>
<input
type="date"
aria-label={`${label}结束日期`}
value={dateTo}
onChange={(event) => setDateTo(event.target.value)}
/>
<div className="archive-header-filter-rules-label">排除「以…开头」</div>
{excludeInputs.length > 0 && (
<div className="archive-header-filter-rule-list">
{excludeInputs.map((keyword, index) => (
<div className="archive-header-filter-rule" key={`exclude-${index}`}>
<input
value={keyword}
placeholder="如 WM-"
aria-label={`排除以该内容开头的${label},第 ${index + 1} 条`}
onChange={(event) => setExcludeInputs((current) => current.map(
(item, itemIndex) => (itemIndex === index ? event.target.value : item),
))}
/>
<button
type="button"
className="archive-header-filter-rule-remove"
aria-label={`删除第 ${index + 1} 条排除规则`}
title="删除这条"
onClick={() => setExcludeInputs((current) => current.filter((_, itemIndex) => itemIndex !== index))}
>
<X size={12} />
</button>
</div>
))}
</div>
)}
<button
type="button"
className="archive-header-filter-add-rule"
onClick={() => setExcludeInputs((current) => [...current, ''])}
>
+ 再加一条
</button>
</div>
<div className="archive-header-filter-values">{optionList}</div>
</div>
) : (
<>
{optionList}
{control.kind === 'dateRange' && (
<div className="archive-header-filter-dates">
<input
type="date"
aria-label={`${label}开始日期`}
value={dateFrom}
onChange={(event) => setDateFrom(event.target.value)}
/>
<span>至</span>
<input
type="date"
aria-label={`${label}结束日期`}
value={dateTo}
onChange={(event) => setDateTo(event.target.value)}
/>
</div>
)}
</>
)}
<div className="archive-header-filter-actions">
@ -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; }
`}</style>

View File

@ -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<string> = 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<string>()
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
}

View File

@ -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(<DropshipAcceptanceButton {...props} canAccept={false} />)
const deniedButton = screen.getByRole('button', { name: '承接 0/3' })
expect(deniedButton).toBeDisabled()
expect(deniedButton).toHaveAttribute('title', '当前账号没有承接权限')
expect(deniedButton).toHaveAttribute('data-state', 'permission')
rerender(<DropshipAcceptanceButton {...props} purchaserCount={2} />)
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(
<DropshipAcceptanceButton {...props} alreadyAccepted purchaserCount={1} />,
)
const acceptedButton = screen.getByRole('button', { name: '已承接 1/3' })
expect(acceptedButton).toBeDisabled()
expect(acceptedButton).toHaveAttribute('data-state', 'accepted')
rerender(<DropshipAcceptanceButton {...props} alreadyAccepted purchaserCount={3} />)
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(<DropshipAcceptanceButton {...props} />)
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(<DropshipAcceptanceButton {...props} />)
fireEvent.click(screen.getByRole('button', { name: '承接 0/3' }))
await waitFor(() => expect(screen.getByRole('button', { name: '已承接 1/3' })).toBeDisabled())
rerender(
<DropshipAcceptanceButton
{...props}
acceptanceRevision="task-1"
alreadyAccepted
purchaserCount={1}
/>,
)
expect(screen.getByRole('button', { name: '已承接 1/3' })).toBeDisabled()
rerender(<DropshipAcceptanceButton {...props} />)
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(<DropshipAcceptanceButton {...props} />)
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(<DropshipAcceptanceButton {...props} />)
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()
})
})

View File

@ -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 <DropshipAcceptanceButtonState key={acceptanceRevision} {...props} />
}
function DropshipAcceptanceButtonState({
barcode,
dateFrom,
dateTo,
alreadyAccepted,
canAccept,
purchaserCount,
}: Omit<DropshipAcceptanceButtonProps, 'acceptanceRevision'>) {
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 (
<button
type="button"
disabled={disabled}
title={title}
data-state={state}
onClick={() => void accept()}
>
<Handshake size={13} aria-hidden="true" />{label}
</button>
)
}

View File

@ -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 (
<DropshipFieldFilterGroup
dateFrom="2026-09-01"
dateTo="2026-09-07"
keyword={overrides.keyword ?? ''}
filters={filters}
>
<DropshipFieldFilter
field="skuOperator"
noun="运营"
allLabel="全部运营"
/>
</DropshipFieldFilterGroup>
)
}
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(
<form onSubmit={(event) => {
event.preventDefault()
submitted()
}}>
<DropshipAutoSubmitDateField
name="dateFrom"
label="开始日期"
defaultValue="2026-09-01"
/>
<DropshipAutoSubmitDateField
name="dateTo"
label="结束日期"
defaultValue="2026-09-07"
/>
</form>,
)
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(
<DropshipFieldFilterGroup
dateFrom="2026-09-01"
dateTo="2026-09-07"
keyword="卧室"
filters={{}}
>
<DropshipFieldFilter field="sku" noun="SKU" allLabel="全部SKU" />
</DropshipFieldFilterGroup>,
)
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(
<DropshipFieldFilterGroup
dateFrom="2026-09-01"
dateTo="2026-09-07"
keyword=""
filters={{}}
>
<DropshipFieldFilter field="purchaser" noun="采购" allLabel="全部采购" />
</DropshipFieldFilterGroup>,
)
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(
<DropshipFieldFilterGroup
dateFrom="2026-09-01"
dateTo="2026-09-07"
keyword=""
filters={{}}
>
<DropshipFieldFilter field="purchaser" noun="采购" allLabel="全部采购" />
<DropshipFieldFilter field="spu" noun="SPU" allLabel="全部SPU" />
</DropshipFieldFilterGroup>,
)
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(
<form aria-label="数据筛选">
<input aria-label="开始日期" name="dateFrom" defaultValue="2026-09-01" />
<input aria-label="结束日期" name="dateTo" defaultValue="2026-09-07" />
<input aria-label="商品检索" name="keyword" defaultValue="" />
<DropshipFieldFilterGroup
dateFrom="2026-09-01"
dateTo="2026-09-07"
keyword=""
filters={{}}
>
<DropshipFieldFilter field="skuOperator" noun="运营" allLabel="全部运营" />
</DropshipFieldFilterGroup>
<button type="submit">查询</button>
</form>,
)
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(
<form aria-label="数据筛选">
<DropshipAutoSubmitDateField
name="dateFrom"
label="开始日期"
defaultValue="2026-09-01"
/>
<input name="dateTo" defaultValue="2026-09-07" />
<DropshipFieldFilterGroup
dateFrom="2026-09-01"
dateTo="2026-09-07"
keyword=""
filters={{}}
>
<DropshipFieldFilter field="skuOperator" noun="运营" allLabel="全部运营" />
</DropshipFieldFilterGroup>
</form>,
)
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<string>((resolve) => { resolveSave = resolve })
jest.mocked(saveDropship1688Filters).mockReturnValue(save)
render(
<form aria-label="数据筛选">
<input aria-label="商品检索" name="keyword" defaultValue="" />
<DropshipFieldFilterGroup
dateFrom="2026-09-01"
dateTo="2026-09-07"
keyword=""
filters={{}}
>
<DropshipFieldFilter field="skuOperator" noun="运营" allLabel="全部运营" />
</DropshipFieldFilterGroup>
<button type="submit">查询</button>
</form>,
)
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())
})
})

View File

@ -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<FilterGroupContextValue | null>(null)
export function DropshipAutoSubmitDateField({
name,
label,
defaultValue,
}: {
name: 'dateFrom' | 'dateTo'
label: string
defaultValue: string
}) {
return (
<label>
<span>{label}</span>
<input
name={name}
type="date"
defaultValue={defaultValue}
onChange={(event) => event.currentTarget.form?.requestSubmit()}
/>
</label>
)
}
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<ReturnType<typeof setTimeout> | null>(null)
const desiredFilters = useRef<Dropship1688Filters | null>(null)
const applyingRef = useRef(false)
const groupRef = useRef<HTMLDivElement>(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 (
<FilterGroupContext.Provider value={{
filters: workingFilters,
pending,
saving,
readPeriod,
scheduleSelection,
cancelScheduledApply,
}}>
<div ref={groupRef} className={styles.dropshipFilterGroup}>
{children}
{saveError ? (
<p className={styles.dropshipFilterGroupError} role="alert">{saveError}</p>
) : null}
</div>
</FilterGroupContext.Provider>
)
}
/**
* 数据明细筛选行的单个筛选项。
* 与寻源明细的筛选控件保持同样的「搜索 + 勾选」交互,但候选项与筛选状态都走服务端:
* 候选来自 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<string[]>([])
const [selection, setSelection] = useState<string[]>([])
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<HTMLDivElement>(null)
const searchRef = useRef<HTMLInputElement>(null)
const listRef = useRef<HTMLDivElement>(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 (
<div className={styles.dropshipFilterField} ref={containerRef}>
<span className={styles.dropshipFilterLabel}>{fieldLabel}</span>
<button
type="button"
className={styles.dropshipFilterTrigger}
aria-label={fieldLabel}
aria-haspopup="dialog"
aria-expanded={open}
disabled={saving || pending}
data-active={Boolean(current)}
title={current ? current.values.join('、') : `搜索并勾选${noun}`}
onClick={() => {
if (open) {
close()
return
}
cancelScheduledApply()
const bounds = containerRef.current?.getBoundingClientRect()
setAlignRight(Boolean(bounds && bounds.left + POPOVER_WIDTH + 8 > window.innerWidth))
setSelection(selected)
setOpen(true)
}}
>
<span className={styles.dropshipFilterTriggerText}>{summary}</span>
{pending || saving
? <LoaderCircle className={styles.sourcingSpinner} size={14} />
: <ChevronDown size={14} aria-hidden="true" />}
</button>
{open ? (
<div
className={styles.sourcingFilterPopover}
role="dialog"
aria-label={`${noun}选项`}
style={alignRight ? { left: 'auto', right: 0 } : undefined}
>
<div className={styles.sourcingFilterSearch}>
<Search size={14} aria-hidden="true" />
<input
ref={searchRef}
type="search"
value={search}
aria-label={`搜索${noun}`}
placeholder={`搜索${noun}`}
onChange={(event) => setSearch(event.target.value)}
/>
{search ? (
<button type="button" aria-label="清空搜索" title="清空搜索" onClick={() => setSearch('')}>
<X size={13} />
</button>
) : null}
</div>
<div className={styles.sourcingFilterActions}>
<button
type="button"
disabled={loading || values.length === 0}
onClick={() => scheduleApply([...new Set([...selection, ...matches])])}
>
全选{debouncedSearch.trim() ? '当前结果' : '全部'}
</button>
<button type="button" disabled={!current && selection.length === 0} onClick={() => scheduleApply([])}>
清空
</button>
<span>{selection.length > 0 ? `已选 ${selection.length} 项` : '未筛选,显示全部'}</span>
</div>
{excludeMode ? (
<p className={styles.dropshipFilterNotice} role="status">
当前筛选是排除模式,勾选后会改为包含模式。
</p>
) : null}
<div
className={styles.sourcingFilterList}
ref={listRef}
style={{ maxHeight: LIST_MAX_HEIGHT }}
onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}
>
{loading ? (
<p className={styles.sourcingFilterEmpty}>加载中…</p>
) : error ? (
<div className={styles.dropshipFilterError} role="alert">
<span>{error}</span>
<button type="button" onClick={() => setRetry((value) => value + 1)}>重试</button>
</div>
) : matches.length === 0 ? (
<p className={styles.sourcingFilterEmpty}>
{waitingForQuery
? '请输入关键词搜索'
: debouncedSearch.trim()
? `没有匹配「${debouncedSearch.trim()}」的选项`
: '没有可选项'}
</p>
) : (
<div style={{ height: matches.length * ROW_HEIGHT, position: 'relative' }}>
<div style={{ position: 'absolute', top: windowStart * ROW_HEIGHT, left: 0, right: 0 }}>
{matches.slice(windowStart, windowStart + WINDOW_SIZE).map((value) => (
<label key={value} className={styles.sourcingFilterOption}>
<input
type="checkbox"
checked={selectedSet.has(value)}
onChange={() => scheduleApply(selectedSet.has(value)
? selection.filter((item) => item !== value)
: [...selection, value])}
/>
<span className={styles.sourcingFilterOptionBox} aria-hidden="true">
<Check size={12} />
</span>
<span className={styles.sourcingFilterOptionText} title={value}>
{value || '(空值)'}
</span>
</label>
))}
</div>
</div>
)}
</div>
</div>
) : null}
</div>
)
}

View File

@ -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> = {}): 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(
<table>
<tbody>
<DropshipSourcingRow
task={options.task ?? task()}
editable={options.editable ?? true}
revocable={options.revocable ?? true}
/>
</tbody>
</table>,
)
}
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()
})
})

View File

@ -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<SourcingDraft>(initialDraft)
const [savedDraft, setSavedDraft] = useState<SourcingDraft>(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 <>
<tr>
<td className={styles.sourcingActionCell}>
<button
type="button"
aria-label={`编辑 ${fieldPrefix} 的寻源明细`}
title={editable ? '编辑寻源明细' : '只能编辑本人承接的寻源任务'}
disabled={!editable}
onClick={openEditor}
>
<Pencil size={14} />编辑
</button>
<button
type="button"
className={styles.sourcingRevokeButton}
aria-label={`撤销 ${fieldPrefix} 的承接`}
title={revokeTitle}
disabled={!canRevoke || revoking}
onClick={() => void revoke()}
>
{revoking ? <LoaderCircle className={styles.sourcingSpinner} size={14} /> : <Undo2 size={14} />}
{revoking ? '撤销中' : revoked ? '已撤销' : '撤销'}
</button>
<span className={styles.sourcingSaveStatus} aria-live="polite">{feedback?.type === 'success' ? feedback.message : ''}</span>
</td>
<td className={styles.sourcingAcceptedAtCell}>
<time dateTime={acceptedAt === '--' ? undefined : acceptedAt.replace(' ', 'T')}>{acceptedAt}</time>
</td>
<td className={styles.sourcingEnabledCell}>
<span className={enabled ? styles.sourcingEnabled : styles.sourcingDisabled}>
{enabled ? '已启用' : '未启用'}
</span>
</td>
<td className={styles.imageCell}>
<DropshipImageCell barcode={task.sourceBarcode} sku={task.sku} hasImage={task.hasImage} />
</td>
<td className={styles.codeCell} title={task.sourceSpu || undefined}>{task.sourceSpu || '--'}</td>
<td className={styles.codeCell} title={task.sourceBarcode}>{task.sourceBarcode}</td>
<td className={styles.numberCell}>{task.sourceCostPrice ? `¥${Number(task.sourceCostPrice).toFixed(2)}` : '--'}</td>
<td>{savedDraft.quotedPriceTaxIncluded ? `¥${savedDraft.quotedPriceTaxIncluded}` : '--'}</td>
<td className={styles.sourcingComparisonCell}>
<output aria-label={`${fieldPrefix} 当前对比`} className={savedComparisonClass}>{differenceText(savedComparison)}</output>
</td>
<td>{savedDraft.invoiceTaxPoint ? `${savedDraft.invoiceTaxPoint}%` : '--'}</td>
<td title={task.sourceSkuOperator || undefined}>{task.sourceSkuOperator || '--'}</td>
<td title={task.purchaserName}>{task.purchaserName}</td>
<td title={savedDraft.supplierName || undefined}>{savedDraft.supplierName || '--'}</td>
<td>{savedDraft.sourcingMode || '--'}</td>
<td className={styles.codeCell} title={savedDraft.jianshangBarcode || undefined}>{savedDraft.jianshangBarcode || '--'}</td>
</tr>
{editing && typeof document !== 'undefined' ? createPortal(
<div className={styles.sourcingEditorBackdrop} role="presentation" onMouseDown={(event) => {
if (event.target === event.currentTarget) closeEditor()
}}>
<form className={styles.sourcingEditor} role="dialog" aria-modal="true" aria-labelledby={`sourcing-editor-${task.id}`} onSubmit={(event) => {
event.preventDefault()
void save()
}}>
<header className={styles.sourcingEditorHeader}>
<div>
<h2 id={`sourcing-editor-${task.id}`}>编辑寻源明细</h2>
<p>{task.sourceBarcode} · 采购:{task.purchaserName} · 代发成本价:{task.sourceCostPrice ? `¥${Number(task.sourceCostPrice).toFixed(2)}` : '--'}</p>
</div>
<button type="button" aria-label="关闭编辑" title="关闭" disabled={saving} onClick={closeEditor}><X size={18} /></button>
</header>
<div className={styles.sourcingEditorGrid}>
<label>
<span>供应商</span>
<input autoFocus aria-label={`${fieldPrefix} 供应商`} disabled={saving} maxLength={200} value={draft.supplierName} onChange={(event) => setField('supplierName', event.target.value)} />
</label>
<label>
<span>报价(含税)</span>
<input aria-label={`${fieldPrefix} 报价(含税)`} disabled={saving} inputMode="decimal" min="0" step="0.0001" type="number" value={draft.quotedPriceTaxIncluded} onChange={(event) => setField('quotedPriceTaxIncluded', event.target.value)} />
</label>
<div className={styles.sourcingEditorCalculated}>
<span>对比</span>
<output aria-label={`${fieldPrefix} 对比`} className={draftComparisonClass}>{differenceText(draftComparison)}</output>
</div>
<label>
<span>发票税点</span>
<input aria-label={`${fieldPrefix} 发票税点`} disabled={saving} inputMode="decimal" max="100" min="0" step="0.0001" type="number" value={draft.invoiceTaxPoint} onChange={(event) => setField('invoiceTaxPoint', event.target.value)} />
</label>
<label>
<span>模式</span>
<select aria-label={`${fieldPrefix} 模式`} disabled={saving} value={draft.sourcingMode} onChange={(event) => setField('sourcingMode', event.target.value)}>
<option value="" disabled hidden>请选择</option>
{SOURCING_MODES.map((mode) => <option key={mode} value={mode}>{mode}</option>)}
</select>
</label>
<label>
<span>简尚条码</span>
<input aria-label={`${fieldPrefix} 简尚条码`} disabled={saving} maxLength={100} value={draft.jianshangBarcode} onChange={(event) => setField('jianshangBarcode', event.target.value)} />
</label>
</div>
{feedback?.type === 'error' ? <p className={styles.sourcingEditorError} role="alert">{feedback.message}</p> : null}
<footer className={styles.sourcingEditorFooter}>
<button type="button" disabled={saving} onClick={closeEditor}>取消</button>
<button type="submit" className={styles.sourcingEditorSave} disabled={saving || !dirty}>
{saving ? <LoaderCircle className={styles.sourcingSpinner} size={15} /> : <Save size={15} />}
{saving ? '保存中' : '保存'}
</button>
</footer>
</form>
</div>,
document.body,
) : null}
</>
}

View File

@ -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<string, unknown> = {}) {
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<string, unknown> = {}) {
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<string, string> = {}) {
return {
ok: true,
headers: new Headers(headers),
json: async () => ({ data }),
blob: async () => new Blob(['workbook']),
} as Response
}
function renderWorkspace(props: Partial<Parameters<typeof DropshipWorkspace>[0]> = {}) {
return render(
<DropshipWorkspace
summary={<dl><dt>真实业绩</dt><dd>¥818,312.29</dd></dl>}
actorUserId="buyer-1"
{...props}
>
<label>商品检索<input defaultValue="DF-123" /></label>
<a href="?dateFrom=2026-09-01&page=2&filterRef=saved">下一页</a>
<div data-testid="table-scroll">商品明细</div>
</DropshipWorkspace>,
)
}
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<HTMLInputElement>('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()
})
})

View File

@ -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<View>('details')
const [purchaserFilter, setPurchaserFilter] = useState<string[]>([])
const [spuFilter, setSpuFilter] = useState<string[]>([])
const [operatorFilter, setOperatorFilter] = useState<string[]>([])
const [sourcingPage, setSourcingPage] = useState<Dropship1688SourcingPageDto | null>(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<Array<HTMLButtonElement | null>>([])
const fileInput = useRef<HTMLInputElement>(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<HTMLButtonElement>, 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 (
<main className={styles.page}>
<div className={styles.workspaceNavigation}>
<div className={styles.workspaceTabs} role="tablist" aria-label="1688代发功能">
{TABS.map((tab, index) => (
<button
key={tab.key}
ref={(element) => { buttons.current[index] = element }}
type="button"
role="tab"
id={`${id}-${tab.key}-tab`}
aria-controls={`${id}-${tab.key}-panel`}
aria-selected={view === tab.key}
tabIndex={view === tab.key ? 0 : -1}
className={view === tab.key ? styles.detailTabActive : styles.detailTab}
onClick={() => setView(tab.key)}
onKeyDown={(event) => handleKeyDown(event, index)}
>
{tab.label}
</button>
))}
</div>
</div>
<section
id={`${id}-details-panel`}
role="tabpanel"
aria-labelledby={`${id}-details-tab`}
className={styles.workspacePanel}
hidden={view !== 'details'}
>
<header className={styles.toolbar}>
{summary}
</header>
{children}
</section>
<section
id={`${id}-sourcing-panel`}
role="tabpanel"
aria-labelledby={`${id}-sourcing-tab`}
className={styles.workspacePanel}
hidden={view !== 'sourcing'}
tabIndex={0}
>
<div className={styles.sourcingToolbar}>
<div className={styles.sourcingFilters} aria-label="寻源明细筛选">
<SourcingFilterSelect
noun="采购"
allLabel="全部采购"
options={sourcingPage?.filterOptions.purchaserNames ?? []}
selected={purchaserFilter}
onChange={(values) => changeSourcingFilter(setPurchaserFilter, values)}
/>
<SourcingFilterSelect
noun="SPU"
allLabel="全部SPU"
options={sourcingPage?.filterOptions.sourceSpus ?? []}
selected={spuFilter}
onChange={(values) => changeSourcingFilter(setSpuFilter, values)}
/>
<SourcingFilterSelect
noun="运营"
allLabel="全部运营"
options={sourcingPage?.filterOptions.sourceSkuOperators ?? []}
selected={operatorFilter}
onChange={(values) => changeSourcingFilter(setOperatorFilter, values)}
/>
<button type="button" className={styles.sourcingResetButton} disabled={!hasSourcingFilters} onClick={resetSourcingFilters}>
<RefreshCw size={14} />重置
</button>
</div>
<div className={styles.sourcingTransferActions}>
<span>{total} 条</span>
{canExportSourcing ? (
<button type="button" disabled={Boolean(transferring) || sourcingLoading || Boolean(sourcingError) || total === 0} onClick={() => void exportSourcingTasks()}>
{transferring === 'export' ? <LoaderCircle className={styles.sourcingSpinner} size={15} /> : <Download size={15} />}
{transferring === 'export' ? '导出中' : '导出模板'}
</button>
) : null}
{canImportSourcing ? (
<>
<button type="button" disabled={Boolean(transferring)} onClick={() => fileInput.current?.click()}>
{transferring === 'import' ? <LoaderCircle className={styles.sourcingSpinner} size={15} /> : <Upload size={15} />}
{transferring === 'import' ? '导入中' : '导入'}
</button>
<input
ref={fileInput}
type="file"
hidden
accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
onChange={(event) => {
const file = event.target.files?.[0]
if (file) void importSourcingTasks(file)
event.currentTarget.value = ''
}}
/>
</>
) : null}
</div>
{transferFeedback ? (
<p className={transferFeedback.type === 'error' ? styles.sourcingTransferError : styles.sourcingTransferSuccess} role={transferFeedback.type === 'error' ? 'alert' : 'status'}>
{transferFeedback.message}
</p>
) : null}
</div>
<section className={styles.sourcingTableRegion} aria-label="寻源明细表区域" aria-busy={sourcingLoading}>
<div className={styles.sourcingTableScroll} tabIndex={0} aria-label="寻源明细横向滚动区域">
<table className={`${styles.table} ${styles.sourcingTable}`} aria-label="寻源明细表">
<colgroup>
{SOURCING_COLUMNS.map((column) => (
<col key={column.key} style={{ width: column.width }} />
))}
</colgroup>
<thead>
<tr>
{SOURCING_COLUMNS.map((column) => (
<th key={column.key} scope="col" className={column.key === 'actions' ? styles.sourcingActionHeader : undefined}>{column.label}</th>
))}
</tr>
</thead>
<tbody>
{sourcingLoading ? (
<tr>
<td className={styles.sourcingEmpty} colSpan={SOURCING_COLUMNS.length}>
<span className={styles.sourcingLoading}><LoaderCircle className={styles.sourcingSpinner} size={16} />正在加载寻源数据</span>
</td>
</tr>
) : sourcingError ? (
<tr>
<td className={styles.sourcingEmpty} colSpan={SOURCING_COLUMNS.length}>
<div className={styles.sourcingLoadError} role="alert">
<span>{sourcingError}</span>
<button type="button" onClick={reloadSourcing}>重新加载</button>
</div>
</td>
</tr>
) : rows.length === 0 ? (
<tr>
<td className={styles.sourcingEmpty} colSpan={SOURCING_COLUMNS.length}>
{hasSourcingFilters ? '当前筛选条件下没有寻源数据' : '暂无寻源数据'}
</td>
</tr>
) : rows.map((task) => (
<DropshipSourcingRow
key={`${task.id}:${task.updatedAt}`}
task={task}
editable={canEditAllSourcing || (canEditSourcing && task.purchaserUserId === actorUserId)}
revocable={canEditSourcing && task.purchaserUserId === actorUserId}
onRevoked={reloadSourcing}
/>
))}
</tbody>
</table>
</div>
</section>
{!sourcingLoading && !sourcingError ? (
<nav aria-label="寻源明细分页" className={styles.pagination}>
<span>共 {total} 条</span>
<button
type="button"
className={currentPage <= 1 ? styles.pageButtonDisabled : styles.pageButton}
disabled={currentPage <= 1}
onClick={() => setSourcingPageNumber(Math.max(1, currentPage - 1))}
>
<ArrowLeft size={13} />上一页
</button>
<strong>{currentPage}</strong>
<span>/ {totalPages} 页</span>
<button
type="button"
className={currentPage >= totalPages ? styles.pageButtonDisabled : styles.pageButton}
disabled={currentPage >= totalPages}
onClick={() => setSourcingPageNumber(Math.min(totalPages, currentPage + 1))}
>
下一页<ArrowRight size={13} />
</button>
<span>每页 {sourcingPage?.pageSize ?? 50} 条</span>
</nav>
) : null}
</section>
</main>
)
}

View File

@ -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<string[]>([])
return (
<SourcingFilterSelect
noun="采购"
allLabel="全部采购"
options={options}
selected={selected}
onChange={setSelected}
/>
)
}
function openList(options: readonly string[] = ['采购甲', '采购乙', '采购丙']) {
render(<Harness options={options} />)
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()
})
})

View File

@ -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<HTMLDivElement>(null)
const searchRef = useRef<HTMLInputElement>(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 (
<div className={styles.sourcingFilterField} ref={containerRef}>
<span className={styles.sourcingFilterLabel}>{fieldLabel}</span>
<button
type="button"
className={styles.sourcingFilterTrigger}
aria-label={fieldLabel}
aria-haspopup="dialog"
aria-expanded={open}
data-active={selected.length > 0}
title={selected.length > 0 ? selected.join('、') : allLabel}
onClick={() => {
if (open) {
close()
return
}
const bounds = containerRef.current?.getBoundingClientRect()
setAlignRight(Boolean(bounds && bounds.left + POPOVER_WIDTH + 8 > window.innerWidth))
setOpen(true)
}}
>
<span className={styles.sourcingFilterTriggerText}>{summary}</span>
<ChevronDown size={14} aria-hidden="true" />
</button>
{open ? (
<div
className={styles.sourcingFilterPopover}
role="dialog"
aria-label={`${noun}选项`}
style={alignRight ? { left: 'auto', right: 0 } : undefined}
>
<div className={styles.sourcingFilterSearch}>
<Search size={14} aria-hidden="true" />
<input
ref={searchRef}
type="search"
value={search}
aria-label={`搜索${noun}`}
placeholder={`搜索${noun}`}
onChange={(event) => setSearch(event.target.value)}
/>
{search ? (
<button type="button" aria-label="清空搜索" title="清空搜索" onClick={() => setSearch('')}>
<X size={13} />
</button>
) : null}
</div>
<div className={styles.sourcingFilterActions}>
<button type="button" disabled={matching.length === 0 || allMatchingChecked} onClick={checkAllMatching}>
全选{search.trim() ? '当前结果' : '全部'}
</button>
<button type="button" disabled={selected.length === 0} onClick={() => onChange([])}>清空</button>
<span>{selected.length > 0 ? `已选 ${selected.length} 项` : '未筛选,显示全部'}</span>
</div>
<div className={styles.sourcingFilterList} style={{ maxHeight: LIST_MAX_HEIGHT }}>
{options.length === 0 ? (
<p className={styles.sourcingFilterEmpty}>暂无可选项</p>
) : matching.length === 0 ? (
<p className={styles.sourcingFilterEmpty}>没有匹配「{search.trim()}」的选项</p>
) : matching.map((option) => {
const checked = selectedSet.has(option)
return (
<label key={option} className={styles.sourcingFilterOption}>
<input type="checkbox" checked={checked} onChange={() => toggle(option)} />
<span className={styles.sourcingFilterOptionBox} aria-hidden="true">
<Check size={12} />
</span>
<span className={styles.sourcingFilterOptionText} title={option}>{option}</span>
</label>
)
})}
</div>
</div>
) : null}
</div>
)
}

View File

@ -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()
})
})

View File

@ -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 (
<main className={styles.page}>
<header className={styles.toolbar}><div className={styles.titleLine}><h1>1688代发数据明细</h1></div></header>
@ -113,52 +123,63 @@ export default async function Dropship1688DataPage({
</main>
)
}
// 条码筛选和商品检索已从工具栏移除,旧链接中的对应条件也不能继续隐式生效。
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 (
<main className={styles.page}>
<header className={styles.toolbar}>
<div>
<div className={styles.titleLine}>
<h1>1688代发数据明细</h1>
<span>本地 DF 数据</span>
</div>
<p>数据更新至 {data.dataUpdatedThrough || '--'},当前共 {integerText(String(data.total))} 个商品</p>
</div>
<DropshipWorkspace
summary={
<dl className={styles.summary}>
<div><dt>发货件数</dt><dd>{integerText(data.summary.shipQty)}</dd></div>
<div><dt>销售金额</dt><dd>{moneyText(data.summary.salesAmount)}</dd></div>
<div><dt>真实业绩</dt><dd>{moneyText(data.summary.realPerformance)}</dd></div>
<div><dt>发货件数</dt><dd>{integerText(data.summary.shipQty)}</dd></div>
<div><dt>毛利额</dt><dd>{moneyText(data.summary.grossProfit)}</dd></div>
<div><dt>售后成本率</dt><dd>{percentText(data.summary.afterSaleCostRate)}</dd></div>
<div><dt>总商品数</dt><dd>{integerText(data.summary.totalProducts)}</dd></div>
<div><dt>有销售金额商品数</dt><dd>{integerText(data.summary.productsWithSalesAmount)}</dd></div>
</dl>
</header>
}
actorUserId={authUser.id}
canEditAllSourcing={access.edit && administrator}
canEditSourcing={canAccept}
canExportSourcing={access.download}
canImportSourcing={canAccept}
>
<form className={styles.filters} method="get">
<form aria-label="数据明细筛选" className={styles.filters} method="get">
{filterRef
? <input type="hidden" name="filterRef" value={filterRef} />
: <input type="hidden" name="columnFilters" value={serializeDropship1688Filters(data.filters)} />}
<div className={styles.filterTitle}><Filter size={15} /><span>筛选</span></div>
<label>
<span>开始日期</span>
<input name="dateFrom" type="date" defaultValue={data.dateFrom} />
</label>
<label>
<span>结束日期</span>
<input name="dateTo" type="date" defaultValue={data.dateTo} />
</label>
<label className={styles.keywordField}>
<span>商品检索</span>
<input name="keyword" type="search" defaultValue={data.keyword} placeholder="SPU / SKU / 条码 / SKU运营" />
</label>
<button className={styles.searchButton} type="submit"><Search size={15} />查询</button>
<DropshipAutoSubmitDateField name="dateFrom" label="开始日期" defaultValue={data.dateFrom} />
<DropshipAutoSubmitDateField name="dateTo" label="结束日期" defaultValue={data.dateTo} />
<DropshipFieldFilterGroup
dateFrom={data.dateFrom}
dateTo={data.dateTo}
keyword={data.keyword}
filters={data.filters}
>
<DropshipFieldFilter field="purchaser" noun="采购" allLabel="全部采购" />
<DropshipFieldFilter field="skuOperator" noun="运营" allLabel="全部运营" />
<DropshipFieldFilter field="spu" noun="SPU" allLabel="全部SPU" />
<DropshipFieldFilter field="sku" noun="SKU" allLabel="全部SKU" />
</DropshipFieldFilterGroup>
<a className={styles.resetButton} href="/supply-chain/new-products/1688-dropship-data">
<RefreshCw size={14} />重置
</a>
@ -176,19 +197,7 @@ export default async function Dropship1688DataPage({
<tr>
{COLUMNS.map((column) => (
<th key={column.label}>
<span className={styles.columnHeading}>
{column.label}
{'filterField' in column && (
<DropshipHeaderFilter
field={column.filterField}
label={column.label}
filters={data.filters}
dateFrom={data.dateFrom}
dateTo={data.dateTo}
keyword={data.keyword}
/>
)}
</span>
<span className={styles.columnHeading}>{column.label}</span>
</th>
))}
</tr>
@ -198,39 +207,69 @@ export default async function Dropship1688DataPage({
<tr>
<td className={styles.empty} colSpan={COLUMNS.length}>当前筛选条件下没有商品</td>
</tr>
) : data.rows.map((row) => (
<tr key={row.id}>
<td className={styles.imageCell}>
<DropshipImageCell
barcode={row.barcode}
sku={row.sku}
hasImage={Boolean(row.image)}
/>
</td>
<td className={styles.numberCell}>{moneyText(row.realPerformance)}</td>
<td className={styles.trendCell}>
<SalesTrendPopover
barcode={row.barcode}
dateFrom={data.dateFrom}
dateTo={data.dateTo}
trend={row.trend}
comparisonTrend={row.comparisonTrend}
/>
</td>
<td className={styles.numberCell}>{moneyText(row.costPrice)}</td>
<td className={styles.numberCell}>{row.shipQty ? integerText(row.shipQty) : '--'}</td>
<td className={styles.numberCell}>{moneyText(row.afterSaleAmount)}</td>
<td className={styles.numberCell}>{percentText(row.afterSaleCostRate)}</td>
<td>{row.skuOperator || '--'}</td>
<td className={styles.codeCell} title={row.spu || undefined}>{row.spu || '--'}</td>
<td className={styles.codeCell} title={row.sku || undefined}>{row.sku || '--'}</td>
<td className={styles.codeCell} title={row.barcode}>{row.barcode}</td>
<td title={row.color || undefined}>{row.color || '--'}</td>
<td className={styles.numberCell}>{moneyText(row.salesAmount)}</td>
<td className={styles.numberCell}>{moneyText(row.grossProfit)}</td>
<td className={styles.numberCell}>{percentText(row.grossMargin)}</td>
</tr>
))}
) : data.rows.map((row) => {
const purchasers = purchasersByBarcode[row.barcode.toUpperCase()] ?? []
return (
<tr key={row.id}>
<td className={styles.imageCell}>
<DropshipImageCell
barcode={row.barcode}
sku={row.sku}
hasImage={Boolean(row.image)}
/>
</td>
<td className={styles.numberCell}>{moneyText(row.realPerformance)}</td>
<td className={styles.trendCell}>
<div className={styles.trendWithActions}>
<SalesTrendPopover
barcode={row.barcode}
dateFrom={data.dateFrom}
dateTo={data.dateTo}
trend={row.trend}
comparisonTrend={row.comparisonTrend}
/>
<div className={styles.rowActions} role="group" aria-label={`${row.sku || row.barcode} 承接采购操作`}>
<DropshipAcceptanceButton
acceptanceRevision={purchasers
.map((purchaser) => `${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}
/>
</div>
</div>
</td>
<td className={styles.purchaserCell}>
{purchasers.length > 0 ? (
<div className={styles.purchaserNames} title={purchasers.map((purchaser) => purchaser.name).join('、')}>
{purchasers.map((purchaser) => (
<span key={purchaser.userId}>{purchaser.name}</span>
))}
</div>
) : '--'}
</td>
<td className={styles.numberCell}>{moneyText(row.totalCost)}</td>
<td className={styles.numberCell}>{moneyText(row.costPrice)}</td>
<td className={styles.numberCell}>{moneyText(row.estimatedFreight)}</td>
<td className={styles.numberCell}>{row.shipQty ? integerText(row.shipQty) : '--'}</td>
<td className={styles.numberCell}>{moneyText(row.afterSaleAmount)}</td>
<td className={styles.numberCell}>{percentText(row.afterSaleCostRate)}</td>
<td>{row.skuOperator || '--'}</td>
<td className={styles.codeCell} title={row.spu || undefined}>{row.spu || '--'}</td>
<td className={styles.codeCell} title={row.sku || undefined}>{row.sku || '--'}</td>
<td className={styles.codeCell} title={row.barcode}>{row.barcode}</td>
<td title={row.color || undefined}>{row.color || '--'}</td>
<td className={styles.numberCell}>{moneyText(row.salesAmount)}</td>
<td className={styles.numberCell}>{moneyText(row.grossProfit)}</td>
<td className={styles.numberCell}>{percentText(row.grossMargin)}</td>
</tr>
)
})}
</tbody>
</table>
</div>
@ -252,6 +291,6 @@ export default async function Dropship1688DataPage({
)}
<span>每页 {data.pageSize} 条</span>
</nav>
</main>
</DropshipWorkspace>
)
}

View File

@ -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: '撤销失败,请稍后重试',
})
})
})

View File

@ -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<void> {
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<ReturnType<typeof dropship1688SourcingService.update>> }
| { 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 : '撤销失败,请稍后重试',
}
}
}

View File

@ -40,7 +40,7 @@ function openDatePicker(event: React.MouseEvent<HTMLInputElement>) {
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<SupplierRecommendedProductFilters>({ ...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<SupplierRecommendedProductRow | 'new' | null>(null)
const [logs, setLogs] = useState<SupplierRecommendedProductChangeLogEntry[] | null>(null)
const [preview, setPreview] = useState<SupplierRecommendedProductRow | null>(null)

View File

@ -2387,6 +2387,9 @@ function ModelViewerComponent({
signature
);
});
const removedNodeNames = Array.from(
appliedMaterialSignatureRef.current.keys(),
).filter((nodeName) => !assignmentByNode.has(nodeName));
const unresolvedNodeNames = new Set<string>();
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))

View File

@ -75,7 +75,7 @@ export const Select = React.forwardRef<HTMLSelectElement, SelectProps>(
disabled,
value,
onChange,
children,
children: _children,
// onClick/onKeyDown 由组件内部的触发按钮接管,不透传(其 select 元素
// 事件签名与 button 不兼容,且外部场景不应覆盖交互实现)。
onClick: _ignoredOnClick,
@ -259,8 +259,12 @@ export const Select = React.forwardRef<HTMLSelectElement, SelectProps>(
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']}
>
<span className={cn(
'truncate text-left',

View File

@ -0,0 +1,103 @@
import * as THREE from "three";
jest.mock("three/examples/jsm/loaders/GLTFLoader.js", () => ({
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<typeof ThreeDEngine>;
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<string, string>;
}
).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();
});
});

View File

@ -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) {

View File

@ -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(),

View File

@ -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', '<one/>')
zip.file('two.xml', '<two/>')
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行数据',
)
})
})

View File

@ -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<WorkbookZipLimits> = {},
): Promise<void> {
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<Uint8Array> {
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<Dropship1688SourcingImportRow[]> {
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<string, number>()
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
}

View File

@ -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: [],
}

View File

@ -1064,6 +1064,29 @@ export async function createInstallationDemoShareLink(
return data.share
}
export async function fetchInstallationDemoShareLink(
drawingId: string,
): Promise<InstallationDemoShareLinkDTO | null> {
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<InstallationDemoShareLinkDTO> {
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<InstallationDemoQrShareDTO> {

View File

@ -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)
}
})
})

View File

@ -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)
}

View File

@ -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' })
})

View File

@ -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 }
}

View File

@ -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 ''
}

View File

@ -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 = [

View File

@ -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' },

View File

@ -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<string, unknown> = {}) {
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()
})
})

View File

@ -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',
}])
})

View File

@ -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/)
})
})

View File

@ -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<Record<string, unknown>> }
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<Record<string, unknown>> }
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()
})
})

View File

@ -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()
})
})

View File

@ -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 },

View File

@ -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<string, string>
purchaserBarcodes: Set<string>
}
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<string, string>,
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<string>()
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<string, string>()),
filters.purchaser
? this.purchaserBarcodesForNames(filters.purchaser.values)
: Promise.resolve(new Set<string>()),
])
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<string, string>()),
input.filters?.purchaser
? this.purchaserBarcodesForNames(input.filters.purchaser.values)
: Promise.resolve(new Set<string>()),
])
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' }],
}),

View File

@ -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<Dropship1688SourcingTaskWithProduct[]> {
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<Dropship1688SourcingTaskRecord | null> {
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<Dropship1688SourcingTaskRecord> {
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<boolean> {
const deleted = await prisma.dropship1688SourcingTask.deleteMany({
where: {
id: input.id,
purchaserUserId: input.purchaserUserId,
jianshangBarcode: '',
},
})
return deleted.count === 1
}
async listTasksByBarcodes(
barcodes: readonly string[],
): Promise<Dropship1688SourcingTaskRecord[]> {
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<void> {
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<Array<{
expected_count: number
matched_count: number
updated_count: number
}>>`
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<Dropship1688ClaimSource | null> {
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<Dropship1688ClaimResult> {
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<Dropship1688SourcingTaskWithProduct[]> {
const tasks = await prisma.dropship1688SourcingTask.findMany({
select: TASK_SELECT,
orderBy: [{ acceptedAt: 'desc' }, { id: 'asc' }],
})
return this.enrichTasks(tasks)
}
async countTasks(filters: Dropship1688SourcingFilters): Promise<number> {
return prisma.dropship1688SourcingTask.count({ where: taskWhere(filters) })
}
async listTasksPage(input: {
filters: Dropship1688SourcingFilters
skip: number
take: number
}): Promise<Dropship1688SourcingTaskWithProduct[]> {
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<Dropship1688SourcingFilterOptions> {
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<Dropship1688SourcingTaskRecord[]> {
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<Dropship1688SourcingPurchaserRecord[]> {
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 }

View File

@ -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)

View File

@ -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();
});
});

View File

@ -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 =

View File

@ -70,6 +70,22 @@ class NotificationDeliveryRepository {
})
}
async findRecipientsByNames(names: string[]): Promise<NotificationRecipient[]> {
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 } })
}

View File

@ -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) => ({

View File

@ -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<string>()
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<ProductArchiveTextFilterKey, Prisma.SupplyChainProductArchiveScalarFieldEnum>
/**
* 「正常编码」取值清单的缓存。
*
* Prisma 7 的字符串过滤不支持正则(生成类型里没有 regex),所以只能先用原生 SQL
* 把符合形态的取值查出来,再拼成 `in` 条件。这些取值只在档案同步时才会变,
* 因此按列缓存几分钟,避免每次翻页都做一次全表正则扫描。
*/
const NORMAL_CODE_CACHE_TTL_MS = 5 * 60 * 1000
const normalCodeValueCache = new Map<string, { values: string[]; expiresAt: number }>()
async function listNormalCodeValues(databaseField: string): Promise<string[]> {
const cached = normalCodeValueCache.get(databaseField)
if (cached && cached.expiresAt > Date.now()) return cached.values
const column = Prisma.raw(`"${databaseField}"`)
const rows = await prisma.$queryRaw<Array<{ value: string | null }>>(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<Prisma.SupplyChainProductArchiveWhereInput[]> {
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<Prisma.SupplyChainProductArchiveWhereInput> {
const base = buildProductArchiveWhere(filters, omitFilter)
const extra = await resolveNormalCodeClauses(filters)
return extra.length > 0 ? { AND: [base, ...extra] } : base
}

View File

@ -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(', ')

View File

@ -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({

View File

@ -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

View File

@ -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> = {}): 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,
},
})
})
})

View File

@ -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: '' })
})
})

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