Files
order_site/docs/成本中心API契约.md
T
yml2213 769bc69bcf refactor(db): 财务渠道迁移合并为单条 113
生产当前在 112,原 113–118 六条迁移合并为 113_finance_channel_cutover:
- 渠道/状态三列 + 从 fulfillment_mode 回填
- 删除旧列及旧索引
- 销售事实列改名 channel
- 财务管道增量索引(原 117/118)
- 移除不再使用的 refund_adjustment 约束(历史退款不入财务)

42 万行副本实测 49 秒完成;生产只需执行一条迁移,不再需要中间回填脚本。
2026-11-01 16:34:12 +08:00

353 lines
14 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 成本中心 API 契约
> 状态:**现行**。后端服务与前端页面都必须严格按此实现,不得各自发挥。
> 最后校准:2026-10-31(履约渠道模型,迁移 113)
> 代码基线:`main`
> 详细业务口径见 [财务与履约口径总纲-2026-10-23.md](财务与履约口径总纲-2026-10-23.md);数据模型见 [成本中心与履约模型.md](成本中心与履约模型.md)。
## 一、字段替换总表
| 旧字段 | 新字段 | 出现位置 |
| --- | --- | --- |
| `cost_items.carrier_type` | `cost_items.cost_model` | DB / 成本项接口 |
| `cost_items.cost_type` | (并入 `cost_model`) | DB / 成本项接口 |
| `cost_snapshots.carrier_type` | (删除) | DB |
| `cost_exceptions.carrier_type` | (删除) | DB |
| `product_catalog.carrier_type` | (删除,改由 `canonical_sku` 前缀推导) | DB / 商品接口 |
| `sales_daily_facts.carrier_type` | `sales_daily_facts.channel` | DB / 销售事实接口 |
| `work_product_rules.legacy_cost_source` | (删除) | DB |
| `manual_expense_records` / `manual_expense_events` | (删除,人工成本只走确认履约) | DB |
## 二、枚举映射
### 2.1 `cost_model`(取代 `cost_type` + `carrier_type`)
成本模型与履约方式正交:专属模型只对对应履约方式生效,通用模型对所有履约方式生效。
| 新值 | 含义 | 取代旧的 |
| --- | --- | --- |
| `affiliate_purchase` | 自动发货上游采购成本 | `cost_type=auto_purchase` |
| `work_order_reward` | 接单平台打手报酬 | `cost_type=work_order_reward` |
| `third_party_voucher_cost` | 第三方卡券采购成本 | 新增 |
| `manual_actual` | 人工客服实际支出 | `cost_type=manual_service` |
| `platform_fee` | 平台服务费 | `cost_type=platform_fee` |
| `payment_fee` | 支付通道费 | `cost_type=payment_fee` |
| `after_sales_loss` | 售后损失 | `cost_type=after_sales_loss` |
| `other` | 其他 | `cost_type=shipping_other` / `cost_type=other` |
### 2.2 `pricing_mode`(精简为 3 个)
`per_item` / `per_order` / `percent_of_revenue`
(删除 `per_hour`、`fixed_daily`——人工成本逐单按实际金额,不按工时)
### 2.3 `channel`(履约渠道,唯一真源)
`work_order` / `affiliate_dash` / `third_party_voucher` / `manual`,
另有两个派生值:`pending`(待分类)、`archived`(断代归档)、`unclassified`(事实桶)。
DB 真源是 `order_items.fulfillment_channel` + `fulfillment_status`;接口字段名统一为 `channel`。
## 三、成本项接口
```
POST /api/v1/admin/cost-center/cost-items
GET /api/v1/admin/cost-center/cost-items
PATCH /api/v1/admin/cost-center/cost-items/:id
DELETE /api/v1/admin/cost-center/cost-items/:id
```
请求体(创建/更新):
```jsonc
{
"code": "可选;留空则按 costModel 自动生成",
"name": "必填",
"costModel": "affiliate_purchase | work_order_reward | manual_actual | platform_fee | payment_fee | after_sales_loss | other",
"pricingMode": "per_item | per_order | percent_of_revenue",
"unitName": "件",
"currency": "CNY",
"status": "active | archived",
"note": ""
}
```
**不再接受 `costType` 与 `carrierType`。**
响应项(`CostItem`):
```jsonc
{
"id": 10,
"code": "sys_affiliate_purchase",
"name": "自动发货上游采购成本",
"costModel": "affiliate_purchase",
"pricingMode": "per_item",
"unitName": "件",
"currency": "CNY",
"status": "active",
"note": "",
"snapshotCount": 0,
"createdAt": "...",
"updatedAt": "..."
}
```
## 四、商品接口
商品**不再返回 `carrierType`**。前端若要按来源分组,用 `canonicalSku` 前缀:
| 前缀 | 来源 | 建议展示名 |
| --- | --- | --- |
| `aff:` | 自动发货 | 自动发货 |
| `tpl:` | 接单模板 | 接单平台 |
| `wo:` | 工单证据 | 接单平台 |
| `man:` | 人工 | 人工 |
| 其他 | 未分类 | 未分类 |
`GET /api/v1/admin/cost-center/products` 的 `carrierType` 查询参数**保留**,
但语义改为「按 `canonical_sku` 前缀筛选」,取值 `affiliate_dash | work_order | manual`。
后端实现方式:
```sql
AND (
($n = 'affiliate_dash' AND p.canonical_sku LIKE 'aff:%')
OR ($n = 'work_order' AND (p.canonical_sku LIKE 'tpl:%' OR p.canonical_sku LIKE 'wo:%'))
OR ($n = 'manual' AND p.canonical_sku LIKE 'man:%')
)
```
### 4.1 渠道映射诊断与未归一队列
| 接口 | 说明 |
| --- | --- |
| `GET /api/v1/admin/cost-center/mappings/diagnostics` | 标准商品数 / 映射数 / 有映射商品数 / 未归一订单项 / 未归一 SKU 组;按 `channel` 拆分聚合 |
| `GET /api/v1/admin/cost-center/mappings/unmapped` | 未归一队列,按「来源 + 店铺 + 平台 SKU + 履约方式」聚合,支持 `keyword` / `provider` / `channel` 与分页 |
| `POST /api/v1/admin/cost-center/mappings/backfill` | 回填订单项映射;返回 `resolvedExceptionCount`(已归一的 `product_mapping_missing` 异常自动收口) |
### 4.2 人工商品归一(已删除)
> 2026-10-31 起商品归一只走 `product_normalize` 管道(模板/人工配置/`aff:`/`tpv:` 直达),
> 不再提供手工归一接口。以下为历史记录。
`POST /api/v1/admin/cost-center/manual-products/normalize`,`finance.config`。
```jsonc
// 请求(全部可选;dryRun=true 只预览)
{ "dateFrom": "2026-07-10", "dateTo": "2026-10-14", "dryRun": false }
// 返回
{
"distinctSkuCount": 1116, // 待处理的内部 SKU 数
"pendingItemCount": 91606, // 待归一的订单项
"createdProductCount": 1116, // 新建的 man: 商品
"updatedItemCount": 91606, // 回填的订单项
"updatedSnapshotCount": 4, // 补了商品维度的成本快照
"resolvedExceptionCount": 91606,
"remainingItemCount": 0
}
```
键的取值:`spec_json->>'skuNick'`(快手)→ `spec_json->>'outSkuSn'`(拼多多)→ `sku_code` 兜底;
商品 `canonical_sku = man:<内部SKU>`,`canonical_name` 优先取 `manual_sku_registry.display_name`,否则取订单里最常见的 `sku_name`。
每日 `cost_finance_sync` 任务会对最近 N 天执行同一归一(不重复收口异常)。
## 五、成本版本接口
路径不变,字段不变:
```jsonc
{
"id": 1,
"costItemId": 10,
"costItemCode": "sys_affiliate_purchase",
"costItemName": "自动发货上游采购成本",
"costModel": "affiliate_purchase",
"pricingMode": "per_item",
"scopeType": "product | rule | shop | provider | global",
"provider": "", "shopId": "",
"canonicalProductId": 3, "canonicalSku": "aff:SKU-1", "canonicalName": "...",
"workProductRuleId": null, "workProductRuleName": "", "workProductRuleKey": "",
"ruleRewardAmountFen": 0, "ruleUnitPriceFen": 0,
"revenueItemCount": 0, "revenueFen": 0, "revenueAvgFen": 0,
"rewardAvgFen": 0, "rewardFen": 0, "amountKind": "unit_price | fixed",
"isSystemPlaceholder": false,
"amountFen": 1000, "rateBps": 0,
"effectiveFrom": "...", "effectiveTo": null,
"source": "manual | upstream_sync | import",
"status": "draft | active | retired",
"changeReason": "",
"createdByAdminUserId": null, "approvedByAdminUserId": null,
"createdAt": "...", "updatedAt": "..."
}
```
`costItemCarrierType` 字段**删除**,改为 `costItemCostModel`。
## 六、成本异常接口
请求参数 `carrierType` / `fulfillmentMode` **删除**;筛选统一用 `channel`:
```jsonc
// 请求
{ "status": "open", "subjectType": "order_item", "channel": "manual" }
```
旧参数示例(已不生效):
```jsonc
// 请求
{ "status": "open", "subjectType": "order_item", "fulfillmentMode": "manual" }
```
后端实现:join `order_items oi ON oi.id = ce.order_item_id` 并过滤 `oi.fulfillment_channel`。
响应项:
```jsonc
{
"id": 1,
"subjectType": "order_item",
"subjectId": 316571,
"orderItemId": 316571,
"workOrderId": null,
"channel": "manual",
"reason": "cost_missing",
"status": "open",
"detail": {},
"createdAt": "...", "resolvedAt": null, "resolvedByAdminUserId": null
}
```
`reason` 取值:`product_mapping_missing`(商品未归一)、`cost_missing`(非人工项缺成本版本)、
`manual_cost_missing`(人工项尚未确认履约/未配置渠道)。`manual_cost_missing` 只监控
「第一次创建人工履约配置之后」的订单项;确认履约写入 `manual_case` 快照后自动 `resolved`。
人工成本快照的 `subjectId` / `subject_id` 统一为 `order_item_id`。
## 七、销售事实接口
`GET /api/v1/admin/sales-profit` 的分组维度字段名为 `channel`,响应分组为 `byChannel`:
```jsonc
{
"channel": "manual",
"itemCount": 102955,
"grossRevenueFen": 1219202470,
"costAmountFen": 32000,
"costMissingCount": 102954,
"grossProfitFen": -1219200470
}
```
筛选参数用 `channel`,取值 `work_order` / `affiliate_dash` / `third_party_voucher` / `manual` / `unclassified`。
## 八、成本中心概览接口
`GET /api/v1/admin/cost-center/overview` 的统计改为按来源前缀与成本模型分组:
```jsonc
{
"productCount": 745,
"mappingCount": 4426,
"costItemCount": 3,
"activeVersionCount": 701,
"openExceptionCount": 157822,
"unmappedOrderItemCount": 145507,
"productSourceCounts": {
"affiliate_dash": 38,
"work_order": 707,
"manual": 0,
"uncategorized": 0
},
"costModelCounts": {
"affiliate_purchase": 1,
"work_order_reward": 1,
"manual_actual": 1
}
}
```
`GET /api/v1/admin/cost-center/options` 返回的 `products[].source` 同样是来源前缀推导值,
`costItems[].costModel` 取代原 `carrierType`。
## 九、后端模块边界(已完成拆分)
原 `apps/backend/src/services/admin/admin-cost-center-service.ts`(4,248 行)已拆为:
| 新文件 | 行数 | 负责的导出 |
| --- | ---: | --- |
| `services/cost-center/cost-center-shared.ts` | ~800 | 类型、常量、归一化函数、`mapXxx` 映射函数、provider 归一、`costModelScopeSql` |
| `services/cost-center/cost-center-overview-service.ts` | ~150 | 总览统计与选项 |
| `services/cost-center/product-catalog-service.ts` | ~1,000 | 商品与渠道映射的 CRUD、回填、选项 |
| `services/cost-center/template-bootstrap-service.ts` | ~1,380 | 接单模板引导、自动发货商品同步、工单证据回填、模板成本版本同步、`buildTemplateMappingPlan` |
| `services/cost-center/cost-definition-service.ts` | ~1,240 | 成本项 / 成本版本 / 成本异常 / 成本预览 / 成本快照写入 |
原文件**已删除**,路由 `apps/backend/src/routes/admin/cost-center.ts` 从新模块导入。
`routes/admin/worker-platform/config.ts` 的模板成本同步也从新模块导入。
## 十、前端模块边界(已完成拆分)
原 `apps/frontend/src/pages/admin/AdminCostCenterPage.tsx`(2,887 行)已拆为:
| 新文件 | 内容 |
| --- | --- |
| `pages/admin/cost-center/CostCenterShell.tsx` | 页面骨架、顶部来源切换(全部/自动发货/接单平台/人工)、Tab 定义 |
| `pages/admin/cost-center/shared.ts` | 常量、类型、标签函数 |
| `pages/admin/cost-center/CostCenterContext.ts` | 页面上下文(`useCostCenter`) |
| `pages/admin/cost-center/ProductCatalogPanel.tsx` | 标准商品 Tab |
| `pages/admin/cost-center/ChannelMappingPanel.tsx` | 渠道映射 Tab |
| `pages/admin/cost-center/CostConfigPanel.tsx` | 成本配置 Tab(按来源切换下面三个) |
| `pages/admin/cost-center/AffiliateSkuPanel.tsx` | 自动发货采购价(成本配置内) |
| `pages/admin/cost-center/CostItemPanel.tsx` | 成本项 Tab |
| `pages/admin/cost-center/CostVersionPanel.tsx` | 成本版本 Tab |
| `pages/admin/cost-center/CostExceptionPanel.tsx` | 成本异常 Tab |
| `pages/admin/cost-center/CostPreviewPanel.tsx` | 成本预览 Tab |
`AdminCostCenterPage.tsx` 只保留 `export default` 转发到 `CostCenterShell`(18 行)。
类型文件 `apps/frontend/src/types/admin/cost-center.ts` 已按本契约改名:
```ts
export type FulfillmentMode = 'work_order' | 'affiliate_dash' | 'legacy_platform' | 'manual'
export type ProductSource = 'affiliate_dash' | 'work_order' | 'manual' | ''
export type CostModel =
| 'affiliate_purchase'
| 'work_order_reward'
| 'manual_actual'
| 'platform_fee'
| 'payment_fee'
| 'after_sales_loss'
| 'other'
```
`CostCarrierType` 已删除。
## 八、总账 / 期间 / 对账接口(2026-10-26)
| 方法 | 路径 | 权限 | 说明 |
| --- | --- | --- | --- |
| GET | `/api/v1/admin/finance/ledger/accounts` | finance.view | 科目表 |
| GET | `/api/v1/admin/finance/ledger/trial-balance?dateFrom&dateTo` | finance.view | 试算平衡 |
| GET | `/api/v1/admin/finance/ledger/entries?dateFrom&dateTo&page&pageSize` | finance.view | 凭证列表(含分录) |
| POST | `/api/v1/admin/finance/ledger/sync` | finance.config | 按日期区间同步销售事实到总账 |
| POST | `/api/v1/admin/finance/ledger/manual-voucher` | finance.config | 手工凭证(借贷必须平衡) |
| GET | `/api/v1/admin/finance/periods` | finance.view | 会计期间列表 |
| POST | `/api/v1/admin/finance/periods/:periodKey/close` | finance.config | 关账(先补凭证) |
| POST | `/api/v1/admin/finance/periods/:periodKey/reopen` | finance.config | 反关账 |
| GET | `/api/v1/admin/finance/reconciliations` | finance.view | 对账批次 |
| POST | `/api/v1/admin/finance/reconciliations/import` | finance.config | 导入平台账单 JSON 并匹配 |
| GET | `/api/v1/admin/finance/reconciliations/:id` | finance.view | 对账明细 |
| POST | `/api/v1/admin/finance/reconciliations/:id/resolve` | finance.config | 标记差异已解决 |
| POST | `/api/v1/admin/kuaishou-industry/orders/:orderId/refunds/approve-and-record` | finance.config | 平台退款(当前仅快手 91) |
确认履约接口新增代录字段:
```jsonc
{
"orderItemId": 123,
"costFen": 100,
"fundAccountId": 45, // 现金路径:管理员/财务指定客服备用金账户
"creditOwnerAdminUserId": 67 // 积分路径:管理员/财务指定客服账号
}
```
客服角色只能使用本人账户;传了也会被服务端忽略。