feat: 定价工作台更新买价支持报价表本地识别与融合预览
All checks were successful
Build and Deploy Front / deploy (push) Successful in 10m58s

本地规则优先解析渠道买价 Excel,失败再 AI 补齐;四步向导含对比与写库后矩阵预览。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
zzh 2026-11-24 18:34:58 +08:00
parent 29d7cbb226
commit 1cb4631480
9 changed files with 4618 additions and 11 deletions

View File

@ -0,0 +1,83 @@
---
name: oms-channel-quote-extract
description: >-
Extracts OMS channel buy-price quotes from vendor Excel sheets for pricing
workbench Step 0. Use when the user uploads 报价表, asks to 更新渠道买价,
parse 重量段/一口价/运费RMB/KG/处理费, or map sheet names to service channels
on /channel/pricingWorkbench.
---
# OMS 渠道报价表提取 · 买价更新
从下游报价 Excel 提取结构化买价,供定价工作台「更新买价」回写渠道草稿买价。
**运行时主路径是本地规则解析**(`channelQuoteLocalParse.ts`),覆盖常见「公斤+票费」「一口价/并排国家列」。
本 skill / AI 仅在本地失败时补齐难拆 sheet。
- 本地:`src/views/channel/pricingWorkbench/channelQuoteLocalParse.ts`
- AI system:`src/views/channel/pricingWorkbench/channelQuoteAiSkill.ts`
- 面板:`src/views/channel/pricingWorkbench/components/ChannelQuoteImportPanel.vue`
## 产出格式(必须)
只输出一个 JSON 对象(可用 \`\`\`json 包裹),禁止编造表中不存在的金额。
```json
{
"sheetName": "3PE ePost",
"isPriceSheet": true,
"skipReason": null,
"currency": "CNY",
"effectiveAt": "2026-05-08",
"channelQuotes": [
{
"channelCodeHint": "3SZ51",
"channelNameHint": "3PE ePost普货",
"serviceSubtype": null,
"mode": "unit_plus_fee",
"destinationHints": ["美国"],
"rows": [
{
"weightStart": 0,
"weightEnd": 0.1,
"zoneHint": "美国",
"freightPerKg": 86,
"handlingPerShipment": 30,
"registrationPerShipment": null,
"flatTotal": null
}
]
}
],
"warnings": []
}
```
### mode
| mode | 含义 | 行字段 |
|------|------|--------|
| `flat` | 一口价(重量点/段 → 总价) | `flatTotal` 必填;`freightPerKg`/`handling*` 为空 |
| `unit_plus_fee` | 运费 RMB/KG + 处理费/挂号费 RMB/票 | `freightPerKg` 与/或 `handlingPerShipment` / `registrationPerShipment` |
### 重量
- 区间 `0-0.1` / `0.101-0.2` → `weightStart` + `weightEnd`
- 单点一口价 `0.5` → 至少填 `weightEnd=0.5`;`weightStart` 可留空由前端按有序上界补成 `(prev-end]`
- 不要输出偏远邮编清单或条款长文
## 硬规则
1. 非报价 sheet(目录、附加费规定、操作指南、偏远邮编、增值服务、纯邮编列表):`isPriceSheet=false`,`channelQuotes=[]`,写清 `skipReason`
2. 列名别名:包裹重量/重量KG、重量段(KG)、运费(RMB/KG)、处理费/操作费(RMB/票)、挂号费、国家/国家名称/分区/对接代码
3. 一 sheet 多个「对接代码」或渠道码 → 拆成多个 `channelQuotes`
4. PAK/WPX 等分段标题写入 `serviceSubtype`,不要当成渠道码
5. sheet 名常含渠道码(如 `3SZ01-3PE Express--优先`),写入 `channelCodeHint` / `channelNameHint`
6. 金额必须来自单元格;说明行、空行忽略
7. 币种默认人民币 → `CNY`;生效日从「生效日期」类文案解析(可空)
## 原则
- 只提取可进 OMS 买价矩阵的运费/处理费/挂号费
- 前端负责匹配 OMS 渠道、价格分区与重量段重建;你只输出结构化报价
- 不确定是否报价表时宁可 `isPriceSheet=false` 并说明原因

View File

@ -5,6 +5,19 @@
## 标准操作顺序
工作台分两个 Tab:
### Tab「更新买价」(四步向导)
1. **提取模型**:上传 Excel → **本地规则优先**解析报价模型(秒级);仅未识别 sheet 可选 AI 补齐。本步不绑渠道、不写库。
2. **候选买价**:将勾选模型规范为候选价表(重量段 `(start-end]`、运费/处理费等),仅内存预览。
3. **对比现网**:绑定 OMS 渠道 + 分区映射 → 候选 vs 现网买价(新增/改价/将删除/未映射分区)。
4. **选择融合**:覆盖匹配价格项 / 仅更新交集 / 放弃 → 确认后才 `price/save`(默认草稿,可发布)。
分区/价格项须已在渠道设计中配置;不自动新建。融合成功后自动切到「合成卖价」并勾选已更新渠道。
### Tab「合成卖价」
1. **选渠道**:多选服务渠道买价(优先已发布快照;无快照则读草稿并警告)。摘要默认折叠;币种不一致会提示并禁用预览。
2. **定规则**:毛利率、差异阈值、排除渠道;可选「对比现网卖价」与「改规则后自动重算」。
3. **预览合成**:对齐分区/重量段,最低买价合成,毛利率硬计算。改规则后结果标过期,可一键重算;超阈值差异可「用 AI 解释」。
@ -13,15 +26,32 @@
成本合成:每个「分区 × 重量段」取参与渠道中的**最低买价**。
毛利率硬计算:`sell = ceil(buy / (1 - m), 分)`;禁止以 AI 填数当唯一真相。
## 更新买价 · 报价表 AI
| 项 | 说明 |
|----|------|
| 入口 | 工作台 Tab「更新买价」 |
| 本地解析 | `channelQuoteLocalParse.ts`:表头识别公斤+票费 / 一口价(含并排国家列、PAK·WPX);上传后自动跑 |
| Skill / AI | `.cursor/skills/oms-channel-quote-extract`;`channelQuoteAiSkill.ts`;场景 `channelQuoteImport`;**仅补齐本地失败 sheet** |
| 候选/融合 | `channelQuoteCandidate.ts` + `channelQuoteApply.ts`(前端硬算,AI 不决策融合) |
| 一口价 `flat` | 包裹重量点/段 → 总价;运费 `calculationFormula=total` |
| 公斤+票费 `unit_plus_fee` | 运费 RMB/KG(`unit`)+ 处理费/操作费 RMB/票(`total`,需渠道已有操作费价格项) |
| 融合方式 | `replaceMatched` 覆盖匹配项重建重量段;`intersectionOnly` 只改交集格子;`abandon` 不写库 |
| Sheet | 名称常含渠道码;一 sheet 多「对接代码」拆多条;目录/附加费/邮编等默认不勾选 |
| 识别性能 | 主路径本地规则;AI 补齐默认并发 3,瘦身 TSV(约 12k 字) |
| 写库 | `POST /channel/service-channel/price/save`,默认草稿;可选发布 |
| 非目标 | 自动建分区/价格项、偏远邮编入库、AI 直接改卖价或替你确认融合 |
## 与发布 / 审批衔接
| 步骤 | 位置 | 说明 |
|------|------|------|
| 生成草稿 | 定价工作台 → 回写草稿 | `POST /channel/pricing-workbench/apply`,`Publish=false` |
| 更新渠道买价 | 定价工作台「更新买价」Tab | 四步后融合写入草稿或发布 |
| 生成卖价草稿 | 定价工作台 → 回写草稿 | `POST /channel/pricing-workbench/apply`,`Publish=false` |
| AI 风险分析 | 销售产品 → 价格发布 | 沿用 `PricePublishAiAssistDrawer` / 发布风险 skill |
| 发布审批 | 销售产品现有流程 | `Channel.SalesProduct.PublishPrice` 审批定义 |
工作台 AI 默认收起;负责调毛利/排除渠道后触发同一套 preview 硬计算,以及解释相对现网卖价超阈值差异。正式出账仍以销售产品发布快照为准。
工作台 AI(调规则)默认收起;负责调毛利/排除渠道后触发同一套 preview 硬计算,以及解释相对现网卖价超阈值差异。正式出账仍以销售产品发布快照为准。
## 差异闸门
@ -36,9 +66,11 @@
- 自动发布卖价、自动改排货分配
- 跨币种汇兑(币种不一致直接阻断)
- 用 AI 替代计费引擎出账
- 「更新买价」自动新建价格分区 / 价格项
## API
- `GET /channel/pricing-workbench/channel-summaries?serviceChannelIds=1,2`
- `POST /channel/pricing-workbench/preview`
- `POST /channel/pricing-workbench/apply`
- 更新买价复用:`GET /channel/service-channel/price/list`、`POST /channel/service-channel/price/save`

View File

@ -61,6 +61,7 @@ export type AiSkillItem = {
export const AI_SKILL_SCENES = [
{ value: 'pricePublish', label: '价格发布风险' },
{ value: 'pricingWorkbench', label: '定价工作台' },
{ value: 'channelQuoteImport', label: '渠道报价提取' },
{ value: 'autoTriggerFormula', label: '自动触发公式' },
{ value: 'billingConditionFormula', label: '计费条件公式' },
{ value: 'receiverAddressParse', label: '收件地址解析' },

View File

@ -0,0 +1,412 @@
/**
* 定价工作台 Step 0:渠道报价表 AI 提取(与 .cursor/skills/oms-channel-quote-extract 对齐)
*/
export type ChannelQuoteMode = 'flat' | 'unit_plus_fee'
export type ChannelQuoteRowRow = {
weightStart?: number | null
weightEnd: number
zoneHint?: string | null
freightPerKg?: number | null
handlingPerShipment?: number | null
registrationPerShipment?: number | null
flatTotal?: number | null
}
export type ChannelQuoteExtracted = {
channelCodeHint?: string | null
channelNameHint?: string | null
serviceSubtype?: string | null
mode: ChannelQuoteMode
destinationHints?: string[]
rows: ChannelQuoteRowRow[]
}
export type ChannelQuoteSheetExtract = {
sheetName: string
isPriceSheet: boolean
skipReason?: string | null
currency?: string | null
effectiveAt?: string | null
channelQuotes: ChannelQuoteExtracted[]
warnings?: string[]
/** 解析用 */
raw?: string
}
export const CHANNEL_QUOTE_AI_DEFAULT_SKILL_KEY = 'oms-channel-quote-extract'
export const CHANNEL_QUOTE_AI_SCENE = 'channelQuoteImport'
const NON_PRICE_SHEET_RE =
/目录|附加费|操作指南|偏远|邮编|增值服务|附录|说明|条款|服务邮编|商业派送服务邮编/i
const SKILL_CORE = `你是 OMS「渠道报价表提取」助手:从单个 Excel sheet 的 TSV 文本中提取可写入服务渠道买价的结构化报价。
## 硬约束
1. 只输出一个 JSON 对象(可用 \`\`\`json 包裹);禁止编造表中不存在的金额
2. 非报价 sheet:isPriceSheet=false,channelQuotes=[],写清 skipReason
3. 一 sheet 多个对接代码/渠道码必须拆成多个 channelQuotes
4. PAK/WPX 等服务分段标题写入 serviceSubtype,不要当成渠道码
5. 金额必须来自单元格;说明行、空行、偏远邮编清单、条款长文一律忽略
## mode
- flat:一口价(包裹重量点/段 → 总价),填 flatTotal;freightPerKg/handling* 为 null
- unit_plus_fee:运费 RMB/KG + 处理费/挂号费 RMB/票,填 freightPerKg / handlingPerShipment / registrationPerShipment
## 重量
- 区间 0-0.1 → weightStart=0, weightEnd=0.1
- 单点 0.5 → 至少 weightEnd=0.5;weightStart 可空
## JSON schema
{
"sheetName": "string",
"isPriceSheet": true,
"skipReason": null,
"currency": "CNY",
"effectiveAt": "YYYY-MM-DD或null",
"channelQuotes": [
{
"channelCodeHint": "3SZ51",
"channelNameHint": "名称提示",
"serviceSubtype": null,
"mode": "flat|unit_plus_fee",
"destinationHints": ["美国"],
"rows": [
{
"weightStart": 0,
"weightEnd": 0.1,
"zoneHint": "美国",
"freightPerKg": 86,
"handlingPerShipment": 30,
"registrationPerShipment": null,
"flatTotal": null
}
]
}
],
"warnings": []
}
`
export function buildChannelQuoteAiSystemPrompt(): string {
return SKILL_CORE
}
export function buildChannelQuoteAiShortSystemPrompt(): string {
return (
'你是 OMS 渠道报价提取助手。对单个 sheet 的 TSV 输出 JSON:' +
'isPriceSheet、channelQuotes[].mode(flat|unit_plus_fee)、rows 重量与金额。禁止编造金额。'
)
}
export function buildChannelQuoteUserContent(input: {
sheetName: string
sheetText: string
hint?: string
}): string {
const lines = [
`Sheet 名称:${input.sheetName}`,
'请提取该 sheet 的全部可写入买价的报价行。',
]
if (input.hint) lines.push(`补充说明:${input.hint}`)
lines.push('Sheet 内容(TSV):')
lines.push(input.sheetText)
return lines.join('\n')
}
/** 默认不勾选识别的非报价 sheet */
export function isLikelyNonPriceSheetName(name: string): boolean {
return NON_PRICE_SHEET_RE.test(String(name || '').trim())
}
function toNum(v: unknown): number | null {
if (v == null || v === '') return null
const n = typeof v === 'number' ? v : Number(String(v).replace(/,/g, '').trim())
return Number.isFinite(n) ? n : null
}
function normalizeCurrency(raw: unknown): string {
const s = String(raw ?? '')
.trim()
.toUpperCase()
if (!s || s.includes('人民币') || s === 'RMB' || s === 'CNY' || String(raw).includes('人民币')) {
return 'CNY'
}
if (s === 'USD' || s.includes('美元')) return 'USD'
if (s === 'HKD' || String(raw).includes('港')) return 'HKD'
return String(raw).trim() || 'CNY'
}
function normalizeMode(raw: unknown): ChannelQuoteMode {
const s = String(raw || '')
.trim()
.toLowerCase()
if (s === 'flat' || s.includes('一口') || s.includes('总价')) return 'flat'
return 'unit_plus_fee'
}
function normalizeRow(raw: any): ChannelQuoteRowRow | null {
if (!raw || typeof raw !== 'object') return null
const weightEnd =
toNum(raw.weightEnd ?? raw.WeightEnd ?? raw.weight ?? raw.Weight ?? raw.maxWeight) ?? null
if (weightEnd == null || weightEnd <= 0) return null
const weightStart = toNum(raw.weightStart ?? raw.WeightStart ?? raw.minWeight)
return {
weightStart: weightStart != null && weightStart >= 0 ? weightStart : null,
weightEnd,
zoneHint:
raw.zoneHint != null
? String(raw.zoneHint)
: raw.country != null
? String(raw.country)
: raw.destination != null
? String(raw.destination)
: null,
freightPerKg: toNum(raw.freightPerKg ?? raw.freight ?? raw.unitPrice),
handlingPerShipment: toNum(
raw.handlingPerShipment ?? raw.handling ?? raw.processFee ?? raw.操作费,
),
registrationPerShipment: toNum(
raw.registrationPerShipment ?? raw.registration ?? raw.挂号费,
),
flatTotal: toNum(raw.flatTotal ?? raw.total ?? raw.一口价),
}
}
function normalizeChannelQuote(raw: any): ChannelQuoteExtracted | null {
if (!raw || typeof raw !== 'object') return null
const rowsRaw = Array.isArray(raw.rows) ? raw.rows : []
const rows = rowsRaw.map(normalizeRow).filter(Boolean) as ChannelQuoteRowRow[]
if (!rows.length) return null
const mode = normalizeMode(raw.mode)
return {
channelCodeHint: raw.channelCodeHint != null ? String(raw.channelCodeHint) : null,
channelNameHint: raw.channelNameHint != null ? String(raw.channelNameHint) : null,
serviceSubtype: raw.serviceSubtype != null ? String(raw.serviceSubtype) : null,
mode,
destinationHints: Array.isArray(raw.destinationHints)
? raw.destinationHints.map((x: any) => String(x)).filter(Boolean)
: [],
rows,
}
}
/** 从模型回复解析 sheet 提取结果 */
export function parseChannelQuoteAiReply(
raw: string,
fallbackSheetName?: string,
): ChannelQuoteSheetExtract {
const text = String(raw || '').trim()
const empty: ChannelQuoteSheetExtract = {
sheetName: fallbackSheetName || '',
isPriceSheet: false,
skipReason: '未能解析 AI 输出',
channelQuotes: [],
warnings: [],
raw: text,
}
if (!text) return empty
const jsonMatch =
text.match(/```json\s*([\s\S]*?)```/i) ||
text.match(/\{[\s\S]*"isPriceSheet"[\s\S]*\}/) ||
text.match(/\{[\s\S]*"channelQuotes"[\s\S]*\}/)
if (!jsonMatch) return empty
try {
const body = jsonMatch[1] || jsonMatch[0]
const obj = JSON.parse(body)
const quotesRaw = Array.isArray(obj.channelQuotes) ? obj.channelQuotes : []
const channelQuotes = quotesRaw
.map(normalizeChannelQuote)
.filter(Boolean) as ChannelQuoteExtracted[]
const isPriceSheet =
typeof obj.isPriceSheet === 'boolean' ? obj.isPriceSheet : channelQuotes.length > 0
return {
sheetName: String(obj.sheetName || fallbackSheetName || ''),
isPriceSheet,
skipReason: obj.skipReason != null ? String(obj.skipReason) : null,
currency: normalizeCurrency(obj.currency),
effectiveAt: obj.effectiveAt != null ? String(obj.effectiveAt) : null,
channelQuotes,
warnings: Array.isArray(obj.warnings) ? obj.warnings.map((x: any) => String(x)) : [],
raw: text,
}
} catch {
return empty
}
}
const SHEET_TEXT_MAX = 28_000
/** 送给 AI 的更瘦上限:降 token、提速 */
const SHEET_AI_TEXT_MAX = 12_000
const SHEET_AI_MAX_ROWS = 180
const SHEET_AI_CELL_MAX = 64
function cellToPlain(c: unknown, maxLen?: number): string {
if (c == null) return ''
let s = String(c).replace(/\t/g, ' ').replace(/\r?\n/g, ' ').trim()
if (maxLen != null && s.length > maxLen) s = `${s.slice(0, maxLen)}…`
return s
}
/** 条款/说明行:长文且几乎无报价数字结构 */
function looksLikeTermsRow(cells: string[]): boolean {
const joined = cells.join(' ')
if (joined.length < 80) return false
const hasPriceShape = /\d+(\.\d+)?/.test(joined) && cells.filter((c) => /^-?\d+(\.\d+)?$/.test(c)).length >= 2
if (hasPriceShape) return false
return /条款|截单|赔偿|注[::]|请您|服务范围|本公司保留|附加费及规定|操作指南/.test(joined) || joined.length > 160
}
/** 将 sheet 二维数组压成 TSV,控制 token */
export function sheetMatrixToTsv(
matrix: (string | number | null | undefined)[][],
opts?: { maxChars?: number; maxRows?: number; slimForAi?: boolean },
): { text: string; truncated: boolean; rowCount: number; colCount: number } {
const slim = Boolean(opts?.slimForAi)
const maxChars = opts?.maxChars ?? (slim ? SHEET_AI_TEXT_MAX : SHEET_TEXT_MAX)
const maxRows = opts?.maxRows ?? (slim ? SHEET_AI_MAX_ROWS : 400)
const cellMax = slim ? SHEET_AI_CELL_MAX : undefined
const raw = matrix || []
// 仅保留在前若干行出现过非空值的列,去掉空白列
const probe = raw.slice(0, Math.min(raw.length, 120))
const maxCol = probe.reduce((m, r) => Math.max(m, (r || []).length), 0)
const colKeep: boolean[] = Array.from({ length: maxCol }, (_, c) =>
probe.some((r) => {
const v = r?.[c]
return v != null && String(v).trim() !== ''
}),
)
const lines: string[] = []
let truncated = false
let colCount = 0
let kept = 0
for (let i = 0; i < raw.length; i++) {
if (kept >= maxRows) {
truncated = true
break
}
const row = raw[i] || []
const cells: string[] = []
for (let c = 0; c < maxCol; c++) {
if (slim && colKeep[c] === false) continue
cells.push(cellToPlain(row[c], cellMax))
}
while (cells.length && cells[cells.length - 1] === '') cells.pop()
if (!cells.some((c) => c.trim())) continue
if (slim && looksLikeTermsRow(cells)) {
truncated = true
continue
}
colCount = Math.max(colCount, cells.length)
lines.push(cells.join('\t'))
kept += 1
}
let text = lines.join('\n')
if (raw.length > maxRows) truncated = true
if (text.length > maxChars) {
text = text.slice(0, maxChars) + '\n…(内容已截断)'
truncated = true
}
return { text, truncated, rowCount: lines.length, colCount }
}
/** 并发池:保持结果顺序 */
export async function mapWithConcurrency<T, R>(
items: T[],
concurrency: number,
worker: (item: T, index: number) => Promise<R>,
): Promise<R[]> {
const n = Math.max(1, Math.min(concurrency, items.length || 1))
const results: R[] = new Array(items.length)
let next = 0
async function runOne() {
while (next < items.length) {
const i = next++
results[i] = await worker(items[i]!, i)
}
}
await Promise.all(Array.from({ length: Math.min(n, items.length) }, () => runOne()))
return results
}
export type WorkbookSheetPreview = {
name: string
selected: boolean
likelyNonPrice: boolean
matrix: (string | number | null)[][]
/** 预览用较全 TSV */
tsv: string
/** 送给 AI 的瘦身 TSV */
tsvAi: string
truncated: boolean
rowCount: number
colCount: number
}
/** 浏览器端解析 xlsx → 各 sheet 预览 */
export async function parseQuoteWorkbook(file: File | ArrayBuffer): Promise<WorkbookSheetPreview[]> {
const XLSX = await import('xlsx')
const buf = file instanceof File ? await file.arrayBuffer() : file
const wb = XLSX.read(buf, { type: 'array', cellDates: true })
const out: WorkbookSheetPreview[] = []
for (const name of wb.SheetNames || []) {
const ws = wb.Sheets[name]
const matrix = (XLSX.utils.sheet_to_json(ws, {
header: 1,
defval: null,
raw: true,
}) || []) as (string | number | null)[][]
const full = sheetMatrixToTsv(matrix)
const slim = sheetMatrixToTsv(matrix, { slimForAi: true })
const likelyNonPrice = isLikelyNonPriceSheetName(name)
out.push({
name,
selected: !likelyNonPrice && full.rowCount > 0,
likelyNonPrice,
matrix,
tsv: full.text,
tsvAi: slim.text,
truncated: full.truncated || slim.truncated,
rowCount: full.rowCount,
colCount: full.colCount,
})
}
return out
}
/** AI 识别默认并发(供应商限流友好) */
export const CHANNEL_QUOTE_AI_CONCURRENCY = 3
/** 从 sheet 名猜测渠道码(如 3SZ01-xxx) */
export function guessChannelCodeFromSheetName(sheetName: string): string | null {
const m = String(sheetName || '').match(/\b([0-9A-Za-z]{3,}[0-9A-Za-z]*)\b/)
if (!m) return null
// 优先匹配常见物流渠道码形态:字母数字混合且含数字
const all = String(sheetName).match(/[A-Za-z0-9]{3,}/g) || []
const withDigit = all.find((x) => /\d/.test(x) && /[A-Za-z]/.test(x))
return withDigit || m[1] || null
}
export function fuzzyScoreChannel(
hintCode: string | null | undefined,
hintName: string | null | undefined,
channelCode: string,
channelName: string,
): number {
const code = String(channelCode || '').trim().toLowerCase()
const name = String(channelName || '').trim().toLowerCase()
const hc = String(hintCode || '').trim().toLowerCase()
const hn = String(hintName || '').trim().toLowerCase()
let score = 0
if (hc && code && (code === hc || code.includes(hc) || hc.includes(code))) score += 100
if (hc && name && name.includes(hc)) score += 60
if (hn && name && (name === hn || name.includes(hn) || hn.includes(name))) score += 40
if (hn && code && code.includes(hn)) score += 20
return score
}

View File

@ -0,0 +1,961 @@
/**
* 报价 JSON → 渠道买价树(重建重量段 + 按价格项填 details)
*/
import { toEnableStatus, isEnableStatusEnabled } from '@/utils/enableStatus'
import {
formatWeightIntervalLeftOpenRightClosed,
parseWeightIntervalBounds,
} from '@/utils/priceWeightInterval'
import type { ChannelQuoteExtracted, ChannelQuotePriceRow } from './channelQuoteAiSkill'
function normalizePriceStatus(status: unknown): number {
if (typeof status === 'boolean') return toEnableStatus(status)
if (isEnableStatusEnabled(status)) return toEnableStatus(true)
const n = Number(status)
if (Number.isFinite(n) && n > 0) return n
return toEnableStatus(true)
}
export type ChannelOptionForQuote = {
id: number
channelCode: string
channelName: string
label: string
}
export type ZoneMapEntry = {
zoneHint: string
/** OMS 价格分区因子值(通常是分区 id 字符串) */
zoneValue: string
zoneLabel: string
}
export type QuoteBindRow = {
key: string
sheetName: string
quote: ChannelQuoteExtracted
currency?: string | null
effectiveAt?: string | null
/** 绑定的 OMS 渠道 */
serviceChannelId?: number
/** zoneHint → zoneValue */
zoneMaps: ZoneMapEntry[]
/** 服务子类 → 货物类型因子值(可选) */
cargoValue?: string | null
enabled: boolean
warnings: string[]
}
export type CostItemKind = 'freight' | 'handling' | 'registration' | 'other'
export function classifyCostItem(costItem: string, priceName?: string): CostItemKind {
const c = String(costItem || '').toLowerCase()
const n = String(priceName || '')
if (c === 'freight' || n.includes('运费')) return 'freight'
if (c === 'handling' || n.includes('操作') || n.includes('处理')) return 'handling'
if (n.includes('挂号') || c.includes('regist') || c.includes('guahao')) return 'registration'
return 'other'
}
function isWeightFactor(factor: string): boolean {
const f = String(factor || '').trim()
return f === 'weight' || f === '重量'
}
function isZoneFactor(factor: string): boolean {
const f = String(factor || '').trim()
return f === 'zone' || f === '分区' || f === '价格分区'
}
function isCargoFactor(factor: string): boolean {
const f = String(factor || '').trim()
return f === 'cargo' || f === '货物类型' || f === '货型'
}
/** 因素列在 factorValuesJson 中的中文键 */
export function factorJsonKey(factor: string): string {
const f = String(factor || '').trim()
if (isWeightFactor(f)) return '重量'
if (isZoneFactor(f)) return '价格分区'
if (isCargoFactor(f)) return '货物类型'
if (f === 'warehouse' || f === '仓库') return '仓库'
if (f === 'remoteZone' || f === '偏远分区') return '偏远分区'
return f
}
/** 将报价行重量规范为有序区间列表 (start-end] */
export function buildWeightIntervalsFromQuoteRows(
rows: ChannelQuotePriceRow[],
): { intervals: string[]; ends: number[] } {
const ends = [
...new Set(
rows
.map((r) => Number(r.weightEnd))
.filter((n) => Number.isFinite(n) && n > 0),
),
].sort((a, b) => a - b)
const intervals = ends.map((end, idx) => {
// 优先使用同行声明的 start(按 end 匹配最近一行)
const withStart = rows.find(
(r) =>
Number(r.weightEnd) === end &&
r.weightStart != null &&
Number.isFinite(Number(r.weightStart)),
)
const start =
withStart != null
? Number(withStart.weightStart)
: idx > 0
? ends[idx - 1]!
: 0
return formatWeightIntervalLeftOpenRightClosed(start, end)
})
return { intervals, ends }
}
function parseFactorValuesJson(raw: unknown): Record<string, string> {
if (!raw) return {}
if (typeof raw === 'string') {
try {
const o = JSON.parse(raw)
return o && typeof o === 'object' ? (o as Record<string, string>) : {}
} catch {
return {}
}
}
if (typeof raw === 'object') return { ...(raw as Record<string, string>) }
return {}
}
export type ExistingPriceItem = {
id?: number | null
serialNumber?: number
status?: number | boolean
priceName?: string
costItem?: string
costUnit?: string
currency?: string
chargingCondition?: string | null
factors?: Array<{
id?: number
serialNumber?: number
factor?: string
factorValues?: string[]
}>
details?: Array<{
id?: number
factorValuesJson?: unknown
calculationFormula?: string
calculatedValue?: number | null
}>
}
export type ApplyPreviewLine = {
costItem: string
priceName: string
formula: string
zoneValue: string
zoneLabel: string
weightSegment: string
newValue: number
oldValue?: number | null
change: 'add' | 'update' | 'same'
}
export type ApplyPreviewResult = {
serviceChannelId: number
weightIntervals: string[]
lines: ApplyPreviewLine[]
warnings: string[]
/** 可直接交给 saveServiceChannelPriceAll 的 prices */
prices: Record<string, any>[]
unmappedRows: number
}
function findOldValue(
details: ExistingPriceItem['details'],
zoneKey: string,
zoneValue: string,
weightKey: string,
weightSegment: string,
): number | null {
if (!details?.length) return null
for (const d of details) {
const fj = parseFactorValuesJson(d.factorValuesJson)
const z = fj[zoneKey] ?? fj['价格分区'] ?? fj['分区'] ?? fj.zone
const w = fj[weightKey] ?? fj['重量'] ?? fj.weight
if (String(z) === String(zoneValue) && String(w) === String(weightSegment)) {
const n = Number(d.calculatedValue)
return Number.isFinite(n) ? n : null
}
}
return null
}
function resolveAmountForItem(
kind: CostItemKind,
mode: ChannelQuoteExtracted['mode'],
row: ChannelQuotePriceRow,
): { value: number | null; formula: string } {
if (kind === 'freight') {
if (mode === 'flat') {
const v = row.flatTotal
return { value: v != null && Number.isFinite(Number(v)) ? Number(v) : null, formula: 'total' }
}
const v = row.freightPerKg
return { value: v != null && Number.isFinite(Number(v)) ? Number(v) : null, formula: 'unit' }
}
if (kind === 'handling') {
const v = row.handlingPerShipment
return { value: v != null && Number.isFinite(Number(v)) ? Number(v) : null, formula: 'total' }
}
if (kind === 'registration') {
const v = row.registrationPerShipment
return { value: v != null && Number.isFinite(Number(v)) ? Number(v) : null, formula: 'total' }
}
return { value: null, formula: 'total' }
}
function zoneLabelOf(maps: ZoneMapEntry[], zoneValue: string): string {
return maps.find((m) => m.zoneValue === zoneValue)?.zoneLabel || zoneValue
}
/**
* 按绑定结果与现有价格项,生成回写预览与 save payload。
* - 重建重量因素值
* - 保留非重量/非分区因子原值的笛卡尔:仅 zone×weight(及可选 cargo)由报价驱动
* - 不自动新建价格项
*/
export function buildChannelPriceApplyPreview(input: {
serviceChannelId: number
bind: QuoteBindRow
existingPrices: ExistingPriceItem[]
}): ApplyPreviewResult {
const { serviceChannelId, bind, existingPrices } = input
const warnings: string[] = [...(bind.warnings || [])]
const quote = bind.quote
const { intervals: weightIntervals } = buildWeightIntervalsFromQuoteRows(quote.rows)
if (!weightIntervals.length) {
warnings.push('报价无有效重量段')
}
const zoneMaps = (bind.zoneMaps || []).filter((z) => z.zoneValue)
if (!zoneMaps.length) {
warnings.push('未配置分区映射,无法写入价格明细')
}
const hasHandlingInQuote = quote.rows.some(
(r) => r.handlingPerShipment != null && Number(r.handlingPerShipment) > 0,
)
const hasRegInQuote = quote.rows.some(
(r) => r.registrationPerShipment != null && Number(r.registrationPerShipment) > 0,
)
const pricesOut: Record<string, any>[] = []
const lines: ApplyPreviewLine[] = []
let unmappedRows = 0
// 统计报价行因无映射丢弃
for (const row of quote.rows) {
const hint = String(row.zoneHint || quote.destinationHints?.[0] || '').trim()
if (hint && !zoneMaps.some((z) => z.zoneHint === hint || !z.zoneHint)) {
const hit = zoneMaps.find(
(z) =>
z.zoneHint === hint ||
z.zoneLabel.includes(hint) ||
hint.includes(z.zoneLabel) ||
z.zoneHint.includes(hint),
)
if (!hit) unmappedRows += 1
}
}
const kindsPresent = new Set(
(existingPrices || []).map((p) => classifyCostItem(String(p.costItem), p.priceName)),
)
if (hasHandlingInQuote && !kindsPresent.has('handling')) {
warnings.push('报价含处理费/操作费,但渠道未配置操作费价格项,请先在渠道设计中增加')
}
if (hasRegInQuote && !kindsPresent.has('registration')) {
warnings.push('报价含挂号费,但渠道未配置对应价格项,请先在渠道设计中增加')
}
if (!kindsPresent.has('freight') && (existingPrices || []).length === 0) {
warnings.push('渠道尚无价格项,请先在服务渠道中设计运费等价格项与分区')
}
for (const price of existingPrices || []) {
const kind = classifyCostItem(String(price.costItem), price.priceName)
if (kind === 'other') {
// 非目标费用项原样保留
pricesOut.push(clonePriceKeepingDetails(price))
continue
}
const factors = (price.factors || []).map((f, idx) => ({
id: f.id,
serialNumber: f.serialNumber ?? idx + 1,
factor: String(f.factor || ''),
factorValues: [...(f.factorValues || [])],
}))
const weightFactor = factors.find((f) => isWeightFactor(f.factor))
const zoneFactor = factors.find((f) => isZoneFactor(f.factor))
const cargoFactor = factors.find((f) => isCargoFactor(f.factor))
if (!weightFactor) {
warnings.push(`价格项「${price.priceName || price.costItem}」无重量因素,已跳过改价`)
pricesOut.push(clonePriceKeepingDetails(price))
continue
}
if (!zoneFactor) {
warnings.push(`价格项「${price.priceName || price.costItem}」无价格分区因素,已跳过改价`)
pricesOut.push(clonePriceKeepingDetails(price))
continue
}
// 重建重量段
weightFactor.factorValues = [...weightIntervals]
// 分区:保留已映射到的 zoneValue(取并集,不自动新建未知分区)
const mappedZoneValues = [...new Set(zoneMaps.map((z) => z.zoneValue).filter(Boolean))]
if (mappedZoneValues.length) {
const keep = (zoneFactor.factorValues || []).filter((v) => mappedZoneValues.includes(String(v)))
zoneFactor.factorValues = keep.length ? keep : mappedZoneValues
}
if (cargoFactor && bind.cargoValue) {
if (!cargoFactor.factorValues.includes(bind.cargoValue)) {
cargoFactor.factorValues = [...cargoFactor.factorValues, bind.cargoValue]
}
}
const zoneKey = factorJsonKey(zoneFactor.factor)
const weightKey = factorJsonKey(weightFactor.factor)
const cargoKey = cargoFactor ? factorJsonKey(cargoFactor.factor) : null
const details: any[] = []
const oldDetails = price.details || []
// 笛卡尔:zone × weight(× cargo 若有绑定)
const zones = zoneFactor.factorValues.length ? zoneFactor.factorValues : mappedZoneValues
const cargos =
cargoFactor && bind.cargoValue
? [bind.cargoValue]
: cargoFactor?.factorValues?.length
? cargoFactor.factorValues
: [null]
for (const zoneValue of zones) {
const zoneHint =
zoneMaps.find((z) => z.zoneValue === zoneValue)?.zoneHint ||
zoneLabelOf(zoneMaps, zoneValue)
for (const weightSegment of weightIntervals) {
for (const cargo of cargos) {
const bounds = parseWeightIntervalBounds(weightSegment)
const quoteRows = quote.rows.filter((r) => {
const end = Number(r.weightEnd)
if (!bounds || !Number.isFinite(end)) return false
if (Math.abs(end - bounds.end) > 1e-9) return false
const rh = String(r.zoneHint || quote.destinationHints?.[0] || '').trim()
if (!rh) return true
// 行 zoneHint 需能映射到当前 zoneValue
const mapHit = zoneMaps.find(
(z) =>
z.zoneValue === zoneValue &&
(z.zoneHint === rh ||
z.zoneLabel.includes(rh) ||
rh.includes(z.zoneLabel) ||
z.zoneHint.includes(rh)),
)
return Boolean(mapHit) || (!zoneMaps.length && !rh)
})
// 若按 zoneHint 滤空,放宽:任意同重量行
const candidates =
quoteRows.length > 0
? quoteRows
: quote.rows.filter((r) => {
const end = Number(r.weightEnd)
return bounds && Number.isFinite(end) && Math.abs(end - bounds.end) < 1e-9
})
// 子类型:若报价带 serviceSubtype 且当前 cargo 不匹配则跳过金额(保留空?)——首期同一 cargo 绑定写全段
const picked = candidates[0]
if (!picked) continue
const { value, formula } = resolveAmountForItem(kind, quote.mode, picked)
if (value == null) continue
const factorValuesJson: Record<string, string> = {
[zoneKey]: String(zoneValue),
[weightKey]: weightSegment,
}
if (cargoKey && cargo != null) factorValuesJson[cargoKey] = String(cargo)
const oldValue = findOldValue(oldDetails, zoneKey, String(zoneValue), weightKey, weightSegment)
let change: ApplyPreviewLine['change'] = 'add'
if (oldValue != null) {
change = Math.abs(oldValue - value) < 1e-9 ? 'same' : 'update'
}
lines.push({
costItem: String(price.costItem || ''),
priceName: String(price.priceName || price.costItem || ''),
formula,
zoneValue: String(zoneValue),
zoneLabel: zoneLabelOf(zoneMaps, String(zoneValue)) || zoneHint,
weightSegment,
newValue: value,
oldValue,
change,
})
details.push({
factorValuesJson,
calculationFormula: formula,
calculatedValue: value,
})
}
}
}
// 其他因子(非 zone/weight/cargo)保留原 factorValues,但不参与本次笛卡尔——若存在则警告
const extraFactors = factors.filter(
(f) => !isWeightFactor(f.factor) && !isZoneFactor(f.factor) && !isCargoFactor(f.factor),
)
if (extraFactors.length) {
warnings.push(
`价格项「${price.priceName || price.costItem}」含额外因子(${extraFactors
.map((f) => f.factor)
.join(',')}),本次按分区×重量重写明细,请核对`,
)
}
pricesOut.push({
id: price.id ?? undefined,
serialNumber: price.serialNumber ?? 1,
status: normalizePriceStatus(price.status),
priceName: price.priceName || '',
costItem: price.costItem || '',
costUnit: price.costUnit || '',
currency: bind.currency || price.currency || 'CNY',
chargingCondition: price.chargingCondition || '',
factors: factors.map((f) => ({
id: f.id,
serialNumber: f.serialNumber,
factor: f.factor,
factorValues: f.factorValues,
})),
details,
})
}
if (unmappedRows > 0) {
warnings.push(`${unmappedRows} 条报价行分区提示未能映射,已跳过对应金额(见分区映射)`)
}
return {
serviceChannelId,
weightIntervals,
lines,
warnings: [...new Set(warnings)],
prices: pricesOut,
unmappedRows,
}
}
function clonePriceKeepingDetails(price: ExistingPriceItem): Record<string, any> {
return {
id: price.id ?? undefined,
serialNumber: price.serialNumber ?? 1,
status: normalizePriceStatus(price.status),
priceName: price.priceName || '',
costItem: price.costItem || '',
costUnit: price.costUnit || '',
currency: price.currency || 'CNY',
chargingCondition: price.chargingCondition || '',
factors: (price.factors || []).map((f, idx) => ({
id: f.id,
serialNumber: f.serialNumber ?? idx + 1,
factor: f.factor,
factorValues: [...(f.factorValues || [])],
})),
details: (price.details || []).map((d) => ({
id: d.id,
factorValuesJson: parseFactorValuesJson(d.factorValuesJson),
calculationFormula: d.calculationFormula || 'total',
calculatedValue: d.calculatedValue ?? 0,
})),
}
}
/** 自动建议分区映射:zoneHint → 已有分区选项 */
export function suggestZoneMaps(
hints: string[],
zoneOptions: Array<{ value: string; label: string }>,
): ZoneMapEntry[] {
const uniq = [...new Set(hints.map((h) => String(h || '').trim()).filter(Boolean))]
return uniq.map((hint) => {
const lower = hint.toLowerCase()
const hit =
zoneOptions.find((z) => z.label === hint || String(z.value) === hint) ||
zoneOptions.find(
(z) =>
z.label.toLowerCase().includes(lower) ||
lower.includes(z.label.toLowerCase()) ||
String(z.value).toLowerCase().includes(lower),
)
return {
zoneHint: hint,
zoneValue: hit ? String(hit.value) : '',
zoneLabel: hit ? hit.label : '',
}
})
}
export function collectZoneHints(quote: ChannelQuoteExtracted): string[] {
const hints: string[] = []
for (const d of quote.destinationHints || []) {
if (d) hints.push(String(d))
}
for (const r of quote.rows || []) {
if (r.zoneHint) hints.push(String(r.zoneHint))
}
return [...new Set(hints.map((h) => h.trim()).filter(Boolean))]
}
export type MergeMode = 'replaceMatched' | 'intersectionOnly' | 'abandon'
export type CompareDiffLine = {
costItem: string
priceName: string
kind: CostItemKind
formula: string
zoneHint: string
zoneValue: string
zoneLabel: string
weightSegment: string
oldValue?: number | null
newValue?: number | null
/** add=仅候选有 / remove=仅现网有 / update / same / unmapped=候选未映射分区 */
change: 'add' | 'remove' | 'update' | 'same' | 'unmapped'
deltaRatio?: number | null
}
export type CompareDiffResult = {
lines: CompareDiffLine[]
unmappedLines: CompareDiffLine[]
warnings: string[]
stats: {
addCount: number
removeCount: number
updateCount: number
sameCount: number
unmappedCount: number
avgDeltaRatio: number | null
candidateWeights: string[]
existingWeights: string[]
addedWeights: string[]
removedWeights: string[]
}
}
function mapZoneHint(
hint: string,
zoneMaps: ZoneMapEntry[],
): ZoneMapEntry | null {
const h = String(hint || '').trim()
if (!h) return zoneMaps.find((z) => z.zoneValue) || null
return (
zoneMaps.find(
(z) =>
z.zoneValue &&
(z.zoneHint === h ||
z.zoneLabel.includes(h) ||
h.includes(z.zoneLabel) ||
z.zoneHint.includes(h)),
) || null
)
}
function existingWeightsOf(prices: ExistingPriceItem[]): string[] {
const set = new Set<string>()
for (const p of prices) {
for (const f of p.factors || []) {
if (isWeightFactor(String(f.factor || ''))) {
;(f.factorValues || []).forEach((v) => set.add(String(v)))
}
}
}
return [...set]
}
function findExistingDetailValue(
price: ExistingPriceItem,
zoneValue: string,
weightSegment: string,
): { value: number | null; formula: string } {
const zoneFactor = (price.factors || []).find((f) => isZoneFactor(String(f.factor || '')))
const weightFactor = (price.factors || []).find((f) => isWeightFactor(String(f.factor || '')))
const zoneKey = zoneFactor ? factorJsonKey(String(zoneFactor.factor)) : '价格分区'
const weightKey = weightFactor ? factorJsonKey(String(weightFactor.factor)) : '重量'
for (const d of price.details || []) {
const fj = parseFactorValuesJson(d.factorValuesJson)
const z = fj[zoneKey] ?? fj['价格分区'] ?? fj['分区'] ?? fj.zone
const w = fj[weightKey] ?? fj['重量'] ?? fj.weight
if (String(z) === String(zoneValue) && String(w) === String(weightSegment)) {
const n = Number(d.calculatedValue)
return {
value: Number.isFinite(n) ? n : null,
formula: String(d.calculationFormula || 'total'),
}
}
}
return { value: null, formula: 'total' }
}
function weightsRoughEqual(a: string, b: string): boolean {
if (a === b) return true
const pa = parseWeightIntervalBounds(a)
const pb = parseWeightIntervalBounds(b)
if (!pa || !pb) return false
return Math.abs(pa.end - pb.end) < 1e-6 && Math.abs(pa.start - pb.start) < 1e-6
}
function findMatchingExistingWeight(candidateW: string, existing: string[]): string | null {
const hit = existing.find((w) => weightsRoughEqual(w, candidateW))
return hit || null
}
/**
* 候选买价 vs 现网买价对比(不写库)
* candidate 分区仍为 hint,经 zoneMaps 映射到 OMS zoneValue
*/
export function buildCompareDiff(input: {
candidate: {
weightIntervals: string[]
feeItems: Array<{
kind: CostItemKind
label: string
costItemCode: string
formula: string
cells: Array<{ zoneHint: string; weightSegment: string; value: number; formula: string }>
}>
currency?: string
}
existingPrices: ExistingPriceItem[]
zoneMaps: ZoneMapEntry[]
}): CompareDiffResult {
const { candidate, existingPrices, zoneMaps } = input
const warnings: string[] = []
const lines: CompareDiffLine[] = []
const unmappedLines: CompareDiffLine[] = []
const mappedZones = zoneMaps.filter((z) => z.zoneValue)
if (!mappedZones.length) warnings.push('请先完成分区映射后再对比')
const existingWeights = existingWeightsOf(existingPrices)
const candidateWeights = [...candidate.weightIntervals]
const addedWeights = candidateWeights.filter(
(w) => !existingWeights.some((e) => weightsRoughEqual(e, w)),
)
const removedWeights = existingWeights.filter(
(w) => !candidateWeights.some((c) => weightsRoughEqual(c, w)),
)
const kindsInExisting = new Map<CostItemKind, ExistingPriceItem>()
for (const p of existingPrices) {
const kind = classifyCostItem(String(p.costItem), p.priceName)
if (kind !== 'other' && !kindsInExisting.has(kind)) kindsInExisting.set(kind, p)
}
for (const fee of candidate.feeItems) {
if (!kindsInExisting.has(fee.kind)) {
warnings.push(`候选含「${fee.label}」,但渠道未配置对应价格项`)
}
}
// 候选格子 → 对比
for (const fee of candidate.feeItems) {
const existing = kindsInExisting.get(fee.kind)
for (const cell of fee.cells) {
const zm = mapZoneHint(cell.zoneHint, mappedZones)
if (!zm) {
unmappedLines.push({
costItem: fee.costItemCode,
priceName: fee.label,
kind: fee.kind,
formula: cell.formula,
zoneHint: cell.zoneHint,
zoneValue: '',
zoneLabel: '',
weightSegment: cell.weightSegment,
newValue: cell.value,
oldValue: null,
change: 'unmapped',
})
continue
}
const matchedW = existing
? findMatchingExistingWeight(cell.weightSegment, existingWeights) || cell.weightSegment
: cell.weightSegment
const old = existing
? findExistingDetailValue(existing, zm.zoneValue, matchedW)
: { value: null, formula: cell.formula }
let change: CompareDiffLine['change'] = 'add'
let deltaRatio: number | null = null
if (old.value != null) {
if (Math.abs(old.value - cell.value) < 1e-9) change = 'same'
else {
change = 'update'
if (old.value !== 0) deltaRatio = (cell.value - old.value) / Math.abs(old.value)
}
}
lines.push({
costItem: existing?.costItem || fee.costItemCode,
priceName: existing?.priceName || fee.label,
kind: fee.kind,
formula: cell.formula,
zoneHint: cell.zoneHint,
zoneValue: zm.zoneValue,
zoneLabel: zm.zoneLabel || zm.zoneValue,
weightSegment: cell.weightSegment,
oldValue: old.value,
newValue: cell.value,
change,
deltaRatio,
})
}
}
// 现网有、候选无的格子 → remove(仅对匹配到的费用项)
for (const [kind, price] of kindsInExisting) {
const fee = candidate.feeItems.find((f) => f.kind === kind)
if (!fee) continue
const zoneFactor = (price.factors || []).find((f) => isZoneFactor(String(f.factor || '')))
const weightFactor = (price.factors || []).find((f) => isWeightFactor(String(f.factor || '')))
if (!zoneFactor || !weightFactor) continue
const zoneKey = factorJsonKey(String(zoneFactor.factor))
const weightKey = factorJsonKey(String(weightFactor.factor))
for (const d of price.details || []) {
const fj = parseFactorValuesJson(d.factorValuesJson)
const z = String(fj[zoneKey] ?? fj['价格分区'] ?? fj['分区'] ?? fj.zone ?? '')
const w = String(fj[weightKey] ?? fj['重量'] ?? fj.weight ?? '')
if (!z || !w) continue
// 仅关注已映射分区
if (!mappedZones.some((m) => m.zoneValue === z)) continue
const stillInCandidate = fee.cells.some((c) => {
const zm = mapZoneHint(c.zoneHint, mappedZones)
return zm?.zoneValue === z && weightsRoughEqual(c.weightSegment, w)
})
if (stillInCandidate) continue
const n = Number(d.calculatedValue)
lines.push({
costItem: String(price.costItem || ''),
priceName: String(price.priceName || price.costItem || ''),
kind,
formula: String(d.calculationFormula || 'total'),
zoneHint: mappedZones.find((m) => m.zoneValue === z)?.zoneHint || '',
zoneValue: z,
zoneLabel: zoneLabelOf(mappedZones, z),
weightSegment: w,
oldValue: Number.isFinite(n) ? n : null,
newValue: null,
change: 'remove',
})
}
}
const updates = lines.filter((l) => l.change === 'update' && l.deltaRatio != null)
const avgDeltaRatio =
updates.length > 0
? updates.reduce((s, l) => s + (l.deltaRatio || 0), 0) / updates.length
: null
return {
lines,
unmappedLines,
warnings: [...new Set(warnings)],
stats: {
addCount: lines.filter((l) => l.change === 'add').length,
removeCount: lines.filter((l) => l.change === 'remove').length,
updateCount: lines.filter((l) => l.change === 'update').length,
sameCount: lines.filter((l) => l.change === 'same').length,
unmappedCount: unmappedLines.length,
avgDeltaRatio,
candidateWeights,
existingWeights,
addedWeights,
removedWeights,
},
}
}
/**
* 按融合模式生成 save payload
* - replaceMatched:匹配费用项按候选重建重量段+明细
* - intersectionOnly:保留现网重量/分区,只改两边都有的格子
*/
export function buildMergePayload(input: {
serviceChannelId: number
mergeMode: MergeMode
candidate: {
currency?: string
weightIntervals: string[]
feeItems: Array<{
kind: CostItemKind
label: string
costItemCode: string
formula: string
cells: Array<{ zoneHint: string; weightSegment: string; value: number; formula: string }>
}>
quote: ChannelQuoteExtracted
}
existingPrices: ExistingPriceItem[]
zoneMaps: ZoneMapEntry[]
cargoValue?: string | null
}): { prices: Record<string, any>[]; warnings: string[] } | null {
if (input.mergeMode === 'abandon') return null
const zoneMaps = (input.zoneMaps || []).filter((z) => z.zoneValue)
const warnings: string[] = []
if (!zoneMaps.length) {
warnings.push('无有效分区映射')
return { prices: [], warnings }
}
// 复用覆盖逻辑:构造 QuoteBindRow + buildChannelPriceApplyPreview
if (input.mergeMode === 'replaceMatched') {
const bind: QuoteBindRow = {
key: 'merge',
sheetName: '',
quote: input.candidate.quote,
currency: input.candidate.currency,
serviceChannelId: input.serviceChannelId,
zoneMaps,
cargoValue: input.cargoValue,
enabled: true,
warnings: [],
}
const preview = buildChannelPriceApplyPreview({
serviceChannelId: input.serviceChannelId,
bind,
existingPrices: input.existingPrices,
})
return { prices: preview.prices, warnings: [...preview.warnings, ...warnings] }
}
// intersectionOnly
const pricesOut: Record<string, any>[] = []
for (const price of input.existingPrices || []) {
const kind = classifyCostItem(String(price.costItem), price.priceName)
if (kind === 'other') {
pricesOut.push(clonePriceKeepingDetails(price))
continue
}
const fee = input.candidate.feeItems.find((f) => f.kind === kind)
if (!fee) {
pricesOut.push(clonePriceKeepingDetails(price))
continue
}
const factors = (price.factors || []).map((f, idx) => ({
id: f.id,
serialNumber: f.serialNumber ?? idx + 1,
factor: String(f.factor || ''),
factorValues: [...(f.factorValues || [])],
}))
const weightFactor = factors.find((f) => isWeightFactor(f.factor))
const zoneFactor = factors.find((f) => isZoneFactor(f.factor))
if (!weightFactor || !zoneFactor) {
pricesOut.push(clonePriceKeepingDetails(price))
continue
}
const zoneKey = factorJsonKey(zoneFactor.factor)
const weightKey = factorJsonKey(weightFactor.factor)
const details = (price.details || []).map((d) => {
const fj = parseFactorValuesJson(d.factorValuesJson)
const z = String(fj[zoneKey] ?? fj['价格分区'] ?? fj['分区'] ?? fj.zone ?? '')
const w = String(fj[weightKey] ?? fj['重量'] ?? fj.weight ?? '')
const hit = fee.cells.find((c) => {
const zm = mapZoneHint(c.zoneHint, zoneMaps)
return zm?.zoneValue === z && weightsRoughEqual(c.weightSegment, w)
})
if (!hit) {
return {
id: d.id,
factorValuesJson: fj,
calculationFormula: d.calculationFormula || 'total',
calculatedValue: d.calculatedValue ?? 0,
}
}
return {
id: d.id,
factorValuesJson: fj,
calculationFormula: hit.formula,
calculatedValue: hit.value,
}
})
pricesOut.push({
id: price.id ?? undefined,
serialNumber: price.serialNumber ?? 1,
status: normalizePriceStatus(price.status),
priceName: price.priceName || '',
costItem: price.costItem || '',
costUnit: price.costUnit || '',
currency: input.candidate.currency || price.currency || 'CNY',
chargingCondition: price.chargingCondition || '',
factors,
details,
})
}
return { prices: pricesOut, warnings }
}
export type MergedPriceMatrixRow = {
key: string
priceName: string
costItem: string
zoneValue: string
zoneLabel: string
weightSegment: string
formula: string
value: number
}
/** 将融合后的 prices 摊平为结果矩阵(融合后长什么样) */
export function flattenMergedPriceMatrix(
prices: Record<string, any>[],
zoneLabelByValue?: Record<string, string>,
): MergedPriceMatrixRow[] {
const rows: MergedPriceMatrixRow[] = []
;(prices || []).forEach((price, pi) => {
const priceName = String(price.priceName || '')
const costItem = String(price.costItem || '')
const factors = price.factors || []
const zoneFactor = factors.find((f: any) => isZoneFactor(String(f.factor || '')))
const weightFactor = factors.find((f: any) => isWeightFactor(String(f.factor || '')))
const zoneKey = zoneFactor ? factorJsonKey(String(zoneFactor.factor)) : '价格分区'
const weightKey = weightFactor ? factorJsonKey(String(weightFactor.factor)) : '重量'
for (const d of price.details || []) {
const fj = parseFactorValuesJson(d.factorValuesJson)
const zoneValue = String(fj[zoneKey] ?? fj['价格分区'] ?? fj['分区'] ?? fj.zone ?? '')
const weightSegment = String(fj[weightKey] ?? fj['重量'] ?? fj.weight ?? '')
if (!weightSegment) continue
const n = Number(d.calculatedValue)
rows.push({
key: `${pi}-${zoneValue}-${weightSegment}-${costItem}`,
priceName,
costItem,
zoneValue,
zoneLabel: zoneLabelByValue?.[zoneValue] || zoneValue || '—',
weightSegment,
formula: String(d.calculationFormula || 'total'),
value: Number.isFinite(n) ? n : 0,
})
}
})
return rows
}

View File

@ -0,0 +1,249 @@
/**
* 报价模型 → 候选买价(内存结构,未落库)
*/
import { parseWeightIntervalBounds } from '@/utils/priceWeightInterval'
import type { ChannelQuoteExtracted, ChannelQuoteMode } from './channelQuoteAiSkill'
import {
buildWeightIntervalsFromQuoteRows,
collectZoneHints,
type CostItemKind,
} from './channelQuoteApply'
export type QuoteModelCard = {
key: string
sheetName: string
currency?: string | null
effectiveAt?: string | null
quote: ChannelQuoteExtracted
selected: boolean
/** local=规则解析 ai=模型补齐 */
extractSource?: 'local' | 'ai'
/** 费用结构摘要 */
hasFreight: boolean
hasHandling: boolean
hasRegistration: boolean
weightEnds: number[]
zoneHints: string[]
rowCount: number
warnings: string[]
}
export type CandidateFeeCell = {
zoneHint: string
weightSegment: string
value: number
formula: 'total' | 'unit'
}
export type CandidateFeeItem = {
kind: CostItemKind
/** 展示名 */
label: string
/** 建议 costItem code */
costItemCode: string
formula: 'total' | 'unit'
cells: CandidateFeeCell[]
}
export type CandidateBuyPrice = {
key: string
sheetName: string
channelCodeHint?: string | null
channelNameHint?: string | null
serviceSubtype?: string | null
mode: ChannelQuoteMode
currency: string
effectiveAt?: string | null
weightIntervals: string[]
zoneHints: string[]
feeItems: CandidateFeeItem[]
/** 源报价(融合时还要用) */
quote: ChannelQuoteExtracted
warnings: string[]
}
export function buildQuoteModelCard(input: {
key: string
sheetName: string
quote: ChannelQuoteExtracted
currency?: string | null
effectiveAt?: string | null
warnings?: string[]
extractSource?: 'local' | 'ai'
}): QuoteModelCard {
const { quote } = input
const { ends } = buildWeightIntervalsFromQuoteRows(quote.rows || [])
const zoneHints = collectZoneHints(quote)
const hasFreight =
quote.mode === 'flat'
? quote.rows.some((r) => r.flatTotal != null && Number(r.flatTotal) > 0)
: quote.rows.some((r) => r.freightPerKg != null && Number(r.freightPerKg) > 0)
const hasHandling = quote.rows.some(
(r) => r.handlingPerShipment != null && Number(r.handlingPerShipment) > 0,
)
const hasRegistration = quote.rows.some(
(r) => r.registrationPerShipment != null && Number(r.registrationPerShipment) > 0,
)
return {
key: input.key,
sheetName: input.sheetName,
currency: input.currency,
effectiveAt: input.effectiveAt,
quote,
selected: true,
extractSource: input.extractSource,
hasFreight,
hasHandling,
hasRegistration,
weightEnds: ends,
zoneHints,
rowCount: quote.rows?.length || 0,
warnings: [...(input.warnings || [])],
}
}
function cellFor(
kind: CostItemKind,
mode: ChannelQuoteMode,
zoneHint: string,
weightSegment: string,
row: ChannelQuoteExtracted['rows'][number],
): CandidateFeeCell | null {
if (kind === 'freight') {
if (mode === 'flat') {
const v = row.flatTotal
if (v == null || !Number.isFinite(Number(v))) return null
return { zoneHint, weightSegment, value: Number(v), formula: 'total' }
}
const v = row.freightPerKg
if (v == null || !Number.isFinite(Number(v))) return null
return { zoneHint, weightSegment, value: Number(v), formula: 'unit' }
}
if (kind === 'handling') {
const v = row.handlingPerShipment
if (v == null || !Number.isFinite(Number(v))) return null
return { zoneHint, weightSegment, value: Number(v), formula: 'total' }
}
if (kind === 'registration') {
const v = row.registrationPerShipment
if (v == null || !Number.isFinite(Number(v))) return null
return { zoneHint, weightSegment, value: Number(v), formula: 'total' }
}
return null
}
/** QuoteModel → 候选买价(OMS 同形内存结构,分区仍为 hint) */
export function buildCandidateBuyPrice(card: QuoteModelCard): CandidateBuyPrice {
const quote = card.quote
const { intervals } = buildWeightIntervalsFromQuoteRows(quote.rows || [])
const zoneHints = collectZoneHints(quote)
const defaultZone = zoneHints[0] || '默认'
const warnings = [...card.warnings]
if (!intervals.length) warnings.push('无有效重量段')
if (!card.hasFreight && !card.hasHandling && !card.hasRegistration) {
warnings.push('未识别到运费/处理费/挂号费金额')
}
const feeItems: CandidateFeeItem[] = []
const pushKind = (kind: CostItemKind, label: string, code: string) => {
const cells: CandidateFeeCell[] = []
for (const weightSegment of intervals) {
const bounds = parseWeightIntervalBounds(weightSegment)
if (!bounds) continue
for (const row of quote.rows || []) {
const end = Number(row.weightEnd)
if (!Number.isFinite(end) || Math.abs(end - bounds.end) > 1e-6) continue
const zh = String(row.zoneHint || defaultZone).trim() || defaultZone
const cell = cellFor(kind, quote.mode, zh, weightSegment, row)
if (!cell) continue
// 同 zone+weight 去重保留首个
if (cells.some((c) => c.zoneHint === cell.zoneHint && c.weightSegment === cell.weightSegment)) {
continue
}
cells.push(cell)
}
}
if (!cells.length) return
const formula = cells[0]!.formula
feeItems.push({ kind, label, costItemCode: code, formula, cells })
}
if (card.hasFreight || quote.mode === 'flat') {
pushKind('freight', '运费', 'freight')
}
if (card.hasHandling) pushKind('handling', '操作费', 'handling')
if (card.hasRegistration) pushKind('registration', '挂号费', 'registration')
return {
key: card.key,
sheetName: card.sheetName,
channelCodeHint: quote.channelCodeHint,
channelNameHint: quote.channelNameHint,
serviceSubtype: quote.serviceSubtype,
mode: quote.mode,
currency: card.currency || 'CNY',
effectiveAt: card.effectiveAt,
weightIntervals: intervals,
zoneHints: zoneHints.length ? zoneHints : [defaultZone],
feeItems,
quote,
warnings: [...new Set(warnings)],
}
}
/** 长说明型子类(PAK 袋尺寸文案)压缩为短标签 */
export function shortServiceSubtype(raw?: string | null): string {
const s = String(raw || '').trim()
if (!s) return ''
if (/^PAK/i.test(s)) return 'PAK'
if (/^WPX/i.test(s)) return 'WPX'
const m = s.match(/^([A-Za-z0-9_-]{2,12})/)
if (m && s.length > 16) return m[1]!
return s.length > 16 ? `${s.slice(0, 14)}…` : s
}
export function candidateDisplayTitle(c: CandidateBuyPrice): string {
const name = c.channelCodeHint || c.channelNameHint || '未命名'
const sub = shortServiceSubtype(c.serviceSubtype)
return sub ? `${name} · ${sub}` : String(name)
}
export function candidateDisplayFullTitle(c: CandidateBuyPrice): string {
const name = c.channelCodeHint || c.channelNameHint || '未命名'
const sub = String(c.serviceSubtype || '').trim()
return sub ? `${name}(${sub})` : String(name)
}
/** 候选明细展平,供表格预览 */
export function flattenCandidateCells(c: CandidateBuyPrice): Array<{
feeLabel: string
kind: CostItemKind
zoneHint: string
weightSegment: string
formula: string
value: number
}> {
const rows: Array<{
feeLabel: string
kind: CostItemKind
zoneHint: string
weightSegment: string
formula: string
value: number
}> = []
for (const fee of c.feeItems) {
for (const cell of fee.cells) {
rows.push({
feeLabel: fee.label,
kind: fee.kind,
zoneHint: cell.zoneHint,
weightSegment: cell.weightSegment,
formula: cell.formula,
value: cell.value,
})
}
}
return rows
}

View File

@ -0,0 +1,562 @@
/**
* 渠道报价表本地规则解析(优先于 AI,毫秒级)
* 覆盖两种常见下游表:公斤+票费、一口价(含并排国家列 / PAK·WPX 分段)
*/
import {
guessChannelCodeFromSheetName,
isLikelyNonPriceSheetName,
type ChannelQuoteExtracted,
type ChannelQuoteRowRow,
type ChannelQuoteSheetExtract,
} from './channelQuoteAiSkill'
export type LocalParseConfidence = 'high' | 'medium' | 'low' | 'none'
export type LocalParseResult = ChannelQuoteSheetExtract & {
confidence: LocalParseConfidence
/** 解析策略标签,便于 UI / 排查 */
strategy?: string | null
}
type Cell = string | number | null | undefined
type Matrix = Cell[][]
function cellStr(c: Cell): string {
if (c == null) return ''
if (typeof c === 'number' && Number.isFinite(c)) return String(c)
return String(c).replace(/\r?\n/g, ' ').trim()
}
function cellNum(c: Cell): number | null {
if (c == null || c === '') return null
if (typeof c === 'number') return Number.isFinite(c) ? c : null
const s = String(c).trim().replace(/,/g, '').replace(/[¥¥元]/g, '')
if (!s || !/^[-+]?\d+(\.\d+)?$/.test(s)) return null
const n = Number(s)
return Number.isFinite(n) ? n : null
}
/** 表头归一:去空白、全角括号说明 */
function normHeader(c: Cell): string {
return cellStr(c)
.replace(/[((][^))]*[))]/g, '')
.replace(/[\s _/\\-]+/g, '')
.toLowerCase()
}
function parseWeightBounds(raw: Cell): { start: number | null; end: number } | null {
if (raw == null || raw === '') return null
if (typeof raw === 'number' && Number.isFinite(raw) && raw > 0) {
return { start: null, end: raw }
}
const s = cellStr(raw).replace(/,/g, '').replace(/kg/gi, '').trim()
if (!s) return null
const range = s.match(/^(\d+(?:\.\d+)?)\s*[-~~—–到至]\s*(\d+(?:\.\d+)?)$/)
if (range) {
const a = Number(range[1])
const b = Number(range[2])
if (!Number.isFinite(a) || !Number.isFinite(b) || b <= 0) return null
return { start: a, end: b }
}
const n = Number(s)
if (!Number.isFinite(n) || n <= 0) return null
return { start: null, end: n }
}
function isHeaderLike(h: string): boolean {
if (!h) return false
return (
/对接代码|渠道代码|渠道编码|产品代码|服务代码/.test(h) ||
/重量段|包裹重量|计费重量|重量kg|^重量$/.test(h) ||
/运费|处理费|操作费|挂号费|一口价|总价/.test(h) ||
/国家名称|^国家$|目的地|分区|zone/.test(h)
)
}
type ColRole =
| 'dock'
| 'weight'
| 'freightKg'
| 'handling'
| 'registration'
| 'country'
| 'flat'
| 'ignore'
function classifyHeader(h: string): ColRole {
if (!h) return 'ignore'
if (/对接代码|渠道代码|渠道编码|产品代码|服务代码/.test(h)) return 'dock'
if (/重量段|包裹重量|计费重量|重量kg|^重量$/.test(h)) return 'weight'
if (/挂号费/.test(h)) return 'registration'
if (/处理费|操作费/.test(h)) return 'handling'
if (/运费/.test(h) && (/kg|公斤|千克/.test(h) || /rmb\/?kg|元\/?kg/.test(h))) return 'freightKg'
if (/运费/.test(h) && !/票|件/.test(h)) return 'freightKg'
if (/一口价|总价|报价|单价|价格|金额/.test(h)) return 'flat'
if (/国家名称|^国家$|目的地|^分区$|zone|destination/.test(h)) return 'country'
if (/尺寸|时效|走货|备注|说明|属性|要求/.test(h)) return 'ignore'
return 'ignore'
}
/** 国家/分区名:短中文或常见英文区名,且不是表头关键字 */
function looksLikeZoneName(raw: string): boolean {
const s = cellStr(raw)
if (!s || s.length > 24) return false
if (isHeaderLike(normHeader(s))) return false
if (/^(pak|wpx|doc|信封|文件)$/i.test(s.trim())) return false
if (/条款|附加费|操作指南|目录|邮编/.test(s)) return false
// 纯数字不当 zone
if (/^[\d.\-]+$/.test(s)) return false
return /[\u4e00-\u9fffA-Za-z]/.test(s)
}
function scanMeta(matrix: Matrix): { currency: string; effectiveAt: string | null; warnings: string[] } {
const warnings: string[] = []
let currency = 'CNY'
let effectiveAt: string | null = null
const probe = matrix.slice(0, 20)
for (const row of probe) {
const line = (row || []).map(cellStr).join(' ')
if (/美元|USD/i.test(line)) currency = 'USD'
else if (/港币|HKD/i.test(line)) currency = 'HKD'
const m =
line.match(/生效\s*日[期间]?\s*[::]?\s*(\d{4}[-/.年]\d{1,2}[-/.月]\d{1,2})/) ||
line.match(/(\d{4}[-/.]\d{1,2}[-/.]\d{1,2})\s*起?\s*生效/)
if (m && !effectiveAt) {
effectiveAt = m[1]!.replace(/[年月日./]/g, '-').replace(/-+/g, '-').replace(/-$/, '')
}
}
return { currency, effectiveAt, warnings }
}
function isSubtypeTitleRow(row: Cell[]): string | null {
const cells = (row || []).map(cellStr).filter(Boolean)
if (!cells.length) return null
const joined = cells.join(' ')
if (cells.length <= 3 && /^(PAK|WPX|DOC)\b/i.test(cells[0]!) && cellNum(row[0]) == null) {
return cells[0]!
}
if (
cells.length <= 4 &&
/\b(PAK|WPX)\b/i.test(joined) &&
!cells.some((_, i) => cellNum(row[i]) != null && i > 0)
) {
return cells[0] || joined.slice(0, 40)
}
// 整行几乎无数字、像分段标题
const nums = (row || []).filter((c) => cellNum(c) != null).length
if (nums === 0 && cells.length <= 3 && /PAK|WPX|文件|包裹|信封/i.test(joined) && joined.length < 40) {
return cells[0] || joined
}
return null
}
function isJunkDataRow(row: Cell[]): boolean {
const joined = (row || []).map(cellStr).join(' ')
if (!joined.trim()) return true
if (joined.length > 120 && /条款|赔偿|截单|本公司|附加费及规定/.test(joined)) return true
return false
}
type RoleMap = { roles: ColRole[]; headers: string[]; zoneByCol: Map<number, string> }
function buildRoleMap(headerRow: Cell[]): RoleMap {
const headers = (headerRow || []).map(normHeader)
const roles: ColRole[] = headers.map(classifyHeader)
const zoneByCol = new Map<number, string>()
;(headerRow || []).forEach((c, i) => {
if (roles[i] !== 'ignore') return
const raw = cellStr(c)
if (looksLikeZoneName(raw)) {
roles[i] = 'flat'
zoneByCol.set(i, raw)
}
})
return { roles, headers, zoneByCol }
}
function findHeaderRow(matrix: Matrix): { index: number; map: RoleMap } | null {
const limit = Math.min(matrix.length, 40)
let best: { index: number; map: RoleMap; score: number } | null = null
for (let i = 0; i < limit; i++) {
const map = buildRoleMap(matrix[i] || [])
const hasWeight = map.roles.includes('weight')
const hasFee =
map.roles.includes('freightKg') ||
map.roles.includes('handling') ||
map.roles.includes('registration') ||
map.roles.includes('flat')
if (!hasWeight || !hasFee) continue
let score = 0
if (map.roles.includes('dock')) score += 3
if (map.roles.includes('freightKg')) score += 4
if (map.roles.includes('handling')) score += 3
if (map.roles.includes('flat') || map.zoneByCol.size) score += 3
if (map.roles.includes('country')) score += 2
score += map.roles.filter((r) => r === 'weight').length
if (!best || score > best.score) best = { index: i, map, score }
}
return best ? { index: best.index, map: best.map } : null
}
/** 公斤+票费:对接代码 + 重量段 + 运费/处理费 */
function parseUnitPlusFee(
matrix: Matrix,
sheetName: string,
headerIndex: number,
map: RoleMap,
meta: ReturnType<typeof scanMeta>,
): LocalParseResult | null {
const dockIdx = map.roles.indexOf('dock')
const weightIdx = map.roles.indexOf('weight')
const freightIdx = map.roles.indexOf('freightKg')
const handlingIdx = map.roles.indexOf('handling')
const regIdx = map.roles.indexOf('registration')
const countryIdx = map.roles.indexOf('country')
if (weightIdx < 0) return null
if (freightIdx < 0 && handlingIdx < 0 && regIdx < 0) return null
type Bucket = {
code: string
name: string | null
subtype: string | null
rows: ChannelQuoteRowRow[]
destinations: Set<string>
}
const buckets = new Map<string, Bucket>()
let currentCode =
guessChannelCodeFromSheetName(sheetName) ||
sheetName.replace(/\s+/g, '').slice(0, 32) ||
'UNKNOWN'
let currentSubtype: string | null = null
let currentName: string | null = null
const ensure = (code: string) => {
const key = `${code}::${currentSubtype || ''}`
if (!buckets.has(key)) {
buckets.set(key, {
code,
name: currentName,
subtype: currentSubtype,
rows: [],
destinations: new Set(),
})
}
return buckets.get(key)!
}
for (let r = headerIndex + 1; r < matrix.length; r++) {
const row = matrix[r] || []
if (isJunkDataRow(row)) continue
const subtype = isSubtypeTitleRow(row)
if (subtype) {
currentSubtype = subtype
continue
}
if (dockIdx >= 0) {
const dock = cellStr(row[dockIdx])
if (dock && !/^[\d.]+$/.test(dock) && dock.length <= 40) {
currentCode = dock
currentName = dock
}
}
const w = parseWeightBounds(row[weightIdx])
if (!w) continue
const freight = freightIdx >= 0 ? cellNum(row[freightIdx]) : null
const handling = handlingIdx >= 0 ? cellNum(row[handlingIdx]) : null
const registration = regIdx >= 0 ? cellNum(row[regIdx]) : null
if (freight == null && handling == null && registration == null) continue
const zone = countryIdx >= 0 ? cellStr(row[countryIdx]) || null : null
const b = ensure(currentCode)
if (zone) b.destinations.add(zone)
b.rows.push({
weightStart: w.start,
weightEnd: w.end,
zoneHint: zone,
freightPerKg: freight,
handlingPerShipment: handling,
registrationPerShipment: registration,
flatTotal: null,
})
}
const channelQuotes: ChannelQuoteExtracted[] = [...buckets.values()]
.filter((b) => b.rows.length > 0)
.map((b) => ({
channelCodeHint: b.code,
channelNameHint: b.name,
serviceSubtype: b.subtype,
mode: 'unit_plus_fee' as const,
destinationHints: [...b.destinations],
rows: b.rows,
}))
if (!channelQuotes.length) return null
const rowCount = channelQuotes.reduce((n, q) => n + q.rows.length, 0)
return {
sheetName,
isPriceSheet: true,
skipReason: null,
currency: meta.currency,
effectiveAt: meta.effectiveAt,
channelQuotes,
warnings: meta.warnings,
confidence: rowCount >= 3 ? 'high' : rowCount >= 1 ? 'medium' : 'none',
strategy: 'unit_plus_fee',
}
}
/**
* 一口价:重量列 + 国家价列;支持并排多组「包裹重量|国家」
* 例:包裹重量 | 美国 | … | 包裹重量 | 美国
*/
function parseFlatBlocks(
matrix: Matrix,
sheetName: string,
headerIndex: number,
headerRow: Cell[],
meta: ReturnType<typeof scanMeta>,
): LocalParseResult | null {
const headers = headerRow || []
type Block = { weightCol: number; priceCols: Array<{ col: number; zone: string }> }
const blocks: Block[] = []
let i = 0
while (i < headers.length) {
const h = normHeader(headers[i])
if (/重量段|包裹重量|计费重量|重量kg|^重量$/.test(h)) {
const priceCols: Array<{ col: number; zone: string }> = []
let j = i + 1
while (j < headers.length) {
const hj = normHeader(headers[j])
if (/重量段|包裹重量|计费重量|重量kg|^重量$/.test(hj)) break
const zoneRaw = cellStr(headers[j])
const role = classifyHeader(hj)
if (role === 'ignore' && looksLikeZoneName(zoneRaw)) {
priceCols.push({ col: j, zone: zoneRaw })
} else if (role === 'flat' || role === 'country') {
// 「一口价」列:zone 可能在上一格或 sheet 名
priceCols.push({
col: j,
zone: role === 'country' ? '' : zoneRaw || guessZoneFromSheet(sheetName) || '默认',
})
} else if (role !== 'ignore') {
break
}
j += 1
}
if (priceCols.length) blocks.push({ weightCol: i, priceCols })
i = j
continue
}
i += 1
}
if (!blocks.length) return null
const codeHint = guessChannelCodeFromSheetName(sheetName)
const nameHint = sheetName
let currentSubtype: string | null = null
const rowsBySubtype = new Map<string, ChannelQuoteRowRow[]>()
const dest = new Set<string>()
const pushRow = (row: ChannelQuoteRowRow) => {
const key = currentSubtype || ''
if (!rowsBySubtype.has(key)) rowsBySubtype.set(key, [])
rowsBySubtype.get(key)!.push(row)
if (row.zoneHint) dest.add(row.zoneHint)
}
for (let r = headerIndex + 1; r < matrix.length; r++) {
const row = matrix[r] || []
if (isJunkDataRow(row)) continue
const subtype = isSubtypeTitleRow(row)
if (subtype) {
currentSubtype = subtype
continue
}
let any = false
for (const block of blocks) {
const w = parseWeightBounds(row[block.weightCol])
if (!w) continue
for (const pc of block.priceCols) {
const price = cellNum(row[pc.col])
if (price == null) continue
any = true
const zone = pc.zone || null
pushRow({
weightStart: w.start,
weightEnd: w.end,
zoneHint: zone,
freightPerKg: null,
handlingPerShipment: null,
registrationPerShipment: null,
flatTotal: price,
})
}
}
// 若没有任何 block 命中,尝试「重量 + 国家列 + 一口价列」单表
if (!any && blocks.length === 1) {
/* already covered */
}
}
const channelQuotes: ChannelQuoteExtracted[] = [...rowsBySubtype.entries()]
.filter(([, rows]) => rows.length > 0)
.map(([subtype, rows]) => ({
channelCodeHint: codeHint,
channelNameHint: nameHint,
serviceSubtype: subtype || null,
mode: 'flat' as const,
destinationHints: [...new Set(rows.map((x) => x.zoneHint).filter(Boolean) as string[])],
rows,
}))
if (!channelQuotes.length) return null
const rowCount = channelQuotes.reduce((n, q) => n + q.rows.length, 0)
return {
sheetName,
isPriceSheet: true,
skipReason: null,
currency: meta.currency,
effectiveAt: meta.effectiveAt,
channelQuotes,
warnings: meta.warnings,
confidence: rowCount >= 3 ? 'high' : 'medium',
strategy: 'flat_blocks',
}
}
function guessZoneFromSheet(sheetName: string): string | null {
const m = String(sheetName).match(/(美国|英国|德国|法国|日本|澳洲|加拿大|欧盟|欧洲)/)
return m ? m[1]! : null
}
/** 重量列 + 国家列 + 价格列(纵表一口价) */
function parseFlatLong(
matrix: Matrix,
sheetName: string,
headerIndex: number,
map: RoleMap,
meta: ReturnType<typeof scanMeta>,
): LocalParseResult | null {
const weightIdx = map.roles.indexOf('weight')
const countryIdx = map.roles.indexOf('country')
const flatIdx = map.roles.findIndex((r, i) => r === 'flat' && !map.zoneByCol.has(i))
const zonePriceCols = [...map.zoneByCol.entries()]
if (weightIdx < 0) return null
if (countryIdx < 0 && flatIdx < 0 && !zonePriceCols.length) return null
// zone 作为列表头的情况交给 flat_blocks
if (zonePriceCols.length && countryIdx < 0) return null
const codeHint = guessChannelCodeFromSheetName(sheetName)
let currentSubtype: string | null = null
const rows: ChannelQuoteRowRow[] = []
for (let r = headerIndex + 1; r < matrix.length; r++) {
const row = matrix[r] || []
if (isJunkDataRow(row)) continue
const subtype = isSubtypeTitleRow(row)
if (subtype) {
currentSubtype = subtype
continue
}
const w = parseWeightBounds(row[weightIdx])
if (!w) continue
if (countryIdx >= 0 && flatIdx >= 0) {
const zone = cellStr(row[countryIdx]) || null
const price = cellNum(row[flatIdx])
if (price == null) continue
rows.push({
weightStart: w.start,
weightEnd: w.end,
zoneHint: zone,
freightPerKg: null,
handlingPerShipment: null,
registrationPerShipment: null,
flatTotal: price,
})
}
}
if (!rows.length) return null
return {
sheetName,
isPriceSheet: true,
skipReason: null,
currency: meta.currency,
effectiveAt: meta.effectiveAt,
channelQuotes: [
{
channelCodeHint: codeHint,
channelNameHint: sheetName,
serviceSubtype: currentSubtype,
mode: 'flat',
destinationHints: [...new Set(rows.map((x) => x.zoneHint).filter(Boolean) as string[])],
rows,
},
],
warnings: meta.warnings,
confidence: rows.length >= 3 ? 'high' : 'medium',
strategy: 'flat_long',
}
}
function emptySkip(sheetName: string, reason: string): LocalParseResult {
return {
sheetName,
isPriceSheet: false,
skipReason: reason,
channelQuotes: [],
warnings: [],
confidence: 'none',
strategy: null,
}
}
/**
* 本地解析单个 sheet 矩阵。
* confidence high/medium 视为可用;low/none 交给 AI 或标失败。
*/
export function parseSheetMatrixLocal(
sheetName: string,
matrix: Matrix,
): LocalParseResult {
const name = String(sheetName || '').trim() || 'sheet'
if (isLikelyNonPriceSheetName(name)) {
return emptySkip(name, 'sheet 名称疑似非报价(目录/附加费/邮编等)')
}
if (!matrix?.length) return emptySkip(name, '空表')
const meta = scanMeta(matrix)
const found = findHeaderRow(matrix)
if (!found) {
return emptySkip(name, '未识别到重量+费用表头')
}
const { index, map } = found
const headerRow = matrix[index] || []
// 优先公斤+票费(有运费KG 或 处理费,且不像纯一口价国家并列表)
const hasUnitFee =
map.roles.includes('freightKg') ||
map.roles.includes('handling') ||
map.roles.includes('registration')
if (hasUnitFee) {
const unit = parseUnitPlusFee(matrix, name, index, map, meta)
if (unit && unit.confidence !== 'none') return unit
}
const flatBlocks = parseFlatBlocks(matrix, name, index, headerRow, meta)
if (flatBlocks && flatBlocks.confidence !== 'none') return flatBlocks
const flatLong = parseFlatLong(matrix, name, index, map, meta)
if (flatLong && flatLong.confidence !== 'none') return flatLong
return emptySkip(name, '表头已找到但未能抽出有效报价行')
}
/** 是否值得交给 AI(本地失败或置信过低) */
export function needsAiFallback(result: LocalParseResult): boolean {
if (!result.isPriceSheet) return !isLikelyNonPriceSheetName(result.sheetName)
if (result.confidence === 'high' || result.confidence === 'medium') return false
return true
}

