feat: 定价工作台报价模板解析与新建渠道草稿买价
All checks were successful
Build and Deploy Front / deploy (push) Successful in 3m58s

支持声明式报价模板(壹号/万国/3PE)、左列渠道识别、对比步预填新建渠道并写入草稿买价;按票挂号费并入操作费 handling。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
zzh 2026-11-25 16:16:49 +08:00
parent c4f7144f47
commit d7e991aece
14 changed files with 1890 additions and 94 deletions

View File

@ -73,9 +73,11 @@ description: >-
2. 列名别名:包裹重量/重量KG、重量段(KG)、运费(RMB/KG)、处理费/操作费(RMB/票)、挂号费、国家/国家名称/分区/对接代码
3. 一 sheet 多个「对接代码」或渠道码 → 拆成多个 `channelQuotes`
4. PAK/WPX 等分段标题写入 `serviceSubtype`,不要当成渠道码
5. sheet 名常含渠道码(如 `3SZ01-3PE Express--优先`),写入 `channelCodeHint` / `channelNameHint`
6. 金额必须来自单元格;说明行、空行忽略
7. 币种默认人民币 → `CNY`;生效日从「生效日期」类文案解析(可空)
5. sheet 名**不一定**是渠道:若「重量段」左侧有合并渠道名(如 `690普货BT(预上网)`),以左列为准拆多条;sheet 名仅作分组
6. sheet 名含渠道码(如 `3SZ01-3PE Express--优先`)或 sheet 名即渠道时,写入 `channelCodeHint` / `channelNameHint`
7. 金额必须来自单元格;说明行、空行忽略
8. 币种默认人民币 → `CNY`;生效日从「生效日期」类文案解析(可空)
9. 若工作台已选声明式模板,优先按模板;本 skill 仅补齐本地失败 sheet
## 原则

View File

