From d7e991aecee8c9d31a6312d9945bcab647b54f3b Mon Sep 17 00:00:00 2001 From: zzh <1368735060@qq.com> Date: Wed, 25 Nov 2026 16:16:49 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=9A=E4=BB=B7=E5=B7=A5=E4=BD=9C?= =?UTF-8?q?=E5=8F=B0=E6=8A=A5=E4=BB=B7=E6=A8=A1=E6=9D=BF=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=E4=B8=8E=E6=96=B0=E5=BB=BA=E6=B8=A0=E9=81=93=E8=8D=89=E7=A8=BF?= =?UTF-8?q?=E4=B9=B0=E4=BB=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 支持声明式报价模板(壹号/万国/3PE)、左列渠道识别、对比步预填新建渠道并写入草稿买价;按票挂号费并入操作费 handling。 Co-authored-by: Cursor --- .../skills/oms-channel-quote-extract/SKILL.md | 8 +- .../oms-channel-quote-template/SKILL.md | 84 +++ docs/定价工作台说明.md | 12 +- scripts/verify-quote-templates.ts | 73 ++ src/api/ai/index.ts | 1 + .../pricingWorkbench/channelQuoteAiSkill.ts | 7 +- .../pricingWorkbench/channelQuoteApply.ts | 189 ++++- .../pricingWorkbench/channelQuoteCandidate.ts | 43 +- .../channelQuoteLocalParse.ts | 384 ++++++++-- .../channelQuoteTemplateAiSkill.ts | 184 +++++ .../channelQuoteTemplateSeeds.ts | 120 ++++ .../channelQuoteTemplateStore.ts | 152 ++++ .../channelQuoteTemplateTypes.ts | 64 ++ .../components/ChannelQuoteImportPanel.vue | 663 +++++++++++++++++- 14 files changed, 1890 insertions(+), 94 deletions(-) create mode 100644 .cursor/skills/oms-channel-quote-template/SKILL.md create mode 100644 scripts/verify-quote-templates.ts create mode 100644 src/views/channel/pricingWorkbench/channelQuoteTemplateAiSkill.ts create mode 100644 src/views/channel/pricingWorkbench/channelQuoteTemplateSeeds.ts create mode 100644 src/views/channel/pricingWorkbench/channelQuoteTemplateStore.ts create mode 100644 src/views/channel/pricingWorkbench/channelQuoteTemplateTypes.ts diff --git a/.cursor/skills/oms-channel-quote-extract/SKILL.md b/.cursor/skills/oms-channel-quote-extract/SKILL.md index 0dd6007..42b799d 100644 --- a/.cursor/skills/oms-channel-quote-extract/SKILL.md +++ b/.cursor/skills/oms-channel-quote-extract/SKILL.md @@ -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 ## 原则 diff --git a/.cursor/skills/oms-channel-quote-template/SKILL.md b/.cursor/skills/oms-channel-quote-template/SKILL.md new file mode 100644 index 0000000..a832fec --- /dev/null +++ b/.cursor/skills/oms-channel-quote-template/SKILL.md @@ -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 diff --git a/docs/定价工作台说明.md b/docs/定价工作台说明.md index 43b630a..c5c86cc 100644 --- a/docs/定价工作台说明.md +++ b/docs/定价工作台说明.md @@ -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 直接改卖价或替你确认融合、模板规则可执行脚本 | ## 与发布 / 审批衔接 diff --git a/scripts/verify-quote-templates.ts b/scripts/verify-quote-templates.ts new file mode 100644 index 0000000..5b676eb --- /dev/null +++ b/scripts/verify-quote-templates.ts @@ -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) diff --git a/src/api/ai/index.ts b/src/api/ai/index.ts index 1f00c75..4969021 100644 --- a/src/api/ai/index.ts +++ b/src/api/ai/index.ts @@ -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: '收件地址解析' }, diff --git a/src/views/channel/pricingWorkbench/channelQuoteAiSkill.ts b/src/views/channel/pricingWorkbench/channelQuoteAiSkill.ts index 4cdc8eb..f458368 100644 --- a/src/views/channel/pricingWorkbench/channelQuoteAiSkill.ts +++ b/src/views/channel/pricingWorkbench/channelQuoteAiSkill.ts @@ -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 0, + selected: !likelyNonPrice, likelyNonPrice, matrix, tsv: full.text, diff --git a/src/views/channel/pricingWorkbench/channelQuoteApply.ts b/src/views/channel/pricingWorkbench/channelQuoteApply.ts index b630dcc..0c5b070 100644 --- a/src/views/channel/pricingWorkbench/channelQuoteApply.ts +++ b/src/views/channel/pricingWorkbench/channelQuoteApply.ts @@ -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() + 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[]; 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[] = [] + let serial = 1 + + for (const fee of fees) { + const weightSet = new Set() + const details: Array<{ + factorValuesJson: Record + 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() + 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[], diff --git a/src/views/channel/pricingWorkbench/channelQuoteCandidate.ts b/src/views/channel/pricingWorkbench/channelQuoteCandidate.ts index 932288f..f101b80 100644 --- a/src/views/channel/pricingWorkbench/channelQuoteCandidate.ts +++ b/src/views/channel/pricingWorkbench/channelQuoteCandidate.ts @@ -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) } diff --git a/src/views/channel/pricingWorkbench/channelQuoteLocalParse.ts b/src/views/channel/pricingWorkbench/channelQuoteLocalParse.ts index 645ece3..baa7e2f 100644 --- a/src/views/channel/pricingWorkbench/channelQuoteLocalParse.ts +++ b/src/views/channel/pricingWorkbench/channelQuoteLocalParse.ts @@ -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 + freightAliasSet: Set + handlingAliasSet: Set + registrationAliasSet: Set + countryAliasSet: Set + channelAliasSet: Set + subtypeRe: RegExp | null +} + +function normalizeAliasToken(s: string): string { + return String(s || '') + .replace(/[((][^))]*[))]/g, '') + .replace(/[\s _/\\-]+/g, '') + .toLowerCase() +} + +function buildAliasSet(list: string[] | undefined): Set { + 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): 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 } -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() ;(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() + 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, + 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() + 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 } const buckets = new Map() - 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, - serviceSubtype: b.subtype, - mode: 'unit_plus_fee' as const, - destinationHints: [...b.destinations], - rows: b.rows, - })) + .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, + 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, + 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 (flatBlocks && flatBlocks.confidence !== 'none') return flatBlocks - - const flatLong = parseFlatLong(matrix, name, index, map, meta) - if (flatLong && flatLong.confidence !== 'none') return flatLong + if (mode === 'flat' || mode === 'auto') { + if (flatLayout !== 'long') { + const flatBlocks = parseFlatBlocks(matrix, name, index, headerRow, meta, ctx) + if (flatBlocks && flatBlocks.confidence !== 'none') return flatBlocks + } + 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) diff --git a/src/views/channel/pricingWorkbench/channelQuoteTemplateAiSkill.ts b/src/views/channel/pricingWorkbench/channelQuoteTemplateAiSkill.ts new file mode 100644 index 0000000..1f197ac --- /dev/null +++ b/src/views/channel/pricingWorkbench/channelQuoteTemplateAiSkill.ts @@ -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 + const name = + String(obj.name || fallbackName || '自定义模板').trim() || '自定义模板' + const templateKey = + String(obj.templateKey || '').trim() || makeTemplateKeyFromName(name) + const sheetPolicyRaw = (obj.sheetPolicy || {}) as Record + const columnsRaw = (obj.columns || {}) as Record + const pricingRaw = (obj.pricing || {}) as Record + const matchRaw = (obj.matchHints || {}) as Record + + 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') +} diff --git a/src/views/channel/pricingWorkbench/channelQuoteTemplateSeeds.ts b/src/views/channel/pricingWorkbench/channelQuoteTemplateSeeds.ts new file mode 100644 index 0000000..39ad7d5 --- /dev/null +++ b/src/views/channel/pricingWorkbench/channelQuoteTemplateSeeds.ts @@ -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) +} diff --git a/src/views/channel/pricingWorkbench/channelQuoteTemplateStore.ts b/src/views/channel/pricingWorkbench/channelQuoteTemplateStore.ts new file mode 100644 index 0000000..67156e8 --- /dev/null +++ b/src/views/channel/pricingWorkbench/channelQuoteTemplateStore.ts @@ -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}` +} diff --git a/src/views/channel/pricingWorkbench/channelQuoteTemplateTypes.ts b/src/views/channel/pricingWorkbench/channelQuoteTemplateTypes.ts new file mode 100644 index 0000000..7e854bd --- /dev/null +++ b/src/views/channel/pricingWorkbench/channelQuoteTemplateTypes.ts @@ -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 + 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 + const src = sp.channelSource + if (src !== 'leftOfWeight' && src !== 'dockColumn' && src !== 'sheetName') return false + const mode = (t.pricing as Record).mode + if (mode !== 'unit_plus_fee' && mode !== 'flat' && mode !== 'auto') return false + return true +} diff --git a/src/views/channel/pricingWorkbench/components/ChannelQuoteImportPanel.vue b/src/views/channel/pricingWorkbench/components/ChannelQuoteImportPanel.vue index 24ba11e..536412b 100644 --- a/src/views/channel/pricingWorkbench/components/ChannelQuoteImportPanel.vue +++ b/src/views/channel/pricingWorkbench/components/ChannelQuoteImportPanel.vue @@ -17,12 +17,63 @@ -
+
+
+ + + + {{ t.name }} + · 内置 + + + + 从当前文件生成 + + + 管理 + + + +
{{ uploadDragOver ? '松开鼠标即可上传' : '将文件拖到此处,或点击上传' }}
-
支持 .xlsx / .xls · 只提取模型,不写库
+
支持 .xlsx / .xls · 按模板本地识别,不写库