File diff suppressed because it is too large Load Diff

View File

@ -3,17 +3,24 @@
<div class="pw-header">
<div class="pw-header-main">
<h2 class="pw-title">定价工作台</h2>
<p class="pw-sub">
<SlidingTabs
class="pw-tabs"
:model-value="activeTab"
:items="tabItems"
aria-label="定价工作台"
@update:model-value="onTabChange"
/>
<p v-if="activeTab === 'sellPrice'" class="pw-sub">
<span class="flow-num">1</span>选渠道
<span class="flow-sep">→</span>
<span class="flow-num">2</span>定规则
<span class="flow-sep">→</span>
<span class="flow-num">3</span>预览合成
<span class="flow-sep">→</span>
<span class="flow-num">4</span>回写草稿(不自动发布)
<span class="flow-num">4</span>回写卖价草稿
</p>
</div>
<div class="pw-header-actions">
<div v-if="activeTab === 'sellPrice'" class="pw-header-actions">
<a-tooltip :content="previewDisabledReason || '按当前渠道与规则合成卖价预览'">
<span class="btn-tip-wrap">
<a-button
@ -42,7 +49,15 @@
</div>
</div>
<div class="pw-body" :class="{ 'ai-open': aiOpen && showAiEntry }">
<div v-if="activeTab === 'buyPrice'" class="pw-tab-panel pw-tab-panel--buy">
<ChannelQuoteImportPanel @applied="onChannelQuoteApplied" />
</div>
<div
v-show="activeTab === 'sellPrice'"
class="pw-body"
:class="{ 'ai-open': aiOpen && showAiEntry }"
>
<!-- 左:1 成本 + 2 规则 -->
<aside class="pw-left pw-card">
<div class="left-top">
@ -432,11 +447,20 @@ import {
import { getServiceChannelOptions } from '@/api/channel/serviceChannel'
import { getSalesProductList, getSalesProductPriceList } from '@/api/channel/salesProduct'
import { hasPermission } from '@/utils/rbac-permission'
import SlidingTabs from '@/components/SlidingTabs/index.vue'
import PricingWorkbenchAiPanel from './components/PricingWorkbenchAiPanel.vue'
import ChannelQuoteImportPanel from './components/ChannelQuoteImportPanel.vue'
import type { PricingWorkbenchAiRulePatch } from './pricingWorkbenchAiSkill'
const router = useRouter()
type WorkbenchTab = 'buyPrice' | 'sellPrice'
const activeTab = ref<WorkbenchTab>('buyPrice')
const tabItems = [
{ key: 'buyPrice', label: '更新买价' },
{ key: 'sellPrice', label: '合成卖价' },
]
const optionsLoading = ref(false)
const channelOptions = ref<{ id: number; label: string }[]>([])
const selectedChannelIds = ref<number[]>([])
@ -477,6 +501,12 @@ let aiDiffHintShown = false
const aiOpen = ref(false)
const aiMode = ref<'rules' | 'diff'>('rules')
function onTabChange(key: string) {
if (key !== 'buyPrice' && key !== 'sellPrice') return
activeTab.value = key
if (key !== 'sellPrice') aiOpen.value = false
}
const showAiEntry = computed(
() =>
hasPermission('Channel.PricingWorkbench') ||
@ -810,6 +840,17 @@ async function onChannelsChange() {
}
}
/** 更新买价成功后:勾选渠道、切到合成卖价 Tab */
async function onChannelQuoteApplied(channelIds: number[]) {
const ids = (channelIds || []).map(Number).filter((n) => n > 0)
if (!ids.length) return
const merged = [...new Set([...selectedChannelIds.value, ...ids])]
selectedChannelIds.value = merged
activeTab.value = 'sellPrice'
await onChannelsChange()
Message.info('已切换到「合成卖价」,并勾选更新后的渠道')
}
async function onProductChange() {
priceId.value = undefined
priceOptions.value = []
@ -1070,29 +1111,65 @@ onMounted(async () => {
}
.pw-header {
display: flex;
align-items: flex-start;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px 16px;
padding: 8px 16px;
flex-shrink: 0;
background: #fff;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
min-height: 48px;
box-sizing: border-box;
}
.pw-header-main {
min-width: 0;
flex: 1;
display: flex;
align-items: center;
gap: 12px;
flex-wrap: nowrap;
}
.pw-title {
margin: 0;
font-size: 18px;
font-size: 16px;
font-weight: 600;
color: var(--color-text-1);
flex-shrink: 0;
line-height: 1.2;
}
.pw-tabs {
margin-top: 0;
max-width: 320px;
flex-shrink: 0;
}
.pw-tab-panel {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
.pw-tab-panel--buy {
:deep(.cq-import) {
flex: 1;
min-height: 0;
max-height: none;
overflow: auto;
}
}
.pw-sub {
margin: 6px 0 0;
margin: 0;
font-size: 12px;
color: var(--color-text-3);
display: flex;
flex-wrap: wrap;
flex-wrap: nowrap;
align-items: center;
gap: 4px;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.flow-num {
display: inline-flex;