@ -0,0 +1,84 @@
---
name: oms-channel-quote-template
description: >-
Generates a declarative OMS quote-parse template (QuoteParseTemplate JSON)
from sample vendor Excel sheet TSVs for pricing workbench. Use when adding a
报价模板, training parse rules from 样例报价表, or mapping 壹号/万国/3PE-like
layouts — not for extracting row amounts (use oms-channel-quote-extract).
---
# OMS 渠道报价解析模板生成
根据供应商报价 Excel 的**样例 sheet TSV**,产出一份可保存的声明式 `QuoteParseTemplate` JSON。
前端本地引擎解释该 JSON 做秒级识别;**禁止**返回可执行代码 / JS / 公式脚本。
运行时镜像:`src/views/channel/pricingWorkbench/channelQuoteTemplateAiSkill.ts`
场景键:`channelQuoteTemplate`
## 产出格式(必须)
只输出一个 JSON 对象(可用 \`\`\`json 包裹):
```json
{
"templateKey": "vendor-slug",
"name": "显示名",
"version": 1,
"matchHints": {
"fileNameIncludes": ["关键词"],
"skipSheetNameRe": "目录|附加费|邮编|操作指南"
},
"sheetPolicy": {
"channelSource": "leftOfWeight",
"channelHeaderAliases": ["对接代码", "渠道名称"],
"channelFillDown": true,
"countryFillDown": false
},
"columns": {
"weightAliases": ["重量段(KG)", "包裹重量"],
"freightPerKgAliases": ["运费(RMB/KG)"],
"handlingAliases": ["处理费(RMB/票)"],
"registrationAliases": ["挂号费"],
"countryAliases": ["国家"]
},
"pricing": {
"mode": "unit_plus_fee",
"flatLayout": null,
"subtypeRowRe": null
},
"currencyDefault": "CNY",
"notes": "一句话说明版式"
}
```
### channelSource
| 值 | 何时用 |
|----|--------|
| `leftOfWeight` | 真实渠道在「重量段」左侧列(常合并下填);**sheet 名只是分组**(如壹号「TK扫一枪 预上网渠道」) |
| `dockColumn` | 有「对接代码 / 渠道代码 / 渠道名称」表头列 |
| `sheetName` | **sheet 名即渠道**(如万国「万国快线-普货」、3PE「3SZ01-…」) |
### pricing.mode
| 值 | 含义 |
|----|------|
| `unit_plus_fee` | 运费 RMB/KG + 处理费/挂号费 RMB/票 |
| `flat` | 一口价;并排「包裹重量\|国家」用 `flatLayout=sideBySideBlocks`;纵表用 `long` |
| `auto` | 仅当版式混杂、无法判定时使用 |
## 硬规则
1. 只根据样例表头与样例行判断;**禁止编造**表中不存在的列名
2. sheet 名**不一定**是渠道——左侧出现「690普货BT(预上网)」这类标签且跨多行重量段 → 必须 `leftOfWeight` + `channelFillDown=true`
3. 国家列首行有值、后续空 → `countryFillDown=true`
4. 目录 / 附加费 / 邮编 / 操作指南 / 禁寄 → 写入 `skipSheetNameRe`
5. PAK / WPX 分段标题 → `subtypeRowRe`,不要当成渠道
6. `templateKey` 用英文短横线 slug;`name` 用中文供应商/产品名
7. 不要输出 `channelQuotes` 明细金额(那是 extract skill 的事)
## 常见版式速查
- **壹号小包**:左列渠道 + 重量段 + 运费/KG + 处理费/票
- **万国优联**:sheet=渠道;国家下填;挂号费 + 运费/KG
- **3PE**:sheet 含渠道码;并排一口价;PAK/WPX subtype

View File

@ -31,16 +31,18 @@
| 项 | 说明 |
|----|------|
| 入口 | 工作台 Tab「更新买价」 |
| 本地解析 | `channelQuoteLocalParse.ts`:表头识别公斤+票费 / 一口价(含并排国家列、PAK·WPX);上传后自动跑 |
| Skill / AI | `.cursor/skills/oms-channel-quote-extract`;`channelQuoteAiSkill.ts`;场景 `channelQuoteImport`;**仅补齐本地失败 sheet** |
| 报价模板 | 上传区选择声明式模板(内置:通用自动 / 壹号小包 / 万国优联 / 3PE);可「从当前文件生成」由 AI 产出规则并保存到 localStorage;支持导出/导入 JSON |
| 本地解析 | `parseSheetMatrixWithTemplate`(`channelQuoteLocalParse.ts`):按模板 `channelSource` + 列别名识别;通用自动仍多策略抢跑 |
| 模板 Skill | `.cursor/skills/oms-channel-quote-template`;`channelQuoteTemplateAiSkill.ts`;场景 `channelQuoteTemplate`;**只生成规则,不抽金额** |
| 提取 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 字) |
| Sheet | sheet 名不一定是渠道(壹号左列才是);万国/3PE 常用 sheet 名;目录/附加费/邮编等默认不勾选 |
| 识别性能 | 主路径本地模板引擎;AI 仅生成模板或补齐失败 sheet |
| 写库 | `POST /channel/service-channel/price/save`,默认草稿;可选发布 |
| 非目标 | 自动建分区/价格项、偏远邮编入库、AI 直接改卖价或替你确认融合 |
| 非目标 | 自动建分区/价格项、偏远邮编入库、AI 直接改卖价或替你确认融合、模板规则可执行脚本 |
## 与发布 / 审批衔接

View File

@ -0,0 +1,73 @@
import XLSX from 'xlsx'
import { parseSheetMatrixWithTemplate } from '../src/views/channel/pricingWorkbench/channelQuoteLocalParse'
import { BUILTIN_QUOTE_TEMPLATES } from '../src/views/channel/pricingWorkbench/channelQuoteTemplateSeeds'
const files = [
{
path: 'd:/wechatremake/xwechat_files/wxid_1ebse7qb7gde12_c306/msg/file/2026-11/壹号小包价格2026.11.07大VIP最低对外底价.xlsx',
templateKey: 'yihao-xiaobao',
sheet: 'TK扫一枪 预上网渠道',
expectModels: 3,
expectNames: ['690普货BT', '690特货ABT', '690纯电BT'],
},
{
path: 'd:/wechatremake/xwechat_files/wxid_1ebse7qb7gde12_c306/msg/file/2026-11/万国优联递球村报价表2026.11.10(1).xlsx',
templateKey: 'wanguo-youlian',
sheet: '万国快线-普货',
expectModels: 1,
expectNames: ['万国快线-普货'],
},
{
path: 'd:/wechatremake/xwechat_files/wxid_1ebse7qb7gde12_c306/msg/file/2026-11/3PE Express&ePost报价表2026-05-08(5).xlsx',
templateKey: '3pe-express',
sheet: '3SZ01-3PE Express--优先',
expectModelsMin: 1,
expectCode: '3SZ01',
},
] as const
let failed = 0
for (const case_ of files) {
const tpl = BUILTIN_QUOTE_TEMPLATES.find((t) => t.templateKey === case_.templateKey)
const wb = XLSX.readFile(case_.path, { cellDates: true })
const ws = wb.Sheets[case_.sheet]
const matrix = XLSX.utils.sheet_to_json(ws, { header: 1, defval: '', raw: false }) as any[][]
const parsed = parseSheetMatrixWithTemplate(case_.sheet, matrix, tpl)
const names = parsed.channelQuotes.map((q) => q.channelNameHint || q.channelCodeHint || '')
const okCount =
'expectModels' in case_ && case_.expectModels != null
? parsed.channelQuotes.length === case_.expectModels
: parsed.channelQuotes.length >= (('expectModelsMin' in case_ && case_.expectModelsMin) || 1)
const okNames =
'expectNames' in case_ && case_.expectNames
? case_.expectNames.every((n) => names.some((x) => String(x).includes(n)))
: true
const okCode =
'expectCode' in case_ && case_.expectCode
? parsed.channelQuotes.some(
(q) =>
String(q.channelCodeHint || '').includes(case_.expectCode) ||
String(q.channelNameHint || '').includes(case_.expectCode),
)
: true
const pass = parsed.isPriceSheet && okCount && okNames && okCode
console.log(
pass ? 'PASS' : 'FAIL',
case_.templateKey,
'|',
case_.sheet,
'| models=',
parsed.channelQuotes.length,
'|',
names.join(' ; '),
'|',
parsed.strategy,
parsed.skipReason || '',
)
if (!pass) {
failed += 1
console.log(JSON.stringify(parsed.channelQuotes.slice(0, 4), null, 2))
}
}
process.exit(failed ? 1 : 0)

View File

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

View File

@ -48,7 +48,8 @@ const SKILL_CORE = `你是 OMS「渠道报价表提取」助手:从单个 Exce
2. 非报价 sheet:isPriceSheet=false,channelQuotes=[],写清 skipReason
3. 一 sheet 多个对接代码/渠道码必须拆成多个 channelQuotes
4. PAK/WPX 等服务分段标题写入 serviceSubtype,不要当成渠道码
5. 金额必须来自单元格;说明行、空行、偏远邮编清单、条款长文一律忽略
5. sheet 名不一定是渠道:重量段左侧合并渠道名(如 690普货BT)须按左列拆多条
6. 金额必须来自单元格;说明行、空行、偏远邮编清单、条款长文一律忽略
## mode
- flat:一口价(包裹重量点/段 → 总价),填 flatTotal;freightPerKg/handling* 为 null
@ -389,11 +390,13 @@ export async function parseQuoteWorkbook(file: File | ArrayBuffer): Promise<Work
}) || []) as (string | number | null)[][]
const matrix = trimSparseMatrixColumns(rawMatrix)
const full = sheetMatrixToTsv(matrix)
// 空 sheet(无非空单元格)不进列表
if (!matrix.length || full.rowCount <= 0) continue
const slim = sheetMatrixToTsv(matrix, { slimForAi: true })
const likelyNonPrice = isLikelyNonPriceSheetName(name)
out.push({
name,
selected: !likelyNonPrice && full.rowCount > 0,
selected: !likelyNonPrice,
likelyNonPrice,
matrix,
tsv: full.text,

View File

@ -260,13 +260,14 @@ function resolveAmountForItem(
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' }
if (kind === 'handling' || kind === 'registration') {
// 按票费用统一按 handling 口径:操作费 + 挂号费合计写入操作费项
const h = row.handlingPerShipment
const r = row.registrationPerShipment
const hv = h != null && Number.isFinite(Number(h)) ? Number(h) : null
const rv = r != null && Number.isFinite(Number(r)) ? Number(r) : null
if (hv == null && rv == null) return { value: null, formula: 'total' }
return { value: (hv ?? 0) + (rv ?? 0), formula: 'total' }
}
return { value: null, formula: 'total' }
}
@ -332,8 +333,8 @@ export function buildChannelPriceApplyPreview(input: {
if (hasHandlingInQuote && !kindsPresent.has('handling')) {
warnings.push('报价含处理费/操作费,但渠道未配置操作费价格项,请先在渠道设计中增加')
}
if (hasRegInQuote && !kindsPresent.has('registration')) {
warnings.push('报价含挂号费,但渠道未配置对应价格项,请先在渠道设计中增加')
if (hasRegInQuote && !kindsPresent.has('handling') && !kindsPresent.has('registration')) {
warnings.push('报价含挂号费/操作费,但渠道未配置操作费价格项,请先在渠道设计中增加')
}
if (!kindsPresent.has('freight') && (existingPrices || []).length === 0) {
warnings.push('渠道尚无价格项,请先在服务渠道中设计运费等价格项与分区')
@ -969,6 +970,176 @@ export type MergedPriceMatrixRow = {
value: number
}
/**
* 新建渠道壳后:按已选 KPI 价格分区 + 候选费用项,组装可 save 的草稿买价树。
* 不依赖现网价格项;分区必须是已有 KPI 区(不新建分区)。
*/
export function buildDraftZoneMapsForCreate(input: {
zoneHints: string[]
selectedZones: Array<{ value: string; label: string }>
}): ZoneMapEntry[] {
const selected = (input.selectedZones || []).filter((z) => z.value)
if (!selected.length) return []
const hints = [...new Set((input.zoneHints || []).map((h) => String(h || '').trim()).filter(Boolean))]
const realHints = hints.filter((h) => h !== '默认')
if (selected.length === 1) {
const z = selected[0]!
const source = realHints.length ? realHints : hints.length ? hints : ['默认']
return source.map((h) => ({
zoneHint: h,
zoneValue: z.value,
zoneLabel: z.label || z.value,
}))
}
if (!realHints.length) {
// 无国家提示:同一套价复制到所选各分区
return selected.map((z) => ({
zoneHint: '默认',
zoneValue: z.value,
zoneLabel: z.label || z.value,
}))
}
const used = new Set<string>()
const maps: ZoneMapEntry[] = []
for (const h of realHints) {
const hit =
selected.find((z) => z.label === h || z.value === h) ||
selected.find((z) => z.label.includes(h) || h.includes(z.label)) ||
selected.find((z) => !used.has(z.value))
if (!hit) continue
used.add(hit.value)
maps.push({ zoneHint: h, zoneValue: hit.value, zoneLabel: hit.label || hit.value })
}
// 未匹配到的 hint 落到第一个已选区,避免丢价
const fallback = selected[0]!
for (const h of realHints) {
if (maps.some((m) => m.zoneHint === h)) continue
maps.push({
zoneHint: h,
zoneValue: fallback.value,
zoneLabel: fallback.label || fallback.value,
})
}
return maps
}
export function buildDraftPricesFromCandidate(input: {
currency?: string | null
weightIntervals: string[]
zoneHints: string[]
feeItems: Array<{
kind: CostItemKind
label: string
costItemCode: string
formula: string
cells: Array<{ zoneHint: string; weightSegment: string; value: number; formula: string }>
}>
zoneMaps: ZoneMapEntry[]
}): { prices: Record<string, any>[]; warnings: string[]; zoneMaps: ZoneMapEntry[] } {
const warnings: string[] = []
const zoneMaps = (input.zoneMaps || []).filter((z) => z.zoneValue)
if (!zoneMaps.length) {
warnings.push('未选择价格分区')
return { prices: [], warnings, zoneMaps }
}
const fees = (input.feeItems || []).filter((f) => f.kind !== 'other' && f.cells?.length)
if (!fees.length) {
warnings.push('候选无运费/操作费可写入')
return { prices: [], warnings, zoneMaps }
}
const zoneValues = [...new Set(zoneMaps.map((z) => z.zoneValue))]
const hasRealHints = (input.zoneHints || []).some((h) => h && h !== '默认')
const prices: Record<string, any>[] = []
let serial = 1
for (const fee of fees) {
const weightSet = new Set<string>()
const details: Array<{
factorValuesJson: Record<string, string>
calculationFormula: string
calculatedValue: number
}> = []
for (const cell of fee.cells) {
const hint = String(cell.zoneHint || '默认').trim() || '默认'
let targets = zoneMaps.filter(
(z) =>
z.zoneHint === hint ||
z.zoneLabel === hint ||
z.zoneLabel.includes(hint) ||
hint.includes(z.zoneLabel),
)
if (!targets.length && (!hasRealHints || hint === '默认')) {
targets = zoneMaps
}
if (!targets.length) {
warnings.push(`费用「${fee.label}」分区提示「${hint}」未映射,已跳过部分格子`)
continue
}
const zoneKey = factorJsonKey('zone')
const weightKey = factorJsonKey('weight')
for (const zm of targets) {
weightSet.add(cell.weightSegment)
details.push({
factorValuesJson: {
[zoneKey]: zm.zoneValue,
[weightKey]: cell.weightSegment,
},
calculationFormula: cell.formula || fee.formula || 'total',
calculatedValue: Number(cell.value) || 0,
})
}
}
// 去重:同分区×重量保留最后一格
const zoneKey = factorJsonKey('zone')
const weightKey = factorJsonKey('weight')
const dedup = new Map<string, (typeof details)[number]>()
for (const d of details) {
const k = `${d.factorValuesJson[zoneKey]}::${d.factorValuesJson[weightKey]}`
dedup.set(k, d)
}
const detailList = [...dedup.values()]
if (!detailList.length) continue
const weights =
(input.weightIntervals || []).length > 0
? [...input.weightIntervals]
: [...weightSet]
prices.push({
serialNumber: serial++,
status: normalizePriceStatus(true),
priceName: fee.label,
costItem: fee.costItemCode || fee.kind,
// 运费一般按千克;操作费(含原挂号费)按票
costUnit: fee.kind === 'freight' ? '千克' : '票',
currency: input.currency || 'CNY',
chargingCondition: '',
factors: [
{
serialNumber: 1,
factor: 'zone',
factorValues: zoneValues,
},
{
serialNumber: 2,
factor: 'weight',
factorValues: weights,
},
],
details: detailList,
})
}
if (!prices.length) warnings.push('未能生成任何草稿价格项')
return { prices, warnings: [...new Set(warnings)], zoneMaps }
}
/** 将融合后的 prices 摊平为结果矩阵(融合后长什么样) */
export function flattenMergedPriceMatrix(
prices: Record<string, any>[],

View File

@ -121,14 +121,17 @@ function cellFor(
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' }
// 按票:操作费 + 挂号费统一进 handling,不单独建 registration
const h = row.handlingPerShipment
const r = row.registrationPerShipment
const hv = h != null && Number.isFinite(Number(h)) ? Number(h) : null
const rv = r != null && Number.isFinite(Number(r)) ? Number(r) : null
if (hv == null && rv == null) return null
return { zoneHint, weightSegment, value: (hv ?? 0) + (rv ?? 0), 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' }
// 保留分支仅兼容旧调用;正式候选不再产出 registration 费用项
return cellFor('handling', mode, zoneHint, weightSegment, row)
}
return null
}
@ -143,7 +146,7 @@ export function buildCandidateBuyPrice(card: QuoteModelCard): CandidateBuyPrice
if (!intervals.length) warnings.push('无有效重量段')
if (!card.hasFreight && !card.hasHandling && !card.hasRegistration) {
warnings.push('未识别到运费/处理费/挂号费金额')
warnings.push('未识别到运费/操作费(含挂号费)金额')
}
const feeItems: CandidateFeeItem[] = []
@ -185,8 +188,10 @@ export function buildCandidateBuyPrice(card: QuoteModelCard): CandidateBuyPrice
if (card.hasFreight || quote.mode === 'flat') {
pushKind('freight', '运费', 'freight')
}
if (card.hasHandling) pushKind('handling', '操作费', 'handling')
if (card.hasRegistration) pushKind('registration', '挂号费', 'registration')
// 操作费、挂号费(按票)一律写入 handling,不新增 registration 价格项
if (card.hasHandling || card.hasRegistration) {
pushKind('handling', '操作费', 'handling')
}
return {
key: card.key,
@ -216,14 +221,30 @@ export function shortServiceSubtype(raw?: string | null): string {
return s.length > 16 ? `${s.slice(0, 14)}…` : s
}
/** 展示优先完整渠道名;避免 codeHint 只剩共用前缀(如三个都叫 690) */
export function preferChannelLabel(
codeHint?: string | null,
nameHint?: string | null,
): string {
const code = String(codeHint || '').trim()
const name = String(nameHint || '').trim()
if (name && code) {
if (name.includes(code) || name.length > code.length) return name
if (/[\u4e00-\u9fff]/.test(name)) return name
}
if (name) return name
if (code) return code
return '未命名'
}
export function candidateDisplayTitle(c: CandidateBuyPrice): string {
const name = c.channelCodeHint || c.channelNameHint || '未命名'
const name = preferChannelLabel(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 name = preferChannelLabel(c.channelCodeHint, c.channelNameHint)
const sub = String(c.serviceSubtype || '').trim()
return sub ? `${name}(${sub})` : String(name)
}

View File

@ -1,6 +1,6 @@
/**
* 渠道报价表本地规则解析(优先于 AI,毫秒级)
* 覆盖两种常见下游表:公斤+票费、一口价(含并排国家列 / PAK·WPX 分段)
* 支持声明式 QuoteParseTemplate;generic-auto 走多策略自动。
*/
import {
guessChannelCodeFromSheetName,
@ -9,6 +9,10 @@ import {
type ChannelQuoteRowRow,
type ChannelQuoteSheetExtract,
} from './channelQuoteAiSkill'
import {
GENERIC_AUTO_TEMPLATE_KEY,
type QuoteParseTemplate,
} from './channelQuoteTemplateTypes'
export type LocalParseConfidence = 'high' | 'medium' | 'low' | 'none'
@ -18,6 +22,74 @@ export type LocalParseResult = ChannelQuoteSheetExtract & {
strategy?: string | null
}
/** 模板解析上下文(别名匹配 + 渠道策略) */
type TemplateCtx = {
template: QuoteParseTemplate
/** 归一化后的别名集合 */
weightAliasSet: Set<string>
freightAliasSet: Set<string>
handlingAliasSet: Set<string>
registrationAliasSet: Set<string>
countryAliasSet: Set<string>
channelAliasSet: Set<string>
subtypeRe: RegExp | null
}
function normalizeAliasToken(s: string): string {
return String(s || '')
.replace(/[((][^))]*[))]/g, '')
.replace(/[\s _/\\-]+/g, '')
.toLowerCase()
}
function buildAliasSet(list: string[] | undefined): Set<string> {
return new Set((list || []).map(normalizeAliasToken).filter(Boolean))
}
function buildTemplateCtx(template: QuoteParseTemplate): TemplateCtx {
return {
template,
weightAliasSet: buildAliasSet(template.columns.weightAliases),
freightAliasSet: buildAliasSet(template.columns.freightPerKgAliases),
handlingAliasSet: buildAliasSet(template.columns.handlingAliases),
registrationAliasSet: buildAliasSet(template.columns.registrationAliases),
countryAliasSet: buildAliasSet(template.columns.countryAliases),
channelAliasSet: buildAliasSet(template.sheetPolicy.channelHeaderAliases),
subtypeRe: template.pricing.subtypeRowRe
? safeRegExp(template.pricing.subtypeRowRe, 'i')
: null,
}
}
function safeRegExp(source: string, flags?: string): RegExp | null {
try {
return new RegExp(source, flags)
} catch {
return null
}
}
function aliasHit(h: string, set: Set<string>): boolean {
if (!h || !set.size) return false
if (set.has(h)) return true
for (const a of set) {
if (a && (h.includes(a) || a.includes(h))) return true
}
return false
}
function looksLikeChannelLabel(raw: string): boolean {
const s = cellStr(raw).trim()
if (!s || s.length < 2 || s.length > 48) return false
if (parseWeightBounds(s)) return false
if (/^[\d.]+$/.test(s)) return false
if (isHeaderLike(normHeader(s))) return false
if (looksLikeSubZoneLabel(s)) return false
if (/条款|附加费|操作指南|目录|邮编|备注|返回目录|截单|生效/.test(s)) return false
if (/妥投|自然日|工作日|尺寸|要求|参考时效/.test(s)) return false
return /[\u4e00-\u9fff]/.test(s) || /[A-Za-z].*\d|\d.*[A-Za-z]/.test(s)
}
type Cell = string | number | null | undefined
type Matrix = Cell[][]
@ -144,7 +216,7 @@ function isSectionTitleCountry(raw: string): boolean {
function isHeaderLike(h: string): boolean {
if (!h) return false
return (
/对接代码|渠道代码|渠道编码|产品代码|服务代码/.test(h) ||
/对接代码|渠道代码|渠道编码|产品代码|服务代码|渠道名称|^渠道$|产品名称/.test(h) ||
isWeightHeader(h) ||
/运费|处理费|操作费|挂号费|一口价|总价/.test(h) ||
/国家名称|^国家$|目的地|分区|zone/.test(h)
@ -161,9 +233,25 @@ type ColRole =
| 'flat'
| 'ignore'
function classifyHeader(h: string): ColRole {
function classifyHeader(h: string, ctx?: TemplateCtx | null): ColRole {
if (!h) return 'ignore'
if (/对接代码|渠道代码|渠道编码|产品代码|服务代码/.test(h)) return 'dock'
if (ctx) {
if (aliasHit(h, ctx.channelAliasSet)) return 'dock'
if (aliasHit(h, ctx.weightAliasSet) || isWeightHeader(h)) return 'weight'
if (aliasHit(h, ctx.registrationAliasSet) || /挂号费/.test(h)) return 'registration'
if (aliasHit(h, ctx.handlingAliasSet) || /处理费|操作费/.test(h)) return 'handling'
if (
aliasHit(h, ctx.freightAliasSet) ||
(/运费/.test(h) && (/kg|公斤|千克/.test(h) || /rmb\/?kg|元\/?kg/.test(h))) ||
(/运费/.test(h) && !/票|件/.test(h))
) {
return 'freightKg'
}
if (aliasHit(h, ctx.countryAliasSet)) return 'country'
}
if (/对接代码|渠道代码|渠道编码|产品代码|服务代码|渠道名称|^渠道名?$|产品名称/.test(h)) {
return 'dock'
}
if (isWeightHeader(h)) return 'weight'
if (/挂号费/.test(h)) return 'registration'
if (/处理费|操作费/.test(h)) return 'handling'
@ -171,7 +259,7 @@ function classifyHeader(h: string): ColRole {
if (/运费/.test(h) && !/票|件/.test(h)) return 'freightKg'
if (/一口价|总价|报价|单价|价格|金额/.test(h)) return 'flat'
if (/国家名称|^国家$|目的地|^分区$|zone|destination/.test(h)) return 'country'
if (/尺寸|时效|走货|备注|说明|属性|要求/.test(h)) return 'ignore'
if (/尺寸|时效|走货|备注|说明|属性|要求|发货地址/.test(h)) return 'ignore'
return 'ignore'
}
@ -208,23 +296,24 @@ function scanMeta(matrix: Matrix): { currency: string; effectiveAt: string | nul
return { currency, effectiveAt, warnings }
}
function isSubtypeTitleRow(row: Cell[]): string | null {
function isSubtypeTitleRow(row: Cell[], subtypeRe?: RegExp | null): string | null {
const cells = (row || []).map(cellStr).filter(Boolean)
if (!cells.length) return null
const joined = cells.join(' ')
const re = subtypeRe || /PAK|WPX|文件|包裹|信封/i
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) &&
re.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) {
if (nums === 0 && cells.length <= 3 && re.test(joined) && joined.length < 40) {
return cells[0] || joined
}
return null
@ -239,9 +328,18 @@ function isJunkDataRow(row: Cell[]): boolean {
type RoleMap = { roles: ColRole[]; headers: string[]; zoneByCol: Map<number, string> }
function buildRoleMap(headerRow: Cell[]): RoleMap {
function buildRoleMap(headerRow: Cell[], ctx?: TemplateCtx | null): RoleMap {
const headers = (headerRow || []).map(normHeader)
const roles: ColRole[] = headers.map(classifyHeader)
const sideBySide = ctx?.template.pricing.flatLayout === 'sideBySideBlocks'
const roles: ColRole[] = headers.map((h, i) => {
const role = classifyHeader(h, ctx)
// 并排一口价:目的地列表头应作为价列,不能占成 country
if (sideBySide && role === 'country') {
const raw = cellStr(headerRow[i])
if (looksLikeZoneName(raw)) return 'ignore'
}
return role
})
const zoneByCol = new Map<number, string>()
;(headerRow || []).forEach((c, i) => {
if (roles[i] !== 'ignore') return
@ -254,11 +352,14 @@ function buildRoleMap(headerRow: Cell[]): RoleMap {
return { roles, headers, zoneByCol }
}
function findHeaderRow(matrix: Matrix): { index: number; map: RoleMap } | null {
function findHeaderRow(
matrix: Matrix,
ctx?: TemplateCtx | null,
): { 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 map = buildRoleMap(matrix[i] || [], ctx)
const hasWeight = map.roles.includes('weight')
const hasFee =
map.roles.includes('freightKg') ||
@ -270,6 +371,7 @@ function findHeaderRow(matrix: Matrix): { index: number; map: RoleMap } | null {
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('registration')) score += 3
if (map.roles.includes('flat') || map.zoneByCol.size) score += 3
if (map.roles.includes('country')) score += 2
const weightCols = map.roles.filter((r) => r === 'weight').length
@ -281,15 +383,61 @@ function findHeaderRow(matrix: Matrix): { index: number; map: RoleMap } | null {
return best ? { index: best.index, map: best.map } : null
}
/** 公斤+票费:对接代码 + 重量段 + 运费/处理费(支持国家列向下填充 + 澳大利亚一区) */
/**
* 重量段左侧渠道名列(表头可空;合并格仅首行有值)
*/
function findLeftChannelColumn(
matrix: Matrix,
headerIndex: number,
map: RoleMap,
weightIdx: number,
): number {
if (weightIdx <= 0) return -1
const probeEnd = Math.min(matrix.length, headerIndex + 120)
let best = -1
let bestScore = 0
for (let c = 0; c < weightIdx; c++) {
const role = map.roles[c] || 'ignore'
if (role === 'weight' || role === 'freightKg' || role === 'handling' || role === 'registration') {
continue
}
const h = map.headers[c] || ''
if (h && /运费|挂号|处理|操作|重量|时效|备注|说明|发货地址/.test(h)) continue
const labels = new Set<string>()
let labelHits = 0
let weightRows = 0
for (let r = headerIndex + 1; r < probeEnd; r++) {
if (!parseWeightBounds(matrix[r]?.[weightIdx])) continue
weightRows += 1
const raw = cellStr(matrix[r]?.[c])
if (raw && looksLikeChannelLabel(raw)) {
labels.add(raw)
labelHits += 1
}
}
if (!labels.size) continue
let score = labels.size * 5 + labelHits
if (c === weightIdx - 1) score += 4
if (role === 'dock' || /渠道|对接|产品|服务|名称/.test(h)) score += 6
if (!h) score += 2
if (labels.size >= 2 && weightRows >= labels.size * 2) score += 4
if (score > bestScore) {
bestScore = score
best = c
}
}
return bestScore >= 6 ? best : weightIdx > 0 ? weightIdx - 1 : -1
}
/** 公斤+票费:对接代码/左列渠道/sheet 名 + 重量段 + 运费/处理费/挂号费 */
function parseUnitPlusFee(
matrix: Matrix,
sheetName: string,
headerIndex: number,
map: RoleMap,
meta: ReturnType<typeof scanMeta>,
ctx?: TemplateCtx | null,
): 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')
@ -298,7 +446,42 @@ function parseUnitPlusFee(
if (weightIdx < 0) return null
if (freightIdx < 0 && handlingIdx < 0 && regIdx < 0) return null
const channelSource = ctx?.template.sheetPolicy.channelSource
const channelFillDown = ctx?.template.sheetPolicy.channelFillDown ?? true
const countryFillDown = ctx?.template.sheetPolicy.countryFillDown ?? true
let channelColIdx = map.roles.indexOf('dock')
if (channelSource === 'leftOfWeight') {
channelColIdx = findLeftChannelColumn(matrix, headerIndex, map, weightIdx)
} else if (channelSource === 'dockColumn') {
if (channelColIdx < 0) {
channelColIdx = findLeftChannelColumn(matrix, headerIndex, map, weightIdx)
}
} else if (channelSource === 'sheetName') {
channelColIdx = -1
} else if (channelColIdx < 0) {
// generic:若左列像渠道名则启用
const left = findLeftChannelColumn(matrix, headerIndex, map, weightIdx)
if (left >= 0) {
let distinct = 0
const seen = new Set<string>()
for (let r = headerIndex + 1; r < Math.min(matrix.length, headerIndex + 80); r++) {
if (!parseWeightBounds(matrix[r]?.[weightIdx])) continue
const lab = cellStr(matrix[r]?.[left])
if (lab && looksLikeChannelLabel(lab) && !seen.has(lab)) {
seen.add(lab)
distinct += 1
}
}
if (distinct >= 2 || (distinct >= 1 && !guessChannelCodeFromSheetName(sheetName))) {
channelColIdx = left
}
}
}
const subZoneIdx = findSubZoneColumn(matrix, headerIndex, map, countryIdx, weightIdx)
const sheetCode = guessChannelCodeFromSheetName(sheetName)
const sheetAsName = sheetName.replace(/\s+/g, ' ').trim()
type Bucket = {
code: string
@ -308,21 +491,23 @@ function parseUnitPlusFee(
destinations: Set<string>
}
const buckets = new Map<string, Bucket>()
let currentCode =
guessChannelCodeFromSheetName(sheetName) ||
sheetName.replace(/\s+/g, '').slice(0, 32) ||
'UNKNOWN'
let currentCode = sheetCode || sheetAsName.slice(0, 48) || 'UNKNOWN'
let currentSubtype: string | null = null
let currentName: string | null = null
let currentName: string | null = channelSource === 'sheetName' ? sheetAsName : null
let currentCountry = ''
let currentSubZone = ''
const ensure = (code: string) => {
const key = `${code}::${currentSubtype || ''}`
if (channelSource === 'sheetName') {
currentCode = sheetCode || sheetAsName
currentName = sheetAsName
}
const ensure = (code: string, name: string | null) => {
const key = `${code}::${name || ''}::${currentSubtype || ''}`
if (!buckets.has(key)) {
buckets.set(key, {
code,
name: currentName,
name,
subtype: currentSubtype,
rows: [],
destinations: new Set(),
@ -334,17 +519,24 @@ function parseUnitPlusFee(
for (let r = headerIndex + 1; r < matrix.length; r++) {
const row = matrix[r] || []
if (isJunkDataRow(row)) continue
const subtype = isSubtypeTitleRow(row)
const subtype = isSubtypeTitleRow(row, ctx?.subtypeRe)
if (subtype) {
currentSubtype = subtype
continue
}
if (dockIdx >= 0) {
const dock = cellStr(row[dockIdx])
if (dock && !/^[\d.]+$/.test(dock) && dock.length <= 40) {
if (channelColIdx >= 0) {
const dock = cellStr(row[channelColIdx])
if (dock && looksLikeChannelLabel(dock)) {
currentCode = dock
currentName = dock
} else if (dock && !/^[\d.]+$/.test(dock) && dock.length <= 48 && !parseWeightBounds(dock)) {
currentCode = dock
currentName = dock
} else if (!channelFillDown && dock) {
// 无下填时不沿用空合并格
}
// channelFillDown:空单元格沿用 current*
}
if (countryIdx >= 0) {
@ -355,9 +547,11 @@ function parseUnitPlusFee(
currentCountry = rawCountry
currentSubZone = ''
} else if (!currentCountry) {
// 极少见:国家列直接写「一区」
currentSubZone = rawCountry
}
} else if (!countryFillDown) {
currentCountry = ''
currentSubZone = ''
}
}
if (subZoneIdx >= 0) {
@ -380,7 +574,16 @@ function parseUnitPlusFee(
: null
if (!zone && countryIdx >= 0) continue
const b = ensure(currentCode)
const codeHint =
channelSource === 'sheetName'
? sheetCode || sheetAsName
: currentCode
const nameHint =
channelSource === 'sheetName'
? sheetAsName
: currentName || currentCode
const b = ensure(codeHint, nameHint)
if (zone) b.destinations.add(zone)
b.rows.push({
weightStart: w.start,
@ -395,14 +598,32 @@ function parseUnitPlusFee(
const channelQuotes: ChannelQuoteExtracted[] = [...buckets.values()]
.filter((b) => b.rows.length > 0)
.map((b) => ({
channelCodeHint: b.code,
channelNameHint: b.name,
.map((b) => {
const label = (b.name || b.code || '').trim()
// 左列/对接列常为完整产品名(含中文);勿再拆成共用数字前缀「690」
const hasHan = /[\u4e00-\u9fff]/.test(label)
let codeHint: string | null = null
if (channelSource === 'sheetName') {
codeHint = guessChannelCodeFromSheetName(label) || (hasHan ? null : label)
} else if (!hasHan) {
codeHint = label || null
} else {
// 仅当能抽出「字母+数字」型码(如 3SZ01)才作 codeHint,避免 690 撞名
const guessed = guessChannelCodeFromSheetName(label)
codeHint =
guessed && /[A-Za-z]/.test(guessed) && /\d/.test(guessed) && guessed.length >= 4
? guessed
: null
}
return {
channelCodeHint: codeHint,
channelNameHint: label || null,
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)
@ -410,12 +631,12 @@ function parseUnitPlusFee(
sheetName,
isPriceSheet: true,
skipReason: null,
currency: meta.currency,
currency: meta.currency || ctx?.template.currencyDefault || 'CNY',
effectiveAt: meta.effectiveAt,
channelQuotes,
warnings: meta.warnings,
confidence: rowCount >= 3 ? 'high' : rowCount >= 1 ? 'medium' : 'none',
strategy: 'unit_plus_fee',
strategy: channelSource ? `unit_plus_fee:${channelSource}` : 'unit_plus_fee',
}
}
@ -429,6 +650,7 @@ function parseFlatBlocks(
headerIndex: number,
headerRow: Cell[],
meta: ReturnType<typeof scanMeta>,
ctx?: TemplateCtx | null,
): LocalParseResult | null {
const headers = headerRow || []
type Block = { weightCol: number; priceCols: Array<{ col: number; zone: string }> }
@ -474,6 +696,7 @@ function parseFlatBlocks(
if (!blocks.length) return null
const channelSource = ctx?.template.sheetPolicy.channelSource || 'sheetName'
const codeHint = guessChannelCodeFromSheetName(sheetName)
const nameHint = sheetName
let currentSubtype: string | null = null
@ -490,7 +713,7 @@ function parseFlatBlocks(
for (let r = headerIndex + 1; r < matrix.length; r++) {
const row = matrix[r] || []
if (isJunkDataRow(row)) continue
const subtype = isSubtypeTitleRow(row)
const subtype = isSubtypeTitleRow(row, ctx?.subtypeRe)
if (subtype) {
currentSubtype = subtype
continue
@ -515,7 +738,6 @@ function parseFlatBlocks(
})
}
}
// 若没有任何 block 命中,尝试「重量 + 国家列 + 一口价列」单表
if (!any && blocks.length === 1) {
/* already covered */
}
@ -524,7 +746,7 @@ function parseFlatBlocks(
const channelQuotes: ChannelQuoteExtracted[] = [...rowsBySubtype.entries()]
.filter(([, rows]) => rows.length > 0)
.map(([subtype, rows]) => ({
channelCodeHint: codeHint,
channelCodeHint: channelSource === 'sheetName' ? codeHint : codeHint,
channelNameHint: nameHint,
serviceSubtype: subtype || null,
mode: 'flat' as const,
@ -538,7 +760,7 @@ function parseFlatBlocks(
sheetName,
isPriceSheet: true,
skipReason: null,
currency: meta.currency,
currency: meta.currency || ctx?.template.currencyDefault || 'CNY',
effectiveAt: meta.effectiveAt,
channelQuotes,
warnings: meta.warnings,
@ -559,6 +781,7 @@ function parseFlatLong(
headerIndex: number,
map: RoleMap,
meta: ReturnType<typeof scanMeta>,
ctx?: TemplateCtx | null,
): LocalParseResult | null {
const weightIdx = map.roles.indexOf('weight')
const countryIdx = map.roles.indexOf('country')
@ -569,6 +792,7 @@ function parseFlatLong(
// zone 作为列表头的情况交给 flat_blocks
if (zonePriceCols.length && countryIdx < 0) return null
const countryFillDown = ctx?.template.sheetPolicy.countryFillDown ?? true
const codeHint = guessChannelCodeFromSheetName(sheetName)
let currentSubtype: string | null = null
let currentCountry = ''
@ -577,7 +801,7 @@ function parseFlatLong(
for (let r = headerIndex + 1; r < matrix.length; r++) {
const row = matrix[r] || []
if (isJunkDataRow(row)) continue
const subtype = isSubtypeTitleRow(row)
const subtype = isSubtypeTitleRow(row, ctx?.subtypeRe)
if (subtype) {
currentSubtype = subtype
continue
@ -587,6 +811,8 @@ function parseFlatLong(
if (rawCountry) {
if (isSectionTitleCountry(rawCountry)) break
currentCountry = rawCountry
} else if (!countryFillDown) {
currentCountry = ''
}
}
const w = parseWeightBounds(row[weightIdx])
@ -613,7 +839,7 @@ function parseFlatLong(
sheetName,
isPriceSheet: true,
skipReason: null,
currency: meta.currency,
currency: meta.currency || ctx?.template.currencyDefault || 'CNY',
effectiveAt: meta.effectiveAt,
channelQuotes: [
{
@ -644,12 +870,13 @@ function emptySkip(sheetName: string, reason: string): LocalParseResult {
}
/**
* 本地解析单个 sheet 矩阵。
* 本地解析单个 sheet 矩阵(通用自动多策略)。
* confidence high/medium 视为可用;low/none 交给 AI 或标失败。
*/
export function parseSheetMatrixLocal(
sheetName: string,
matrix: Matrix,
ctx?: TemplateCtx | null,
): LocalParseResult {
const name = String(sheetName || '').trim() || 'sheet'
if (isLikelyNonPriceSheetName(name)) {
@ -658,33 +885,82 @@ export function parseSheetMatrixLocal(
if (!matrix?.length) return emptySkip(name, '空表')
const meta = scanMeta(matrix)
const found = findHeaderRow(matrix)
if (ctx?.template.currencyDefault && meta.currency === 'CNY') {
meta.currency = ctx.template.currencyDefault
}
const found = findHeaderRow(matrix, ctx)
if (!found) {
return emptySkip(name, '未识别到重量+费用表头')
}
const { index, map } = found
const headerRow = matrix[index] || []
const mode = ctx?.template.pricing.mode || 'auto'
const flatLayout = ctx?.template.pricing.flatLayout
// 优先公斤+票费(有运费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 (mode === 'unit_plus_fee' || (mode === 'auto' && hasUnitFee)) {
const unit = parseUnitPlusFee(matrix, name, index, map, meta, ctx)
if (unit && unit.confidence !== 'none') return unit
if (mode === 'unit_plus_fee') {
return emptySkip(name, '公斤+票费模板未能抽出有效报价行')
}
}
const flatBlocks = parseFlatBlocks(matrix, name, index, headerRow, meta)
if (mode === 'flat' || mode === 'auto') {
if (flatLayout !== 'long') {
const flatBlocks = parseFlatBlocks(matrix, name, index, headerRow, meta, ctx)
if (flatBlocks && flatBlocks.confidence !== 'none') return flatBlocks
const flatLong = parseFlatLong(matrix, name, index, map, meta)
}
if (flatLayout !== 'sideBySideBlocks') {
const flatLong = parseFlatLong(matrix, name, index, map, meta, ctx)
if (flatLong && flatLong.confidence !== 'none') return flatLong
}
if (mode === 'flat') {
return emptySkip(name, '一口价模板未能抽出有效报价行')
}
}
return emptySkip(name, '表头已找到但未能抽出有效报价行')
}
function shouldSkipByTemplate(sheetName: string, template: QuoteParseTemplate): boolean {
const reSrc = template.matchHints?.skipSheetNameRe
if (!reSrc) return isLikelyNonPriceSheetName(sheetName)
const re = safeRegExp(reSrc, 'i')
if (re) return re.test(sheetName)
return isLikelyNonPriceSheetName(sheetName)
}
/**
* 按声明式模板解析 sheet。generic-auto / mode=auto 走多策略;其它模板按 channelSource + mode 执行。
*/
export function parseSheetMatrixWithTemplate(
sheetName: string,
matrix: Matrix,
template: QuoteParseTemplate | null | undefined,
): LocalParseResult {
const name = String(sheetName || '').trim() || 'sheet'
if (!template || template.templateKey === GENERIC_AUTO_TEMPLATE_KEY) {
return parseSheetMatrixLocal(name, matrix)
}
if (shouldSkipByTemplate(name, template)) {
return emptySkip(name, '模板规则跳过该 sheet(目录/附加费/邮编等)')
}
if (!matrix?.length) return emptySkip(name, '空表')
const ctx = buildTemplateCtx(template)
const result = parseSheetMatrixLocal(name, matrix, ctx)
if (result.strategy && !String(result.strategy).includes(template.templateKey)) {
result.strategy = `${template.templateKey}:${result.strategy}`
}
return result
}
/** 是否值得交给 AI(本地失败或置信过低) */
export function needsAiFallback(result: LocalParseResult): boolean {
if (!result.isPriceSheet) return !isLikelyNonPriceSheetName(result.sheetName)

View File

@ -0,0 +1,184 @@
/**
* 定价工作台:从样例 sheet 生成 QuoteParseTemplate(与 .cursor/skills/oms-channel-quote-template 对齐)
*/
import {
isQuoteParseTemplate,
type QuoteChannelSource,
type QuoteFlatLayout,
type QuoteParseTemplate,
type QuotePricingMode,
} from './channelQuoteTemplateTypes'
import { makeTemplateKeyFromName } from './channelQuoteTemplateStore'
export const CHANNEL_QUOTE_TEMPLATE_AI_SCENE = 'channelQuoteTemplate'
export const CHANNEL_QUOTE_TEMPLATE_DEFAULT_SKILL_KEY = 'oms-channel-quote-template'
const SKILL_CORE = `你是 OMS「渠道报价解析模板」助手:根据样例 Excel sheet 的 TSV,产出一份声明式 QuoteParseTemplate JSON,供前端本地引擎秒级识别。
## 硬约束
1. 只输出一个 JSON 对象(可用 \`\`\`json 包裹);禁止可执行代码/JS/公式
2. 禁止编造样例中不存在的列名;金额明细不要输出(那是报价提取 skill)
3. sheet 名不一定是渠道:重量段左侧有合并渠道名(如 690普货BT)→ channelSource=leftOfWeight 且 channelFillDown=true
4. sheet 名即渠道(万国快线-普货 / 3SZ01-xxx)→ channelSource=sheetName
5. 有「对接代码」表头 → channelSource=dockColumn
6. 国家列下填 → countryFillDown=true;并排一口价 → mode=flat + flatLayout=sideBySideBlocks
7. 目录/附加费/邮编/操作指南写入 skipSheetNameRe;PAK/WPX 写入 subtypeRowRe
## JSON 字段
templateKey, name, version=1,
matchHints.fileNameIncludes[], matchHints.skipSheetNameRe,
sheetPolicy.channelSource(leftOfWeight|dockColumn|sheetName),
sheetPolicy.channelHeaderAliases[], channelFillDown, countryFillDown,
columns.weightAliases / freightPerKgAliases / handlingAliases / registrationAliases / countryAliases,
pricing.mode(unit_plus_fee|flat|auto), pricing.flatLayout(sideBySideBlocks|long|null),
pricing.subtypeRowRe, currencyDefault, notes
`
export function buildChannelQuoteTemplateSystemPrompt(): string {
return SKILL_CORE
}
export function buildChannelQuoteTemplateUserContent(input: {
templateName: string
fileName?: string
sheets: Array<{ sheetName: string; sheetText: string }>
}): string {
const lines = [
`请为供应商报价表生成一份 QuoteParseTemplate。`,
`建议显示名:${input.templateName}`,
]
if (input.fileName) lines.push(`文件名:${input.fileName}`)
lines.push(`样例 sheet 数:${input.sheets.length}`)
for (const s of input.sheets) {
lines.push('')
lines.push(`=== Sheet: ${s.sheetName} ===`)
lines.push(s.sheetText)
}
lines.push('')
lines.push('只输出 QuoteParseTemplate JSON。')
return lines.join('\n')
}
function asStringArray(v: unknown): string[] {
if (!Array.isArray(v)) return []
return v.map((x) => String(x || '').trim()).filter(Boolean)
}
function normalizeChannelSource(raw: unknown): QuoteChannelSource {
const s = String(raw || '')
.trim()
.toLowerCase()
if (s === 'leftofweight' || s.includes('left') || s.includes('左侧')) return 'leftOfWeight'
if (s === 'sheetname' || s.includes('sheet')) return 'sheetName'
return 'dockColumn'
}
function normalizeMode(raw: unknown): QuotePricingMode {
const s = String(raw || '')
.trim()
.toLowerCase()
if (s === 'flat' || s.includes('一口')) return 'flat'
if (s === 'auto') return 'auto'
return 'unit_plus_fee'
}
function normalizeFlatLayout(raw: unknown): QuoteFlatLayout | undefined {
const s = String(raw || '')
.trim()
.toLowerCase()
if (!s || s === 'null' || s === 'undefined') return undefined
if (s.includes('long') || s.includes('纵')) return 'long'
if (s.includes('side') || s.includes('并排') || s.includes('block')) return 'sideBySideBlocks'
return undefined
}
function extractJsonObject(text: string): unknown {
const raw = String(text || '').trim()
if (!raw) throw new Error('AI 返回为空')
const fenced = raw.match(/```(?:json)?\s*([\s\S]*?)```/i)
const body = (fenced?.[1] || raw).trim()
const start = body.indexOf('{')
const end = body.lastIndexOf('}')
if (start < 0 || end <= start) throw new Error('AI 返回中未找到 JSON 对象')
return JSON.parse(body.slice(start, end + 1))
}
/** 解析 AI 回复为 QuoteParseTemplate */
export function parseQuoteTemplateAiReply(
text: string,
fallbackName?: string,
): QuoteParseTemplate {
const obj = extractJsonObject(text) as Record<string, unknown>
const name =
String(obj.name || fallbackName || '自定义模板').trim() || '自定义模板'
const templateKey =
String(obj.templateKey || '').trim() || makeTemplateKeyFromName(name)
const sheetPolicyRaw = (obj.sheetPolicy || {}) as Record<string, unknown>
const columnsRaw = (obj.columns || {}) as Record<string, unknown>
const pricingRaw = (obj.pricing || {}) as Record<string, unknown>
const matchRaw = (obj.matchHints || {}) as Record<string, unknown>
const draft: QuoteParseTemplate = {
templateKey,
name,
version: 1,
builtin: false,
matchHints: {
fileNameIncludes: asStringArray(matchRaw.fileNameIncludes),
skipSheetNameRe:
matchRaw.skipSheetNameRe != null
? String(matchRaw.skipSheetNameRe)
: '目录|附加费|操作指南|偏远|邮编|增值服务|附录|说明|条款',
},
sheetPolicy: {
channelSource: normalizeChannelSource(sheetPolicyRaw.channelSource),
channelHeaderAliases: asStringArray(sheetPolicyRaw.channelHeaderAliases),
channelFillDown: sheetPolicyRaw.channelFillDown !== false,
countryFillDown: Boolean(sheetPolicyRaw.countryFillDown),
},
columns: {
weightAliases: asStringArray(columnsRaw.weightAliases).length
? asStringArray(columnsRaw.weightAliases)
: ['重量段', '包裹重量', '重量'],
freightPerKgAliases: asStringArray(columnsRaw.freightPerKgAliases),
handlingAliases: asStringArray(columnsRaw.handlingAliases),
registrationAliases: asStringArray(columnsRaw.registrationAliases),
countryAliases: asStringArray(columnsRaw.countryAliases),
},
pricing: {
mode: normalizeMode(pricingRaw.mode),
flatLayout: normalizeFlatLayout(pricingRaw.flatLayout),
subtypeRowRe:
pricingRaw.subtypeRowRe != null && String(pricingRaw.subtypeRowRe).trim()
? String(pricingRaw.subtypeRowRe).trim()
: undefined,
},
currencyDefault: String(obj.currencyDefault || 'CNY').trim() || 'CNY',
notes: obj.notes != null ? String(obj.notes) : undefined,
}
if (!isQuoteParseTemplate(draft)) {
throw new Error('AI 返回的模板结构无效')
}
return draft
}
/** 从 matrix 抽瘦身 TSV,供模板生成 */
export function matrixToTemplateSampleTsv(
matrix: (string | number | null | undefined)[][],
maxRows = 28,
maxCols = 10,
): string {
const rows = (matrix || []).slice(0, maxRows)
return rows
.map((row) =>
(row || [])
.slice(0, maxCols)
.map((c) => {
if (c == null) return ''
return String(c).replace(/\t/g, ' ').replace(/\r?\n/g, ' ').trim()
})
.join('\t'),
)
.join('\n')
}

View File

@ -0,0 +1,120 @@
/**
* 内置报价解析模板(对应壹号 / 万国 / 3PE 三类版式)
*/
import {
GENERIC_AUTO_TEMPLATE_KEY,
type QuoteParseTemplate,
} from './channelQuoteTemplateTypes'
export const BUILTIN_QUOTE_TEMPLATES: QuoteParseTemplate[] = [
{
templateKey: GENERIC_AUTO_TEMPLATE_KEY,
name: '通用自动',
version: 1,
builtin: true,
sheetPolicy: {
channelSource: 'dockColumn',
channelHeaderAliases: ['对接代码', '渠道代码', '渠道编码', '产品代码', '渠道名称'],
channelFillDown: true,
countryFillDown: true,
},
columns: {
weightAliases: ['重量段', '重量段(KG)', '包裹重量', '重量KG', '重量'],
freightPerKgAliases: ['运费', '运费(RMB/KG)', '运费(RMB/KG)'],
handlingAliases: ['处理费', '操作费', '处理费(RMB/票)'],
registrationAliases: ['挂号费', '挂号费(RMB/票)'],
countryAliases: ['国家', '国家名称', '目的地', '分区'],
},
pricing: { mode: 'auto' },
currencyDefault: 'CNY',
notes: '多策略自动:对接代码/左列渠道/sheet 名 + 公斤票费或一口价',
},
{
templateKey: 'yihao-xiaobao',
name: '壹号小包',
version: 1,
builtin: true,
matchHints: {
fileNameIncludes: ['壹号', '小包'],
skipSheetNameRe:
'目录|附加费|操作指南|偏远|邮编|增值服务|附录|说明|条款|禁寄|异形|导入模板|Tax|Sheet\\d*',
},
sheetPolicy: {
channelSource: 'leftOfWeight',
channelHeaderAliases: ['对接代码', '渠道名称', '渠道'],
channelFillDown: true,
countryFillDown: false,
},
columns: {
weightAliases: ['重量段', '重量段(KG)', '重量段(KG)'],
freightPerKgAliases: ['运费', '运费(RMB/KG)', '运费(RMB/KG)', '运费(RMB/KG)'],
handlingAliases: ['处理费', '处理费(RMB/票)', '处理费(RMB/票)', '操作费'],
registrationAliases: ['挂号费'],
countryAliases: ['国家', '国家名称'],
},
pricing: { mode: 'unit_plus_fee' },
currencyDefault: 'CNY',
notes:
'sheet 名多为分组(如 TK扫一枪 预上网渠道);真实渠道在重量段左侧合并列,需下填拆成多模型',
},
{
templateKey: 'wanguo-youlian',
name: '万国优联',
version: 1,
builtin: true,
matchHints: {
fileNameIncludes: ['万国', '优联', '递球'],
skipSheetNameRe: '目录|附加费|操作指南|偏远|邮编|增值|附录|说明|条款',
},
sheetPolicy: {
channelSource: 'sheetName',
channelFillDown: false,
countryFillDown: true,
},
columns: {
weightAliases: ['重量段', '重量段(kg)', '重量段(kg)', '重量段(KG)'],
freightPerKgAliases: ['运费', '运费(RMB/KG)', '运费(RMB/KG)'],
handlingAliases: ['处理费', '操作费'],
registrationAliases: ['挂号费', '挂号费(RMB/票)', '挂号费(RMB/票)'],
countryAliases: ['国家', '国家名称'],
},
pricing: { mode: 'unit_plus_fee' },
currencyDefault: 'CNY',
notes: '每个价格 sheet 名即渠道;国家列合并下填;挂号费+运费/KG',
},
{
templateKey: '3pe-express',
name: '3PE Express',
version: 1,
builtin: true,
matchHints: {
fileNameIncludes: ['3PE', '3pe', 'ePost'],
skipSheetNameRe:
'目录|附加费|操作指南|偏远|邮编|增值服务|附录|说明|条款|商业派送服务邮编',
},
sheetPolicy: {
channelSource: 'sheetName',
channelFillDown: false,
countryFillDown: false,
},
columns: {
weightAliases: ['包裹重量', '重量'],
freightPerKgAliases: [],
handlingAliases: [],
registrationAliases: [],
// 并排一口价时国家名是价列表头,勿写入 countryAliases(否则会被当成纵表国家列)
countryAliases: [],
},
pricing: {
mode: 'flat',
flatLayout: 'sideBySideBlocks',
subtypeRowRe: 'PAK|WPX|DOC|文件|信封',
},
currencyDefault: 'CNY',
notes: 'sheet 名含渠道码(如 3SZ01);并排包裹重量|国家一口价;PAK/WPX 为 serviceSubtype',
},
]
export function getBuiltinTemplate(key: string): QuoteParseTemplate | undefined {
return BUILTIN_QUOTE_TEMPLATES.find((t) => t.templateKey === key)
}

View File

@ -0,0 +1,152 @@
/**
* 报价解析模板存储:内置种子 + localStorage 用户模板
*/
import { BUILTIN_QUOTE_TEMPLATES } from './channelQuoteTemplateSeeds'
import {
GENERIC_AUTO_TEMPLATE_KEY,
isQuoteParseTemplate,
type QuoteParseTemplate,
} from './channelQuoteTemplateTypes'
const STORAGE_KEY = 'oms.pricingWorkbench.quoteParseTemplates.v1'
const SELECTED_KEY = 'oms.pricingWorkbench.quoteParseTemplateKey'
type StoredBlob = {
templates: QuoteParseTemplate[]
}
function readUserTemplates(): QuoteParseTemplate[] {
try {
const raw = localStorage.getItem(STORAGE_KEY)
if (!raw) return []
const parsed = JSON.parse(raw) as StoredBlob
const list = Array.isArray(parsed?.templates) ? parsed.templates : []
return list.filter(isQuoteParseTemplate).map((t) => ({ ...t, builtin: false, version: 1 }))
} catch {
return []
}
}
function writeUserTemplates(list: QuoteParseTemplate[]) {
const templates = list
.filter((t) => !t.builtin && t.templateKey !== GENERIC_AUTO_TEMPLATE_KEY)
.map((t) => ({ ...t, builtin: false, version: 1 as const }))
localStorage.setItem(STORAGE_KEY, JSON.stringify({ templates } satisfies StoredBlob))
}
/** 内置 + 用户模板(同 key 时用户覆盖内置同名以外的自定义) */
export function listQuoteParseTemplates(): QuoteParseTemplate[] {
const user = readUserTemplates()
const userKeys = new Set(user.map((t) => t.templateKey))
const builtins = BUILTIN_QUOTE_TEMPLATES.filter((t) => !userKeys.has(t.templateKey))
return [...builtins, ...user]
}
export function getQuoteParseTemplate(key: string): QuoteParseTemplate | undefined {
return listQuoteParseTemplates().find((t) => t.templateKey === key)
}
export function getSelectedTemplateKey(): string {
try {
const k = localStorage.getItem(SELECTED_KEY)?.trim()
if (k && getQuoteParseTemplate(k)) return k
} catch {
/* ignore */
}
return GENERIC_AUTO_TEMPLATE_KEY
}
export function setSelectedTemplateKey(key: string) {
localStorage.setItem(SELECTED_KEY, key || GENERIC_AUTO_TEMPLATE_KEY)
}
export function upsertQuoteParseTemplate(template: QuoteParseTemplate): QuoteParseTemplate {
if (!isQuoteParseTemplate(template)) {
throw new Error('无效的报价解析模板')
}
const builtin = BUILTIN_QUOTE_TEMPLATES.find((t) => t.templateKey === template.templateKey)
if (builtin?.builtin && template.templateKey === GENERIC_AUTO_TEMPLATE_KEY) {
throw new Error('不能覆盖「通用自动」模板')
}
const next: QuoteParseTemplate = {
...template,
version: 1,
builtin: false,
templateKey: template.templateKey.trim(),
name: template.name.trim(),
}
const user = readUserTemplates().filter((t) => t.templateKey !== next.templateKey)
user.push(next)
writeUserTemplates(user)
return next
}
export function deleteQuoteParseTemplate(templateKey: string): boolean {
const builtin = BUILTIN_QUOTE_TEMPLATES.find((t) => t.templateKey === templateKey)
if (builtin?.builtin) return false
const user = readUserTemplates()
const next = user.filter((t) => t.templateKey !== templateKey)
if (next.length === user.length) return false
writeUserTemplates(next)
if (getSelectedTemplateKey() === templateKey) {
setSelectedTemplateKey(GENERIC_AUTO_TEMPLATE_KEY)
}
return true
}
export function renameQuoteParseTemplate(templateKey: string, name: string): boolean {
const n = String(name || '').trim()
if (!n) return false
const user = readUserTemplates()
const idx = user.findIndex((t) => t.templateKey === templateKey)
if (idx < 0) return false
user[idx] = { ...user[idx]!, name: n }
writeUserTemplates(user)
return true
}
export function exportQuoteParseTemplates(): string {
const user = readUserTemplates()
return JSON.stringify({ version: 1, templates: user }, null, 2)
}
export function importQuoteParseTemplates(jsonText: string): number {
const raw = JSON.parse(jsonText)
const list = Array.isArray(raw)
? raw
: Array.isArray(raw?.templates)
? raw.templates
: isQuoteParseTemplate(raw)
? [raw]
: []
let n = 0
for (const item of list) {
if (!isQuoteParseTemplate(item)) continue
if (item.templateKey === GENERIC_AUTO_TEMPLATE_KEY) continue
upsertQuoteParseTemplate({ ...item, builtin: false })
n += 1
}
return n
}
/** 按文件名猜测内置模板 */
export function suggestTemplateKeyByFileName(fileName: string): string {
const name = String(fileName || '')
for (const t of BUILTIN_QUOTE_TEMPLATES) {
if (t.templateKey === GENERIC_AUTO_TEMPLATE_KEY) continue
const hints = t.matchHints?.fileNameIncludes || []
if (hints.some((h) => h && name.includes(h))) return t.templateKey
}
return getSelectedTemplateKey()
}
export function makeTemplateKeyFromName(name: string): string {
const base = String(name || 'custom')
.trim()
.toLowerCase()
.replace(/[^\u4e00-\u9fffA-Za-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 40)
const suffix = Date.now().toString(36).slice(-4)
return `${base || 'custom'}-${suffix}`
}

View File

@ -0,0 +1,64 @@
/**
* 报价表声明式解析模板(AI 生成 / 用户保存,本地引擎解释)
* 禁止可执行脚本;仅枚举策略 + 列别名。
*/
export type QuoteChannelSource = 'leftOfWeight' | 'dockColumn' | 'sheetName'
export type QuotePricingMode = 'unit_plus_fee' | 'flat' | 'auto'
export type QuoteFlatLayout = 'sideBySideBlocks' | 'long'
export type QuoteParseTemplate = {
templateKey: string
name: string
version: 1
/** 内置种子不可删;用户模板可删 */
builtin?: boolean
matchHints?: {
fileNameIncludes?: string[]
/** 跳过非报价 sheet 名(正则字符串) */
skipSheetNameRe?: string
}
sheetPolicy: {
channelSource: QuoteChannelSource
/** 对接代码 / 渠道名称 等表头别名 */
channelHeaderAliases?: string[]
channelFillDown: boolean
countryFillDown: boolean
}
columns: {
weightAliases: string[]
freightPerKgAliases: string[]
handlingAliases: string[]
registrationAliases: string[]
countryAliases: string[]
}
pricing: {
mode: QuotePricingMode
flatLayout?: QuoteFlatLayout
/** 分段标题行,如 PAK|WPX */
subtypeRowRe?: string
}
currencyDefault?: string
notes?: string
}
export const GENERIC_AUTO_TEMPLATE_KEY = 'generic-auto'
export function isQuoteParseTemplate(raw: unknown): raw is QuoteParseTemplate {
if (!raw || typeof raw !== 'object') return false
const t = raw as Record<string, unknown>
if (typeof t.templateKey !== 'string' || !t.templateKey.trim()) return false
if (typeof t.name !== 'string' || !t.name.trim()) return false
if (t.version !== 1) return false
if (!t.sheetPolicy || typeof t.sheetPolicy !== 'object') return false
if (!t.columns || typeof t.columns !== 'object') return false
if (!t.pricing || typeof t.pricing !== 'object') return false
const sp = t.sheetPolicy as Record<string, unknown>
const src = sp.channelSource
if (src !== 'leftOfWeight' && src !== 'dockColumn' && src !== 'sheetName') return false
const mode = (t.pricing as Record<string, unknown>).mode
if (mode !== 'unit_plus_fee' && mode !== 'flat' && mode !== 'auto') return false
return true
}

View File

@ -17,12 +17,63 @@
</nav>
<!-- 1 提取 -->
<div v-show="phase === 'extract'" class="cq-phase">
<div v-show="phase === 'extract'" class="cq-phase cq-phase--extract">
<div class="cq-top-row">
<section class="cq-panel cq-panel--upload">
<div class="cq-panel-head">
<span class="cq-section-label">上传报价表</span>
</div>
<div class="cq-template-row">
<label class="label">报价模板</label>
<a-select
v-model="selectedTemplateKey"
:disabled="parsing || extracting"
placeholder="选择解析模板"
allow-search
style="flex: 1; min-width: 160px"
@change="onTemplateChange"
>
<a-option
v-for="t in quoteTemplates"
:key="t.templateKey"
:value="t.templateKey"
:label="t.name"
>
{{ t.name }}
<span v-if="t.builtin" class="cq-muted"> · 内置</span>
</a-option>
</a-select>
<a-button
size="small"
:disabled="!canGenerateTemplate"
:loading="generatingTemplate"
@click="runGenerateTemplate"
>
从当前文件生成
</a-button>
<a-dropdown trigger="click" :disabled="parsing || extracting">
<a-button size="small">管理</a-button>
<template #content>
<a-doption :disabled="!canExportTemplates" @click="exportTemplates">
导出用户模板
</a-doption>
<a-doption @click="triggerImportTemplates">导入模板 JSON</a-doption>
<a-doption
:disabled="!canDeleteSelectedTemplate"
@click="removeSelectedUserTemplate"
>
删除当前用户模板
</a-doption>
</template>
</a-dropdown>
<input
ref="templateImportInputRef"
type="file"
accept=".json,application/json"
class="cq-native-file-input"
@change="onImportTemplatesFile"
/>
</div>
<div class="cq-upload-row">
<div
class="cq-upload-area"
@ -39,7 +90,7 @@
<div class="cq-upload-text">
{{ uploadDragOver ? '松开鼠标即可上传' : '将文件拖到此处,或点击上传' }}
</div>
<div class="cq-upload-inline-tip">支持 .xlsx / .xls · 只提取模型,不写库</div>
<div class="cq-upload-inline-tip">支持 .xlsx / .xls · 按模板本地识别,不写库</div>
</template>
<template v-else>
<div class="cq-upload-file-name" :title="fileName">{{ fileName }}</div>
@ -192,7 +243,7 @@
<div class="cq-model-card-top">
<a-checkbox v-model="card.selected" />
<div class="cq-model-title">
<strong>{{ card.quote.channelCodeHint || card.quote.channelNameHint || '未命名' }}</strong>
<strong>{{ preferChannelLabel(card.quote.channelCodeHint, card.quote.channelNameHint) }}</strong>
<span v-if="card.quote.serviceSubtype" class="cq-muted" :title="card.quote.serviceSubtype">
{{ shortServiceSubtype(card.quote.serviceSubtype) }}
</span>
@ -208,8 +259,9 @@
</div>
<div class="cq-model-meta">
<a-tag v-if="card.hasFreight" size="small" color="arcoblue">运费</a-tag>
<a-tag v-if="card.hasHandling" size="small" color="green">处理费</a-tag>
<a-tag v-if="card.hasRegistration" size="small" color="orangered">挂号费</a-tag>
<a-tag v-if="card.hasHandling || card.hasRegistration" size="small" color="green">
操作费
</a-tag>
<span class="cq-muted">{{ card.sheetName }}</span>
<span class="cq-muted">{{ card.rowCount }} 行</span>
<span class="cq-muted">重量 {{ card.weightEnds.length }}</span>
@ -331,6 +383,12 @@
/>
</a-select>
</div>
<a-button
:disabled="!activeCandidate"
@click="openCreateChannelModal"
>
新建渠道
</a-button>
<a-button
class="app-btn-search cq-compare-refresh"
:loading="compareLoading"
@ -446,6 +504,92 @@
去选择融合
</a-button>
</div>
<a-modal
v-model:visible="createChannelVisible"
title="新建服务渠道(预填)"
:width="560"
unmount-on-close
:on-before-ok="confirmCreateChannel"
@cancel="createChannelVisible = false"
>
<p class="cq-muted cq-create-channel-tip">
创建渠道壳,并可选已有 KPI 价格分区;勾选后可用当前候选生成草稿买价(不新建分区,不走融合三种模式)。
</p>
<div class="cq-create-channel-form">
<div class="field">
<label class="label">服务商分组</label>
<a-select
v-model="createChannelForm.groupId"
allow-search
placeholder="选择分组"
:loading="channelGroupsLoading"
>
<a-option
v-for="g in channelGroupOptions"
:key="g.id"
:value="g.id"
:label="g.label"
/>
</a-select>
</div>
<div class="field">
<label class="label">渠道编码</label>
<a-input
v-model="createChannelForm.channelCode"
placeholder="必填,可改"
allow-clear
@blur="createChannelForm.channelCode = normalizeChannelCode(createChannelForm.channelCode)"
/>
</div>
<div class="field">
<label class="label">渠道名称</label>
<a-input v-model="createChannelForm.channelName" placeholder="必填" allow-clear />
</div>
<div class="field">
<label class="label">价格分区</label>
<a-select
v-model="createChannelForm.zoneValues"
multiple
allow-search
allow-clear
placeholder="选择已有 KPI 价格分区"
:loading="priceAreaOptionsLoading"
:max-tag-count="3"
>
<a-option
v-for="z in priceAreaOptions"
:key="z.value"
:value="z.value"
:label="z.label"
/>
</a-select>
</div>
<div class="field cq-create-channel-check">
<a-checkbox
v-model="createChannelForm.writeDraftPrices"
:disabled="!createChannelForm.zoneValues.length"
>
用当前候选生成草稿买价
</a-checkbox>
<span class="cq-muted">
{{
createChannelForm.zoneValues.length
? '按所选分区 × 候选重量段写入运费/操作费(草稿;挂号费并入操作费)'
: '请先选择价格分区'
}}
</span>
</div>
<div class="field">
<label class="label">说明</label>
<a-textarea
v-model="createChannelForm.description"
:auto-size="{ minRows: 2, maxRows: 4 }"
placeholder="可选"
/>
</div>
</div>
</a-modal>
</div>
<!-- 4 融合 -->
@ -546,10 +690,13 @@ import { useRouter } from 'vue-router'
import ExcelFileIcon from '@/components/icons/ExcelFileIcon.vue'
import { chatAi, listAiProviders, listAiSkills, type AiSkillItem } from '@/api/ai'
import {
createServiceChannel,
getServiceChannelGroupList,
getServiceChannelList,
getServiceChannelPriceList,
saveServiceChannelPriceAll,
} from '@/api/channel/serviceChannel'
import { ENABLE_STATUS } from '@/utils/enableStatus'
import {
postForewarningServiceKpiAreaGetKpiAreaInfos,
postForewarningServiceKpiAreaGetKpiAreas,
@ -574,11 +721,33 @@ import {
} from '../channelQuoteAiSkill'
import {
needsAiFallback,
parseSheetMatrixLocal,
type LocalParseResult,
parseSheetMatrixWithTemplate,
} from '../channelQuoteLocalParse'
import {
CHANNEL_QUOTE_TEMPLATE_AI_SCENE,
CHANNEL_QUOTE_TEMPLATE_DEFAULT_SKILL_KEY,
buildChannelQuoteTemplateSystemPrompt,
buildChannelQuoteTemplateUserContent,
matrixToTemplateSampleTsv,
parseQuoteTemplateAiReply,
} from '../channelQuoteTemplateAiSkill'
import {
deleteQuoteParseTemplate,
exportQuoteParseTemplates,
getQuoteParseTemplate,
getSelectedTemplateKey,
importQuoteParseTemplates,
listQuoteParseTemplates,
makeTemplateKeyFromName,
setSelectedTemplateKey,
suggestTemplateKeyByFileName,
upsertQuoteParseTemplate,
} from '../channelQuoteTemplateStore'
import type { QuoteParseTemplate } from '../channelQuoteTemplateTypes'
import {
buildCompareDiff,
buildDraftPricesFromCandidate,
buildDraftZoneMapsForCreate,
buildMergePayload,
collectZoneHints,
flattenMergedPriceMatrix,
@ -596,6 +765,7 @@ import {
candidateDisplayFullTitle,
candidateDisplayTitle,
flattenCandidateCells,
preferChannelLabel,
shortServiceSubtype,
type CandidateBuyPrice,
type QuoteModelCard,
@ -681,6 +851,248 @@ const channelsLoading = ref(false)
const channelOptions = ref<ChannelOptionForQuote[]>([])
const priceCache = reactive<Record<number, ExistingPriceItem[]>>({})
const createChannelVisible = ref(false)
const createChannelSaving = ref(false)
const channelGroupsLoading = ref(false)
const channelGroupOptions = ref<Array<{ id: number; label: string }>>([])
const priceAreaOptionsLoading = ref(false)
const priceAreaOptions = ref<Array<{ value: string; label: string }>>([])
const createChannelForm = reactive({
groupId: undefined as number | undefined,
channelCode: '',
channelName: '',
description: '',
zoneValues: [] as string[],
writeDraftPrices: true,
})
function normalizeChannelCode(value: unknown): string {
return String(value ?? '')
.trim()
.replace(/\s+/g, '')
}
/** 从候选 hint 猜可填的编码(仅字母数字;中文产品名则抽数字字母片段) */
function suggestPrefillChannelCode(codeHint?: string | null, nameHint?: string | null): string {
const code = normalizeChannelCode(codeHint)
if (code && /^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$/.test(code)) return code
const parts = String(nameHint || codeHint || '').match(/[A-Za-z0-9]+/g) || []
return parts.join('').slice(0, 32)
}
async function loadChannelGroups() {
channelGroupsLoading.value = true
try {
const items = await getServiceChannelGroupList({})
channelGroupOptions.value = (items || [])
.map((x: any) => {
const id = Number(x.id ?? x.Id)
const name = String(
x.groupName ?? x.GroupName ?? x.name ?? x.Name ?? x.providerName ?? '',
).trim()
if (!Number.isFinite(id) || id <= 0) return null
return { id, label: name || `分组 #${id}` }
})
.filter(Boolean) as Array<{ id: number; label: string }>
} catch (e: any) {
channelGroupOptions.value = []
Message.error(e?.message || '加载服务商分组失败')
} finally {
channelGroupsLoading.value = false
}
}
async function loadPriceAreaOptions() {
priceAreaOptionsLoading.value = true
try {
const areaRes = await postForewarningServiceKpiAreaGetKpiAreas({
page: 1,
pageSize: 500,
areaType: 'price',
} as any)
const areaItems = (areaRes as any)?.items ?? (areaRes as any)?.Items ?? []
priceAreaOptions.value = (areaItems as any[])
.filter((it) => {
const t = String(it?.areaType ?? it?.AreaType ?? 'price').toLowerCase()
return !t || t === 'price'
})
.map((it: any) => {
const id = String(it?.id ?? it?.Id ?? '')
const label = String(it?.name ?? it?.Name ?? id)
return id ? { value: id, label } : null
})
.filter(Boolean) as Array<{ value: string; label: string }>
} catch (e: any) {
priceAreaOptions.value = []
Message.error(e?.message || '加载价格分区失败')
} finally {
priceAreaOptionsLoading.value = false
}
}
function suggestPrefillZonesFromCandidate(c: CandidateBuyPrice): string[] {
const hints = (c.zoneHints || []).filter((h) => h && h !== '默认')
if (!hints.length || !priceAreaOptions.value.length) return []
const picked: string[] = []
for (const h of hints) {
const hit =
priceAreaOptions.value.find((z) => z.label === h || z.value === h) ||
priceAreaOptions.value.find((z) => z.label.includes(h) || h.includes(z.label))
if (hit && !picked.includes(hit.value)) picked.push(hit.value)
}
return picked
}
async function openCreateChannelModal() {
const c = activeCandidate.value
if (!c) {
Message.warning('请先选择候选')
return
}
const name = preferChannelLabel(c.channelCodeHint, c.channelNameHint)
createChannelForm.channelName = name === '未命名' ? '' : name
createChannelForm.channelCode = suggestPrefillChannelCode(c.channelCodeHint, c.channelNameHint)
createChannelForm.description = [
c.sheetName ? `来自报价 sheet:${c.sheetName}` : '',
c.mode === 'flat' ? '计价:一口价' : '计价:公斤+票费',
]
.filter(Boolean)
.join(';')
createChannelForm.writeDraftPrices = true
await Promise.all([
channelGroupOptions.value.length ? Promise.resolve() : loadChannelGroups(),
priceAreaOptions.value.length ? Promise.resolve() : loadPriceAreaOptions(),
])
if (
createChannelForm.groupId == null ||
!channelGroupOptions.value.some((g) => g.id === createChannelForm.groupId)
) {
createChannelForm.groupId = channelGroupOptions.value[0]?.id
}
createChannelForm.zoneValues = suggestPrefillZonesFromCandidate(c)
if (!createChannelForm.zoneValues.length) createChannelForm.writeDraftPrices = false
createChannelVisible.value = true
}
async function confirmCreateChannel(): Promise<boolean> {
const code = normalizeChannelCode(createChannelForm.channelCode)
const name = String(createChannelForm.channelName || '').trim()
const groupId = Number(createChannelForm.groupId)
const writeDraft = createChannelForm.writeDraftPrices
const zoneValues = [...createChannelForm.zoneValues]
if (!code || !name) {
Message.warning('请填写渠道编码和名称')
return false
}
if (!Number.isFinite(groupId) || groupId <= 0) {
Message.warning('请选择服务商分组')
return false
}
if (writeDraft && !zoneValues.length) {
Message.warning('生成草稿买价前请选择价格分区')
return false
}
const c = activeCandidate.value
if (writeDraft && !c) {
Message.warning('当前无候选,无法生成草稿买价')
return false
}
createChannelSaving.value = true
try {
await createServiceChannel({
groupId,
channelCode: code,
channelName: name,
minTime: 0,
maxTime: 0,
forecastType: 'waybill',
forecastCode: '',
description: String(createChannelForm.description || '').trim(),
preScript: '',
isActive: ENABLE_STATUS.enabled,
})
await loadChannels()
const matched =
channelOptions.value.find(
(o) => o.channelCode.toLowerCase() === code.toLowerCase(),
) ||
channelOptions.value.find((o) => o.channelName === name)
if (!matched) {
Message.warning('渠道已创建,但未能自动定位新渠道,请手动选择')
return true
}
compareChannelId.value = matched.id
let draftMsg = '渠道已创建并绑定'
if (writeDraft && c) {
const selectedZones = zoneValues.map((value) => {
const opt = priceAreaOptions.value.find((z) => z.value === value)
return { value, label: opt?.label || value }
})
const draftMaps = buildDraftZoneMapsForCreate({
zoneHints: c.zoneHints || [],
selectedZones,
})
const draft = buildDraftPricesFromCandidate({
currency: c.currency,
weightIntervals: c.weightIntervals,
zoneHints: c.zoneHints,
feeItems: c.feeItems,
zoneMaps: draftMaps,
})
if (!draft.prices.length) {
Message.warning(
`渠道已创建,但草稿买价未生成:${draft.warnings.join(';') || '无有效明细'}`,
)
await onCompareChannelChange()
return true
}
await saveServiceChannelPriceAll({
serviceChannelId: matched.id,
publish: false,
prices: draft.prices,
})
delete priceCache[matched.id]
zoneMaps.value = draftMaps.map((z) => ({ ...z }))
await ensureChannelMeta(matched.id)
const prices = priceCache[matched.id] || []
const zoneValueSet = new Set<string>()
for (const price of prices) {
for (const f of price.factors || []) {
const fac = String(f.factor || '')
if (fac === 'zone' || fac === '分区' || fac === '价格分区') {
;(f.factorValues || []).forEach((v) => zoneValueSet.add(String(v)))
}
}
}
const labels = await resolveZoneLabels([...zoneValueSet])
zoneOptions.value = [...zoneValueSet].map((value) => ({
value,
label: labels[value] ? `${labels[value]} (${value})` : value,
}))
if (!zoneMaps.value.length) {
zoneMaps.value = suggestZoneMaps(collectZoneHints(c.quote), zoneOptions.value)
}
compareResult.value = null
if (canRunCompare.value) await runCompare()
draftMsg = `渠道已创建,并写入 ${draft.prices.length} 个草稿价格项`
if (draft.warnings.length) draftMsg += `(${draft.warnings[0]})`
} else {
await onCompareChannelChange()
}
Message.success(draftMsg)
return true
} catch (e: any) {
Message.error(e?.message || '新建渠道失败')
return false
} finally {
createChannelSaving.value = false
}
}
const providersLoading = ref(false)
const providers = ref<AiProviderItem[]>([])
const providerKey = ref('')
@ -690,6 +1102,154 @@ const skillKey = ref(CHANNEL_QUOTE_AI_DEFAULT_SKILL_KEY)
const skills = ref<AiSkillItem[]>([])
const skillsLoading = ref(false)
const quoteTemplates = ref<QuoteParseTemplate[]>(listQuoteParseTemplates())
const selectedTemplateKey = ref(getSelectedTemplateKey())
const generatingTemplate = ref(false)
const templateImportInputRef = ref<HTMLInputElement | null>(null)
const selectedTemplate = computed(
() => getQuoteParseTemplate(selectedTemplateKey.value) || quoteTemplates.value[0],
)
const canGenerateTemplate = computed(
() =>
Boolean(fileName.value && sheets.value.length) &&
Boolean(providerKey.value && modelId.value) &&
!parsing.value &&
!extracting.value &&
!generatingTemplate.value,
)
const canExportTemplates = computed(() =>
quoteTemplates.value.some((t) => !t.builtin),
)
const canDeleteSelectedTemplate = computed(() => {
const t = selectedTemplate.value
return Boolean(t && !t.builtin)
})
function refreshQuoteTemplates() {
quoteTemplates.value = listQuoteParseTemplates()
}
function onTemplateChange() {
setSelectedTemplateKey(selectedTemplateKey.value)
}
function exportTemplates() {
try {
const text = exportQuoteParseTemplates()
const blob = new Blob([text], { type: 'application/json;charset=utf-8' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `quote-parse-templates-${Date.now()}.json`
a.click()
URL.revokeObjectURL(url)
Message.success('已导出用户模板')
} catch (e: any) {
Message.error(e?.message || '导出失败')
}
}
function triggerImportTemplates() {
templateImportInputRef.value?.click()
}
async function onImportTemplatesFile(e: Event) {
const input = e.target as HTMLInputElement
const file = input.files?.[0]
input.value = ''
if (!file) return
try {
const text = await file.text()
const n = importQuoteParseTemplates(text)
refreshQuoteTemplates()
Message.success(n ? `已导入 ${n} 个模板` : '未导入有效模板')
} catch (err: any) {
Message.error(err?.message || '导入失败')
}
}
function removeSelectedUserTemplate() {
const key = selectedTemplateKey.value
if (!deleteQuoteParseTemplate(key)) {
Message.warning('内置模板不可删除')
return
}
refreshQuoteTemplates()
selectedTemplateKey.value = getSelectedTemplateKey()
Message.success('已删除模板')
}
async function resolveTemplateSystemPrompt(): Promise<string> {
try {
const list = await listAiSkills({
scene: CHANNEL_QUOTE_TEMPLATE_AI_SCENE,
includeContent: true,
enabledOnly: true,
})
const hit =
list.find((s) => s.skillKey === CHANNEL_QUOTE_TEMPLATE_DEFAULT_SKILL_KEY) || list[0]
const content = String(hit?.content || '').trim()
if (content) return content
} catch {
/* use builtin */
}
return buildChannelQuoteTemplateSystemPrompt()
}
async function runGenerateTemplate() {
if (!canGenerateTemplate.value) return
const targets = sheets.value
.filter((s) => selectedSheetNames.value.includes(s.name) || !s.likelyNonPrice)
.filter((s) => !s.likelyNonPrice)
.slice(0, 3)
const sampleSheets = (targets.length ? targets : sheets.value.slice(0, 3)).map((s) => ({
sheetName: s.name,
sheetText: matrixToTemplateSampleTsv(s.matrix),
}))
if (!sampleSheets.length) {
Message.warning('没有可用于生成模板的 sheet')
return
}
generatingTemplate.value = true
try {
const baseName = String(fileName.value || '自定义')
.replace(/\.(xlsx|xls)$/i, '')
.slice(0, 40)
const systemPrompt = await resolveTemplateSystemPrompt()
const res = await chatAi({
providerKey: providerKey.value,
model: modelId.value,
scene: CHANNEL_QUOTE_TEMPLATE_AI_SCENE,
messages: [
{ role: 'system', content: systemPrompt },
{
role: 'user',
content: buildChannelQuoteTemplateUserContent({
templateName: baseName,
fileName: fileName.value,
sheets: sampleSheets,
}),
},
],
})
const reply = String((res as any)?.content ?? (res as any)?.message ?? res ?? '')
let draft = parseQuoteTemplateAiReply(reply, baseName)
if (!draft.templateKey || draft.templateKey === 'generic-auto') {
draft = { ...draft, templateKey: makeTemplateKeyFromName(draft.name || baseName) }
}
const saved = upsertQuoteParseTemplate(draft)
refreshQuoteTemplates()
selectedTemplateKey.value = saved.templateKey
setSelectedTemplateKey(saved.templateKey)
Message.success(`已生成并保存模板「${saved.name}」`)
} catch (e: any) {
Message.error(e?.message || '生成模板失败')
} finally {
generatingTemplate.value = false
}
}
const enabledProviders = computed(() =>
providers.value.filter((p) => p.enabled && Boolean(p.apiKey)),
)
@ -1176,6 +1736,11 @@ async function ingestQuoteFile(raw: File) {
fileName.value = raw.name
sheets.value = await parseQuoteWorkbook(raw)
selectedSheetNames.value = sheets.value.filter((s) => s.selected).map((s) => s.name)
const suggested = suggestTemplateKeyByFileName(raw.name)
if (suggested && getQuoteParseTemplate(suggested)) {
selectedTemplateKey.value = suggested
setSelectedTemplateKey(suggested)
}
parsing.value = false
await runLocalExtract({ fromUpload: true })
} catch (e: any) {
@ -1298,7 +1863,8 @@ async function runLocalExtract(opts?: { fromUpload?: boolean }) {
let okSheets = 0
for (const sheet of targets) {
if (extractAborted) break
const parsed = parseSheetMatrixLocal(sheet.name, sheet.matrix)
const tpl = selectedTemplate.value
const parsed = parseSheetMatrixWithTemplate(sheet.name, sheet.matrix, tpl)
extractDone.value += 1
if (parsed.isPriceSheet && parsed.channelQuotes.length && !needsAiFallback(parsed)) {
okSheets += 1
@ -1313,7 +1879,9 @@ async function runLocalExtract(opts?: { fromUpload?: boolean }) {
}
modelCards.value = cards
aiPendingSheetNames.value = pending
extractSummary.value = `本地成功 ${okSheets} 张 · 模型 ${cards.length} 个` +
const tplName = selectedTemplate.value?.name || '通用'
extractSummary.value =
`模板「${tplName}」· 本地成功 ${okSheets} 张 · 模型 ${cards.length} 个` +
(pending.length ? ` · 未识别 ${pending.length} 张(可 AI 补齐)` : '')
if (!cards.length && pending.length) {
Message.warning(`本地未抽出报价,还有 ${pending.length} 张可用 AI 补齐`)
@ -1567,6 +2135,13 @@ async function doSave(publish: boolean) {
watch(sendSkill, savePrefs)
watch(skillKey, savePrefs)
watch(
() => createChannelForm.zoneValues.length,
(n, prev) => {
if (n > 0 && !prev) createChannelForm.writeDraftPrices = true
if (n === 0) createChannelForm.writeDraftPrices = false
},
)
onMounted(() => {
loadPrefs()
@ -1655,6 +2230,36 @@ onMounted(() => {
flex-direction: column;
gap: 8px;
}
/** 提取步:外层不滚,报价模型区内部滚动,页脚贴底 */
.cq-phase--extract {
overflow: hidden;
.cq-top-row,
.cq-extract-summary,
.cq-panel--sheets,
.cq-error {
flex-shrink: 0;
}
.cq-panel--result {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
overflow: hidden;
.cq-panel-head {
flex-shrink: 0;
}
.cq-model-grid {
flex: 1;
min-height: 0;
overflow: auto;
align-content: start;
}
}
.cq-phase-footer {
position: static;
box-shadow: none;
}
}
.cq-intro {
margin: 0;
color: #86909c;
@ -1680,6 +2285,18 @@ onMounted(() => {
height: 100%;
box-sizing: border-box;
}
.cq-template-row {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
flex-wrap: wrap;
.label {
flex-shrink: 0;
color: #4e5969;
font-size: 13px;
}
}
.cq-upload-row {
display: flex;
align-items: stretch;
@ -1970,19 +2587,45 @@ onMounted(() => {
font-size: 12px;
}
.cq-phase-footer {
position: sticky;
bottom: 0;
z-index: 5;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: flex-end;
gap: 8px;
margin-top: auto;
padding-top: 12px;
padding: 12px 0 4px;
border-top: 1px solid #e5e6eb;
background: #fff;
flex-shrink: 0;
box-shadow: 0 -6px 12px -8px rgba(0, 0, 0, 0.08);
> .cq-muted {
margin-right: auto;
}
}
.cq-create-channel-tip {
margin: 0 0 12px;
line-height: 1.5;
}
.cq-create-channel-form {
display: flex;
flex-direction: column;
gap: 10px;
.field {
display: flex;
flex-direction: column;
gap: 4px;
}
.label {
font-size: 13px;
color: #4e5969;
}
}
.cq-create-channel-check {
gap: 6px !important;
}
.cq-cand-tabs {
display: flex;
flex-wrap: wrap;