Compare commits
2 Commits
3e7d895253
...
1cb4631480
| Author | SHA1 | Date | |
|---|---|---|---|
| 1cb4631480 | |||
| 29d7cbb226 |
83
.cursor/skills/oms-channel-quote-extract/SKILL.md
Normal file
83
.cursor/skills/oms-channel-quote-extract/SKILL.md
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
---
|
||||||
|
name: oms-channel-quote-extract
|
||||||
|
description: >-
|
||||||
|
Extracts OMS channel buy-price quotes from vendor Excel sheets for pricing
|
||||||
|
workbench Step 0. Use when the user uploads 报价表, asks to 更新渠道买价,
|
||||||
|
parse 重量段/一口价/运费RMB/KG/处理费, or map sheet names to service channels
|
||||||
|
on /channel/pricingWorkbench.
|
||||||
|
---
|
||||||
|
|
||||||
|
# OMS 渠道报价表提取 · 买价更新
|
||||||
|
|
||||||
|
从下游报价 Excel 提取结构化买价,供定价工作台「更新买价」回写渠道草稿买价。
|
||||||
|
|
||||||
|
**运行时主路径是本地规则解析**(`channelQuoteLocalParse.ts`),覆盖常见「公斤+票费」「一口价/并排国家列」。
|
||||||
|
本 skill / AI 仅在本地失败时补齐难拆 sheet。
|
||||||
|
|
||||||
|
- 本地:`src/views/channel/pricingWorkbench/channelQuoteLocalParse.ts`
|
||||||
|
- AI system:`src/views/channel/pricingWorkbench/channelQuoteAiSkill.ts`
|
||||||
|
- 面板:`src/views/channel/pricingWorkbench/components/ChannelQuoteImportPanel.vue`
|
||||||
|
|
||||||
|
## 产出格式(必须)
|
||||||
|
|
||||||
|
只输出一个 JSON 对象(可用 \`\`\`json 包裹),禁止编造表中不存在的金额。
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"sheetName": "3PE ePost",
|
||||||
|
"isPriceSheet": true,
|
||||||
|
"skipReason": null,
|
||||||
|
"currency": "CNY",
|
||||||
|
"effectiveAt": "2026-05-08",
|
||||||
|
"channelQuotes": [
|
||||||
|
{
|
||||||
|
"channelCodeHint": "3SZ51",
|
||||||
|
"channelNameHint": "3PE ePost普货",
|
||||||
|
"serviceSubtype": null,
|
||||||
|
"mode": "unit_plus_fee",
|
||||||
|
"destinationHints": ["美国"],
|
||||||
|
"rows": [
|
||||||
|
{
|
||||||
|
"weightStart": 0,
|
||||||
|
"weightEnd": 0.1,
|
||||||
|
"zoneHint": "美国",
|
||||||
|
"freightPerKg": 86,
|
||||||
|
"handlingPerShipment": 30,
|
||||||
|
"registrationPerShipment": null,
|
||||||
|
"flatTotal": null
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"warnings": []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### mode
|
||||||
|
|
||||||
|
| mode | 含义 | 行字段 |
|
||||||
|
|------|------|--------|
|
||||||
|
| `flat` | 一口价(重量点/段 → 总价) | `flatTotal` 必填;`freightPerKg`/`handling*` 为空 |
|
||||||
|
| `unit_plus_fee` | 运费 RMB/KG + 处理费/挂号费 RMB/票 | `freightPerKg` 与/或 `handlingPerShipment` / `registrationPerShipment` |
|
||||||
|
|
||||||
|
### 重量
|
||||||
|
|
||||||
|
- 区间 `0-0.1` / `0.101-0.2` → `weightStart` + `weightEnd`
|
||||||
|
- 单点一口价 `0.5` → 至少填 `weightEnd=0.5`;`weightStart` 可留空由前端按有序上界补成 `(prev-end]`
|
||||||
|
- 不要输出偏远邮编清单或条款长文
|
||||||
|
|
||||||
|
## 硬规则
|
||||||
|
|
||||||
|
1. 非报价 sheet(目录、附加费规定、操作指南、偏远邮编、增值服务、纯邮编列表):`isPriceSheet=false`,`channelQuotes=[]`,写清 `skipReason`
|
||||||
|
2. 列名别名:包裹重量/重量KG、重量段(KG)、运费(RMB/KG)、处理费/操作费(RMB/票)、挂号费、国家/国家名称/分区/对接代码
|
||||||
|
3. 一 sheet 多个「对接代码」或渠道码 → 拆成多个 `channelQuotes`
|
||||||
|
4. PAK/WPX 等分段标题写入 `serviceSubtype`,不要当成渠道码
|
||||||
|
5. sheet 名常含渠道码(如 `3SZ01-3PE Express--优先`),写入 `channelCodeHint` / `channelNameHint`
|
||||||
|
6. 金额必须来自单元格;说明行、空行忽略
|
||||||
|
7. 币种默认人民币 → `CNY`;生效日从「生效日期」类文案解析(可空)
|
||||||
|
|
||||||
|
## 原则
|
||||||
|
|
||||||
|
- 只提取可进 OMS 买价矩阵的运费/处理费/挂号费
|
||||||
|
- 前端负责匹配 OMS 渠道、价格分区与重量段重建;你只输出结构化报价
|
||||||
|
- 不确定是否报价表时宁可 `isPriceSheet=false` 并说明原因
|
||||||
@ -5,6 +5,19 @@
|
|||||||
|
|
||||||
## 标准操作顺序
|
## 标准操作顺序
|
||||||
|
|
||||||
|
工作台分两个 Tab:
|
||||||
|
|
||||||
|
### Tab「更新买价」(四步向导)
|
||||||
|
|
||||||
|
1. **提取模型**:上传 Excel → **本地规则优先**解析报价模型(秒级);仅未识别 sheet 可选 AI 补齐。本步不绑渠道、不写库。
|
||||||
|
2. **候选买价**:将勾选模型规范为候选价表(重量段 `(start-end]`、运费/处理费等),仅内存预览。
|
||||||
|
3. **对比现网**:绑定 OMS 渠道 + 分区映射 → 候选 vs 现网买价(新增/改价/将删除/未映射分区)。
|
||||||
|
4. **选择融合**:覆盖匹配价格项 / 仅更新交集 / 放弃 → 确认后才 `price/save`(默认草稿,可发布)。
|
||||||
|
|
||||||
|
分区/价格项须已在渠道设计中配置;不自动新建。融合成功后自动切到「合成卖价」并勾选已更新渠道。
|
||||||
|
|
||||||
|
### Tab「合成卖价」
|
||||||
|
|
||||||
1. **选渠道**:多选服务渠道买价(优先已发布快照;无快照则读草稿并警告)。摘要默认折叠;币种不一致会提示并禁用预览。
|
1. **选渠道**:多选服务渠道买价(优先已发布快照;无快照则读草稿并警告)。摘要默认折叠;币种不一致会提示并禁用预览。
|
||||||
2. **定规则**:毛利率、差异阈值、排除渠道;可选「对比现网卖价」与「改规则后自动重算」。
|
2. **定规则**:毛利率、差异阈值、排除渠道;可选「对比现网卖价」与「改规则后自动重算」。
|
||||||
3. **预览合成**:对齐分区/重量段,最低买价合成,毛利率硬计算。改规则后结果标过期,可一键重算;超阈值差异可「用 AI 解释」。
|
3. **预览合成**:对齐分区/重量段,最低买价合成,毛利率硬计算。改规则后结果标过期,可一键重算;超阈值差异可「用 AI 解释」。
|
||||||
@ -13,15 +26,32 @@
|
|||||||
成本合成:每个「分区 × 重量段」取参与渠道中的**最低买价**。
|
成本合成:每个「分区 × 重量段」取参与渠道中的**最低买价**。
|
||||||
毛利率硬计算:`sell = ceil(buy / (1 - m), 分)`;禁止以 AI 填数当唯一真相。
|
毛利率硬计算:`sell = ceil(buy / (1 - m), 分)`;禁止以 AI 填数当唯一真相。
|
||||||
|
|
||||||
|
## 更新买价 · 报价表 AI
|
||||||
|
|
||||||
|
| 项 | 说明 |
|
||||||
|
|----|------|
|
||||||
|
| 入口 | 工作台 Tab「更新买价」 |
|
||||||
|
| 本地解析 | `channelQuoteLocalParse.ts`:表头识别公斤+票费 / 一口价(含并排国家列、PAK·WPX);上传后自动跑 |
|
||||||
|
| Skill / AI | `.cursor/skills/oms-channel-quote-extract`;`channelQuoteAiSkill.ts`;场景 `channelQuoteImport`;**仅补齐本地失败 sheet** |
|
||||||
|
| 候选/融合 | `channelQuoteCandidate.ts` + `channelQuoteApply.ts`(前端硬算,AI 不决策融合) |
|
||||||
|
| 一口价 `flat` | 包裹重量点/段 → 总价;运费 `calculationFormula=total` |
|
||||||
|
| 公斤+票费 `unit_plus_fee` | 运费 RMB/KG(`unit`)+ 处理费/操作费 RMB/票(`total`,需渠道已有操作费价格项) |
|
||||||
|
| 融合方式 | `replaceMatched` 覆盖匹配项重建重量段;`intersectionOnly` 只改交集格子;`abandon` 不写库 |
|
||||||
|
| Sheet | 名称常含渠道码;一 sheet 多「对接代码」拆多条;目录/附加费/邮编等默认不勾选 |
|
||||||
|
| 识别性能 | 主路径本地规则;AI 补齐默认并发 3,瘦身 TSV(约 12k 字) |
|
||||||
|
| 写库 | `POST /channel/service-channel/price/save`,默认草稿;可选发布 |
|
||||||
|
| 非目标 | 自动建分区/价格项、偏远邮编入库、AI 直接改卖价或替你确认融合 |
|
||||||
|
|
||||||
## 与发布 / 审批衔接
|
## 与发布 / 审批衔接
|
||||||
|
|
||||||
| 步骤 | 位置 | 说明 |
|
| 步骤 | 位置 | 说明 |
|
||||||
|------|------|------|
|
|------|------|------|
|
||||||
| 生成草稿 | 定价工作台 → 回写草稿 | `POST /channel/pricing-workbench/apply`,`Publish=false` |
|
| 更新渠道买价 | 定价工作台「更新买价」Tab | 四步后融合写入草稿或发布 |
|
||||||
|
| 生成卖价草稿 | 定价工作台 → 回写草稿 | `POST /channel/pricing-workbench/apply`,`Publish=false` |
|
||||||
| AI 风险分析 | 销售产品 → 价格发布 | 沿用 `PricePublishAiAssistDrawer` / 发布风险 skill |
|
| AI 风险分析 | 销售产品 → 价格发布 | 沿用 `PricePublishAiAssistDrawer` / 发布风险 skill |
|
||||||
| 发布审批 | 销售产品现有流程 | `Channel.SalesProduct.PublishPrice` 审批定义 |
|
| 发布审批 | 销售产品现有流程 | `Channel.SalesProduct.PublishPrice` 审批定义 |
|
||||||
|
|
||||||
工作台 AI 默认收起;负责调毛利/排除渠道后触发同一套 preview 硬计算,以及解释相对现网卖价超阈值差异。正式出账仍以销售产品发布快照为准。
|
工作台 AI(调规则)默认收起;负责调毛利/排除渠道后触发同一套 preview 硬计算,以及解释相对现网卖价超阈值差异。正式出账仍以销售产品发布快照为准。
|
||||||
|
|
||||||
## 差异闸门
|
## 差异闸门
|
||||||
|
|
||||||
@ -36,9 +66,11 @@
|
|||||||
- 自动发布卖价、自动改排货分配
|
- 自动发布卖价、自动改排货分配
|
||||||
- 跨币种汇兑(币种不一致直接阻断)
|
- 跨币种汇兑(币种不一致直接阻断)
|
||||||
- 用 AI 替代计费引擎出账
|
- 用 AI 替代计费引擎出账
|
||||||
|
- 「更新买价」自动新建价格分区 / 价格项
|
||||||
|
|
||||||
## API
|
## API
|
||||||
|
|
||||||
- `GET /channel/pricing-workbench/channel-summaries?serviceChannelIds=1,2`
|
- `GET /channel/pricing-workbench/channel-summaries?serviceChannelIds=1,2`
|
||||||
- `POST /channel/pricing-workbench/preview`
|
- `POST /channel/pricing-workbench/preview`
|
||||||
- `POST /channel/pricing-workbench/apply`
|
- `POST /channel/pricing-workbench/apply`
|
||||||
|
- 更新买价复用:`GET /channel/service-channel/price/list`、`POST /channel/service-channel/price/save`
|
||||||
|
|||||||
@ -61,6 +61,7 @@ export type AiSkillItem = {
|
|||||||
export const AI_SKILL_SCENES = [
|
export const AI_SKILL_SCENES = [
|
||||||
{ value: 'pricePublish', label: '价格发布风险' },
|
{ value: 'pricePublish', label: '价格发布风险' },
|
||||||
{ value: 'pricingWorkbench', label: '定价工作台' },
|
{ value: 'pricingWorkbench', label: '定价工作台' },
|
||||||
|
{ value: 'channelQuoteImport', label: '渠道报价提取' },
|
||||||
{ value: 'autoTriggerFormula', label: '自动触发公式' },
|
{ value: 'autoTriggerFormula', label: '自动触发公式' },
|
||||||
{ value: 'billingConditionFormula', label: '计费条件公式' },
|
{ value: 'billingConditionFormula', label: '计费条件公式' },
|
||||||
{ value: 'receiverAddressParse', label: '收件地址解析' },
|
{ value: 'receiverAddressParse', label: '收件地址解析' },
|
||||||
|
|||||||
@ -6460,7 +6460,12 @@ export default {
|
|||||||
'channel.salesProducts.placeholder.productCode': 'Uppercase, digits, - only',
|
'channel.salesProducts.placeholder.productCode': 'Uppercase, digits, - only',
|
||||||
'channel.salesProducts.placeholder.productName': 'Enter product name',
|
'channel.salesProducts.placeholder.productName': 'Enter product name',
|
||||||
'channel.salesProducts.placeholder.productDescription': 'Customer-facing description (optional)',
|
'channel.salesProducts.placeholder.productDescription': 'Customer-facing description (optional)',
|
||||||
'channel.salesProducts.placeholder.preStorageScript': 'Script before order persistence (optional)',
|
'channel.salesProducts.placeholder.preStorageScript':
|
||||||
|
"e.g. 收件人地址1 = 收件人地址1 + ' ' + 收件人地址2",
|
||||||
|
'channel.salesProducts.preStorageScript.hint':
|
||||||
|
'Chinese assign: field = expr; changes are persisted on the order',
|
||||||
|
'channel.salesProducts.preStorageScript.fieldHint':
|
||||||
|
'Aligned with place-order fields; writable: addresses/declaration strings and L/W/H/actual weight',
|
||||||
'channel.salesProducts.tip.productCode':
|
'channel.salesProducts.tip.productCode':
|
||||||
'Rule: region/country code + 01 line/02 express/03 postal/04 packet + other.\nExample: US04-5DAY\nUppercase letters, digits, and - only; can be changed later via the edit action',
|
'Rule: region/country code + 01 line/02 express/03 postal/04 packet + other.\nExample: US04-5DAY\nUppercase letters, digits, and - only; can be changed later via the edit action',
|
||||||
'channel.salesProducts.form.editProductCode': 'Edit',
|
'channel.salesProducts.form.editProductCode': 'Edit',
|
||||||
@ -6474,7 +6479,8 @@ export default {
|
|||||||
'channel.salesProducts.tip.group': 'Used for website/admin grouping, e.g. express parcel',
|
'channel.salesProducts.tip.group': 'Used for website/admin grouping, e.g. express parcel',
|
||||||
'channel.salesProducts.tip.efficiency': 'Estimated transit days shown to customers',
|
'channel.salesProducts.tip.efficiency': 'Estimated transit days shown to customers',
|
||||||
'channel.salesProducts.tip.labelTemplate': 'System label template used when printing',
|
'channel.salesProducts.tip.labelTemplate': 'System label template used when printing',
|
||||||
'channel.salesProducts.tip.preStorageScript': 'Advanced: rewrite/validate order fields before save; leave empty if unused',
|
'channel.salesProducts.tip.preStorageScript':
|
||||||
|
'Rewrite recipient/sender fields before order persist (saved to DB); Chinese assign DSL; AI assisted',
|
||||||
'channel.salesProducts.form.placeholder.labelTemplate': 'Select label template (global default if empty)',
|
'channel.salesProducts.form.placeholder.labelTemplate': 'Select label template (global default if empty)',
|
||||||
'channel.salesProducts.form.blacklistArea': 'Blacklist area',
|
'channel.salesProducts.form.blacklistArea': 'Blacklist area',
|
||||||
'channel.salesProducts.form.remoteAreaDivision': 'Remote area division',
|
'channel.salesProducts.form.remoteAreaDivision': 'Remote area division',
|
||||||
@ -6652,7 +6658,16 @@ export default {
|
|||||||
'Weight rule for payable chargeable weight (independent of sales-product receivable weight)',
|
'Weight rule for payable chargeable weight (independent of sales-product receivable weight)',
|
||||||
'channel.serviceChannels.tip.weightRounding':
|
'channel.serviceChannels.tip.weightRounding':
|
||||||
'Weight rounding for payable chargeable weight (independent of sales-product receivable rounding)',
|
'Weight rounding for payable chargeable weight (independent of sales-product receivable rounding)',
|
||||||
'channel.serviceChannels.tip.preScript': 'Script to rewrite/validate fields before forecast; leave empty if unused',
|
'channel.serviceChannels.tip.preScript':
|
||||||
|
'Rewrite recipient/sender fields before downstream forecast (payload only, does not persist order); Chinese assign DSL; AI assisted',
|
||||||
|
'channel.serviceChannels.preScript.aiWrite': 'AI write script',
|
||||||
|
'channel.serviceChannels.preScript.insertField': 'Insert field',
|
||||||
|
'channel.serviceChannels.preScript.operators': 'Operators',
|
||||||
|
'channel.serviceChannels.preScript.fields': 'Fields',
|
||||||
|
'channel.serviceChannels.preScript.fieldHint':
|
||||||
|
'Aligned with place-order fields; writable: addresses/declaration strings and L/W/H/actual weight',
|
||||||
|
'channel.serviceChannels.preScript.hint':
|
||||||
|
'Chinese assign: field = expr; multi-line OK; affects forecast payload only',
|
||||||
'channel.serviceChannels.form.placeholder.input': 'Please enter',
|
'channel.serviceChannels.form.placeholder.input': 'Please enter',
|
||||||
'channel.serviceChannels.form.placeholder.select': 'Please select',
|
'channel.serviceChannels.form.placeholder.select': 'Please select',
|
||||||
'channel.serviceChannels.form.placeholder.min': 'Min',
|
'channel.serviceChannels.form.placeholder.min': 'Min',
|
||||||
@ -6660,7 +6675,8 @@ export default {
|
|||||||
'channel.serviceChannels.form.placeholder.selectForecastType': 'Please select forecast number type',
|
'channel.serviceChannels.form.placeholder.selectForecastType': 'Please select forecast number type',
|
||||||
'channel.serviceChannels.form.placeholder.forecastCode': 'Enter forecast channel code',
|
'channel.serviceChannels.form.placeholder.forecastCode': 'Enter forecast channel code',
|
||||||
'channel.serviceChannels.form.placeholder.description': 'Enter channel description',
|
'channel.serviceChannels.form.placeholder.description': 'Enter channel description',
|
||||||
'channel.serviceChannels.form.placeholder.preScript': 'Enter pre-forecast script',
|
'channel.serviceChannels.form.placeholder.preScript':
|
||||||
|
"e.g. 收件人地址1 = 收件人地址1 + ' ' + 收件人地址2",
|
||||||
'channel.serviceChannels.price.effectiveVersion': 'Effective version: {version}',
|
'channel.serviceChannels.price.effectiveVersion': 'Effective version: {version}',
|
||||||
'channel.serviceChannels.price.table.serialNo': 'No.',
|
'channel.serviceChannels.price.table.serialNo': 'No.',
|
||||||
'channel.serviceChannels.price.table.status': 'Status',
|
'channel.serviceChannels.price.table.status': 'Status',
|
||||||
|
|||||||
@ -6466,7 +6466,12 @@ export default {
|
|||||||
'channel.salesProducts.placeholder.productCode': '仅大写字母、数字、-',
|
'channel.salesProducts.placeholder.productCode': '仅大写字母、数字、-',
|
||||||
'channel.salesProducts.placeholder.productName': '请输入产品名称',
|
'channel.salesProducts.placeholder.productName': '请输入产品名称',
|
||||||
'channel.salesProducts.placeholder.productDescription': '面向客户的产品说明(选填)',
|
'channel.salesProducts.placeholder.productDescription': '面向客户的产品说明(选填)',
|
||||||
'channel.salesProducts.placeholder.preStorageScript': '订单落库前执行的脚本(选填)',
|
'channel.salesProducts.placeholder.preStorageScript':
|
||||||
|
"例:收件人地址1 = 收件人地址1 + ' ' + 收件人地址2",
|
||||||
|
'channel.salesProducts.preStorageScript.hint':
|
||||||
|
'中文赋值:字段 = 表达式;改写会写入订单',
|
||||||
|
'channel.salesProducts.preStorageScript.fieldHint':
|
||||||
|
'字段对齐下单页;可写收/发件、申报字符串与长宽高/实重;其它为只读引用',
|
||||||
'channel.salesProducts.tip.productCode':
|
'channel.salesProducts.tip.productCode':
|
||||||
'命名规则:地区/国家代码 + 01专线/02快递/03邮政/04小包 + 其他。\n示例:US04-5DAY\n仅支持大写字母、数字和 -;创建后可通过修改入口单独改代码',
|
'命名规则:地区/国家代码 + 01专线/02快递/03邮政/04小包 + 其他。\n示例:US04-5DAY\n仅支持大写字母、数字和 -;创建后可通过修改入口单独改代码',
|
||||||
'channel.salesProducts.form.editProductCode': '修改',
|
'channel.salesProducts.form.editProductCode': '修改',
|
||||||
@ -6480,7 +6485,8 @@ export default {
|
|||||||
'channel.salesProducts.tip.group': '用于官网/后台分组展示,如专线小包',
|
'channel.salesProducts.tip.group': '用于官网/后台分组展示,如专线小包',
|
||||||
'channel.salesProducts.tip.efficiency': '预计时效区间(天),展示给客户参考',
|
'channel.salesProducts.tip.efficiency': '预计时效区间(天),展示给客户参考',
|
||||||
'channel.salesProducts.tip.labelTemplate': '下单打印使用的系统面单模板',
|
'channel.salesProducts.tip.labelTemplate': '下单打印使用的系统面单模板',
|
||||||
'channel.salesProducts.tip.preStorageScript': '高级能力:落库前改写/校验订单字段,无脚本可留空',
|
'channel.salesProducts.tip.preStorageScript':
|
||||||
|
'下单落库前改写收/发件人字段并写入订单;中文赋值语法,可用 AI 生成',
|
||||||
'channel.salesProducts.form.blacklistArea': '黑名单区',
|
'channel.salesProducts.form.blacklistArea': '黑名单区',
|
||||||
'channel.salesProducts.form.remoteAreaDivision': '偏远分区',
|
'channel.salesProducts.form.remoteAreaDivision': '偏远分区',
|
||||||
'channel.salesProducts.form.priceArea': '价格分区',
|
'channel.salesProducts.form.priceArea': '价格分区',
|
||||||
@ -6655,7 +6661,16 @@ export default {
|
|||||||
'channel.serviceChannels.tip.blacklistArea': '收件地址命中该分区时跳过本渠道排货(与销售产品黑名单独立)',
|
'channel.serviceChannels.tip.blacklistArea': '收件地址命中该分区时跳过本渠道排货(与销售产品黑名单独立)',
|
||||||
'channel.serviceChannels.tip.weightRule': '应付计费重所用计重规则(与销售产品应收计重独立)',
|
'channel.serviceChannels.tip.weightRule': '应付计费重所用计重规则(与销售产品应收计重独立)',
|
||||||
'channel.serviceChannels.tip.weightRounding': '应付计费重所用计重进位(与销售产品应收进位独立)',
|
'channel.serviceChannels.tip.weightRounding': '应付计费重所用计重进位(与销售产品应收进位独立)',
|
||||||
'channel.serviceChannels.tip.preScript': '预报前改写/校验字段的脚本,无需求可留空',
|
'channel.serviceChannels.tip.preScript':
|
||||||
|
'预报推下游前改写收/发件人字段(仅影响本次报文,不回写订单);中文赋值语法,可用 AI 生成',
|
||||||
|
'channel.serviceChannels.preScript.aiWrite': 'AI 写脚本',
|
||||||
|
'channel.serviceChannels.preScript.insertField': '插入字段',
|
||||||
|
'channel.serviceChannels.preScript.operators': '运算符',
|
||||||
|
'channel.serviceChannels.preScript.fields': '字段',
|
||||||
|
'channel.serviceChannels.preScript.fieldHint':
|
||||||
|
'字段对齐下单页;可写收/发件、申报字符串与长宽高/实重;其它为只读引用',
|
||||||
|
'channel.serviceChannels.preScript.hint':
|
||||||
|
'中文赋值:字段 = 表达式;多行换行;只改预报报文',
|
||||||
'channel.serviceChannels.form.placeholder.input': '请输入',
|
'channel.serviceChannels.form.placeholder.input': '请输入',
|
||||||
'channel.serviceChannels.form.placeholder.select': '请选择',
|
'channel.serviceChannels.form.placeholder.select': '请选择',
|
||||||
'channel.serviceChannels.form.placeholder.min': '最小值',
|
'channel.serviceChannels.form.placeholder.min': '最小值',
|
||||||
@ -6663,7 +6678,8 @@ export default {
|
|||||||
'channel.serviceChannels.form.placeholder.selectForecastType': '请选择预报单号类型',
|
'channel.serviceChannels.form.placeholder.selectForecastType': '请选择预报单号类型',
|
||||||
'channel.serviceChannels.form.placeholder.forecastCode': '请输入预报渠道code',
|
'channel.serviceChannels.form.placeholder.forecastCode': '请输入预报渠道code',
|
||||||
'channel.serviceChannels.form.placeholder.description': '请输入渠道说明',
|
'channel.serviceChannels.form.placeholder.description': '请输入渠道说明',
|
||||||
'channel.serviceChannels.form.placeholder.preScript': '请输入预报前执行脚本',
|
'channel.serviceChannels.form.placeholder.preScript':
|
||||||
|
"例:收件人地址1 = 收件人地址1 + ' ' + 收件人地址2",
|
||||||
'channel.serviceChannels.price.effectiveVersion': '生效版本: {version}',
|
'channel.serviceChannels.price.effectiveVersion': '生效版本: {version}',
|
||||||
'channel.serviceChannels.price.table.serialNo': '序号',
|
'channel.serviceChannels.price.table.serialNo': '序号',
|
||||||
'channel.serviceChannels.price.table.status': '状态',
|
'channel.serviceChannels.price.table.status': '状态',
|
||||||
|
|||||||
@ -188,6 +188,8 @@ const props = defineProps<{
|
|||||||
shortSystemPrompt?: string
|
shortSystemPrompt?: string
|
||||||
/** 用户消息末尾输出格式提示 */
|
/** 用户消息末尾输出格式提示 */
|
||||||
outputHint?: string
|
outputHint?: string
|
||||||
|
/** 自定义字段目录拼接(如预报/落库脚本仅下单字段) */
|
||||||
|
appendCatalog?: (core: string) => string
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
const resolvedStorageKey = computed(() => props.storageKey || DEFAULT_STORAGE_KEY)
|
const resolvedStorageKey = computed(() => props.storageKey || DEFAULT_STORAGE_KEY)
|
||||||
@ -354,6 +356,7 @@ async function loadSkills() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function resolveSystemPrompt(): string {
|
function resolveSystemPrompt(): string {
|
||||||
|
const appendCatalog = props.appendCatalog || appendFormulaFieldCatalog
|
||||||
if (!sendSkill.value) {
|
if (!sendSkill.value) {
|
||||||
return (
|
return (
|
||||||
props.shortSystemPrompt ||
|
props.shortSystemPrompt ||
|
||||||
@ -362,7 +365,7 @@ function resolveSystemPrompt(): string {
|
|||||||
}
|
}
|
||||||
const fromList = skills.value.find((s) => s.skillKey === skillKey.value)
|
const fromList = skills.value.find((s) => s.skillKey === skillKey.value)
|
||||||
const content = String(fromList?.content || '').trim()
|
const content = String(fromList?.content || '').trim()
|
||||||
if (content) return appendFormulaFieldCatalog(content)
|
if (content) return appendCatalog(content)
|
||||||
if (props.fallbackSystemPrompt?.trim()) return props.fallbackSystemPrompt.trim()
|
if (props.fallbackSystemPrompt?.trim()) return props.fallbackSystemPrompt.trim()
|
||||||
return buildFormulaAiSystemPrompt()
|
return buildFormulaAiSystemPrompt()
|
||||||
}
|
}
|
||||||
|
|||||||
@ -104,6 +104,16 @@ export function appendFormulaFieldCatalog(core: string): string {
|
|||||||
|
|
||||||
export const FORMULA_AI_DEFAULT_SKILL_KEY = 'oms-auto-trigger-formula'
|
export const FORMULA_AI_DEFAULT_SKILL_KEY = 'oms-auto-trigger-formula'
|
||||||
|
|
||||||
|
function isAssignLine(line: string): boolean {
|
||||||
|
const i = line.indexOf('=')
|
||||||
|
if (i <= 0) return false
|
||||||
|
const prev = line[i - 1]
|
||||||
|
const next = line[i + 1]
|
||||||
|
if (prev === '!' || prev === '<' || prev === '>' || prev === '=') return false
|
||||||
|
if (next === '=') return false
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
/** 从 AI 回复中解析公式块 */
|
/** 从 AI 回复中解析公式块 */
|
||||||
export function parseAiFormulaReply(raw: string): ParsedAiFormula {
|
export function parseAiFormulaReply(raw: string): ParsedAiFormula {
|
||||||
const text = String(raw || '').trim()
|
const text = String(raw || '').trim()
|
||||||
@ -120,28 +130,47 @@ export function parseAiFormulaReply(raw: string): ParsedAiFormula {
|
|||||||
text.match(/验证样例[::]\s*(.+?)(?:\n|$)/)?.[1]?.trim() ??
|
text.match(/验证样例[::]\s*(.+?)(?:\n|$)/)?.[1]?.trim() ??
|
||||||
undefined
|
undefined
|
||||||
|
|
||||||
let expression =
|
// 预报前脚本:支持「脚本:」后多行赋值
|
||||||
text.match(/公式[::]\s*(.+?)(?:\n|$)/)?.[1]?.trim() ??
|
let expression = ''
|
||||||
''
|
const scriptBlock = text.match(/脚本[::]\s*\n?([\s\S]*?)(?=\n\s*说明[::]|$)/)
|
||||||
|
if (scriptBlock?.[1]?.trim()) {
|
||||||
|
expression = scriptBlock[1].trim()
|
||||||
|
}
|
||||||
|
|
||||||
if (!expression) {
|
if (!expression) {
|
||||||
// 尝试取 fenced code 或首行像公式的内容
|
expression = text.match(/公式[::]\s*(.+?)(?:\n|$)/)?.[1]?.trim() ?? ''
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!expression) {
|
||||||
|
// 尝试取 fenced code 或首行像公式/赋值的内容
|
||||||
const fence = text.match(/```(?:\w*)?\s*\n?([\s\S]*?)```/)
|
const fence = text.match(/```(?:\w*)?\s*\n?([\s\S]*?)```/)
|
||||||
if (fence?.[1]) {
|
if (fence?.[1]) {
|
||||||
const inner = fence[1].trim()
|
const inner = fence[1].trim()
|
||||||
expression =
|
expression =
|
||||||
|
inner.match(/脚本[::]\s*\n?([\s\S]*)/)?.[1]?.trim() ||
|
||||||
inner.match(/公式[::]\s*(.+?)(?:\n|$)/)?.[1]?.trim() ||
|
inner.match(/公式[::]\s*(.+?)(?:\n|$)/)?.[1]?.trim() ||
|
||||||
inner.split('\n').find((l) => /包含\(|\(\)|&&|\|\|/.test(l))?.trim() ||
|
inner
|
||||||
|
.split('\n')
|
||||||
|
.filter((l) => /包含\(|\(\)|&&|\|\|/.test(l) || isAssignLine(l))
|
||||||
|
.join('\n')
|
||||||
|
.trim() ||
|
||||||
''
|
''
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!expression) {
|
if (!expression) {
|
||||||
const candidate = text
|
const lines = text.split('\n').map((l) => l.trim())
|
||||||
.split('\n')
|
const assignLines = lines.filter(
|
||||||
.map((l) => l.trim())
|
(l) => isAssignLine(l) && !/^(时机|操作|说明|验证|脚本|公式)/.test(l),
|
||||||
.find((l) => /包含\(|\(\)|&&|\|\|/.test(l) && !/^(时机|操作|说明|验证)/.test(l))
|
)
|
||||||
expression = candidate || ''
|
if (assignLines.length) {
|
||||||
|
expression = assignLines.join('\n')
|
||||||
|
} else {
|
||||||
|
const candidate = lines.find(
|
||||||
|
(l) => /包含\(|\(\)|&&|\|\|/.test(l) && !/^(时机|操作|说明|验证)/.test(l),
|
||||||
|
)
|
||||||
|
expression = candidate || ''
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 去掉可能的围栏残片
|
// 去掉可能的围栏残片
|
||||||
|
|||||||
412
src/views/channel/pricingWorkbench/channelQuoteAiSkill.ts
Normal file
412
src/views/channel/pricingWorkbench/channelQuoteAiSkill.ts
Normal file
@ -0,0 +1,412 @@
|
|||||||
|
/**
|
||||||
|
* 定价工作台 Step 0:渠道报价表 AI 提取(与 .cursor/skills/oms-channel-quote-extract 对齐)
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type ChannelQuoteMode = 'flat' | 'unit_plus_fee'
|
||||||
|
|
||||||
|
export type ChannelQuoteRowRow = {
|
||||||
|
weightStart?: number | null
|
||||||
|
weightEnd: number
|
||||||
|
zoneHint?: string | null
|
||||||
|
freightPerKg?: number | null
|
||||||
|
handlingPerShipment?: number | null
|
||||||
|
registrationPerShipment?: number | null
|
||||||
|
flatTotal?: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ChannelQuoteExtracted = {
|
||||||
|
channelCodeHint?: string | null
|
||||||
|
channelNameHint?: string | null
|
||||||
|
serviceSubtype?: string | null
|
||||||
|
mode: ChannelQuoteMode
|
||||||
|
destinationHints?: string[]
|
||||||
|
rows: ChannelQuoteRowRow[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ChannelQuoteSheetExtract = {
|
||||||
|
sheetName: string
|
||||||
|
isPriceSheet: boolean
|
||||||
|
skipReason?: string | null
|
||||||
|
currency?: string | null
|
||||||
|
effectiveAt?: string | null
|
||||||
|
channelQuotes: ChannelQuoteExtracted[]
|
||||||
|
warnings?: string[]
|
||||||
|
/** 解析用 */
|
||||||
|
raw?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CHANNEL_QUOTE_AI_DEFAULT_SKILL_KEY = 'oms-channel-quote-extract'
|
||||||
|
export const CHANNEL_QUOTE_AI_SCENE = 'channelQuoteImport'
|
||||||
|
|
||||||
|
const NON_PRICE_SHEET_RE =
|
||||||
|
/目录|附加费|操作指南|偏远|邮编|增值服务|附录|说明|条款|服务邮编|商业派送服务邮编/i
|
||||||
|
|
||||||
|
const SKILL_CORE = `你是 OMS「渠道报价表提取」助手:从单个 Excel sheet 的 TSV 文本中提取可写入服务渠道买价的结构化报价。
|
||||||
|
|
||||||
|
## 硬约束
|
||||||
|
1. 只输出一个 JSON 对象(可用 \`\`\`json 包裹);禁止编造表中不存在的金额
|
||||||
|
2. 非报价 sheet:isPriceSheet=false,channelQuotes=[],写清 skipReason
|
||||||
|
3. 一 sheet 多个对接代码/渠道码必须拆成多个 channelQuotes
|
||||||
|
4. PAK/WPX 等服务分段标题写入 serviceSubtype,不要当成渠道码
|
||||||
|
5. 金额必须来自单元格;说明行、空行、偏远邮编清单、条款长文一律忽略
|
||||||
|
|
||||||
|
## mode
|
||||||
|
- flat:一口价(包裹重量点/段 → 总价),填 flatTotal;freightPerKg/handling* 为 null
|
||||||
|
- unit_plus_fee:运费 RMB/KG + 处理费/挂号费 RMB/票,填 freightPerKg / handlingPerShipment / registrationPerShipment
|
||||||
|
|
||||||
|
## 重量
|
||||||
|
- 区间 0-0.1 → weightStart=0, weightEnd=0.1
|
||||||
|
- 单点 0.5 → 至少 weightEnd=0.5;weightStart 可空
|
||||||
|
|
||||||
|
## JSON schema
|
||||||
|
{
|
||||||
|
"sheetName": "string",
|
||||||
|
"isPriceSheet": true,
|
||||||
|
"skipReason": null,
|
||||||
|
"currency": "CNY",
|
||||||
|
"effectiveAt": "YYYY-MM-DD或null",
|
||||||
|
"channelQuotes": [
|
||||||
|
{
|
||||||
|
"channelCodeHint": "3SZ51",
|
||||||
|
"channelNameHint": "名称提示",
|
||||||
|
"serviceSubtype": null,
|
||||||
|
"mode": "flat|unit_plus_fee",
|
||||||
|
"destinationHints": ["美国"],
|
||||||
|
"rows": [
|
||||||
|
{
|
||||||
|
"weightStart": 0,
|
||||||
|
"weightEnd": 0.1,
|
||||||
|
"zoneHint": "美国",
|
||||||
|
"freightPerKg": 86,
|
||||||
|
"handlingPerShipment": 30,
|
||||||
|
"registrationPerShipment": null,
|
||||||
|
"flatTotal": null
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"warnings": []
|
||||||
|
}
|
||||||
|
`
|
||||||
|
|
||||||
|
export function buildChannelQuoteAiSystemPrompt(): string {
|
||||||
|
return SKILL_CORE
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildChannelQuoteAiShortSystemPrompt(): string {
|
||||||
|
return (
|
||||||
|
'你是 OMS 渠道报价提取助手。对单个 sheet 的 TSV 输出 JSON:' +
|
||||||
|
'isPriceSheet、channelQuotes[].mode(flat|unit_plus_fee)、rows 重量与金额。禁止编造金额。'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildChannelQuoteUserContent(input: {
|
||||||
|
sheetName: string
|
||||||
|
sheetText: string
|
||||||
|
hint?: string
|
||||||
|
}): string {
|
||||||
|
const lines = [
|
||||||
|
`Sheet 名称:${input.sheetName}`,
|
||||||
|
'请提取该 sheet 的全部可写入买价的报价行。',
|
||||||
|
]
|
||||||
|
if (input.hint) lines.push(`补充说明:${input.hint}`)
|
||||||
|
lines.push('Sheet 内容(TSV):')
|
||||||
|
lines.push(input.sheetText)
|
||||||
|
return lines.join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 默认不勾选识别的非报价 sheet */
|
||||||
|
export function isLikelyNonPriceSheetName(name: string): boolean {
|
||||||
|
return NON_PRICE_SHEET_RE.test(String(name || '').trim())
|
||||||
|
}
|
||||||
|
|
||||||
|
function toNum(v: unknown): number | null {
|
||||||
|
if (v == null || v === '') return null
|
||||||
|
const n = typeof v === 'number' ? v : Number(String(v).replace(/,/g, '').trim())
|
||||||
|
return Number.isFinite(n) ? n : null
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeCurrency(raw: unknown): string {
|
||||||
|
const s = String(raw ?? '')
|
||||||
|
.trim()
|
||||||
|
.toUpperCase()
|
||||||
|
if (!s || s.includes('人民币') || s === 'RMB' || s === 'CNY' || String(raw).includes('人民币')) {
|
||||||
|
return 'CNY'
|
||||||
|
}
|
||||||
|
if (s === 'USD' || s.includes('美元')) return 'USD'
|
||||||
|
if (s === 'HKD' || String(raw).includes('港')) return 'HKD'
|
||||||
|
return String(raw).trim() || 'CNY'
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeMode(raw: unknown): ChannelQuoteMode {
|
||||||
|
const s = String(raw || '')
|
||||||
|
.trim()
|
||||||
|
.toLowerCase()
|
||||||
|
if (s === 'flat' || s.includes('一口') || s.includes('总价')) return 'flat'
|
||||||
|
return 'unit_plus_fee'
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeRow(raw: any): ChannelQuoteRowRow | null {
|
||||||
|
if (!raw || typeof raw !== 'object') return null
|
||||||
|
const weightEnd =
|
||||||
|
toNum(raw.weightEnd ?? raw.WeightEnd ?? raw.weight ?? raw.Weight ?? raw.maxWeight) ?? null
|
||||||
|
if (weightEnd == null || weightEnd <= 0) return null
|
||||||
|
const weightStart = toNum(raw.weightStart ?? raw.WeightStart ?? raw.minWeight)
|
||||||
|
return {
|
||||||
|
weightStart: weightStart != null && weightStart >= 0 ? weightStart : null,
|
||||||
|
weightEnd,
|
||||||
|
zoneHint:
|
||||||
|
raw.zoneHint != null
|
||||||
|
? String(raw.zoneHint)
|
||||||
|
: raw.country != null
|
||||||
|
? String(raw.country)
|
||||||
|
: raw.destination != null
|
||||||
|
? String(raw.destination)
|
||||||
|
: null,
|
||||||
|
freightPerKg: toNum(raw.freightPerKg ?? raw.freight ?? raw.unitPrice),
|
||||||
|
handlingPerShipment: toNum(
|
||||||
|
raw.handlingPerShipment ?? raw.handling ?? raw.processFee ?? raw.操作费,
|
||||||
|
),
|
||||||
|
registrationPerShipment: toNum(
|
||||||
|
raw.registrationPerShipment ?? raw.registration ?? raw.挂号费,
|
||||||
|
),
|
||||||
|
flatTotal: toNum(raw.flatTotal ?? raw.total ?? raw.一口价),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeChannelQuote(raw: any): ChannelQuoteExtracted | null {
|
||||||
|
if (!raw || typeof raw !== 'object') return null
|
||||||
|
const rowsRaw = Array.isArray(raw.rows) ? raw.rows : []
|
||||||
|
const rows = rowsRaw.map(normalizeRow).filter(Boolean) as ChannelQuoteRowRow[]
|
||||||
|
if (!rows.length) return null
|
||||||
|
const mode = normalizeMode(raw.mode)
|
||||||
|
return {
|
||||||
|
channelCodeHint: raw.channelCodeHint != null ? String(raw.channelCodeHint) : null,
|
||||||
|
channelNameHint: raw.channelNameHint != null ? String(raw.channelNameHint) : null,
|
||||||
|
serviceSubtype: raw.serviceSubtype != null ? String(raw.serviceSubtype) : null,
|
||||||
|
mode,
|
||||||
|
destinationHints: Array.isArray(raw.destinationHints)
|
||||||
|
? raw.destinationHints.map((x: any) => String(x)).filter(Boolean)
|
||||||
|
: [],
|
||||||
|
rows,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从模型回复解析 sheet 提取结果 */
|
||||||
|
export function parseChannelQuoteAiReply(
|
||||||
|
raw: string,
|
||||||
|
fallbackSheetName?: string,
|
||||||
|
): ChannelQuoteSheetExtract {
|
||||||
|
const text = String(raw || '').trim()
|
||||||
|
const empty: ChannelQuoteSheetExtract = {
|
||||||
|
sheetName: fallbackSheetName || '',
|
||||||
|
isPriceSheet: false,
|
||||||
|
skipReason: '未能解析 AI 输出',
|
||||||
|
channelQuotes: [],
|
||||||
|
warnings: [],
|
||||||
|
raw: text,
|
||||||
|
}
|
||||||
|
if (!text) return empty
|
||||||
|
|
||||||
|
const jsonMatch =
|
||||||
|
text.match(/```json\s*([\s\S]*?)```/i) ||
|
||||||
|
text.match(/\{[\s\S]*"isPriceSheet"[\s\S]*\}/) ||
|
||||||
|
text.match(/\{[\s\S]*"channelQuotes"[\s\S]*\}/)
|
||||||
|
if (!jsonMatch) return empty
|
||||||
|
|
||||||
|
try {
|
||||||
|
const body = jsonMatch[1] || jsonMatch[0]
|
||||||
|
const obj = JSON.parse(body)
|
||||||
|
const quotesRaw = Array.isArray(obj.channelQuotes) ? obj.channelQuotes : []
|
||||||
|
const channelQuotes = quotesRaw
|
||||||
|
.map(normalizeChannelQuote)
|
||||||
|
.filter(Boolean) as ChannelQuoteExtracted[]
|
||||||
|
const isPriceSheet =
|
||||||
|
typeof obj.isPriceSheet === 'boolean' ? obj.isPriceSheet : channelQuotes.length > 0
|
||||||
|
return {
|
||||||
|
sheetName: String(obj.sheetName || fallbackSheetName || ''),
|
||||||
|
isPriceSheet,
|
||||||
|
skipReason: obj.skipReason != null ? String(obj.skipReason) : null,
|
||||||
|
currency: normalizeCurrency(obj.currency),
|
||||||
|
effectiveAt: obj.effectiveAt != null ? String(obj.effectiveAt) : null,
|
||||||
|
channelQuotes,
|
||||||
|
warnings: Array.isArray(obj.warnings) ? obj.warnings.map((x: any) => String(x)) : [],
|
||||||
|
raw: text,
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return empty
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const SHEET_TEXT_MAX = 28_000
|
||||||
|
/** 送给 AI 的更瘦上限:降 token、提速 */
|
||||||
|
const SHEET_AI_TEXT_MAX = 12_000
|
||||||
|
const SHEET_AI_MAX_ROWS = 180
|
||||||
|
const SHEET_AI_CELL_MAX = 64
|
||||||
|
|
||||||
|
function cellToPlain(c: unknown, maxLen?: number): string {
|
||||||
|
if (c == null) return ''
|
||||||
|
let s = String(c).replace(/\t/g, ' ').replace(/\r?\n/g, ' ').trim()
|
||||||
|
if (maxLen != null && s.length > maxLen) s = `${s.slice(0, maxLen)}…`
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 条款/说明行:长文且几乎无报价数字结构 */
|
||||||
|
function looksLikeTermsRow(cells: string[]): boolean {
|
||||||
|
const joined = cells.join(' ')
|
||||||
|
if (joined.length < 80) return false
|
||||||
|
const hasPriceShape = /\d+(\.\d+)?/.test(joined) && cells.filter((c) => /^-?\d+(\.\d+)?$/.test(c)).length >= 2
|
||||||
|
if (hasPriceShape) return false
|
||||||
|
return /条款|截单|赔偿|注[::]|请您|服务范围|本公司保留|附加费及规定|操作指南/.test(joined) || joined.length > 160
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 将 sheet 二维数组压成 TSV,控制 token */
|
||||||
|
export function sheetMatrixToTsv(
|
||||||
|
matrix: (string | number | null | undefined)[][],
|
||||||
|
opts?: { maxChars?: number; maxRows?: number; slimForAi?: boolean },
|
||||||
|
): { text: string; truncated: boolean; rowCount: number; colCount: number } {
|
||||||
|
const slim = Boolean(opts?.slimForAi)
|
||||||
|
const maxChars = opts?.maxChars ?? (slim ? SHEET_AI_TEXT_MAX : SHEET_TEXT_MAX)
|
||||||
|
const maxRows = opts?.maxRows ?? (slim ? SHEET_AI_MAX_ROWS : 400)
|
||||||
|
const cellMax = slim ? SHEET_AI_CELL_MAX : undefined
|
||||||
|
|
||||||
|
const raw = matrix || []
|
||||||
|
// 仅保留在前若干行出现过非空值的列,去掉空白列
|
||||||
|
const probe = raw.slice(0, Math.min(raw.length, 120))
|
||||||
|
const maxCol = probe.reduce((m, r) => Math.max(m, (r || []).length), 0)
|
||||||
|
const colKeep: boolean[] = Array.from({ length: maxCol }, (_, c) =>
|
||||||
|
probe.some((r) => {
|
||||||
|
const v = r?.[c]
|
||||||
|
return v != null && String(v).trim() !== ''
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const lines: string[] = []
|
||||||
|
let truncated = false
|
||||||
|
let colCount = 0
|
||||||
|
let kept = 0
|
||||||
|
for (let i = 0; i < raw.length; i++) {
|
||||||
|
if (kept >= maxRows) {
|
||||||
|
truncated = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
const row = raw[i] || []
|
||||||
|
const cells: string[] = []
|
||||||
|
for (let c = 0; c < maxCol; c++) {
|
||||||
|
if (slim && colKeep[c] === false) continue
|
||||||
|
cells.push(cellToPlain(row[c], cellMax))
|
||||||
|
}
|
||||||
|
while (cells.length && cells[cells.length - 1] === '') cells.pop()
|
||||||
|
if (!cells.some((c) => c.trim())) continue
|
||||||
|
if (slim && looksLikeTermsRow(cells)) {
|
||||||
|
truncated = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
colCount = Math.max(colCount, cells.length)
|
||||||
|
lines.push(cells.join('\t'))
|
||||||
|
kept += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
let text = lines.join('\n')
|
||||||
|
if (raw.length > maxRows) truncated = true
|
||||||
|
if (text.length > maxChars) {
|
||||||
|
text = text.slice(0, maxChars) + '\n…(内容已截断)'
|
||||||
|
truncated = true
|
||||||
|
}
|
||||||
|
return { text, truncated, rowCount: lines.length, colCount }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 并发池:保持结果顺序 */
|
||||||
|
export async function mapWithConcurrency<T, R>(
|
||||||
|
items: T[],
|
||||||
|
concurrency: number,
|
||||||
|
worker: (item: T, index: number) => Promise<R>,
|
||||||
|
): Promise<R[]> {
|
||||||
|
const n = Math.max(1, Math.min(concurrency, items.length || 1))
|
||||||
|
const results: R[] = new Array(items.length)
|
||||||
|
let next = 0
|
||||||
|
async function runOne() {
|
||||||
|
while (next < items.length) {
|
||||||
|
const i = next++
|
||||||
|
results[i] = await worker(items[i]!, i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await Promise.all(Array.from({ length: Math.min(n, items.length) }, () => runOne()))
|
||||||
|
return results
|
||||||
|
}
|
||||||
|
|
||||||
|
export type WorkbookSheetPreview = {
|
||||||
|
name: string
|
||||||
|
selected: boolean
|
||||||
|
likelyNonPrice: boolean
|
||||||
|
matrix: (string | number | null)[][]
|
||||||
|
/** 预览用较全 TSV */
|
||||||
|
tsv: string
|
||||||
|
/** 送给 AI 的瘦身 TSV */
|
||||||
|
tsvAi: string
|
||||||
|
truncated: boolean
|
||||||
|
rowCount: number
|
||||||
|
colCount: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 浏览器端解析 xlsx → 各 sheet 预览 */
|
||||||
|
export async function parseQuoteWorkbook(file: File | ArrayBuffer): Promise<WorkbookSheetPreview[]> {
|
||||||
|
const XLSX = await import('xlsx')
|
||||||
|
const buf = file instanceof File ? await file.arrayBuffer() : file
|
||||||
|
const wb = XLSX.read(buf, { type: 'array', cellDates: true })
|
||||||
|
const out: WorkbookSheetPreview[] = []
|
||||||
|
for (const name of wb.SheetNames || []) {
|
||||||
|
const ws = wb.Sheets[name]
|
||||||
|
const matrix = (XLSX.utils.sheet_to_json(ws, {
|
||||||
|
header: 1,
|
||||||
|
defval: null,
|
||||||
|
raw: true,
|
||||||
|
}) || []) as (string | number | null)[][]
|
||||||
|
const full = sheetMatrixToTsv(matrix)
|
||||||
|
const slim = sheetMatrixToTsv(matrix, { slimForAi: true })
|
||||||
|
const likelyNonPrice = isLikelyNonPriceSheetName(name)
|
||||||
|
out.push({
|
||||||
|
name,
|
||||||
|
selected: !likelyNonPrice && full.rowCount > 0,
|
||||||
|
likelyNonPrice,
|
||||||
|
matrix,
|
||||||
|
tsv: full.text,
|
||||||
|
tsvAi: slim.text,
|
||||||
|
truncated: full.truncated || slim.truncated,
|
||||||
|
rowCount: full.rowCount,
|
||||||
|
colCount: full.colCount,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** AI 识别默认并发(供应商限流友好) */
|
||||||
|
export const CHANNEL_QUOTE_AI_CONCURRENCY = 3
|
||||||
|
|
||||||
|
/** 从 sheet 名猜测渠道码(如 3SZ01-xxx) */
|
||||||
|
export function guessChannelCodeFromSheetName(sheetName: string): string | null {
|
||||||
|
const m = String(sheetName || '').match(/\b([0-9A-Za-z]{3,}[0-9A-Za-z]*)\b/)
|
||||||
|
if (!m) return null
|
||||||
|
// 优先匹配常见物流渠道码形态:字母数字混合且含数字
|
||||||
|
const all = String(sheetName).match(/[A-Za-z0-9]{3,}/g) || []
|
||||||
|
const withDigit = all.find((x) => /\d/.test(x) && /[A-Za-z]/.test(x))
|
||||||
|
return withDigit || m[1] || null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fuzzyScoreChannel(
|
||||||
|
hintCode: string | null | undefined,
|
||||||
|
hintName: string | null | undefined,
|
||||||
|
channelCode: string,
|
||||||
|
channelName: string,
|
||||||
|
): number {
|
||||||
|
const code = String(channelCode || '').trim().toLowerCase()
|
||||||
|
const name = String(channelName || '').trim().toLowerCase()
|
||||||
|
const hc = String(hintCode || '').trim().toLowerCase()
|
||||||
|
const hn = String(hintName || '').trim().toLowerCase()
|
||||||
|
let score = 0
|
||||||
|
if (hc && code && (code === hc || code.includes(hc) || hc.includes(code))) score += 100
|
||||||
|
if (hc && name && name.includes(hc)) score += 60
|
||||||
|
if (hn && name && (name === hn || name.includes(hn) || hn.includes(name))) score += 40
|
||||||
|
if (hn && code && code.includes(hn)) score += 20
|
||||||
|
return score
|
||||||
|
}
|
||||||
961
src/views/channel/pricingWorkbench/channelQuoteApply.ts
Normal file
961
src/views/channel/pricingWorkbench/channelQuoteApply.ts
Normal file
@ -0,0 +1,961 @@
|
|||||||
|
/**
|
||||||
|
* 报价 JSON → 渠道买价树(重建重量段 + 按价格项填 details)
|
||||||
|
*/
|
||||||
|
import { toEnableStatus, isEnableStatusEnabled } from '@/utils/enableStatus'
|
||||||
|
import {
|
||||||
|
formatWeightIntervalLeftOpenRightClosed,
|
||||||
|
parseWeightIntervalBounds,
|
||||||
|
} from '@/utils/priceWeightInterval'
|
||||||
|
import type { ChannelQuoteExtracted, ChannelQuotePriceRow } from './channelQuoteAiSkill'
|
||||||
|
|
||||||
|
function normalizePriceStatus(status: unknown): number {
|
||||||
|
if (typeof status === 'boolean') return toEnableStatus(status)
|
||||||
|
if (isEnableStatusEnabled(status)) return toEnableStatus(true)
|
||||||
|
const n = Number(status)
|
||||||
|
if (Number.isFinite(n) && n > 0) return n
|
||||||
|
return toEnableStatus(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ChannelOptionForQuote = {
|
||||||
|
id: number
|
||||||
|
channelCode: string
|
||||||
|
channelName: string
|
||||||
|
label: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ZoneMapEntry = {
|
||||||
|
zoneHint: string
|
||||||
|
/** OMS 价格分区因子值(通常是分区 id 字符串) */
|
||||||
|
zoneValue: string
|
||||||
|
zoneLabel: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type QuoteBindRow = {
|
||||||
|
key: string
|
||||||
|
sheetName: string
|
||||||
|
quote: ChannelQuoteExtracted
|
||||||
|
currency?: string | null
|
||||||
|
effectiveAt?: string | null
|
||||||
|
/** 绑定的 OMS 渠道 */
|
||||||
|
serviceChannelId?: number
|
||||||
|
/** zoneHint → zoneValue */
|
||||||
|
zoneMaps: ZoneMapEntry[]
|
||||||
|
/** 服务子类 → 货物类型因子值(可选) */
|
||||||
|
cargoValue?: string | null
|
||||||
|
enabled: boolean
|
||||||
|
warnings: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CostItemKind = 'freight' | 'handling' | 'registration' | 'other'
|
||||||
|
|
||||||
|
export function classifyCostItem(costItem: string, priceName?: string): CostItemKind {
|
||||||
|
const c = String(costItem || '').toLowerCase()
|
||||||
|
const n = String(priceName || '')
|
||||||
|
if (c === 'freight' || n.includes('运费')) return 'freight'
|
||||||
|
if (c === 'handling' || n.includes('操作') || n.includes('处理')) return 'handling'
|
||||||
|
if (n.includes('挂号') || c.includes('regist') || c.includes('guahao')) return 'registration'
|
||||||
|
return 'other'
|
||||||
|
}
|
||||||
|
|
||||||
|
function isWeightFactor(factor: string): boolean {
|
||||||
|
const f = String(factor || '').trim()
|
||||||
|
return f === 'weight' || f === '重量'
|
||||||
|
}
|
||||||
|
|
||||||
|
function isZoneFactor(factor: string): boolean {
|
||||||
|
const f = String(factor || '').trim()
|
||||||
|
return f === 'zone' || f === '分区' || f === '价格分区'
|
||||||
|
}
|
||||||
|
|
||||||
|
function isCargoFactor(factor: string): boolean {
|
||||||
|
const f = String(factor || '').trim()
|
||||||
|
return f === 'cargo' || f === '货物类型' || f === '货型'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 因素列在 factorValuesJson 中的中文键 */
|
||||||
|
export function factorJsonKey(factor: string): string {
|
||||||
|
const f = String(factor || '').trim()
|
||||||
|
if (isWeightFactor(f)) return '重量'
|
||||||
|
if (isZoneFactor(f)) return '价格分区'
|
||||||
|
if (isCargoFactor(f)) return '货物类型'
|
||||||
|
if (f === 'warehouse' || f === '仓库') return '仓库'
|
||||||
|
if (f === 'remoteZone' || f === '偏远分区') return '偏远分区'
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 将报价行重量规范为有序区间列表 (start-end] */
|
||||||
|
export function buildWeightIntervalsFromQuoteRows(
|
||||||
|
rows: ChannelQuotePriceRow[],
|
||||||
|
): { intervals: string[]; ends: number[] } {
|
||||||
|
const ends = [
|
||||||
|
...new Set(
|
||||||
|
rows
|
||||||
|
.map((r) => Number(r.weightEnd))
|
||||||
|
.filter((n) => Number.isFinite(n) && n > 0),
|
||||||
|
),
|
||||||
|
].sort((a, b) => a - b)
|
||||||
|
|
||||||
|
const intervals = ends.map((end, idx) => {
|
||||||
|
// 优先使用同行声明的 start(按 end 匹配最近一行)
|
||||||
|
const withStart = rows.find(
|
||||||
|
(r) =>
|
||||||
|
Number(r.weightEnd) === end &&
|
||||||
|
r.weightStart != null &&
|
||||||
|
Number.isFinite(Number(r.weightStart)),
|
||||||
|
)
|
||||||
|
const start =
|
||||||
|
withStart != null
|
||||||
|
? Number(withStart.weightStart)
|
||||||
|
: idx > 0
|
||||||
|
? ends[idx - 1]!
|
||||||
|
: 0
|
||||||
|
return formatWeightIntervalLeftOpenRightClosed(start, end)
|
||||||
|
})
|
||||||
|
return { intervals, ends }
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseFactorValuesJson(raw: unknown): Record<string, string> {
|
||||||
|
if (!raw) return {}
|
||||||
|
if (typeof raw === 'string') {
|
||||||
|
try {
|
||||||
|
const o = JSON.parse(raw)
|
||||||
|
return o && typeof o === 'object' ? (o as Record<string, string>) : {}
|
||||||
|
} catch {
|
||||||
|
return {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (typeof raw === 'object') return { ...(raw as Record<string, string>) }
|
||||||
|
return {}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ExistingPriceItem = {
|
||||||
|
id?: number | null
|
||||||
|
serialNumber?: number
|
||||||
|
status?: number | boolean
|
||||||
|
priceName?: string
|
||||||
|
costItem?: string
|
||||||
|
costUnit?: string
|
||||||
|
currency?: string
|
||||||
|
chargingCondition?: string | null
|
||||||
|
factors?: Array<{
|
||||||
|
id?: number
|
||||||
|
serialNumber?: number
|
||||||
|
factor?: string
|
||||||
|
factorValues?: string[]
|
||||||
|
}>
|
||||||
|
details?: Array<{
|
||||||
|
id?: number
|
||||||
|
factorValuesJson?: unknown
|
||||||
|
calculationFormula?: string
|
||||||
|
calculatedValue?: number | null
|
||||||
|
}>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ApplyPreviewLine = {
|
||||||
|
costItem: string
|
||||||
|
priceName: string
|
||||||
|
formula: string
|
||||||
|
zoneValue: string
|
||||||
|
zoneLabel: string
|
||||||
|
weightSegment: string
|
||||||
|
newValue: number
|
||||||
|
oldValue?: number | null
|
||||||
|
change: 'add' | 'update' | 'same'
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ApplyPreviewResult = {
|
||||||
|
serviceChannelId: number
|
||||||
|
weightIntervals: string[]
|
||||||
|
lines: ApplyPreviewLine[]
|
||||||
|
warnings: string[]
|
||||||
|
/** 可直接交给 saveServiceChannelPriceAll 的 prices */
|
||||||
|
prices: Record<string, any>[]
|
||||||
|
unmappedRows: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function findOldValue(
|
||||||
|
details: ExistingPriceItem['details'],
|
||||||
|
zoneKey: string,
|
||||||
|
zoneValue: string,
|
||||||
|
weightKey: string,
|
||||||
|
weightSegment: string,
|
||||||
|
): number | null {
|
||||||
|
if (!details?.length) return null
|
||||||
|
for (const d of details) {
|
||||||
|
const fj = parseFactorValuesJson(d.factorValuesJson)
|
||||||
|
const z = fj[zoneKey] ?? fj['价格分区'] ?? fj['分区'] ?? fj.zone
|
||||||
|
const w = fj[weightKey] ?? fj['重量'] ?? fj.weight
|
||||||
|
if (String(z) === String(zoneValue) && String(w) === String(weightSegment)) {
|
||||||
|
const n = Number(d.calculatedValue)
|
||||||
|
return Number.isFinite(n) ? n : null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveAmountForItem(
|
||||||
|
kind: CostItemKind,
|
||||||
|
mode: ChannelQuoteExtracted['mode'],
|
||||||
|
row: ChannelQuotePriceRow,
|
||||||
|
): { value: number | null; formula: string } {
|
||||||
|
if (kind === 'freight') {
|
||||||
|
if (mode === 'flat') {
|
||||||
|
const v = row.flatTotal
|
||||||
|
return { value: v != null && Number.isFinite(Number(v)) ? Number(v) : null, formula: 'total' }
|
||||||
|
}
|
||||||
|
const v = row.freightPerKg
|
||||||
|
return { value: v != null && Number.isFinite(Number(v)) ? Number(v) : null, formula: 'unit' }
|
||||||
|
}
|
||||||
|
if (kind === 'handling') {
|
||||||
|
const v = row.handlingPerShipment
|
||||||
|
return { value: v != null && Number.isFinite(Number(v)) ? Number(v) : null, formula: 'total' }
|
||||||
|
}
|
||||||
|
if (kind === 'registration') {
|
||||||
|
const v = row.registrationPerShipment
|
||||||
|
return { value: v != null && Number.isFinite(Number(v)) ? Number(v) : null, formula: 'total' }
|
||||||
|
}
|
||||||
|
return { value: null, formula: 'total' }
|
||||||
|
}
|
||||||
|
|
||||||
|
function zoneLabelOf(maps: ZoneMapEntry[], zoneValue: string): string {
|
||||||
|
return maps.find((m) => m.zoneValue === zoneValue)?.zoneLabel || zoneValue
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按绑定结果与现有价格项,生成回写预览与 save payload。
|
||||||
|
* - 重建重量因素值
|
||||||
|
* - 保留非重量/非分区因子原值的笛卡尔:仅 zone×weight(及可选 cargo)由报价驱动
|
||||||
|
* - 不自动新建价格项
|
||||||
|
*/
|
||||||
|
export function buildChannelPriceApplyPreview(input: {
|
||||||
|
serviceChannelId: number
|
||||||
|
bind: QuoteBindRow
|
||||||
|
existingPrices: ExistingPriceItem[]
|
||||||
|
}): ApplyPreviewResult {
|
||||||
|
const { serviceChannelId, bind, existingPrices } = input
|
||||||
|
const warnings: string[] = [...(bind.warnings || [])]
|
||||||
|
const quote = bind.quote
|
||||||
|
const { intervals: weightIntervals } = buildWeightIntervalsFromQuoteRows(quote.rows)
|
||||||
|
|
||||||
|
if (!weightIntervals.length) {
|
||||||
|
warnings.push('报价无有效重量段')
|
||||||
|
}
|
||||||
|
|
||||||
|
const zoneMaps = (bind.zoneMaps || []).filter((z) => z.zoneValue)
|
||||||
|
if (!zoneMaps.length) {
|
||||||
|
warnings.push('未配置分区映射,无法写入价格明细')
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasHandlingInQuote = quote.rows.some(
|
||||||
|
(r) => r.handlingPerShipment != null && Number(r.handlingPerShipment) > 0,
|
||||||
|
)
|
||||||
|
const hasRegInQuote = quote.rows.some(
|
||||||
|
(r) => r.registrationPerShipment != null && Number(r.registrationPerShipment) > 0,
|
||||||
|
)
|
||||||
|
|
||||||
|
const pricesOut: Record<string, any>[] = []
|
||||||
|
const lines: ApplyPreviewLine[] = []
|
||||||
|
let unmappedRows = 0
|
||||||
|
|
||||||
|
// 统计报价行因无映射丢弃
|
||||||
|
for (const row of quote.rows) {
|
||||||
|
const hint = String(row.zoneHint || quote.destinationHints?.[0] || '').trim()
|
||||||
|
if (hint && !zoneMaps.some((z) => z.zoneHint === hint || !z.zoneHint)) {
|
||||||
|
const hit = zoneMaps.find(
|
||||||
|
(z) =>
|
||||||
|
z.zoneHint === hint ||
|
||||||
|
z.zoneLabel.includes(hint) ||
|
||||||
|
hint.includes(z.zoneLabel) ||
|
||||||
|
z.zoneHint.includes(hint),
|
||||||
|
)
|
||||||
|
if (!hit) unmappedRows += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const kindsPresent = new Set(
|
||||||
|
(existingPrices || []).map((p) => classifyCostItem(String(p.costItem), p.priceName)),
|
||||||
|
)
|
||||||
|
if (hasHandlingInQuote && !kindsPresent.has('handling')) {
|
||||||
|
warnings.push('报价含处理费/操作费,但渠道未配置操作费价格项,请先在渠道设计中增加')
|
||||||
|
}
|
||||||
|
if (hasRegInQuote && !kindsPresent.has('registration')) {
|
||||||
|
warnings.push('报价含挂号费,但渠道未配置对应价格项,请先在渠道设计中增加')
|
||||||
|
}
|
||||||
|
if (!kindsPresent.has('freight') && (existingPrices || []).length === 0) {
|
||||||
|
warnings.push('渠道尚无价格项,请先在服务渠道中设计运费等价格项与分区')
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const price of existingPrices || []) {
|
||||||
|
const kind = classifyCostItem(String(price.costItem), price.priceName)
|
||||||
|
if (kind === 'other') {
|
||||||
|
// 非目标费用项原样保留
|
||||||
|
pricesOut.push(clonePriceKeepingDetails(price))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
const factors = (price.factors || []).map((f, idx) => ({
|
||||||
|
id: f.id,
|
||||||
|
serialNumber: f.serialNumber ?? idx + 1,
|
||||||
|
factor: String(f.factor || ''),
|
||||||
|
factorValues: [...(f.factorValues || [])],
|
||||||
|
}))
|
||||||
|
|
||||||
|
const weightFactor = factors.find((f) => isWeightFactor(f.factor))
|
||||||
|
const zoneFactor = factors.find((f) => isZoneFactor(f.factor))
|
||||||
|
const cargoFactor = factors.find((f) => isCargoFactor(f.factor))
|
||||||
|
|
||||||
|
if (!weightFactor) {
|
||||||
|
warnings.push(`价格项「${price.priceName || price.costItem}」无重量因素,已跳过改价`)
|
||||||
|
pricesOut.push(clonePriceKeepingDetails(price))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (!zoneFactor) {
|
||||||
|
warnings.push(`价格项「${price.priceName || price.costItem}」无价格分区因素,已跳过改价`)
|
||||||
|
pricesOut.push(clonePriceKeepingDetails(price))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// 重建重量段
|
||||||
|
weightFactor.factorValues = [...weightIntervals]
|
||||||
|
|
||||||
|
// 分区:保留已映射到的 zoneValue(取并集,不自动新建未知分区)
|
||||||
|
const mappedZoneValues = [...new Set(zoneMaps.map((z) => z.zoneValue).filter(Boolean))]
|
||||||
|
if (mappedZoneValues.length) {
|
||||||
|
const keep = (zoneFactor.factorValues || []).filter((v) => mappedZoneValues.includes(String(v)))
|
||||||
|
zoneFactor.factorValues = keep.length ? keep : mappedZoneValues
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cargoFactor && bind.cargoValue) {
|
||||||
|
if (!cargoFactor.factorValues.includes(bind.cargoValue)) {
|
||||||
|
cargoFactor.factorValues = [...cargoFactor.factorValues, bind.cargoValue]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const zoneKey = factorJsonKey(zoneFactor.factor)
|
||||||
|
const weightKey = factorJsonKey(weightFactor.factor)
|
||||||
|
const cargoKey = cargoFactor ? factorJsonKey(cargoFactor.factor) : null
|
||||||
|
|
||||||
|
const details: any[] = []
|
||||||
|
const oldDetails = price.details || []
|
||||||
|
|
||||||
|
// 笛卡尔:zone × weight(× cargo 若有绑定)
|
||||||
|
const zones = zoneFactor.factorValues.length ? zoneFactor.factorValues : mappedZoneValues
|
||||||
|
const cargos =
|
||||||
|
cargoFactor && bind.cargoValue
|
||||||
|
? [bind.cargoValue]
|
||||||
|
: cargoFactor?.factorValues?.length
|
||||||
|
? cargoFactor.factorValues
|
||||||
|
: [null]
|
||||||
|
|
||||||
|
for (const zoneValue of zones) {
|
||||||
|
const zoneHint =
|
||||||
|
zoneMaps.find((z) => z.zoneValue === zoneValue)?.zoneHint ||
|
||||||
|
zoneLabelOf(zoneMaps, zoneValue)
|
||||||
|
for (const weightSegment of weightIntervals) {
|
||||||
|
for (const cargo of cargos) {
|
||||||
|
const bounds = parseWeightIntervalBounds(weightSegment)
|
||||||
|
const quoteRows = quote.rows.filter((r) => {
|
||||||
|
const end = Number(r.weightEnd)
|
||||||
|
if (!bounds || !Number.isFinite(end)) return false
|
||||||
|
if (Math.abs(end - bounds.end) > 1e-9) return false
|
||||||
|
const rh = String(r.zoneHint || quote.destinationHints?.[0] || '').trim()
|
||||||
|
if (!rh) return true
|
||||||
|
// 行 zoneHint 需能映射到当前 zoneValue
|
||||||
|
const mapHit = zoneMaps.find(
|
||||||
|
(z) =>
|
||||||
|
z.zoneValue === zoneValue &&
|
||||||
|
(z.zoneHint === rh ||
|
||||||
|
z.zoneLabel.includes(rh) ||
|
||||||
|
rh.includes(z.zoneLabel) ||
|
||||||
|
z.zoneHint.includes(rh)),
|
||||||
|
)
|
||||||
|
return Boolean(mapHit) || (!zoneMaps.length && !rh)
|
||||||
|
})
|
||||||
|
// 若按 zoneHint 滤空,放宽:任意同重量行
|
||||||
|
const candidates =
|
||||||
|
quoteRows.length > 0
|
||||||
|
? quoteRows
|
||||||
|
: quote.rows.filter((r) => {
|
||||||
|
const end = Number(r.weightEnd)
|
||||||
|
return bounds && Number.isFinite(end) && Math.abs(end - bounds.end) < 1e-9
|
||||||
|
})
|
||||||
|
|
||||||
|
// 子类型:若报价带 serviceSubtype 且当前 cargo 不匹配则跳过金额(保留空?)——首期同一 cargo 绑定写全段
|
||||||
|
const picked = candidates[0]
|
||||||
|
if (!picked) continue
|
||||||
|
|
||||||
|
const { value, formula } = resolveAmountForItem(kind, quote.mode, picked)
|
||||||
|
if (value == null) continue
|
||||||
|
|
||||||
|
const factorValuesJson: Record<string, string> = {
|
||||||
|
[zoneKey]: String(zoneValue),
|
||||||
|
[weightKey]: weightSegment,
|
||||||
|
}
|
||||||
|
if (cargoKey && cargo != null) factorValuesJson[cargoKey] = String(cargo)
|
||||||
|
|
||||||
|
const oldValue = findOldValue(oldDetails, zoneKey, String(zoneValue), weightKey, weightSegment)
|
||||||
|
let change: ApplyPreviewLine['change'] = 'add'
|
||||||
|
if (oldValue != null) {
|
||||||
|
change = Math.abs(oldValue - value) < 1e-9 ? 'same' : 'update'
|
||||||
|
}
|
||||||
|
lines.push({
|
||||||
|
costItem: String(price.costItem || ''),
|
||||||
|
priceName: String(price.priceName || price.costItem || ''),
|
||||||
|
formula,
|
||||||
|
zoneValue: String(zoneValue),
|
||||||
|
zoneLabel: zoneLabelOf(zoneMaps, String(zoneValue)) || zoneHint,
|
||||||
|
weightSegment,
|
||||||
|
newValue: value,
|
||||||
|
oldValue,
|
||||||
|
change,
|
||||||
|
})
|
||||||
|
details.push({
|
||||||
|
factorValuesJson,
|
||||||
|
calculationFormula: formula,
|
||||||
|
calculatedValue: value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 其他因子(非 zone/weight/cargo)保留原 factorValues,但不参与本次笛卡尔——若存在则警告
|
||||||
|
const extraFactors = factors.filter(
|
||||||
|
(f) => !isWeightFactor(f.factor) && !isZoneFactor(f.factor) && !isCargoFactor(f.factor),
|
||||||
|
)
|
||||||
|
if (extraFactors.length) {
|
||||||
|
warnings.push(
|
||||||
|
`价格项「${price.priceName || price.costItem}」含额外因子(${extraFactors
|
||||||
|
.map((f) => f.factor)
|
||||||
|
.join(',')}),本次按分区×重量重写明细,请核对`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pricesOut.push({
|
||||||
|
id: price.id ?? undefined,
|
||||||
|
serialNumber: price.serialNumber ?? 1,
|
||||||
|
status: normalizePriceStatus(price.status),
|
||||||
|
priceName: price.priceName || '',
|
||||||
|
costItem: price.costItem || '',
|
||||||
|
costUnit: price.costUnit || '',
|
||||||
|
currency: bind.currency || price.currency || 'CNY',
|
||||||
|
chargingCondition: price.chargingCondition || '',
|
||||||
|
factors: factors.map((f) => ({
|
||||||
|
id: f.id,
|
||||||
|
serialNumber: f.serialNumber,
|
||||||
|
factor: f.factor,
|
||||||
|
factorValues: f.factorValues,
|
||||||
|
})),
|
||||||
|
details,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if (unmappedRows > 0) {
|
||||||
|
warnings.push(`${unmappedRows} 条报价行分区提示未能映射,已跳过对应金额(见分区映射)`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
serviceChannelId,
|
||||||
|
weightIntervals,
|
||||||
|
lines,
|
||||||
|
warnings: [...new Set(warnings)],
|
||||||
|
prices: pricesOut,
|
||||||
|
unmappedRows,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function clonePriceKeepingDetails(price: ExistingPriceItem): Record<string, any> {
|
||||||
|
return {
|
||||||
|
id: price.id ?? undefined,
|
||||||
|
serialNumber: price.serialNumber ?? 1,
|
||||||
|
status: normalizePriceStatus(price.status),
|
||||||
|
priceName: price.priceName || '',
|
||||||
|
costItem: price.costItem || '',
|
||||||
|
costUnit: price.costUnit || '',
|
||||||
|
currency: price.currency || 'CNY',
|
||||||
|
chargingCondition: price.chargingCondition || '',
|
||||||
|
factors: (price.factors || []).map((f, idx) => ({
|
||||||
|
id: f.id,
|
||||||
|
serialNumber: f.serialNumber ?? idx + 1,
|
||||||
|
factor: f.factor,
|
||||||
|
factorValues: [...(f.factorValues || [])],
|
||||||
|
})),
|
||||||
|
details: (price.details || []).map((d) => ({
|
||||||
|
id: d.id,
|
||||||
|
factorValuesJson: parseFactorValuesJson(d.factorValuesJson),
|
||||||
|
calculationFormula: d.calculationFormula || 'total',
|
||||||
|
calculatedValue: d.calculatedValue ?? 0,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 自动建议分区映射:zoneHint → 已有分区选项 */
|
||||||
|
export function suggestZoneMaps(
|
||||||
|
hints: string[],
|
||||||
|
zoneOptions: Array<{ value: string; label: string }>,
|
||||||
|
): ZoneMapEntry[] {
|
||||||
|
const uniq = [...new Set(hints.map((h) => String(h || '').trim()).filter(Boolean))]
|
||||||
|
return uniq.map((hint) => {
|
||||||
|
const lower = hint.toLowerCase()
|
||||||
|
const hit =
|
||||||
|
zoneOptions.find((z) => z.label === hint || String(z.value) === hint) ||
|
||||||
|
zoneOptions.find(
|
||||||
|
(z) =>
|
||||||
|
z.label.toLowerCase().includes(lower) ||
|
||||||
|
lower.includes(z.label.toLowerCase()) ||
|
||||||
|
String(z.value).toLowerCase().includes(lower),
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
zoneHint: hint,
|
||||||
|
zoneValue: hit ? String(hit.value) : '',
|
||||||
|
zoneLabel: hit ? hit.label : '',
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function collectZoneHints(quote: ChannelQuoteExtracted): string[] {
|
||||||
|
const hints: string[] = []
|
||||||
|
for (const d of quote.destinationHints || []) {
|
||||||
|
if (d) hints.push(String(d))
|
||||||
|
}
|
||||||
|
for (const r of quote.rows || []) {
|
||||||
|
if (r.zoneHint) hints.push(String(r.zoneHint))
|
||||||
|
}
|
||||||
|
return [...new Set(hints.map((h) => h.trim()).filter(Boolean))]
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MergeMode = 'replaceMatched' | 'intersectionOnly' | 'abandon'
|
||||||
|
|
||||||
|
export type CompareDiffLine = {
|
||||||
|
costItem: string
|
||||||
|
priceName: string
|
||||||
|
kind: CostItemKind
|
||||||
|
formula: string
|
||||||
|
zoneHint: string
|
||||||
|
zoneValue: string
|
||||||
|
zoneLabel: string
|
||||||
|
weightSegment: string
|
||||||
|
oldValue?: number | null
|
||||||
|
newValue?: number | null
|
||||||
|
/** add=仅候选有 / remove=仅现网有 / update / same / unmapped=候选未映射分区 */
|
||||||
|
change: 'add' | 'remove' | 'update' | 'same' | 'unmapped'
|
||||||
|
deltaRatio?: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CompareDiffResult = {
|
||||||
|
lines: CompareDiffLine[]
|
||||||
|
unmappedLines: CompareDiffLine[]
|
||||||
|
warnings: string[]
|
||||||
|
stats: {
|
||||||
|
addCount: number
|
||||||
|
removeCount: number
|
||||||
|
updateCount: number
|
||||||
|
sameCount: number
|
||||||
|
unmappedCount: number
|
||||||
|
avgDeltaRatio: number | null
|
||||||
|
candidateWeights: string[]
|
||||||
|
existingWeights: string[]
|
||||||
|
addedWeights: string[]
|
||||||
|
removedWeights: string[]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapZoneHint(
|
||||||
|
hint: string,
|
||||||
|
zoneMaps: ZoneMapEntry[],
|
||||||
|
): ZoneMapEntry | null {
|
||||||
|
const h = String(hint || '').trim()
|
||||||
|
if (!h) return zoneMaps.find((z) => z.zoneValue) || null
|
||||||
|
return (
|
||||||
|
zoneMaps.find(
|
||||||
|
(z) =>
|
||||||
|
z.zoneValue &&
|
||||||
|
(z.zoneHint === h ||
|
||||||
|
z.zoneLabel.includes(h) ||
|
||||||
|
h.includes(z.zoneLabel) ||
|
||||||
|
z.zoneHint.includes(h)),
|
||||||
|
) || null
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function existingWeightsOf(prices: ExistingPriceItem[]): string[] {
|
||||||
|
const set = new Set<string>()
|
||||||
|
for (const p of prices) {
|
||||||
|
for (const f of p.factors || []) {
|
||||||
|
if (isWeightFactor(String(f.factor || ''))) {
|
||||||
|
;(f.factorValues || []).forEach((v) => set.add(String(v)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...set]
|
||||||
|
}
|
||||||
|
|
||||||
|
function findExistingDetailValue(
|
||||||
|
price: ExistingPriceItem,
|
||||||
|
zoneValue: string,
|
||||||
|
weightSegment: string,
|
||||||
|
): { value: number | null; formula: string } {
|
||||||
|
const zoneFactor = (price.factors || []).find((f) => isZoneFactor(String(f.factor || '')))
|
||||||
|
const weightFactor = (price.factors || []).find((f) => isWeightFactor(String(f.factor || '')))
|
||||||
|
const zoneKey = zoneFactor ? factorJsonKey(String(zoneFactor.factor)) : '价格分区'
|
||||||
|
const weightKey = weightFactor ? factorJsonKey(String(weightFactor.factor)) : '重量'
|
||||||
|
for (const d of price.details || []) {
|
||||||
|
const fj = parseFactorValuesJson(d.factorValuesJson)
|
||||||
|
const z = fj[zoneKey] ?? fj['价格分区'] ?? fj['分区'] ?? fj.zone
|
||||||
|
const w = fj[weightKey] ?? fj['重量'] ?? fj.weight
|
||||||
|
if (String(z) === String(zoneValue) && String(w) === String(weightSegment)) {
|
||||||
|
const n = Number(d.calculatedValue)
|
||||||
|
return {
|
||||||
|
value: Number.isFinite(n) ? n : null,
|
||||||
|
formula: String(d.calculationFormula || 'total'),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { value: null, formula: 'total' }
|
||||||
|
}
|
||||||
|
|
||||||
|
function weightsRoughEqual(a: string, b: string): boolean {
|
||||||
|
if (a === b) return true
|
||||||
|
const pa = parseWeightIntervalBounds(a)
|
||||||
|
const pb = parseWeightIntervalBounds(b)
|
||||||
|
if (!pa || !pb) return false
|
||||||
|
return Math.abs(pa.end - pb.end) < 1e-6 && Math.abs(pa.start - pb.start) < 1e-6
|
||||||
|
}
|
||||||
|
|
||||||
|
function findMatchingExistingWeight(candidateW: string, existing: string[]): string | null {
|
||||||
|
const hit = existing.find((w) => weightsRoughEqual(w, candidateW))
|
||||||
|
return hit || null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 候选买价 vs 现网买价对比(不写库)
|
||||||
|
* candidate 分区仍为 hint,经 zoneMaps 映射到 OMS zoneValue
|
||||||
|
*/
|
||||||
|
export function buildCompareDiff(input: {
|
||||||
|
candidate: {
|
||||||
|
weightIntervals: string[]
|
||||||
|
feeItems: Array<{
|
||||||
|
kind: CostItemKind
|
||||||
|
label: string
|
||||||
|
costItemCode: string
|
||||||
|
formula: string
|
||||||
|
cells: Array<{ zoneHint: string; weightSegment: string; value: number; formula: string }>
|
||||||
|
}>
|
||||||
|
currency?: string
|
||||||
|
}
|
||||||
|
existingPrices: ExistingPriceItem[]
|
||||||
|
zoneMaps: ZoneMapEntry[]
|
||||||
|
}): CompareDiffResult {
|
||||||
|
const { candidate, existingPrices, zoneMaps } = input
|
||||||
|
const warnings: string[] = []
|
||||||
|
const lines: CompareDiffLine[] = []
|
||||||
|
const unmappedLines: CompareDiffLine[] = []
|
||||||
|
const mappedZones = zoneMaps.filter((z) => z.zoneValue)
|
||||||
|
|
||||||
|
if (!mappedZones.length) warnings.push('请先完成分区映射后再对比')
|
||||||
|
|
||||||
|
const existingWeights = existingWeightsOf(existingPrices)
|
||||||
|
const candidateWeights = [...candidate.weightIntervals]
|
||||||
|
const addedWeights = candidateWeights.filter(
|
||||||
|
(w) => !existingWeights.some((e) => weightsRoughEqual(e, w)),
|
||||||
|
)
|
||||||
|
const removedWeights = existingWeights.filter(
|
||||||
|
(w) => !candidateWeights.some((c) => weightsRoughEqual(c, w)),
|
||||||
|
)
|
||||||
|
|
||||||
|
const kindsInExisting = new Map<CostItemKind, ExistingPriceItem>()
|
||||||
|
for (const p of existingPrices) {
|
||||||
|
const kind = classifyCostItem(String(p.costItem), p.priceName)
|
||||||
|
if (kind !== 'other' && !kindsInExisting.has(kind)) kindsInExisting.set(kind, p)
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const fee of candidate.feeItems) {
|
||||||
|
if (!kindsInExisting.has(fee.kind)) {
|
||||||
|
warnings.push(`候选含「${fee.label}」,但渠道未配置对应价格项`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 候选格子 → 对比
|
||||||
|
for (const fee of candidate.feeItems) {
|
||||||
|
const existing = kindsInExisting.get(fee.kind)
|
||||||
|
for (const cell of fee.cells) {
|
||||||
|
const zm = mapZoneHint(cell.zoneHint, mappedZones)
|
||||||
|
if (!zm) {
|
||||||
|
unmappedLines.push({
|
||||||
|
costItem: fee.costItemCode,
|
||||||
|
priceName: fee.label,
|
||||||
|
kind: fee.kind,
|
||||||
|
formula: cell.formula,
|
||||||
|
zoneHint: cell.zoneHint,
|
||||||
|
zoneValue: '',
|
||||||
|
zoneLabel: '',
|
||||||
|
weightSegment: cell.weightSegment,
|
||||||
|
newValue: cell.value,
|
||||||
|
oldValue: null,
|
||||||
|
change: 'unmapped',
|
||||||
|
})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const matchedW = existing
|
||||||
|
? findMatchingExistingWeight(cell.weightSegment, existingWeights) || cell.weightSegment
|
||||||
|
: cell.weightSegment
|
||||||
|
const old = existing
|
||||||
|
? findExistingDetailValue(existing, zm.zoneValue, matchedW)
|
||||||
|
: { value: null, formula: cell.formula }
|
||||||
|
let change: CompareDiffLine['change'] = 'add'
|
||||||
|
let deltaRatio: number | null = null
|
||||||
|
if (old.value != null) {
|
||||||
|
if (Math.abs(old.value - cell.value) < 1e-9) change = 'same'
|
||||||
|
else {
|
||||||
|
change = 'update'
|
||||||
|
if (old.value !== 0) deltaRatio = (cell.value - old.value) / Math.abs(old.value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines.push({
|
||||||
|
costItem: existing?.costItem || fee.costItemCode,
|
||||||
|
priceName: existing?.priceName || fee.label,
|
||||||
|
kind: fee.kind,
|
||||||
|
formula: cell.formula,
|
||||||
|
zoneHint: cell.zoneHint,
|
||||||
|
zoneValue: zm.zoneValue,
|
||||||
|
zoneLabel: zm.zoneLabel || zm.zoneValue,
|
||||||
|
weightSegment: cell.weightSegment,
|
||||||
|
oldValue: old.value,
|
||||||
|
newValue: cell.value,
|
||||||
|
change,
|
||||||
|
deltaRatio,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 现网有、候选无的格子 → remove(仅对匹配到的费用项)
|
||||||
|
for (const [kind, price] of kindsInExisting) {
|
||||||
|
const fee = candidate.feeItems.find((f) => f.kind === kind)
|
||||||
|
if (!fee) continue
|
||||||
|
const zoneFactor = (price.factors || []).find((f) => isZoneFactor(String(f.factor || '')))
|
||||||
|
const weightFactor = (price.factors || []).find((f) => isWeightFactor(String(f.factor || '')))
|
||||||
|
if (!zoneFactor || !weightFactor) continue
|
||||||
|
const zoneKey = factorJsonKey(String(zoneFactor.factor))
|
||||||
|
const weightKey = factorJsonKey(String(weightFactor.factor))
|
||||||
|
for (const d of price.details || []) {
|
||||||
|
const fj = parseFactorValuesJson(d.factorValuesJson)
|
||||||
|
const z = String(fj[zoneKey] ?? fj['价格分区'] ?? fj['分区'] ?? fj.zone ?? '')
|
||||||
|
const w = String(fj[weightKey] ?? fj['重量'] ?? fj.weight ?? '')
|
||||||
|
if (!z || !w) continue
|
||||||
|
// 仅关注已映射分区
|
||||||
|
if (!mappedZones.some((m) => m.zoneValue === z)) continue
|
||||||
|
const stillInCandidate = fee.cells.some((c) => {
|
||||||
|
const zm = mapZoneHint(c.zoneHint, mappedZones)
|
||||||
|
return zm?.zoneValue === z && weightsRoughEqual(c.weightSegment, w)
|
||||||
|
})
|
||||||
|
if (stillInCandidate) continue
|
||||||
|
const n = Number(d.calculatedValue)
|
||||||
|
lines.push({
|
||||||
|
costItem: String(price.costItem || ''),
|
||||||
|
priceName: String(price.priceName || price.costItem || ''),
|
||||||
|
kind,
|
||||||
|
formula: String(d.calculationFormula || 'total'),
|
||||||
|
zoneHint: mappedZones.find((m) => m.zoneValue === z)?.zoneHint || '',
|
||||||
|
zoneValue: z,
|
||||||
|
zoneLabel: zoneLabelOf(mappedZones, z),
|
||||||
|
weightSegment: w,
|
||||||
|
oldValue: Number.isFinite(n) ? n : null,
|
||||||
|
newValue: null,
|
||||||
|
change: 'remove',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const updates = lines.filter((l) => l.change === 'update' && l.deltaRatio != null)
|
||||||
|
const avgDeltaRatio =
|
||||||
|
updates.length > 0
|
||||||
|
? updates.reduce((s, l) => s + (l.deltaRatio || 0), 0) / updates.length
|
||||||
|
: null
|
||||||
|
|
||||||
|
return {
|
||||||
|
lines,
|
||||||
|
unmappedLines,
|
||||||
|
warnings: [...new Set(warnings)],
|
||||||
|
stats: {
|
||||||
|
addCount: lines.filter((l) => l.change === 'add').length,
|
||||||
|
removeCount: lines.filter((l) => l.change === 'remove').length,
|
||||||
|
updateCount: lines.filter((l) => l.change === 'update').length,
|
||||||
|
sameCount: lines.filter((l) => l.change === 'same').length,
|
||||||
|
unmappedCount: unmappedLines.length,
|
||||||
|
avgDeltaRatio,
|
||||||
|
candidateWeights,
|
||||||
|
existingWeights,
|
||||||
|
addedWeights,
|
||||||
|
removedWeights,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按融合模式生成 save payload
|
||||||
|
* - replaceMatched:匹配费用项按候选重建重量段+明细
|
||||||
|
* - intersectionOnly:保留现网重量/分区,只改两边都有的格子
|
||||||
|
*/
|
||||||
|
export function buildMergePayload(input: {
|
||||||
|
serviceChannelId: number
|
||||||
|
mergeMode: MergeMode
|
||||||
|
candidate: {
|
||||||
|
currency?: string
|
||||||
|
weightIntervals: string[]
|
||||||
|
feeItems: Array<{
|
||||||
|
kind: CostItemKind
|
||||||
|
label: string
|
||||||
|
costItemCode: string
|
||||||
|
formula: string
|
||||||
|
cells: Array<{ zoneHint: string; weightSegment: string; value: number; formula: string }>
|
||||||
|
}>
|
||||||
|
quote: ChannelQuoteExtracted
|
||||||
|
}
|
||||||
|
existingPrices: ExistingPriceItem[]
|
||||||
|
zoneMaps: ZoneMapEntry[]
|
||||||
|
cargoValue?: string | null
|
||||||
|
}): { prices: Record<string, any>[]; warnings: string[] } | null {
|
||||||
|
if (input.mergeMode === 'abandon') return null
|
||||||
|
|
||||||
|
const zoneMaps = (input.zoneMaps || []).filter((z) => z.zoneValue)
|
||||||
|
const warnings: string[] = []
|
||||||
|
if (!zoneMaps.length) {
|
||||||
|
warnings.push('无有效分区映射')
|
||||||
|
return { prices: [], warnings }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 复用覆盖逻辑:构造 QuoteBindRow + buildChannelPriceApplyPreview
|
||||||
|
if (input.mergeMode === 'replaceMatched') {
|
||||||
|
const bind: QuoteBindRow = {
|
||||||
|
key: 'merge',
|
||||||
|
sheetName: '',
|
||||||
|
quote: input.candidate.quote,
|
||||||
|
currency: input.candidate.currency,
|
||||||
|
serviceChannelId: input.serviceChannelId,
|
||||||
|
zoneMaps,
|
||||||
|
cargoValue: input.cargoValue,
|
||||||
|
enabled: true,
|
||||||
|
warnings: [],
|
||||||
|
}
|
||||||
|
const preview = buildChannelPriceApplyPreview({
|
||||||
|
serviceChannelId: input.serviceChannelId,
|
||||||
|
bind,
|
||||||
|
existingPrices: input.existingPrices,
|
||||||
|
})
|
||||||
|
return { prices: preview.prices, warnings: [...preview.warnings, ...warnings] }
|
||||||
|
}
|
||||||
|
|
||||||
|
// intersectionOnly
|
||||||
|
const pricesOut: Record<string, any>[] = []
|
||||||
|
for (const price of input.existingPrices || []) {
|
||||||
|
const kind = classifyCostItem(String(price.costItem), price.priceName)
|
||||||
|
if (kind === 'other') {
|
||||||
|
pricesOut.push(clonePriceKeepingDetails(price))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const fee = input.candidate.feeItems.find((f) => f.kind === kind)
|
||||||
|
if (!fee) {
|
||||||
|
pricesOut.push(clonePriceKeepingDetails(price))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
const factors = (price.factors || []).map((f, idx) => ({
|
||||||
|
id: f.id,
|
||||||
|
serialNumber: f.serialNumber ?? idx + 1,
|
||||||
|
factor: String(f.factor || ''),
|
||||||
|
factorValues: [...(f.factorValues || [])],
|
||||||
|
}))
|
||||||
|
const weightFactor = factors.find((f) => isWeightFactor(f.factor))
|
||||||
|
const zoneFactor = factors.find((f) => isZoneFactor(f.factor))
|
||||||
|
if (!weightFactor || !zoneFactor) {
|
||||||
|
pricesOut.push(clonePriceKeepingDetails(price))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
const zoneKey = factorJsonKey(zoneFactor.factor)
|
||||||
|
const weightKey = factorJsonKey(weightFactor.factor)
|
||||||
|
const details = (price.details || []).map((d) => {
|
||||||
|
const fj = parseFactorValuesJson(d.factorValuesJson)
|
||||||
|
const z = String(fj[zoneKey] ?? fj['价格分区'] ?? fj['分区'] ?? fj.zone ?? '')
|
||||||
|
const w = String(fj[weightKey] ?? fj['重量'] ?? fj.weight ?? '')
|
||||||
|
const hit = fee.cells.find((c) => {
|
||||||
|
const zm = mapZoneHint(c.zoneHint, zoneMaps)
|
||||||
|
return zm?.zoneValue === z && weightsRoughEqual(c.weightSegment, w)
|
||||||
|
})
|
||||||
|
if (!hit) {
|
||||||
|
return {
|
||||||
|
id: d.id,
|
||||||
|
factorValuesJson: fj,
|
||||||
|
calculationFormula: d.calculationFormula || 'total',
|
||||||
|
calculatedValue: d.calculatedValue ?? 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id: d.id,
|
||||||
|
factorValuesJson: fj,
|
||||||
|
calculationFormula: hit.formula,
|
||||||
|
calculatedValue: hit.value,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
pricesOut.push({
|
||||||
|
id: price.id ?? undefined,
|
||||||
|
serialNumber: price.serialNumber ?? 1,
|
||||||
|
status: normalizePriceStatus(price.status),
|
||||||
|
priceName: price.priceName || '',
|
||||||
|
costItem: price.costItem || '',
|
||||||
|
costUnit: price.costUnit || '',
|
||||||
|
currency: input.candidate.currency || price.currency || 'CNY',
|
||||||
|
chargingCondition: price.chargingCondition || '',
|
||||||
|
factors,
|
||||||
|
details,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return { prices: pricesOut, warnings }
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MergedPriceMatrixRow = {
|
||||||
|
key: string
|
||||||
|
priceName: string
|
||||||
|
costItem: string
|
||||||
|
zoneValue: string
|
||||||
|
zoneLabel: string
|
||||||
|
weightSegment: string
|
||||||
|
formula: string
|
||||||
|
value: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 将融合后的 prices 摊平为结果矩阵(融合后长什么样) */
|
||||||
|
export function flattenMergedPriceMatrix(
|
||||||
|
prices: Record<string, any>[],
|
||||||
|
zoneLabelByValue?: Record<string, string>,
|
||||||
|
): MergedPriceMatrixRow[] {
|
||||||
|
const rows: MergedPriceMatrixRow[] = []
|
||||||
|
;(prices || []).forEach((price, pi) => {
|
||||||
|
const priceName = String(price.priceName || '')
|
||||||
|
const costItem = String(price.costItem || '')
|
||||||
|
const factors = price.factors || []
|
||||||
|
const zoneFactor = factors.find((f: any) => isZoneFactor(String(f.factor || '')))
|
||||||
|
const weightFactor = factors.find((f: any) => isWeightFactor(String(f.factor || '')))
|
||||||
|
const zoneKey = zoneFactor ? factorJsonKey(String(zoneFactor.factor)) : '价格分区'
|
||||||
|
const weightKey = weightFactor ? factorJsonKey(String(weightFactor.factor)) : '重量'
|
||||||
|
for (const d of price.details || []) {
|
||||||
|
const fj = parseFactorValuesJson(d.factorValuesJson)
|
||||||
|
const zoneValue = String(fj[zoneKey] ?? fj['价格分区'] ?? fj['分区'] ?? fj.zone ?? '')
|
||||||
|
const weightSegment = String(fj[weightKey] ?? fj['重量'] ?? fj.weight ?? '')
|
||||||
|
if (!weightSegment) continue
|
||||||
|
const n = Number(d.calculatedValue)
|
||||||
|
rows.push({
|
||||||
|
key: `${pi}-${zoneValue}-${weightSegment}-${costItem}`,
|
||||||
|
priceName,
|
||||||
|
costItem,
|
||||||
|
zoneValue,
|
||||||
|
zoneLabel: zoneLabelByValue?.[zoneValue] || zoneValue || '—',
|
||||||
|
weightSegment,
|
||||||
|
formula: String(d.calculationFormula || 'total'),
|
||||||
|
value: Number.isFinite(n) ? n : 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return rows
|
||||||
|
}
|
||||||
249
src/views/channel/pricingWorkbench/channelQuoteCandidate.ts
Normal file
249
src/views/channel/pricingWorkbench/channelQuoteCandidate.ts
Normal file
@ -0,0 +1,249 @@
|
|||||||
|
/**
|
||||||
|
* 报价模型 → 候选买价(内存结构,未落库)
|
||||||
|
*/
|
||||||
|
import { parseWeightIntervalBounds } from '@/utils/priceWeightInterval'
|
||||||
|
import type { ChannelQuoteExtracted, ChannelQuoteMode } from './channelQuoteAiSkill'
|
||||||
|
import {
|
||||||
|
buildWeightIntervalsFromQuoteRows,
|
||||||
|
collectZoneHints,
|
||||||
|
type CostItemKind,
|
||||||
|
} from './channelQuoteApply'
|
||||||
|
|
||||||
|
export type QuoteModelCard = {
|
||||||
|
key: string
|
||||||
|
sheetName: string
|
||||||
|
currency?: string | null
|
||||||
|
effectiveAt?: string | null
|
||||||
|
quote: ChannelQuoteExtracted
|
||||||
|
selected: boolean
|
||||||
|
/** local=规则解析 ai=模型补齐 */
|
||||||
|
extractSource?: 'local' | 'ai'
|
||||||
|
/** 费用结构摘要 */
|
||||||
|
hasFreight: boolean
|
||||||
|
hasHandling: boolean
|
||||||
|
hasRegistration: boolean
|
||||||
|
weightEnds: number[]
|
||||||
|
zoneHints: string[]
|
||||||
|
rowCount: number
|
||||||
|
warnings: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CandidateFeeCell = {
|
||||||
|
zoneHint: string
|
||||||
|
weightSegment: string
|
||||||
|
value: number
|
||||||
|
formula: 'total' | 'unit'
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CandidateFeeItem = {
|
||||||
|
kind: CostItemKind
|
||||||
|
/** 展示名 */
|
||||||
|
label: string
|
||||||
|
/** 建议 costItem code */
|
||||||
|
costItemCode: string
|
||||||
|
formula: 'total' | 'unit'
|
||||||
|
cells: CandidateFeeCell[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CandidateBuyPrice = {
|
||||||
|
key: string
|
||||||
|
sheetName: string
|
||||||
|
channelCodeHint?: string | null
|
||||||
|
channelNameHint?: string | null
|
||||||
|
serviceSubtype?: string | null
|
||||||
|
mode: ChannelQuoteMode
|
||||||
|
currency: string
|
||||||
|
effectiveAt?: string | null
|
||||||
|
weightIntervals: string[]
|
||||||
|
zoneHints: string[]
|
||||||
|
feeItems: CandidateFeeItem[]
|
||||||
|
/** 源报价(融合时还要用) */
|
||||||
|
quote: ChannelQuoteExtracted
|
||||||
|
warnings: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildQuoteModelCard(input: {
|
||||||
|
key: string
|
||||||
|
sheetName: string
|
||||||
|
quote: ChannelQuoteExtracted
|
||||||
|
currency?: string | null
|
||||||
|
effectiveAt?: string | null
|
||||||
|
warnings?: string[]
|
||||||
|
extractSource?: 'local' | 'ai'
|
||||||
|
}): QuoteModelCard {
|
||||||
|
const { quote } = input
|
||||||
|
const { ends } = buildWeightIntervalsFromQuoteRows(quote.rows || [])
|
||||||
|
const zoneHints = collectZoneHints(quote)
|
||||||
|
const hasFreight =
|
||||||
|
quote.mode === 'flat'
|
||||||
|
? quote.rows.some((r) => r.flatTotal != null && Number(r.flatTotal) > 0)
|
||||||
|
: quote.rows.some((r) => r.freightPerKg != null && Number(r.freightPerKg) > 0)
|
||||||
|
const hasHandling = quote.rows.some(
|
||||||
|
(r) => r.handlingPerShipment != null && Number(r.handlingPerShipment) > 0,
|
||||||
|
)
|
||||||
|
const hasRegistration = quote.rows.some(
|
||||||
|
(r) => r.registrationPerShipment != null && Number(r.registrationPerShipment) > 0,
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
key: input.key,
|
||||||
|
sheetName: input.sheetName,
|
||||||
|
currency: input.currency,
|
||||||
|
effectiveAt: input.effectiveAt,
|
||||||
|
quote,
|
||||||
|
selected: true,
|
||||||
|
extractSource: input.extractSource,
|
||||||
|
hasFreight,
|
||||||
|
hasHandling,
|
||||||
|
hasRegistration,
|
||||||
|
weightEnds: ends,
|
||||||
|
zoneHints,
|
||||||
|
rowCount: quote.rows?.length || 0,
|
||||||
|
warnings: [...(input.warnings || [])],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function cellFor(
|
||||||
|
kind: CostItemKind,
|
||||||
|
mode: ChannelQuoteMode,
|
||||||
|
zoneHint: string,
|
||||||
|
weightSegment: string,
|
||||||
|
row: ChannelQuoteExtracted['rows'][number],
|
||||||
|
): CandidateFeeCell | null {
|
||||||
|
if (kind === 'freight') {
|
||||||
|
if (mode === 'flat') {
|
||||||
|
const v = row.flatTotal
|
||||||
|
if (v == null || !Number.isFinite(Number(v))) return null
|
||||||
|
return { zoneHint, weightSegment, value: Number(v), formula: 'total' }
|
||||||
|
}
|
||||||
|
const v = row.freightPerKg
|
||||||
|
if (v == null || !Number.isFinite(Number(v))) return null
|
||||||
|
return { zoneHint, weightSegment, value: Number(v), formula: 'unit' }
|
||||||
|
}
|
||||||
|
if (kind === 'handling') {
|
||||||
|
const v = row.handlingPerShipment
|
||||||
|
if (v == null || !Number.isFinite(Number(v))) return null
|
||||||
|
return { zoneHint, weightSegment, value: Number(v), formula: 'total' }
|
||||||
|
}
|
||||||
|
if (kind === 'registration') {
|
||||||
|
const v = row.registrationPerShipment
|
||||||
|
if (v == null || !Number.isFinite(Number(v))) return null
|
||||||
|
return { zoneHint, weightSegment, value: Number(v), formula: 'total' }
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** QuoteModel → 候选买价(OMS 同形内存结构,分区仍为 hint) */
|
||||||
|
export function buildCandidateBuyPrice(card: QuoteModelCard): CandidateBuyPrice {
|
||||||
|
const quote = card.quote
|
||||||
|
const { intervals } = buildWeightIntervalsFromQuoteRows(quote.rows || [])
|
||||||
|
const zoneHints = collectZoneHints(quote)
|
||||||
|
const defaultZone = zoneHints[0] || '默认'
|
||||||
|
const warnings = [...card.warnings]
|
||||||
|
|
||||||
|
if (!intervals.length) warnings.push('无有效重量段')
|
||||||
|
if (!card.hasFreight && !card.hasHandling && !card.hasRegistration) {
|
||||||
|
warnings.push('未识别到运费/处理费/挂号费金额')
|
||||||
|
}
|
||||||
|
|
||||||
|
const feeItems: CandidateFeeItem[] = []
|
||||||
|
|
||||||
|
const pushKind = (kind: CostItemKind, label: string, code: string) => {
|
||||||
|
const cells: CandidateFeeCell[] = []
|
||||||
|
for (const weightSegment of intervals) {
|
||||||
|
const bounds = parseWeightIntervalBounds(weightSegment)
|
||||||
|
if (!bounds) continue
|
||||||
|
for (const row of quote.rows || []) {
|
||||||
|
const end = Number(row.weightEnd)
|
||||||
|
if (!Number.isFinite(end) || Math.abs(end - bounds.end) > 1e-6) continue
|
||||||
|
const zh = String(row.zoneHint || defaultZone).trim() || defaultZone
|
||||||
|
const cell = cellFor(kind, quote.mode, zh, weightSegment, row)
|
||||||
|
if (!cell) continue
|
||||||
|
// 同 zone+weight 去重保留首个
|
||||||
|
if (cells.some((c) => c.zoneHint === cell.zoneHint && c.weightSegment === cell.weightSegment)) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
cells.push(cell)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!cells.length) return
|
||||||
|
const formula = cells[0]!.formula
|
||||||
|
feeItems.push({ kind, label, costItemCode: code, formula, cells })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (card.hasFreight || quote.mode === 'flat') {
|
||||||
|
pushKind('freight', '运费', 'freight')
|
||||||
|
}
|
||||||
|
if (card.hasHandling) pushKind('handling', '操作费', 'handling')
|
||||||
|
if (card.hasRegistration) pushKind('registration', '挂号费', 'registration')
|
||||||
|
|
||||||
|
return {
|
||||||
|
key: card.key,
|
||||||
|
sheetName: card.sheetName,
|
||||||
|
channelCodeHint: quote.channelCodeHint,
|
||||||
|
channelNameHint: quote.channelNameHint,
|
||||||
|
serviceSubtype: quote.serviceSubtype,
|
||||||
|
mode: quote.mode,
|
||||||
|
currency: card.currency || 'CNY',
|
||||||
|
effectiveAt: card.effectiveAt,
|
||||||
|
weightIntervals: intervals,
|
||||||
|
zoneHints: zoneHints.length ? zoneHints : [defaultZone],
|
||||||
|
feeItems,
|
||||||
|
quote,
|
||||||
|
warnings: [...new Set(warnings)],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 长说明型子类(PAK 袋尺寸文案)压缩为短标签 */
|
||||||
|
export function shortServiceSubtype(raw?: string | null): string {
|
||||||
|
const s = String(raw || '').trim()
|
||||||
|
if (!s) return ''
|
||||||
|
if (/^PAK/i.test(s)) return 'PAK'
|
||||||
|
if (/^WPX/i.test(s)) return 'WPX'
|
||||||
|
const m = s.match(/^([A-Za-z0-9_-]{2,12})/)
|
||||||
|
if (m && s.length > 16) return m[1]!
|
||||||
|
return s.length > 16 ? `${s.slice(0, 14)}…` : s
|
||||||
|
}
|
||||||
|
|
||||||
|
export function candidateDisplayTitle(c: CandidateBuyPrice): string {
|
||||||
|
const name = c.channelCodeHint || c.channelNameHint || '未命名'
|
||||||
|
const sub = shortServiceSubtype(c.serviceSubtype)
|
||||||
|
return sub ? `${name} · ${sub}` : String(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function candidateDisplayFullTitle(c: CandidateBuyPrice): string {
|
||||||
|
const name = c.channelCodeHint || c.channelNameHint || '未命名'
|
||||||
|
const sub = String(c.serviceSubtype || '').trim()
|
||||||
|
return sub ? `${name}(${sub})` : String(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 候选明细展平,供表格预览 */
|
||||||
|
export function flattenCandidateCells(c: CandidateBuyPrice): Array<{
|
||||||
|
feeLabel: string
|
||||||
|
kind: CostItemKind
|
||||||
|
zoneHint: string
|
||||||
|
weightSegment: string
|
||||||
|
formula: string
|
||||||
|
value: number
|
||||||
|
}> {
|
||||||
|
const rows: Array<{
|
||||||
|
feeLabel: string
|
||||||
|
kind: CostItemKind
|
||||||
|
zoneHint: string
|
||||||
|
weightSegment: string
|
||||||
|
formula: string
|
||||||
|
value: number
|
||||||
|
}> = []
|
||||||
|
for (const fee of c.feeItems) {
|
||||||
|
for (const cell of fee.cells) {
|
||||||
|
rows.push({
|
||||||
|
feeLabel: fee.label,
|
||||||
|
kind: fee.kind,
|
||||||
|
zoneHint: cell.zoneHint,
|
||||||
|
weightSegment: cell.weightSegment,
|
||||||
|
formula: cell.formula,
|
||||||
|
value: cell.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rows
|
||||||
|
}
|
||||||
562
src/views/channel/pricingWorkbench/channelQuoteLocalParse.ts
Normal file
562
src/views/channel/pricingWorkbench/channelQuoteLocalParse.ts
Normal file
@ -0,0 +1,562 @@
|
|||||||
|
/**
|
||||||
|
* 渠道报价表本地规则解析(优先于 AI,毫秒级)
|
||||||
|
* 覆盖两种常见下游表:公斤+票费、一口价(含并排国家列 / PAK·WPX 分段)
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
guessChannelCodeFromSheetName,
|
||||||
|
isLikelyNonPriceSheetName,
|
||||||
|
type ChannelQuoteExtracted,
|
||||||
|
type ChannelQuoteRowRow,
|
||||||
|
type ChannelQuoteSheetExtract,
|
||||||
|
} from './channelQuoteAiSkill'
|
||||||
|
|
||||||
|
export type LocalParseConfidence = 'high' | 'medium' | 'low' | 'none'
|
||||||
|
|
||||||
|
export type LocalParseResult = ChannelQuoteSheetExtract & {
|
||||||
|
confidence: LocalParseConfidence
|
||||||
|
/** 解析策略标签,便于 UI / 排查 */
|
||||||
|
strategy?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
type Cell = string | number | null | undefined
|
||||||
|
type Matrix = Cell[][]
|
||||||
|
|
||||||
|
function cellStr(c: Cell): string {
|
||||||
|
if (c == null) return ''
|
||||||
|
if (typeof c === 'number' && Number.isFinite(c)) return String(c)
|
||||||
|
return String(c).replace(/\r?\n/g, ' ').trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
function cellNum(c: Cell): number | null {
|
||||||
|
if (c == null || c === '') return null
|
||||||
|
if (typeof c === 'number') return Number.isFinite(c) ? c : null
|
||||||
|
const s = String(c).trim().replace(/,/g, '').replace(/[¥¥元]/g, '')
|
||||||
|
if (!s || !/^[-+]?\d+(\.\d+)?$/.test(s)) return null
|
||||||
|
const n = Number(s)
|
||||||
|
return Number.isFinite(n) ? n : null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 表头归一:去空白、全角括号说明 */
|
||||||
|
function normHeader(c: Cell): string {
|
||||||
|
return cellStr(c)
|
||||||
|
.replace(/[((][^))]*[))]/g, '')
|
||||||
|
.replace(/[\s _/\\-]+/g, '')
|
||||||
|
.toLowerCase()
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseWeightBounds(raw: Cell): { start: number | null; end: number } | null {
|
||||||
|
if (raw == null || raw === '') return null
|
||||||
|
if (typeof raw === 'number' && Number.isFinite(raw) && raw > 0) {
|
||||||
|
return { start: null, end: raw }
|
||||||
|
}
|
||||||
|
const s = cellStr(raw).replace(/,/g, '').replace(/kg/gi, '').trim()
|
||||||
|
if (!s) return null
|
||||||
|
const range = s.match(/^(\d+(?:\.\d+)?)\s*[-~~—–到至]\s*(\d+(?:\.\d+)?)$/)
|
||||||
|
if (range) {
|
||||||
|
const a = Number(range[1])
|
||||||
|
const b = Number(range[2])
|
||||||
|
if (!Number.isFinite(a) || !Number.isFinite(b) || b <= 0) return null
|
||||||
|
return { start: a, end: b }
|
||||||
|
}
|
||||||
|
const n = Number(s)
|
||||||
|
if (!Number.isFinite(n) || n <= 0) return null
|
||||||
|
return { start: null, end: n }
|
||||||
|
}
|
||||||
|
|
||||||
|
function isHeaderLike(h: string): boolean {
|
||||||
|
if (!h) return false
|
||||||
|
return (
|
||||||
|
/对接代码|渠道代码|渠道编码|产品代码|服务代码/.test(h) ||
|
||||||
|
/重量段|包裹重量|计费重量|重量kg|^重量$/.test(h) ||
|
||||||
|
/运费|处理费|操作费|挂号费|一口价|总价/.test(h) ||
|
||||||
|
/国家名称|^国家$|目的地|分区|zone/.test(h)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
type ColRole =
|
||||||
|
| 'dock'
|
||||||
|
| 'weight'
|
||||||
|
| 'freightKg'
|
||||||
|
| 'handling'
|
||||||
|
| 'registration'
|
||||||
|
| 'country'
|
||||||
|
| 'flat'
|
||||||
|
| 'ignore'
|
||||||
|
|
||||||
|
function classifyHeader(h: string): ColRole {
|
||||||
|
if (!h) return 'ignore'
|
||||||
|
if (/对接代码|渠道代码|渠道编码|产品代码|服务代码/.test(h)) return 'dock'
|
||||||
|
if (/重量段|包裹重量|计费重量|重量kg|^重量$/.test(h)) return 'weight'
|
||||||
|
if (/挂号费/.test(h)) return 'registration'
|
||||||
|
if (/处理费|操作费/.test(h)) return 'handling'
|
||||||
|
if (/运费/.test(h) && (/kg|公斤|千克/.test(h) || /rmb\/?kg|元\/?kg/.test(h))) return 'freightKg'
|
||||||
|
if (/运费/.test(h) && !/票|件/.test(h)) return 'freightKg'
|
||||||
|
if (/一口价|总价|报价|单价|价格|金额/.test(h)) return 'flat'
|
||||||
|
if (/国家名称|^国家$|目的地|^分区$|zone|destination/.test(h)) return 'country'
|
||||||
|
if (/尺寸|时效|走货|备注|说明|属性|要求/.test(h)) return 'ignore'
|
||||||
|
return 'ignore'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 国家/分区名:短中文或常见英文区名,且不是表头关键字 */
|
||||||
|
function looksLikeZoneName(raw: string): boolean {
|
||||||
|
const s = cellStr(raw)
|
||||||
|
if (!s || s.length > 24) return false
|
||||||
|
if (isHeaderLike(normHeader(s))) return false
|
||||||
|
if (/^(pak|wpx|doc|信封|文件)$/i.test(s.trim())) return false
|
||||||
|
if (/条款|附加费|操作指南|目录|邮编/.test(s)) return false
|
||||||
|
// 纯数字不当 zone
|
||||||
|
if (/^[\d.\-]+$/.test(s)) return false
|
||||||
|
return /[\u4e00-\u9fffA-Za-z]/.test(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
function scanMeta(matrix: Matrix): { currency: string; effectiveAt: string | null; warnings: string[] } {
|
||||||
|
const warnings: string[] = []
|
||||||
|
let currency = 'CNY'
|
||||||
|
let effectiveAt: string | null = null
|
||||||
|
const probe = matrix.slice(0, 20)
|
||||||
|
for (const row of probe) {
|
||||||
|
const line = (row || []).map(cellStr).join(' ')
|
||||||
|
if (/美元|USD/i.test(line)) currency = 'USD'
|
||||||
|
else if (/港币|HKD/i.test(line)) currency = 'HKD'
|
||||||
|
const m =
|
||||||
|
line.match(/生效\s*日[期间]?\s*[::]?\s*(\d{4}[-/.年]\d{1,2}[-/.月]\d{1,2})/) ||
|
||||||
|
line.match(/(\d{4}[-/.]\d{1,2}[-/.]\d{1,2})\s*起?\s*生效/)
|
||||||
|
if (m && !effectiveAt) {
|
||||||
|
effectiveAt = m[1]!.replace(/[年月日./]/g, '-').replace(/-+/g, '-').replace(/-$/, '')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { currency, effectiveAt, warnings }
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSubtypeTitleRow(row: Cell[]): string | null {
|
||||||
|
const cells = (row || []).map(cellStr).filter(Boolean)
|
||||||
|
if (!cells.length) return null
|
||||||
|
const joined = cells.join(' ')
|
||||||
|
if (cells.length <= 3 && /^(PAK|WPX|DOC)\b/i.test(cells[0]!) && cellNum(row[0]) == null) {
|
||||||
|
return cells[0]!
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
cells.length <= 4 &&
|
||||||
|
/\b(PAK|WPX)\b/i.test(joined) &&
|
||||||
|
!cells.some((_, i) => cellNum(row[i]) != null && i > 0)
|
||||||
|
) {
|
||||||
|
return cells[0] || joined.slice(0, 40)
|
||||||
|
}
|
||||||
|
// 整行几乎无数字、像分段标题
|
||||||
|
const nums = (row || []).filter((c) => cellNum(c) != null).length
|
||||||
|
if (nums === 0 && cells.length <= 3 && /PAK|WPX|文件|包裹|信封/i.test(joined) && joined.length < 40) {
|
||||||
|
return cells[0] || joined
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
function isJunkDataRow(row: Cell[]): boolean {
|
||||||
|
const joined = (row || []).map(cellStr).join(' ')
|
||||||
|
if (!joined.trim()) return true
|
||||||
|
if (joined.length > 120 && /条款|赔偿|截单|本公司|附加费及规定/.test(joined)) return true
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
type RoleMap = { roles: ColRole[]; headers: string[]; zoneByCol: Map<number, string> }
|
||||||
|
|
||||||
|
function buildRoleMap(headerRow: Cell[]): RoleMap {
|
||||||
|
const headers = (headerRow || []).map(normHeader)
|
||||||
|
const roles: ColRole[] = headers.map(classifyHeader)
|
||||||
|
const zoneByCol = new Map<number, string>()
|
||||||
|
;(headerRow || []).forEach((c, i) => {
|
||||||
|
if (roles[i] !== 'ignore') return
|
||||||
|
const raw = cellStr(c)
|
||||||
|
if (looksLikeZoneName(raw)) {
|
||||||
|
roles[i] = 'flat'
|
||||||
|
zoneByCol.set(i, raw)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return { roles, headers, zoneByCol }
|
||||||
|
}
|
||||||
|
|
||||||
|
function findHeaderRow(matrix: Matrix): { index: number; map: RoleMap } | null {
|
||||||
|
const limit = Math.min(matrix.length, 40)
|
||||||
|
let best: { index: number; map: RoleMap; score: number } | null = null
|
||||||
|
for (let i = 0; i < limit; i++) {
|
||||||
|
const map = buildRoleMap(matrix[i] || [])
|
||||||
|
const hasWeight = map.roles.includes('weight')
|
||||||
|
const hasFee =
|
||||||
|
map.roles.includes('freightKg') ||
|
||||||
|
map.roles.includes('handling') ||
|
||||||
|
map.roles.includes('registration') ||
|
||||||
|
map.roles.includes('flat')
|
||||||
|
if (!hasWeight || !hasFee) continue
|
||||||
|
let score = 0
|
||||||
|
if (map.roles.includes('dock')) score += 3
|
||||||
|
if (map.roles.includes('freightKg')) score += 4
|
||||||
|
if (map.roles.includes('handling')) score += 3
|
||||||
|
if (map.roles.includes('flat') || map.zoneByCol.size) score += 3
|
||||||
|
if (map.roles.includes('country')) score += 2
|
||||||
|
score += map.roles.filter((r) => r === 'weight').length
|
||||||
|
if (!best || score > best.score) best = { index: i, map, score }
|
||||||
|
}
|
||||||
|
return best ? { index: best.index, map: best.map } : null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 公斤+票费:对接代码 + 重量段 + 运费/处理费 */
|
||||||
|
function parseUnitPlusFee(
|
||||||
|
matrix: Matrix,
|
||||||
|
sheetName: string,
|
||||||
|
headerIndex: number,
|
||||||
|
map: RoleMap,
|
||||||
|
meta: ReturnType<typeof scanMeta>,
|
||||||
|
): LocalParseResult | null {
|
||||||
|
const dockIdx = map.roles.indexOf('dock')
|
||||||
|
const weightIdx = map.roles.indexOf('weight')
|
||||||
|
const freightIdx = map.roles.indexOf('freightKg')
|
||||||
|
const handlingIdx = map.roles.indexOf('handling')
|
||||||
|
const regIdx = map.roles.indexOf('registration')
|
||||||
|
const countryIdx = map.roles.indexOf('country')
|
||||||
|
if (weightIdx < 0) return null
|
||||||
|
if (freightIdx < 0 && handlingIdx < 0 && regIdx < 0) return null
|
||||||
|
|
||||||
|
type Bucket = {
|
||||||
|
code: string
|
||||||
|
name: string | null
|
||||||
|
subtype: string | null
|
||||||
|
rows: ChannelQuoteRowRow[]
|
||||||
|
destinations: Set<string>
|
||||||
|
}
|
||||||
|
const buckets = new Map<string, Bucket>()
|
||||||
|
let currentCode =
|
||||||
|
guessChannelCodeFromSheetName(sheetName) ||
|
||||||
|
sheetName.replace(/\s+/g, '').slice(0, 32) ||
|
||||||
|
'UNKNOWN'
|
||||||
|
let currentSubtype: string | null = null
|
||||||
|
let currentName: string | null = null
|
||||||
|
|
||||||
|
const ensure = (code: string) => {
|
||||||
|
const key = `${code}::${currentSubtype || ''}`
|
||||||
|
if (!buckets.has(key)) {
|
||||||
|
buckets.set(key, {
|
||||||
|
code,
|
||||||
|
name: currentName,
|
||||||
|
subtype: currentSubtype,
|
||||||
|
rows: [],
|
||||||
|
destinations: new Set(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return buckets.get(key)!
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let r = headerIndex + 1; r < matrix.length; r++) {
|
||||||
|
const row = matrix[r] || []
|
||||||
|
if (isJunkDataRow(row)) continue
|
||||||
|
const subtype = isSubtypeTitleRow(row)
|
||||||
|
if (subtype) {
|
||||||
|
currentSubtype = subtype
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (dockIdx >= 0) {
|
||||||
|
const dock = cellStr(row[dockIdx])
|
||||||
|
if (dock && !/^[\d.]+$/.test(dock) && dock.length <= 40) {
|
||||||
|
currentCode = dock
|
||||||
|
currentName = dock
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const w = parseWeightBounds(row[weightIdx])
|
||||||
|
if (!w) continue
|
||||||
|
const freight = freightIdx >= 0 ? cellNum(row[freightIdx]) : null
|
||||||
|
const handling = handlingIdx >= 0 ? cellNum(row[handlingIdx]) : null
|
||||||
|
const registration = regIdx >= 0 ? cellNum(row[regIdx]) : null
|
||||||
|
if (freight == null && handling == null && registration == null) continue
|
||||||
|
const zone = countryIdx >= 0 ? cellStr(row[countryIdx]) || null : null
|
||||||
|
const b = ensure(currentCode)
|
||||||
|
if (zone) b.destinations.add(zone)
|
||||||
|
b.rows.push({
|
||||||
|
weightStart: w.start,
|
||||||
|
weightEnd: w.end,
|
||||||
|
zoneHint: zone,
|
||||||
|
freightPerKg: freight,
|
||||||
|
handlingPerShipment: handling,
|
||||||
|
registrationPerShipment: registration,
|
||||||
|
flatTotal: null,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const channelQuotes: ChannelQuoteExtracted[] = [...buckets.values()]
|
||||||
|
.filter((b) => b.rows.length > 0)
|
||||||
|
.map((b) => ({
|
||||||
|
channelCodeHint: b.code,
|
||||||
|
channelNameHint: b.name,
|
||||||
|
serviceSubtype: b.subtype,
|
||||||
|
mode: 'unit_plus_fee' as const,
|
||||||
|
destinationHints: [...b.destinations],
|
||||||
|
rows: b.rows,
|
||||||
|
}))
|
||||||
|
|
||||||
|
if (!channelQuotes.length) return null
|
||||||
|
const rowCount = channelQuotes.reduce((n, q) => n + q.rows.length, 0)
|
||||||
|
return {
|
||||||
|
sheetName,
|
||||||
|
isPriceSheet: true,
|
||||||
|
skipReason: null,
|
||||||
|
currency: meta.currency,
|
||||||
|
effectiveAt: meta.effectiveAt,
|
||||||
|
channelQuotes,
|
||||||
|
warnings: meta.warnings,
|
||||||
|
confidence: rowCount >= 3 ? 'high' : rowCount >= 1 ? 'medium' : 'none',
|
||||||
|
strategy: 'unit_plus_fee',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 一口价:重量列 + 国家价列;支持并排多组「包裹重量|国家」
|
||||||
|
* 例:包裹重量 | 美国 | … | 包裹重量 | 美国
|
||||||
|
*/
|
||||||
|
function parseFlatBlocks(
|
||||||
|
matrix: Matrix,
|
||||||
|
sheetName: string,
|
||||||
|
headerIndex: number,
|
||||||
|
headerRow: Cell[],
|
||||||
|
meta: ReturnType<typeof scanMeta>,
|
||||||
|
): LocalParseResult | null {
|
||||||
|
const headers = headerRow || []
|
||||||
|
type Block = { weightCol: number; priceCols: Array<{ col: number; zone: string }> }
|
||||||
|
const blocks: Block[] = []
|
||||||
|
let i = 0
|
||||||
|
while (i < headers.length) {
|
||||||
|
const h = normHeader(headers[i])
|
||||||
|
if (/重量段|包裹重量|计费重量|重量kg|^重量$/.test(h)) {
|
||||||
|
const priceCols: Array<{ col: number; zone: string }> = []
|
||||||
|
let j = i + 1
|
||||||
|
while (j < headers.length) {
|
||||||
|
const hj = normHeader(headers[j])
|
||||||
|
if (/重量段|包裹重量|计费重量|重量kg|^重量$/.test(hj)) break
|
||||||
|
const zoneRaw = cellStr(headers[j])
|
||||||
|
const role = classifyHeader(hj)
|
||||||
|
if (role === 'ignore' && looksLikeZoneName(zoneRaw)) {
|
||||||
|
priceCols.push({ col: j, zone: zoneRaw })
|
||||||
|
} else if (role === 'flat' || role === 'country') {
|
||||||
|
// 「一口价」列:zone 可能在上一格或 sheet 名
|
||||||
|
priceCols.push({
|
||||||
|
col: j,
|
||||||
|
zone: role === 'country' ? '' : zoneRaw || guessZoneFromSheet(sheetName) || '默认',
|
||||||
|
})
|
||||||
|
} else if (role !== 'ignore') {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
j += 1
|
||||||
|
}
|
||||||
|
if (priceCols.length) blocks.push({ weightCol: i, priceCols })
|
||||||
|
i = j
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!blocks.length) return null
|
||||||
|
|
||||||
|
const codeHint = guessChannelCodeFromSheetName(sheetName)
|
||||||
|
const nameHint = sheetName
|
||||||
|
let currentSubtype: string | null = null
|
||||||
|
const rowsBySubtype = new Map<string, ChannelQuoteRowRow[]>()
|
||||||
|
const dest = new Set<string>()
|
||||||
|
|
||||||
|
const pushRow = (row: ChannelQuoteRowRow) => {
|
||||||
|
const key = currentSubtype || ''
|
||||||
|
if (!rowsBySubtype.has(key)) rowsBySubtype.set(key, [])
|
||||||
|
rowsBySubtype.get(key)!.push(row)
|
||||||
|
if (row.zoneHint) dest.add(row.zoneHint)
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let r = headerIndex + 1; r < matrix.length; r++) {
|
||||||
|
const row = matrix[r] || []
|
||||||
|
if (isJunkDataRow(row)) continue
|
||||||
|
const subtype = isSubtypeTitleRow(row)
|
||||||
|
if (subtype) {
|
||||||
|
currentSubtype = subtype
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
let any = false
|
||||||
|
for (const block of blocks) {
|
||||||
|
const w = parseWeightBounds(row[block.weightCol])
|
||||||
|
if (!w) continue
|
||||||
|
for (const pc of block.priceCols) {
|
||||||
|
const price = cellNum(row[pc.col])
|
||||||
|
if (price == null) continue
|
||||||
|
any = true
|
||||||
|
const zone = pc.zone || null
|
||||||
|
pushRow({
|
||||||
|
weightStart: w.start,
|
||||||
|
weightEnd: w.end,
|
||||||
|
zoneHint: zone,
|
||||||
|
freightPerKg: null,
|
||||||
|
handlingPerShipment: null,
|
||||||
|
registrationPerShipment: null,
|
||||||
|
flatTotal: price,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 若没有任何 block 命中,尝试「重量 + 国家列 + 一口价列」单表
|
||||||
|
if (!any && blocks.length === 1) {
|
||||||
|
/* already covered */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const channelQuotes: ChannelQuoteExtracted[] = [...rowsBySubtype.entries()]
|
||||||
|
.filter(([, rows]) => rows.length > 0)
|
||||||
|
.map(([subtype, rows]) => ({
|
||||||
|
channelCodeHint: codeHint,
|
||||||
|
channelNameHint: nameHint,
|
||||||
|
serviceSubtype: subtype || null,
|
||||||
|
mode: 'flat' as const,
|
||||||
|
destinationHints: [...new Set(rows.map((x) => x.zoneHint).filter(Boolean) as string[])],
|
||||||
|
rows,
|
||||||
|
}))
|
||||||
|
|
||||||
|
if (!channelQuotes.length) return null
|
||||||
|
const rowCount = channelQuotes.reduce((n, q) => n + q.rows.length, 0)
|
||||||
|
return {
|
||||||
|
sheetName,
|
||||||
|
isPriceSheet: true,
|
||||||
|
skipReason: null,
|
||||||
|
currency: meta.currency,
|
||||||
|
effectiveAt: meta.effectiveAt,
|
||||||
|
channelQuotes,
|
||||||
|
warnings: meta.warnings,
|
||||||
|
confidence: rowCount >= 3 ? 'high' : 'medium',
|
||||||
|
strategy: 'flat_blocks',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function guessZoneFromSheet(sheetName: string): string | null {
|
||||||
|
const m = String(sheetName).match(/(美国|英国|德国|法国|日本|澳洲|加拿大|欧盟|欧洲)/)
|
||||||
|
return m ? m[1]! : null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 重量列 + 国家列 + 价格列(纵表一口价) */
|
||||||
|
function parseFlatLong(
|
||||||
|
matrix: Matrix,
|
||||||
|
sheetName: string,
|
||||||
|
headerIndex: number,
|
||||||
|
map: RoleMap,
|
||||||
|
meta: ReturnType<typeof scanMeta>,
|
||||||
|
): LocalParseResult | null {
|
||||||
|
const weightIdx = map.roles.indexOf('weight')
|
||||||
|
const countryIdx = map.roles.indexOf('country')
|
||||||
|
const flatIdx = map.roles.findIndex((r, i) => r === 'flat' && !map.zoneByCol.has(i))
|
||||||
|
const zonePriceCols = [...map.zoneByCol.entries()]
|
||||||
|
if (weightIdx < 0) return null
|
||||||
|
if (countryIdx < 0 && flatIdx < 0 && !zonePriceCols.length) return null
|
||||||
|
// zone 作为列表头的情况交给 flat_blocks
|
||||||
|
if (zonePriceCols.length && countryIdx < 0) return null
|
||||||
|
|
||||||
|
const codeHint = guessChannelCodeFromSheetName(sheetName)
|
||||||
|
let currentSubtype: string | null = null
|
||||||
|
const rows: ChannelQuoteRowRow[] = []
|
||||||
|
|
||||||
|
for (let r = headerIndex + 1; r < matrix.length; r++) {
|
||||||
|
const row = matrix[r] || []
|
||||||
|
if (isJunkDataRow(row)) continue
|
||||||
|
const subtype = isSubtypeTitleRow(row)
|
||||||
|
if (subtype) {
|
||||||
|
currentSubtype = subtype
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const w = parseWeightBounds(row[weightIdx])
|
||||||
|
if (!w) continue
|
||||||
|
if (countryIdx >= 0 && flatIdx >= 0) {
|
||||||
|
const zone = cellStr(row[countryIdx]) || null
|
||||||
|
const price = cellNum(row[flatIdx])
|
||||||
|
if (price == null) continue
|
||||||
|
rows.push({
|
||||||
|
weightStart: w.start,
|
||||||
|
weightEnd: w.end,
|
||||||
|
zoneHint: zone,
|
||||||
|
freightPerKg: null,
|
||||||
|
handlingPerShipment: null,
|
||||||
|
registrationPerShipment: null,
|
||||||
|
flatTotal: price,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!rows.length) return null
|
||||||
|
return {
|
||||||
|
sheetName,
|
||||||
|
isPriceSheet: true,
|
||||||
|
skipReason: null,
|
||||||
|
currency: meta.currency,
|
||||||
|
effectiveAt: meta.effectiveAt,
|
||||||
|
channelQuotes: [
|
||||||
|
{
|
||||||
|
channelCodeHint: codeHint,
|
||||||
|
channelNameHint: sheetName,
|
||||||
|
serviceSubtype: currentSubtype,
|
||||||
|
mode: 'flat',
|
||||||
|
destinationHints: [...new Set(rows.map((x) => x.zoneHint).filter(Boolean) as string[])],
|
||||||
|
rows,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
warnings: meta.warnings,
|
||||||
|
confidence: rows.length >= 3 ? 'high' : 'medium',
|
||||||
|
strategy: 'flat_long',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function emptySkip(sheetName: string, reason: string): LocalParseResult {
|
||||||
|
return {
|
||||||
|
sheetName,
|
||||||
|
isPriceSheet: false,
|
||||||
|
skipReason: reason,
|
||||||
|
channelQuotes: [],
|
||||||
|
warnings: [],
|
||||||
|
confidence: 'none',
|
||||||
|
strategy: null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 本地解析单个 sheet 矩阵。
|
||||||
|
* confidence high/medium 视为可用;low/none 交给 AI 或标失败。
|
||||||
|
*/
|
||||||
|
export function parseSheetMatrixLocal(
|
||||||
|
sheetName: string,
|
||||||
|
matrix: Matrix,
|
||||||
|
): LocalParseResult {
|
||||||
|
const name = String(sheetName || '').trim() || 'sheet'
|
||||||
|
if (isLikelyNonPriceSheetName(name)) {
|
||||||
|
return emptySkip(name, 'sheet 名称疑似非报价(目录/附加费/邮编等)')
|
||||||
|
}
|
||||||
|
if (!matrix?.length) return emptySkip(name, '空表')
|
||||||
|
|
||||||
|
const meta = scanMeta(matrix)
|
||||||
|
const found = findHeaderRow(matrix)
|
||||||
|
if (!found) {
|
||||||
|
return emptySkip(name, '未识别到重量+费用表头')
|
||||||
|
}
|
||||||
|
|
||||||
|
const { index, map } = found
|
||||||
|
const headerRow = matrix[index] || []
|
||||||
|
|
||||||
|
// 优先公斤+票费(有运费KG 或 处理费,且不像纯一口价国家并列表)
|
||||||
|
const hasUnitFee =
|
||||||
|
map.roles.includes('freightKg') ||
|
||||||
|
map.roles.includes('handling') ||
|
||||||
|
map.roles.includes('registration')
|
||||||
|
if (hasUnitFee) {
|
||||||
|
const unit = parseUnitPlusFee(matrix, name, index, map, meta)
|
||||||
|
if (unit && unit.confidence !== 'none') return unit
|
||||||
|
}
|
||||||
|
|
||||||
|
const flatBlocks = parseFlatBlocks(matrix, name, index, headerRow, meta)
|
||||||
|
if (flatBlocks && flatBlocks.confidence !== 'none') return flatBlocks
|
||||||
|
|
||||||
|
const flatLong = parseFlatLong(matrix, name, index, map, meta)
|
||||||
|
if (flatLong && flatLong.confidence !== 'none') return flatLong
|
||||||
|
|
||||||
|
return emptySkip(name, '表头已找到但未能抽出有效报价行')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 是否值得交给 AI(本地失败或置信过低) */
|
||||||
|
export function needsAiFallback(result: LocalParseResult): boolean {
|
||||||
|
if (!result.isPriceSheet) return !isLikelyNonPriceSheetName(result.sheetName)
|
||||||
|
if (result.confidence === 'high' || result.confidence === 'medium') return false
|
||||||
|
return true
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@ -3,17 +3,24 @@
|
|||||||
<div class="pw-header">
|
<div class="pw-header">
|
||||||
<div class="pw-header-main">
|
<div class="pw-header-main">
|
||||||
<h2 class="pw-title">定价工作台</h2>
|
<h2 class="pw-title">定价工作台</h2>
|
||||||
<p class="pw-sub">
|
<SlidingTabs
|
||||||
|
class="pw-tabs"
|
||||||
|
:model-value="activeTab"
|
||||||
|
:items="tabItems"
|
||||||
|
aria-label="定价工作台"
|
||||||
|
@update:model-value="onTabChange"
|
||||||
|
/>
|
||||||
|
<p v-if="activeTab === 'sellPrice'" class="pw-sub">
|
||||||
<span class="flow-num">1</span>选渠道
|
<span class="flow-num">1</span>选渠道
|
||||||
<span class="flow-sep">→</span>
|
<span class="flow-sep">→</span>
|
||||||
<span class="flow-num">2</span>定规则
|
<span class="flow-num">2</span>定规则
|
||||||
<span class="flow-sep">→</span>
|
<span class="flow-sep">→</span>
|
||||||
<span class="flow-num">3</span>预览合成
|
<span class="flow-num">3</span>预览合成
|
||||||
<span class="flow-sep">→</span>
|
<span class="flow-sep">→</span>
|
||||||
<span class="flow-num">4</span>回写草稿(不自动发布)
|
<span class="flow-num">4</span>回写卖价草稿
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="pw-header-actions">
|
<div v-if="activeTab === 'sellPrice'" class="pw-header-actions">
|
||||||
<a-tooltip :content="previewDisabledReason || '按当前渠道与规则合成卖价预览'">
|
<a-tooltip :content="previewDisabledReason || '按当前渠道与规则合成卖价预览'">
|
||||||
<span class="btn-tip-wrap">
|
<span class="btn-tip-wrap">
|
||||||
<a-button
|
<a-button
|
||||||
@ -42,7 +49,15 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="pw-body" :class="{ 'ai-open': aiOpen && showAiEntry }">
|
<div v-if="activeTab === 'buyPrice'" class="pw-tab-panel pw-tab-panel--buy">
|
||||||
|
<ChannelQuoteImportPanel @applied="onChannelQuoteApplied" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-show="activeTab === 'sellPrice'"
|
||||||
|
class="pw-body"
|
||||||
|
:class="{ 'ai-open': aiOpen && showAiEntry }"
|
||||||
|
>
|
||||||
<!-- 左:1 成本 + 2 规则 -->
|
<!-- 左:1 成本 + 2 规则 -->
|
||||||
<aside class="pw-left pw-card">
|
<aside class="pw-left pw-card">
|
||||||
<div class="left-top">
|
<div class="left-top">
|
||||||
@ -432,11 +447,20 @@ import {
|
|||||||
import { getServiceChannelOptions } from '@/api/channel/serviceChannel'
|
import { getServiceChannelOptions } from '@/api/channel/serviceChannel'
|
||||||
import { getSalesProductList, getSalesProductPriceList } from '@/api/channel/salesProduct'
|
import { getSalesProductList, getSalesProductPriceList } from '@/api/channel/salesProduct'
|
||||||
import { hasPermission } from '@/utils/rbac-permission'
|
import { hasPermission } from '@/utils/rbac-permission'
|
||||||
|
import SlidingTabs from '@/components/SlidingTabs/index.vue'
|
||||||
import PricingWorkbenchAiPanel from './components/PricingWorkbenchAiPanel.vue'
|
import PricingWorkbenchAiPanel from './components/PricingWorkbenchAiPanel.vue'
|
||||||
|
import ChannelQuoteImportPanel from './components/ChannelQuoteImportPanel.vue'
|
||||||
import type { PricingWorkbenchAiRulePatch } from './pricingWorkbenchAiSkill'
|
import type { PricingWorkbenchAiRulePatch } from './pricingWorkbenchAiSkill'
|
||||||
|
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
|
||||||
|
type WorkbenchTab = 'buyPrice' | 'sellPrice'
|
||||||
|
const activeTab = ref<WorkbenchTab>('buyPrice')
|
||||||
|
const tabItems = [
|
||||||
|
{ key: 'buyPrice', label: '更新买价' },
|
||||||
|
{ key: 'sellPrice', label: '合成卖价' },
|
||||||
|
]
|
||||||
|
|
||||||
const optionsLoading = ref(false)
|
const optionsLoading = ref(false)
|
||||||
const channelOptions = ref<{ id: number; label: string }[]>([])
|
const channelOptions = ref<{ id: number; label: string }[]>([])
|
||||||
const selectedChannelIds = ref<number[]>([])
|
const selectedChannelIds = ref<number[]>([])
|
||||||
@ -477,6 +501,12 @@ let aiDiffHintShown = false
|
|||||||
const aiOpen = ref(false)
|
const aiOpen = ref(false)
|
||||||
const aiMode = ref<'rules' | 'diff'>('rules')
|
const aiMode = ref<'rules' | 'diff'>('rules')
|
||||||
|
|
||||||
|
function onTabChange(key: string) {
|
||||||
|
if (key !== 'buyPrice' && key !== 'sellPrice') return
|
||||||
|
activeTab.value = key
|
||||||
|
if (key !== 'sellPrice') aiOpen.value = false
|
||||||
|
}
|
||||||
|
|
||||||
const showAiEntry = computed(
|
const showAiEntry = computed(
|
||||||
() =>
|
() =>
|
||||||
hasPermission('Channel.PricingWorkbench') ||
|
hasPermission('Channel.PricingWorkbench') ||
|
||||||
@ -810,6 +840,17 @@ async function onChannelsChange() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 更新买价成功后:勾选渠道、切到合成卖价 Tab */
|
||||||
|
async function onChannelQuoteApplied(channelIds: number[]) {
|
||||||
|
const ids = (channelIds || []).map(Number).filter((n) => n > 0)
|
||||||
|
if (!ids.length) return
|
||||||
|
const merged = [...new Set([...selectedChannelIds.value, ...ids])]
|
||||||
|
selectedChannelIds.value = merged
|
||||||
|
activeTab.value = 'sellPrice'
|
||||||
|
await onChannelsChange()
|
||||||
|
Message.info('已切换到「合成卖价」,并勾选更新后的渠道')
|
||||||
|
}
|
||||||
|
|
||||||
async function onProductChange() {
|
async function onProductChange() {
|
||||||
priceId.value = undefined
|
priceId.value = undefined
|
||||||
priceOptions.value = []
|
priceOptions.value = []
|
||||||
@ -1070,29 +1111,65 @@ onMounted(async () => {
|
|||||||
}
|
}
|
||||||
.pw-header {
|
.pw-header {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: flex-start;
|
align-items: center;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
gap: 12px;
|
gap: 12px;
|
||||||
padding: 12px 16px;
|
padding: 8px 16px;
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
background: #fff;
|
background: #fff;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
|
||||||
|
min-height: 48px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
.pw-header-main {
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
flex-wrap: nowrap;
|
||||||
}
|
}
|
||||||
.pw-title {
|
.pw-title {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
font-size: 18px;
|
font-size: 16px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: var(--color-text-1);
|
color: var(--color-text-1);
|
||||||
|
flex-shrink: 0;
|
||||||
|
line-height: 1.2;
|
||||||
|
}
|
||||||
|
.pw-tabs {
|
||||||
|
margin-top: 0;
|
||||||
|
max-width: 320px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.pw-tab-panel {
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.pw-tab-panel--buy {
|
||||||
|
:deep(.cq-import) {
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
max-height: none;
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
.pw-sub {
|
.pw-sub {
|
||||||
margin: 6px 0 0;
|
margin: 0;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: var(--color-text-3);
|
color: var(--color-text-3);
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-wrap: nowrap;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
.flow-num {
|
.flow-num {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
|
|||||||
@ -58,6 +58,16 @@
|
|||||||
import { IconPlus, IconDelete, IconSearch, IconEdit, IconDragArrow, IconQuestionCircleFill, IconQuestionCircle, IconSync } from '@arco-design/web-vue/es/icon';
|
import { IconPlus, IconDelete, IconSearch, IconEdit, IconDragArrow, IconQuestionCircleFill, IconQuestionCircle, IconSync } from '@arco-design/web-vue/es/icon';
|
||||||
import FormLabelWithPreview from './components/FormLabelWithPreview.vue';
|
import FormLabelWithPreview from './components/FormLabelWithPreview.vue';
|
||||||
import BillingConditionEditor from './components/BillingConditionEditor.vue';
|
import BillingConditionEditor from './components/BillingConditionEditor.vue';
|
||||||
|
import PreScriptEditor from '@/views/channel/serviceChannels/components/PreScriptEditor.vue';
|
||||||
|
import {
|
||||||
|
PRE_STORAGE_SCRIPT_AI_CHAT_SCENE,
|
||||||
|
PRE_STORAGE_SCRIPT_AI_DEFAULT_SKILL_KEY,
|
||||||
|
PRE_STORAGE_SCRIPT_AI_QUICK_PROMPTS,
|
||||||
|
PRE_STORAGE_SCRIPT_AI_SCENE,
|
||||||
|
PRE_STORAGE_SCRIPT_AI_STORAGE_KEY,
|
||||||
|
buildPreStorageScriptAiShortSystemPrompt,
|
||||||
|
buildPreStorageScriptAiSystemPrompt,
|
||||||
|
} from './preStorageScriptAiSkill';
|
||||||
import ChannelReferencePreviewModal, {
|
import ChannelReferencePreviewModal, {
|
||||||
type ReferencePreviewType,
|
type ReferencePreviewType,
|
||||||
} from './components/ChannelReferencePreviewModal.vue';
|
} from './components/ChannelReferencePreviewModal.vue';
|
||||||
@ -107,6 +117,8 @@
|
|||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const userStore = useUserStore();
|
const userStore = useUserStore();
|
||||||
const rbacUserStore = useRbacUserStore();
|
const rbacUserStore = useRbacUserStore();
|
||||||
|
const preStorageFallbackPrompt = buildPreStorageScriptAiSystemPrompt();
|
||||||
|
const preStorageShortPrompt = buildPreStorageScriptAiShortSystemPrompt();
|
||||||
|
|
||||||
function getPricePublishOperatorName(): string {
|
function getPricePublishOperatorName(): string {
|
||||||
return (
|
return (
|
||||||
@ -5576,12 +5588,21 @@
|
|||||||
<!-- 第五行 -->
|
<!-- 第五行 -->
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<div class="form-item full-width">
|
<div class="form-item full-width">
|
||||||
<label class="form-label">{{ t('channel.salesProducts.form.preStorageScript') }}</label>
|
<PreScriptEditor
|
||||||
<a-textarea
|
|
||||||
v-model="formData.preStorageScript"
|
v-model="formData.preStorageScript"
|
||||||
:placeholder="t('channel.salesProducts.form.placeholder.input')"
|
:label="t('channel.salesProducts.form.preStorageScript')"
|
||||||
:rows="4"
|
:label-tip="t('channel.salesProducts.tip.preStorageScript')"
|
||||||
class="form-textarea"
|
:placeholder="t('channel.salesProducts.placeholder.preStorageScript')"
|
||||||
|
:rows="5"
|
||||||
|
:skill-scene="PRE_STORAGE_SCRIPT_AI_SCENE"
|
||||||
|
:default-skill-key="PRE_STORAGE_SCRIPT_AI_DEFAULT_SKILL_KEY"
|
||||||
|
:storage-key="PRE_STORAGE_SCRIPT_AI_STORAGE_KEY"
|
||||||
|
:chat-scene="PRE_STORAGE_SCRIPT_AI_CHAT_SCENE"
|
||||||
|
:quick-prompts="PRE_STORAGE_SCRIPT_AI_QUICK_PROMPTS"
|
||||||
|
:fallback-system-prompt="preStorageFallbackPrompt"
|
||||||
|
:short-system-prompt="preStorageShortPrompt"
|
||||||
|
:hint-text="t('channel.salesProducts.preStorageScript.hint')"
|
||||||
|
:field-hint-text="t('channel.salesProducts.preStorageScript.fieldHint')"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -6320,18 +6341,21 @@
|
|||||||
</div>
|
</div>
|
||||||
<div v-if="addProductShowAdvanced" class="form-row">
|
<div v-if="addProductShowAdvanced" class="form-row">
|
||||||
<div class="form-item full-width">
|
<div class="form-item full-width">
|
||||||
<label class="form-label label-with-tip">
|
<PreScriptEditor
|
||||||
{{ t('channel.salesProducts.form.preStorageScript') }}
|
|
||||||
<a-tooltip :content="t('channel.salesProducts.tip.preStorageScript')">
|
|
||||||
<icon-question-circle class="tip-icon" />
|
|
||||||
</a-tooltip>
|
|
||||||
</label>
|
|
||||||
<a-textarea
|
|
||||||
v-model="addProductFormData.preStorageScript"
|
v-model="addProductFormData.preStorageScript"
|
||||||
|
:label="t('channel.salesProducts.form.preStorageScript')"
|
||||||
|
:label-tip="t('channel.salesProducts.tip.preStorageScript')"
|
||||||
:placeholder="t('channel.salesProducts.placeholder.preStorageScript')"
|
:placeholder="t('channel.salesProducts.placeholder.preStorageScript')"
|
||||||
:auto-size="{ minRows: 3, maxRows: 8 }"
|
:rows="4"
|
||||||
class="form-textarea"
|
:skill-scene="PRE_STORAGE_SCRIPT_AI_SCENE"
|
||||||
allow-clear
|
:default-skill-key="PRE_STORAGE_SCRIPT_AI_DEFAULT_SKILL_KEY"
|
||||||
|
:storage-key="PRE_STORAGE_SCRIPT_AI_STORAGE_KEY"
|
||||||
|
:chat-scene="PRE_STORAGE_SCRIPT_AI_CHAT_SCENE"
|
||||||
|
:quick-prompts="PRE_STORAGE_SCRIPT_AI_QUICK_PROMPTS"
|
||||||
|
:fallback-system-prompt="preStorageFallbackPrompt"
|
||||||
|
:short-system-prompt="preStorageShortPrompt"
|
||||||
|
:hint-text="t('channel.salesProducts.preStorageScript.hint')"
|
||||||
|
:field-hint-text="t('channel.salesProducts.preStorageScript.fieldHint')"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
64
src/views/channel/salesProducts/preStorageScriptAiSkill.ts
Normal file
64
src/views/channel/salesProducts/preStorageScriptAiSkill.ts
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
import { appendPreScriptFieldCatalog } from '@/views/channel/serviceChannels/preScriptMeta'
|
||||||
|
|
||||||
|
const SKILL_CORE = `你是 OMS「销售产品落库前执行脚本」助手。根据用户中文描述,生成可粘贴到销售产品 PreStorageScript 的中文赋值脚本(ChineseAssignScriptEvaluator)。
|
||||||
|
|
||||||
|
## 场景
|
||||||
|
|
||||||
|
- 订单创建落库之前,改写下单相关字段(拼地址、拼品名 SKU、微调长宽高等)
|
||||||
|
- 改写结果会写入订单库(与渠道预报前脚本不同:预报前只改报文不落库)
|
||||||
|
- 字段范围对齐「单票下单」录入项;不要使用状态/问题件/计费重/体积重等无关字段
|
||||||
|
- 不要生成接口通 Natasha C#,不要生成自动触发布尔公式
|
||||||
|
|
||||||
|
## 产出格式(必须)
|
||||||
|
|
||||||
|
脚本:
|
||||||
|
一行或多行赋值语句
|
||||||
|
说明:一句话
|
||||||
|
|
||||||
|
## 语法硬规则
|
||||||
|
|
||||||
|
- 每条语句:可写字段 = 表达式
|
||||||
|
- 可写:收/发件人与申报字符串(申报首行);件重尺仅 长度/宽度/高度/实重
|
||||||
|
- 右侧可引用目录中的字段(订单基本信息多为只读)、单引号字符串、数字、+ - * / ()
|
||||||
|
- 字符串拼接用 +;多语句换行或分号;# 为注释
|
||||||
|
- 禁止 == != && ||、包含()、有值()、为空()、双引号、英文字段名
|
||||||
|
- 禁止写:计费重、体积重、体积、件重尺类型、HS编码(用进口/出口HS编码)、发件人是否默认
|
||||||
|
- 总长度 ≤ 10000
|
||||||
|
|
||||||
|
## 示例
|
||||||
|
|
||||||
|
脚本:
|
||||||
|
收件人地址1 = 收件人地址1 + ' ' + 收件人地址2
|
||||||
|
收件人地址2 = ''
|
||||||
|
说明:落库前把地址2拼进地址1并清空地址2
|
||||||
|
|
||||||
|
脚本:
|
||||||
|
英文品名 = 中文品名 + ' ' + SKU
|
||||||
|
说明:落库前英文品名拼上 SKU(申报首行)
|
||||||
|
|
||||||
|
脚本:
|
||||||
|
长度 = 长度 + 1
|
||||||
|
说明:落库前长边加 1cm
|
||||||
|
`
|
||||||
|
|
||||||
|
export const PRE_STORAGE_SCRIPT_AI_DEFAULT_SKILL_KEY = 'oms-sales-product-pre-storage-script'
|
||||||
|
export const PRE_STORAGE_SCRIPT_AI_SCENE = 'salesProductPreStorageScript'
|
||||||
|
export const PRE_STORAGE_SCRIPT_AI_CHAT_SCENE = 'sales_product_pre_storage_script'
|
||||||
|
export const PRE_STORAGE_SCRIPT_AI_STORAGE_KEY = 'oms.salesProduct.preStorageScriptAi'
|
||||||
|
|
||||||
|
export function buildPreStorageScriptAiSystemPrompt(): string {
|
||||||
|
return appendPreScriptFieldCatalog(SKILL_CORE)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildPreStorageScriptAiShortSystemPrompt(): string {
|
||||||
|
return (
|
||||||
|
'你是 OMS 落库前脚本助手。只输出「脚本:」下的赋值语句;' +
|
||||||
|
'字段对齐下单页;改写会写入订单;勿写计费重/状态字段。'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PRE_STORAGE_SCRIPT_AI_QUICK_PROMPTS = [
|
||||||
|
'把收件人地址2拼到地址1后面,中间空格,并清空地址2',
|
||||||
|
'英文品名拼上 SKU',
|
||||||
|
'长度加 1',
|
||||||
|
]
|
||||||
440
src/views/channel/serviceChannels/components/PreScriptEditor.vue
Normal file
440
src/views/channel/serviceChannels/components/PreScriptEditor.vue
Normal file
@ -0,0 +1,440 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
/**
|
||||||
|
* 服务渠道「预报前执行脚本」编辑器:
|
||||||
|
* AI 写脚本 + 字段/运算符插入(中文赋值 DSL)。
|
||||||
|
*/
|
||||||
|
import { computed, nextTick, ref, watch } from 'vue'
|
||||||
|
import { useI18n } from 'vue-i18n'
|
||||||
|
import { IconQuestionCircle } from '@arco-design/web-vue/es/icon'
|
||||||
|
import FormulaAiAssistDrawer from '@/views/channel/autoTrigger/components/FormulaAiAssistDrawer.vue'
|
||||||
|
import {
|
||||||
|
PRE_SCRIPT_AI_CHAT_SCENE,
|
||||||
|
PRE_SCRIPT_AI_DEFAULT_SKILL_KEY,
|
||||||
|
PRE_SCRIPT_AI_QUICK_PROMPTS,
|
||||||
|
PRE_SCRIPT_AI_SCENE,
|
||||||
|
PRE_SCRIPT_AI_STORAGE_KEY,
|
||||||
|
buildPreScriptAiShortSystemPrompt,
|
||||||
|
buildPreScriptAiSystemPrompt,
|
||||||
|
} from '../preScriptAiSkill'
|
||||||
|
import {
|
||||||
|
PRE_SCRIPT_CATEGORIES,
|
||||||
|
PRE_SCRIPT_MAX_LENGTH,
|
||||||
|
PRE_SCRIPT_OPERATORS,
|
||||||
|
appendPreScriptFieldCatalog,
|
||||||
|
preScriptChipsByTable,
|
||||||
|
} from '../preScriptMeta'
|
||||||
|
|
||||||
|
const props = withDefaults(
|
||||||
|
defineProps<{
|
||||||
|
modelValue: string
|
||||||
|
label?: string
|
||||||
|
labelTip?: string
|
||||||
|
placeholder?: string
|
||||||
|
rows?: number
|
||||||
|
/** 覆盖默认渠道预报前 AI 配置(落库前等场景传入) */
|
||||||
|
skillScene?: string
|
||||||
|
defaultSkillKey?: string
|
||||||
|
storageKey?: string
|
||||||
|
chatScene?: string
|
||||||
|
quickPrompts?: string[]
|
||||||
|
fallbackSystemPrompt?: string
|
||||||
|
shortSystemPrompt?: string
|
||||||
|
outputHint?: string
|
||||||
|
hintText?: string
|
||||||
|
fieldHintText?: string
|
||||||
|
}>(),
|
||||||
|
{
|
||||||
|
label: '',
|
||||||
|
labelTip: '',
|
||||||
|
placeholder: '',
|
||||||
|
rows: 4,
|
||||||
|
skillScene: '',
|
||||||
|
defaultSkillKey: '',
|
||||||
|
storageKey: '',
|
||||||
|
chatScene: '',
|
||||||
|
quickPrompts: undefined,
|
||||||
|
fallbackSystemPrompt: '',
|
||||||
|
shortSystemPrompt: '',
|
||||||
|
outputHint: '',
|
||||||
|
hintText: '',
|
||||||
|
fieldHintText: '',
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
'update:modelValue': [string]
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const { t } = useI18n()
|
||||||
|
const textareaRef = ref<HTMLTextAreaElement | null>(null)
|
||||||
|
const aiVisible = ref(false)
|
||||||
|
const fieldPopoverVisible = ref(false)
|
||||||
|
const activeCategory = ref('t_order_recipient')
|
||||||
|
|
||||||
|
const resolvedFallbackPrompt = computed(
|
||||||
|
() => props.fallbackSystemPrompt || buildPreScriptAiSystemPrompt(),
|
||||||
|
)
|
||||||
|
const resolvedShortPrompt = computed(
|
||||||
|
() => props.shortSystemPrompt || buildPreScriptAiShortSystemPrompt(),
|
||||||
|
)
|
||||||
|
const resolvedOutputHint = computed(
|
||||||
|
() =>
|
||||||
|
props.outputHint ||
|
||||||
|
'请按 skill 规定的格式输出(脚本/说明)。多行赋值请放在「脚本:」后。',
|
||||||
|
)
|
||||||
|
const resolvedSkillScene = computed(() => props.skillScene || PRE_SCRIPT_AI_SCENE)
|
||||||
|
const resolvedSkillKey = computed(
|
||||||
|
() => props.defaultSkillKey || PRE_SCRIPT_AI_DEFAULT_SKILL_KEY,
|
||||||
|
)
|
||||||
|
const resolvedStorageKey = computed(() => props.storageKey || PRE_SCRIPT_AI_STORAGE_KEY)
|
||||||
|
const resolvedChatScene = computed(() => props.chatScene || PRE_SCRIPT_AI_CHAT_SCENE)
|
||||||
|
const resolvedQuickPrompts = computed(() =>
|
||||||
|
props.quickPrompts?.length ? props.quickPrompts : PRE_SCRIPT_AI_QUICK_PROMPTS,
|
||||||
|
)
|
||||||
|
const resolvedHint = computed(
|
||||||
|
() => props.hintText || t('channel.serviceChannels.preScript.hint'),
|
||||||
|
)
|
||||||
|
const resolvedFieldHint = computed(
|
||||||
|
() => props.fieldHintText || t('channel.serviceChannels.preScript.fieldHint'),
|
||||||
|
)
|
||||||
|
|
||||||
|
const charCount = computed(() => (props.modelValue || '').length)
|
||||||
|
const activeChips = computed(() => preScriptChipsByTable(activeCategory.value))
|
||||||
|
const toolbarInline = computed(() => !!props.label)
|
||||||
|
|
||||||
|
function updateValue(next: string) {
|
||||||
|
emit('update:modelValue', next.slice(0, PRE_SCRIPT_MAX_LENGTH))
|
||||||
|
}
|
||||||
|
|
||||||
|
function onInput(e: Event) {
|
||||||
|
updateValue((e.target as HTMLTextAreaElement).value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function onAiApply(payload: { expression: string }) {
|
||||||
|
updateValue((payload.expression || '').slice(0, PRE_SCRIPT_MAX_LENGTH))
|
||||||
|
}
|
||||||
|
|
||||||
|
async function insertAtCursor(text: string) {
|
||||||
|
const current = props.modelValue || ''
|
||||||
|
const el = textareaRef.value
|
||||||
|
if (!el) {
|
||||||
|
updateValue((current + text).slice(0, PRE_SCRIPT_MAX_LENGTH))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const start = el.selectionStart ?? current.length
|
||||||
|
const end = el.selectionEnd ?? start
|
||||||
|
const next = (current.slice(0, start) + text + current.slice(end)).slice(0, PRE_SCRIPT_MAX_LENGTH)
|
||||||
|
updateValue(next)
|
||||||
|
await nextTick()
|
||||||
|
const pos = Math.min(start + text.length, next.length)
|
||||||
|
el.focus()
|
||||||
|
el.setSelectionRange(pos, pos)
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => props.modelValue,
|
||||||
|
(val) => {
|
||||||
|
if ((val || '').length > PRE_SCRIPT_MAX_LENGTH) {
|
||||||
|
updateValue((val || '').slice(0, PRE_SCRIPT_MAX_LENGTH))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="pre-script-editor" :class="{ 'has-inline-toolbar': toolbarInline }">
|
||||||
|
<div v-if="toolbarInline" class="editor-label">
|
||||||
|
{{ label }}
|
||||||
|
<a-tooltip v-if="labelTip" :content="labelTip">
|
||||||
|
<icon-question-circle class="tip-icon" />
|
||||||
|
</a-tooltip>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="formula-text-wrap">
|
||||||
|
<textarea
|
||||||
|
ref="textareaRef"
|
||||||
|
class="formula-textarea"
|
||||||
|
:value="modelValue || ''"
|
||||||
|
:rows="rows"
|
||||||
|
:maxlength="PRE_SCRIPT_MAX_LENGTH"
|
||||||
|
:placeholder="placeholder || t('channel.serviceChannels.form.placeholder.preScript')"
|
||||||
|
@input="onInput"
|
||||||
|
/>
|
||||||
|
<div class="char-count">{{ charCount }}/{{ PRE_SCRIPT_MAX_LENGTH }}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="editor-footer" :class="{ 'editor-footer--inline': toolbarInline }">
|
||||||
|
<div class="editor-actions">
|
||||||
|
<a-button
|
||||||
|
type="secondary"
|
||||||
|
:size="toolbarInline ? 'mini' : 'small'"
|
||||||
|
@click="aiVisible = true"
|
||||||
|
>
|
||||||
|
{{ t('channel.serviceChannels.preScript.aiWrite') }}
|
||||||
|
</a-button>
|
||||||
|
<a-popover
|
||||||
|
v-model:popup-visible="fieldPopoverVisible"
|
||||||
|
trigger="click"
|
||||||
|
position="bl"
|
||||||
|
:content-style="{ padding: '16px', width: '520px', maxWidth: '92vw' }"
|
||||||
|
>
|
||||||
|
<a-button type="secondary" :size="toolbarInline ? 'mini' : 'small'">
|
||||||
|
{{ t('channel.serviceChannels.preScript.insertField') }}
|
||||||
|
</a-button>
|
||||||
|
<template #content>
|
||||||
|
<div class="field-popover">
|
||||||
|
<div class="section-label">{{ t('channel.serviceChannels.preScript.operators') }}</div>
|
||||||
|
<div class="chip-bar">
|
||||||
|
<button
|
||||||
|
v-for="op in PRE_SCRIPT_OPERATORS"
|
||||||
|
:key="op.label"
|
||||||
|
type="button"
|
||||||
|
class="chip-btn"
|
||||||
|
@click="insertAtCursor(op.insert)"
|
||||||
|
>
|
||||||
|
{{ op.label }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="section-label">{{ t('channel.serviceChannels.preScript.fields') }}</div>
|
||||||
|
<div class="category-tabs">
|
||||||
|
<button
|
||||||
|
v-for="cat in PRE_SCRIPT_CATEGORIES"
|
||||||
|
:key="cat.key"
|
||||||
|
type="button"
|
||||||
|
class="category-tab"
|
||||||
|
:class="{ active: activeCategory === cat.key }"
|
||||||
|
@click="activeCategory = cat.key"
|
||||||
|
>
|
||||||
|
{{ cat.label }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p class="field-hint">{{ resolvedFieldHint }}</p>
|
||||||
|
<div class="chip-bar field-chips">
|
||||||
|
<button
|
||||||
|
v-for="(chip, idx) in activeChips"
|
||||||
|
:key="`${chip.table}-${chip.label}-${idx}`"
|
||||||
|
type="button"
|
||||||
|
class="chip-btn"
|
||||||
|
:class="{ writable: chip.writable }"
|
||||||
|
:title="`${chip.refHint}${chip.writable ? '(可写)' : '(只读引用)'}`"
|
||||||
|
@click="insertAtCursor(chip.insert)"
|
||||||
|
>
|
||||||
|
{{ chip.label }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</a-popover>
|
||||||
|
</div>
|
||||||
|
<span class="editor-hint">{{ resolvedHint }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<FormulaAiAssistDrawer
|
||||||
|
v-model:visible="aiVisible"
|
||||||
|
:current-formula="modelValue || ''"
|
||||||
|
:skill-scene="resolvedSkillScene"
|
||||||
|
:default-skill-key="resolvedSkillKey"
|
||||||
|
:storage-key="resolvedStorageKey"
|
||||||
|
:chat-scene="resolvedChatScene"
|
||||||
|
:quick-prompts="resolvedQuickPrompts"
|
||||||
|
:fallback-system-prompt="resolvedFallbackPrompt"
|
||||||
|
:short-system-prompt="resolvedShortPrompt"
|
||||||
|
:output-hint="resolvedOutputHint"
|
||||||
|
:append-catalog="appendPreScriptFieldCatalog"
|
||||||
|
@apply="onAiApply"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style lang="less" scoped>
|
||||||
|
.pre-script-editor {
|
||||||
|
width: 100%;
|
||||||
|
|
||||||
|
&.has-inline-toolbar {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: auto minmax(0, 1fr);
|
||||||
|
grid-template-areas:
|
||||||
|
'label footer'
|
||||||
|
'text text';
|
||||||
|
column-gap: 12px;
|
||||||
|
row-gap: 6px;
|
||||||
|
align-items: center;
|
||||||
|
|
||||||
|
.editor-label {
|
||||||
|
grid-area: label;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editor-footer {
|
||||||
|
grid-area: footer;
|
||||||
|
margin-top: 0;
|
||||||
|
justify-content: flex-end;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.formula-text-wrap {
|
||||||
|
grid-area: text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.editor-label {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--color-text-2);
|
||||||
|
white-space: nowrap;
|
||||||
|
line-height: 22px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tip-icon {
|
||||||
|
color: var(--color-text-3);
|
||||||
|
cursor: help;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.formula-text-wrap {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.formula-textarea {
|
||||||
|
width: 100%;
|
||||||
|
min-height: 96px;
|
||||||
|
max-height: 240px;
|
||||||
|
resize: vertical;
|
||||||
|
box-sizing: border-box;
|
||||||
|
padding: 8px 12px 24px;
|
||||||
|
border: 1px solid var(--color-border-2);
|
||||||
|
border-radius: 4px;
|
||||||
|
font-family: var(--app-font-mono);
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.5;
|
||||||
|
color: var(--color-text-1);
|
||||||
|
background: var(--app-card-bg);
|
||||||
|
outline: none;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
border-color: var(--color-border-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
&:focus {
|
||||||
|
border-color: var(--app-primary-color, #2d8c8c);
|
||||||
|
box-shadow: 0 0 0 2px rgba(45, 140, 140, 0.12);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.char-count {
|
||||||
|
position: absolute;
|
||||||
|
right: 10px;
|
||||||
|
bottom: 6px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--color-text-3);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editor-footer {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px 12px;
|
||||||
|
margin-top: 6px;
|
||||||
|
|
||||||
|
&--inline {
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.editor-actions {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editor-hint {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--color-text-3);
|
||||||
|
line-height: 1.4;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field-popover {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
max-height: 480px;
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-label {
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--color-text-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.field-hint {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--color-text-3);
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chip-bar {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field-chips {
|
||||||
|
max-height: 280px;
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chip-btn {
|
||||||
|
height: 30px;
|
||||||
|
padding: 0 10px;
|
||||||
|
border: 1px solid var(--color-border-2);
|
||||||
|
border-radius: 4px;
|
||||||
|
background: var(--color-fill-2);
|
||||||
|
color: var(--color-text-1);
|
||||||
|
font-size: 13px;
|
||||||
|
cursor: pointer;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
border-color: var(--app-primary-color, #2d8c8c);
|
||||||
|
color: var(--app-primary-color, #2d8c8c);
|
||||||
|
background: rgba(45, 140, 140, 0.06);
|
||||||
|
}
|
||||||
|
|
||||||
|
&.writable {
|
||||||
|
border-color: rgba(45, 140, 140, 0.35);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.category-tabs {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.category-tab {
|
||||||
|
height: 26px;
|
||||||
|
padding: 0 8px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--color-text-3);
|
||||||
|
font-size: 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
|
||||||
|
&.active {
|
||||||
|
background: rgba(45, 140, 140, 0.1);
|
||||||
|
color: var(--app-primary-color, #2d8c8c);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@ -318,12 +318,12 @@
|
|||||||
|
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<div class="form-item full-width">
|
<div class="form-item full-width">
|
||||||
<label class="form-label">{{ t('channel.serviceChannels.form.preScript') }}</label>
|
<PreScriptEditor
|
||||||
<a-textarea
|
v-model="formData.preScript"
|
||||||
v-model="formData.preScript"
|
:label="t('channel.serviceChannels.form.preScript')"
|
||||||
|
:label-tip="t('channel.serviceChannels.tip.preScript')"
|
||||||
:placeholder="t('channel.serviceChannels.form.placeholder.preScript')"
|
:placeholder="t('channel.serviceChannels.form.placeholder.preScript')"
|
||||||
:rows="4"
|
:rows="5"
|
||||||
class="form-textarea"
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -1394,20 +1394,13 @@
|
|||||||
}}
|
}}
|
||||||
</a-button>
|
</a-button>
|
||||||
</div>
|
</div>
|
||||||
<a-form-item v-if="addChannelShowAdvanced">
|
<a-form-item v-if="addChannelShowAdvanced" hide-label>
|
||||||
<template #label>
|
<PreScriptEditor
|
||||||
<span class="label-with-tip">
|
|
||||||
{{ t('channel.serviceChannels.form.preScript') }}
|
|
||||||
<a-tooltip :content="t('channel.serviceChannels.tip.preScript')">
|
|
||||||
<icon-question-circle class="tip-icon" />
|
|
||||||
</a-tooltip>
|
|
||||||
</span>
|
|
||||||
</template>
|
|
||||||
<a-textarea
|
|
||||||
v-model="addChannelForm.preScript"
|
v-model="addChannelForm.preScript"
|
||||||
|
:label="t('channel.serviceChannels.form.preScript')"
|
||||||
|
:label-tip="t('channel.serviceChannels.tip.preScript')"
|
||||||
:placeholder="t('channel.serviceChannels.form.placeholder.preScript')"
|
:placeholder="t('channel.serviceChannels.form.placeholder.preScript')"
|
||||||
:auto-size="{ minRows: 3, maxRows: 8 }"
|
:rows="4"
|
||||||
allow-clear
|
|
||||||
/>
|
/>
|
||||||
</a-form-item>
|
</a-form-item>
|
||||||
</a-form>
|
</a-form>
|
||||||
@ -1602,6 +1595,7 @@ import { getWarehouseList } from '@/api/system/warehouse'
|
|||||||
import CustomLeftMenu from '@/components/CustomLeftMenu/index.vue'
|
import CustomLeftMenu from '@/components/CustomLeftMenu/index.vue'
|
||||||
import type { CustomLeftMenuTreeNode } from '@/components/CustomLeftMenu/types'
|
import type { CustomLeftMenuTreeNode } from '@/components/CustomLeftMenu/types'
|
||||||
import BillingConditionEditor from '@/views/channel/salesProducts/components/BillingConditionEditor.vue'
|
import BillingConditionEditor from '@/views/channel/salesProducts/components/BillingConditionEditor.vue'
|
||||||
|
import PreScriptEditor from '@/views/channel/serviceChannels/components/PreScriptEditor.vue'
|
||||||
import { ENABLE_STATUS, isEnableStatusEnabled, toEnableStatus } from '@/utils/enableStatus'
|
import { ENABLE_STATUS, isEnableStatusEnabled, toEnableStatus } from '@/utils/enableStatus'
|
||||||
import { pickResolvedAudit } from '@/utils/auditFields'
|
import { pickResolvedAudit } from '@/utils/auditFields'
|
||||||
|
|
||||||
|
|||||||
65
src/views/channel/serviceChannels/preScriptAiSkill.ts
Normal file
65
src/views/channel/serviceChannels/preScriptAiSkill.ts
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
import { appendPreScriptFieldCatalog } from './preScriptMeta'
|
||||||
|
|
||||||
|
const SKILL_CORE = `你是 OMS「服务渠道预报前执行脚本」助手。根据用户中文描述,生成可粘贴到渠道 PreScript 的中文赋值脚本(ChineseAssignScriptEvaluator)。
|
||||||
|
|
||||||
|
## 场景
|
||||||
|
|
||||||
|
- 预报推送给下游之前,改写下单相关字段(拼地址、拼品名 SKU、微调长宽高等)
|
||||||
|
- 只影响本次预报报文,不回写订单库
|
||||||
|
- 字段范围对齐「单票下单」录入项;不要使用状态/问题件/计费重/体积重等无关字段
|
||||||
|
- 不要生成接口通 Natasha C#,不要生成自动触发布尔公式
|
||||||
|
|
||||||
|
## 产出格式(必须)
|
||||||
|
|
||||||
|
脚本:
|
||||||
|
一行或多行赋值语句
|
||||||
|
说明:一句话
|
||||||
|
|
||||||
|
## 语法硬规则
|
||||||
|
|
||||||
|
- 每条语句:可写字段 = 表达式
|
||||||
|
- 可写:收/发件人与申报字符串(申报首行);件重尺仅 长度/宽度/高度/实重
|
||||||
|
- 右侧可引用目录中的字段(订单基本信息多为只读)、单引号字符串、数字、+ - * / ()
|
||||||
|
- 字符串拼接用 +;多语句换行或分号;# 为注释
|
||||||
|
- 禁止 == != && ||、包含()、有值()、为空()、双引号、英文字段名
|
||||||
|
- 禁止写:计费重、体积重、体积、件重尺类型、HS编码(用进口/出口HS编码)、发件人是否默认
|
||||||
|
- 总长度 ≤ 10000
|
||||||
|
|
||||||
|
## 示例
|
||||||
|
|
||||||
|
脚本:
|
||||||
|
收件人地址1 = 收件人地址1 + ' ' + 收件人地址2
|
||||||
|
收件人地址2 = ''
|
||||||
|
说明:把地址2拼进地址1并清空地址2
|
||||||
|
|
||||||
|
脚本:
|
||||||
|
英文品名 = 中文品名 + ' ' + SKU
|
||||||
|
说明:预报时英文品名拼上 SKU(申报首行)
|
||||||
|
|
||||||
|
脚本:
|
||||||
|
长度 = 长度 + 1
|
||||||
|
说明:预报时长边加 1cm
|
||||||
|
`
|
||||||
|
|
||||||
|
export const PRE_SCRIPT_AI_DEFAULT_SKILL_KEY = 'oms-service-channel-pre-script'
|
||||||
|
export const PRE_SCRIPT_AI_SCENE = 'serviceChannelPreScript'
|
||||||
|
export const PRE_SCRIPT_AI_CHAT_SCENE = 'service_channel_pre_script'
|
||||||
|
export const PRE_SCRIPT_AI_STORAGE_KEY = 'oms.serviceChannel.preScriptAi'
|
||||||
|
|
||||||
|
export function buildPreScriptAiSystemPrompt(): string {
|
||||||
|
return appendPreScriptFieldCatalog(SKILL_CORE)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildPreScriptAiShortSystemPrompt(): string {
|
||||||
|
return (
|
||||||
|
'你是 OMS 预报前脚本助手。只输出「脚本:」下的赋值语句;' +
|
||||||
|
"字段对齐下单页;可写如收件人地址1、英文品名、长度/实重;勿写计费重/状态字段。"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PRE_SCRIPT_AI_QUICK_PROMPTS = [
|
||||||
|
'把收件人地址2拼到地址1后面,中间空格,并清空地址2',
|
||||||
|
'把省州、城市拼到收件人地址1前面',
|
||||||
|
'英文品名拼上 SKU',
|
||||||
|
'长度加 1',
|
||||||
|
]
|
||||||
248
src/views/channel/serviceChannels/preScriptMeta.ts
Normal file
248
src/views/channel/serviceChannels/preScriptMeta.ts
Normal file
@ -0,0 +1,248 @@
|
|||||||
|
import {
|
||||||
|
FORMULA_MAX_LENGTH,
|
||||||
|
ORDER_TABLE_CATEGORIES,
|
||||||
|
ORDER_TABLE_FIELDS,
|
||||||
|
type OrderTableFieldDef,
|
||||||
|
} from '@/views/channel/autoTrigger/formulaMeta'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 对齐单票下单页(placeOrder)录入/回填字段:
|
||||||
|
* 剔除状态/问题件/理赔/下游凭证、系统计算件重尺、通用 HS编码、发件人是否默认等。
|
||||||
|
* table.field → 是否出现在脚本字段面板(RHS 可引用)。
|
||||||
|
*/
|
||||||
|
const PLACE_ORDER_FIELD_KEYS = new Set<string>([
|
||||||
|
// 订单基本(下单「基本信息」+ H5 COD/跟踪号)
|
||||||
|
't_order.ClientNo',
|
||||||
|
't_order.TrackNo',
|
||||||
|
't_order.ServiceNo',
|
||||||
|
't_order.ProductCode',
|
||||||
|
't_order.ConsigneeCountry',
|
||||||
|
't_order.ConsigneeCountryName',
|
||||||
|
't_order.CargoAttribute',
|
||||||
|
't_order.ExportCustomsMode',
|
||||||
|
't_order.WarehouseId',
|
||||||
|
't_order.CustomerId',
|
||||||
|
't_order.IsCod',
|
||||||
|
't_order.CodCurrency',
|
||||||
|
't_order.CodSum',
|
||||||
|
't_order.DeclaredCurrency',
|
||||||
|
't_order.DeclaredSum',
|
||||||
|
't_order.Quantity',
|
||||||
|
't_order.AdditionalServices',
|
||||||
|
|
||||||
|
// 收件人
|
||||||
|
't_order_recipient.RecipientsName',
|
||||||
|
't_order_recipient.CompanyName',
|
||||||
|
't_order_recipient.Phone',
|
||||||
|
't_order_recipient.TelePhone',
|
||||||
|
't_order_recipient.Email',
|
||||||
|
't_order_recipient.ZipCode',
|
||||||
|
't_order_recipient.Province',
|
||||||
|
't_order_recipient.City',
|
||||||
|
't_order_recipient.StreetNumber',
|
||||||
|
't_order_recipient.StreetAddress1',
|
||||||
|
't_order_recipient.StreetAddress2',
|
||||||
|
't_order_recipient.StreetAddress3',
|
||||||
|
't_order_recipient.TaxNo',
|
||||||
|
't_order_recipient.CertificateNo',
|
||||||
|
't_order_recipient.Eori',
|
||||||
|
't_order_recipient.Vat',
|
||||||
|
|
||||||
|
// 发件人(地址簿回填;不含 IsDefault)
|
||||||
|
't_order_sender.SenderName',
|
||||||
|
't_order_sender.Company',
|
||||||
|
't_order_sender.Province',
|
||||||
|
't_order_sender.City',
|
||||||
|
't_order_sender.ZipCode',
|
||||||
|
't_order_sender.StreetAddress1',
|
||||||
|
't_order_sender.StreetAddress2',
|
||||||
|
't_order_sender.StreetAddress3',
|
||||||
|
't_order_sender.HouseNumber',
|
||||||
|
't_order_sender.Phone',
|
||||||
|
't_order_sender.TelePhone',
|
||||||
|
't_order_sender.Email',
|
||||||
|
|
||||||
|
// 申报(不含通用 HsCode;金额/总重派生仍可引用)
|
||||||
|
't_order_declaration.CnName',
|
||||||
|
't_order_declaration.EnName',
|
||||||
|
't_order_declaration.Sku',
|
||||||
|
't_order_declaration.Unit',
|
||||||
|
't_order_declaration.UnitPrice',
|
||||||
|
't_order_declaration.UnitWeight',
|
||||||
|
't_order_declaration.Quantity',
|
||||||
|
't_order_declaration.Amount',
|
||||||
|
't_order_declaration.Weight',
|
||||||
|
't_order_declaration.ImHsCode',
|
||||||
|
't_order_declaration.ExHsCode',
|
||||||
|
't_order_declaration.DeclareElement',
|
||||||
|
't_order_declaration.ProductId',
|
||||||
|
't_order_declaration.NonStdProductId',
|
||||||
|
't_order_declaration.StdProductId',
|
||||||
|
't_order_declaration.Category',
|
||||||
|
't_order_declaration.Brand',
|
||||||
|
't_order_declaration.BrandType',
|
||||||
|
't_order_declaration.Distribution',
|
||||||
|
't_order_declaration.Material',
|
||||||
|
't_order_declaration.EnMaterial',
|
||||||
|
't_order_declaration.Purpose',
|
||||||
|
't_order_declaration.Attributes',
|
||||||
|
't_order_declaration.OriginCountry',
|
||||||
|
't_order_declaration.SalesLink',
|
||||||
|
't_order_declaration.Model',
|
||||||
|
't_order_declaration.Specifications',
|
||||||
|
't_order_declaration.Comment',
|
||||||
|
|
||||||
|
// 件重尺:下单只填实重+长宽高
|
||||||
|
't_order_weight.Length',
|
||||||
|
't_order_weight.Width',
|
||||||
|
't_order_weight.Height',
|
||||||
|
't_order_weight.ActualWeight',
|
||||||
|
])
|
||||||
|
|
||||||
|
/** 可写字段(LHS):收/发件人与申报字符串 + 件重尺四数值 */
|
||||||
|
const WRITABLE_FIELD_KEYS = new Set<string>([
|
||||||
|
't_order_recipient.RecipientsName',
|
||||||
|
't_order_recipient.CompanyName',
|
||||||
|
't_order_recipient.Phone',
|
||||||
|
't_order_recipient.TelePhone',
|
||||||
|
't_order_recipient.Email',
|
||||||
|
't_order_recipient.ZipCode',
|
||||||
|
't_order_recipient.Province',
|
||||||
|
't_order_recipient.City',
|
||||||
|
't_order_recipient.StreetNumber',
|
||||||
|
't_order_recipient.StreetAddress1',
|
||||||
|
't_order_recipient.StreetAddress2',
|
||||||
|
't_order_recipient.StreetAddress3',
|
||||||
|
't_order_recipient.TaxNo',
|
||||||
|
't_order_recipient.CertificateNo',
|
||||||
|
't_order_recipient.Eori',
|
||||||
|
't_order_recipient.Vat',
|
||||||
|
|
||||||
|
't_order_sender.SenderName',
|
||||||
|
't_order_sender.Company',
|
||||||
|
't_order_sender.Province',
|
||||||
|
't_order_sender.City',
|
||||||
|
't_order_sender.ZipCode',
|
||||||
|
't_order_sender.StreetAddress1',
|
||||||
|
't_order_sender.StreetAddress2',
|
||||||
|
't_order_sender.StreetAddress3',
|
||||||
|
't_order_sender.HouseNumber',
|
||||||
|
't_order_sender.Phone',
|
||||||
|
't_order_sender.TelePhone',
|
||||||
|
't_order_sender.Email',
|
||||||
|
|
||||||
|
't_order_declaration.CnName',
|
||||||
|
't_order_declaration.EnName',
|
||||||
|
't_order_declaration.Sku',
|
||||||
|
't_order_declaration.Unit',
|
||||||
|
't_order_declaration.ImHsCode',
|
||||||
|
't_order_declaration.ExHsCode',
|
||||||
|
't_order_declaration.DeclareElement',
|
||||||
|
't_order_declaration.ProductId',
|
||||||
|
't_order_declaration.NonStdProductId',
|
||||||
|
't_order_declaration.StdProductId',
|
||||||
|
't_order_declaration.Category',
|
||||||
|
't_order_declaration.Brand',
|
||||||
|
't_order_declaration.BrandType',
|
||||||
|
't_order_declaration.Distribution',
|
||||||
|
't_order_declaration.Material',
|
||||||
|
't_order_declaration.EnMaterial',
|
||||||
|
't_order_declaration.Purpose',
|
||||||
|
't_order_declaration.Attributes',
|
||||||
|
't_order_declaration.OriginCountry',
|
||||||
|
't_order_declaration.SalesLink',
|
||||||
|
't_order_declaration.Model',
|
||||||
|
't_order_declaration.Specifications',
|
||||||
|
't_order_declaration.Comment',
|
||||||
|
|
||||||
|
't_order_weight.Length',
|
||||||
|
't_order_weight.Width',
|
||||||
|
't_order_weight.Height',
|
||||||
|
't_order_weight.ActualWeight',
|
||||||
|
])
|
||||||
|
|
||||||
|
function fieldKey(f: Pick<OrderTableFieldDef, 'table' | 'field'>) {
|
||||||
|
return `${f.table}.${f.field}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PRE_SCRIPT_VISIBLE_FIELDS: OrderTableFieldDef[] = ORDER_TABLE_FIELDS.filter((f) =>
|
||||||
|
PLACE_ORDER_FIELD_KEYS.has(fieldKey(f)),
|
||||||
|
)
|
||||||
|
|
||||||
|
export const PRE_SCRIPT_WRITABLE_FIELDS: OrderTableFieldDef[] = PRE_SCRIPT_VISIBLE_FIELDS.filter((f) =>
|
||||||
|
WRITABLE_FIELD_KEYS.has(fieldKey(f)),
|
||||||
|
)
|
||||||
|
|
||||||
|
export const PRE_SCRIPT_WRITABLE_LABELS = new Set(
|
||||||
|
PRE_SCRIPT_WRITABLE_FIELDS.map((f) => f.label),
|
||||||
|
)
|
||||||
|
|
||||||
|
/** 插入字段分类(与下单步骤对齐) */
|
||||||
|
export const PRE_SCRIPT_CATEGORIES = ORDER_TABLE_CATEGORIES.filter((c) =>
|
||||||
|
[
|
||||||
|
't_order',
|
||||||
|
't_order_recipient',
|
||||||
|
't_order_sender',
|
||||||
|
't_order_declaration',
|
||||||
|
't_order_weight',
|
||||||
|
].includes(c.key),
|
||||||
|
)
|
||||||
|
|
||||||
|
export const PRE_SCRIPT_OPERATORS = [
|
||||||
|
{ label: '=', insert: ' = ' },
|
||||||
|
{ label: '+', insert: ' + ' },
|
||||||
|
{ label: '-', insert: ' - ' },
|
||||||
|
{ label: '×', insert: ' * ' },
|
||||||
|
{ label: '÷', insert: ' / ' },
|
||||||
|
{ label: "''", insert: "''" },
|
||||||
|
{ label: '(', insert: '(' },
|
||||||
|
{ label: ')', insert: ')' },
|
||||||
|
{ label: ';', insert: ';\n' },
|
||||||
|
]
|
||||||
|
|
||||||
|
export const PRE_SCRIPT_MAX_LENGTH = FORMULA_MAX_LENGTH
|
||||||
|
|
||||||
|
function fieldUsageHint(f: OrderTableFieldDef): string {
|
||||||
|
const writable = WRITABLE_FIELD_KEYS.has(fieldKey(f))
|
||||||
|
if (writable && f.valueType === 'string') {
|
||||||
|
return `${f.label}(可写)|右侧引用直接写中文名`
|
||||||
|
}
|
||||||
|
if (writable && f.valueType === 'number') {
|
||||||
|
return `${f.label}(可写数值)|如 ${f.label} = ${f.label} + 1`
|
||||||
|
}
|
||||||
|
return `${f.label}(只读引用)`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 拼进 AI system:仅下单相关字段 */
|
||||||
|
export function appendPreScriptFieldCatalog(core: string): string {
|
||||||
|
const byTable = new Map<string, OrderTableFieldDef[]>()
|
||||||
|
for (const f of PRE_SCRIPT_VISIBLE_FIELDS) {
|
||||||
|
const list = byTable.get(f.table) ?? []
|
||||||
|
list.push(f)
|
||||||
|
byTable.set(f.table, list)
|
||||||
|
}
|
||||||
|
const lines: string[] = ['## 可用字段目录(仅下单相关;勿编造未列出的中文名)', '']
|
||||||
|
for (const [table, fields] of byTable) {
|
||||||
|
lines.push(`### ${table}`)
|
||||||
|
for (const f of fields) {
|
||||||
|
lines.push(`- ${f.label} (${f.valueType}) → ${fieldUsageHint(f)}`)
|
||||||
|
}
|
||||||
|
lines.push('')
|
||||||
|
}
|
||||||
|
return `${core.trim()}\n\n${lines.join('\n').trim()}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function preScriptChipsByTable(tableKey: string) {
|
||||||
|
return PRE_SCRIPT_VISIBLE_FIELDS.filter((f) => f.table === tableKey).map((f) => {
|
||||||
|
const writable = WRITABLE_FIELD_KEYS.has(fieldKey(f))
|
||||||
|
return {
|
||||||
|
label: f.label,
|
||||||
|
table: f.table,
|
||||||
|
insert: f.label,
|
||||||
|
refHint: writable
|
||||||
|
? `${f.table}.${f.field}(可写)`
|
||||||
|
: `${f.table}.${f.field}(只读引用)`,
|
||||||
|
writable,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user