refactor(finance): 成本模型与履约方式正交,拆分成本中心巨型文件

后端:
- 删除 services/admin/admin-cost-center-service.ts(4,248 行),拆为
  services/cost-center/ 下 5 个模块:
  cost-center-shared(类型/枚举/归一化/映射/costModelScopeSql)、
  cost-center-overview(总览与选项)、
  product-catalog(商品与渠道映射)、
  template-bootstrap(模板引导、自动发货同步、工单证据回填)、
  cost-definition(成本项/版本/异常/预览/快照)
- cost_items.carrier_type / cost_type 改为单一 cost_model;专属模型只对
  对应履约方式生效,通用模型对所有履约方式生效
- cost_snapshots / cost_exceptions 删除载体列;按履约方式筛异常改用
  IN 半连接(248k 异常下 EXISTS 逐行回表 2.7s -> 170ms)
- sales_daily_facts.carrier_type -> fulfillment_mode
- 人工支出按 cost_model 归类;履约方式只读 order_items.fulfillment_mode
- 移除 syncOpenCostExceptionCarrierTypes:异常表已无载体列可同步

前端:
- AdminCostCenterPage.tsx(2,887 行 -> 18 行转发),拆为
  pages/admin/cost-center/ 下 8 个 Panel + shared + CostCenterContext
- CostCarrierType 删除;新增 FulfillmentMode / ProductSource / CostModel
- 销售毛利页 carrierType -> fulfillmentMode

同步补两个索引:idx_order_items_fulfillment_id(异常半连接)、
idx_work_categories_name(商品目录分类 lateral join)。
This commit is contained in:
yml2213
2026-10-23 16:06:25 +08:00
parent 5c549a2dc5
commit 63ae32d18c
33 changed files with 8107 additions and 7335 deletions
@@ -0,0 +1,575 @@
/**
* 渠道映射 Tab:来源 + 店铺 + 平台 SKU -> 标准商品。
*
* 映射唯一键包含匹配方式与名称键,91 同店铺复用 sku_code 才能消歧。
*/
import { SearchOutlined, SyncOutlined } from '@ant-design/icons'
import {
App,
Button,
Card,
Form,
Input,
InputNumber,
Modal,
Select,
Space,
Switch,
Table,
Tag,
Typography,
} from 'antd'
import type { TableColumnsType } from 'antd'
import { useQuery } from '@tanstack/react-query'
import { useState } from 'react'
import {
backfillAdminNormalizedQuantities,
backfillAdminProductMappings,
createAdminChannelProductMapping,
deleteAdminChannelProductMapping,
fetchAdminChannelProductMappings,
updateAdminChannelProductMapping,
} from '@/services/admin'
import type { ChannelProductMapping, ChannelProductMappingGroup } from '@/types/admin'
import {
ADMIN_DEFAULT_PAGE_SIZE,
buildAdminLocalTablePagination,
buildAdminTablePagination,
} from '@/utils/admin-pagination'
import { useCostCenter } from './CostCenterContext'
import {
MAPPING_MATCH_TYPE_OPTIONS,
mappingMatchTypeLabel,
providerLabel,
type MappingFormValues,
} from './shared'
export function ChannelMappingPanel() {
const { message, modal } = App.useApp()
const { canConfig, productSourceFilter, options, refreshAll } = useCostCenter()
const [mappingForm] = Form.useForm<MappingFormValues>()
const [mappingKeyword, setMappingKeyword] = useState('')
const [mappingProvider, setMappingProvider] = useState('')
const [mappingPage, setMappingPage] = useState(1)
const [mappingPageSize, setMappingPageSize] = useState(ADMIN_DEFAULT_PAGE_SIZE)
const [expandedMappingProductIds, setExpandedMappingProductIds] = useState<string[]>([])
const [mappingDetailPageSize, setMappingDetailPageSize] = useState(10)
const [mappingModalOpen, setMappingModalOpen] = useState(false)
const [editingMapping, setEditingMapping] = useState<ChannelProductMapping | null>(null)
const mappingsQuery = useQuery({
queryKey: [
'admin-cost-center-mappings',
productSourceFilter,
mappingKeyword,
mappingProvider,
mappingPage,
mappingPageSize,
],
queryFn: () =>
fetchAdminChannelProductMappings({
keyword: mappingKeyword || undefined,
provider: mappingProvider || undefined,
carrierType: productSourceFilter,
page: mappingPage,
pageSize: mappingPageSize,
}),
})
const mappingGroups = mappingsQuery.data?.data.groups || []
const mappingTotal = mappingsQuery.data?.data.pagination.mappingTotal || 0
const mappingGroupTotal = mappingsQuery.data?.data.pagination.total || 0
const providers = options?.providers || []
const productOptions =
options?.products
.filter((item) => !productSourceFilter || item.source === productSourceFilter)
.map((item) => ({
value: item.id,
label: `${item.canonicalName}(${item.canonicalSku})`,
})) || []
function openCreateMapping() {
setEditingMapping(null)
mappingForm.resetFields()
mappingForm.setFieldsValue({
provider: providers[0] || '91kaquan',
matchType: 'sku_code',
quantityMultiplier: 1,
confidence: 'manual',
source: 'manual',
enabled: true,
})
setMappingModalOpen(true)
}
function openEditMapping(item: ChannelProductMapping) {
setEditingMapping(item)
mappingForm.setFieldsValue({
provider: item.provider,
shopId: item.shopId,
platformSkuCode: item.platformSkuCode,
platformSkuName: item.platformSkuName,
matchType: item.matchType,
canonicalProductId: item.canonicalProductId,
quantityMultiplier: item.quantityMultiplier,
confidence: item.confidence,
source: item.source,
enabled: item.enabled,
note: item.note,
})
setMappingModalOpen(true)
}
async function submitMapping(values: MappingFormValues) {
try {
if (editingMapping) {
await updateAdminChannelProductMapping(editingMapping.id, values)
message.success('渠道映射已更新')
} else {
await createAdminChannelProductMapping(values)
message.success('渠道映射已创建')
}
setMappingModalOpen(false)
refreshAll()
} catch (error) {
message.error(error instanceof Error ? error.message : '保存渠道映射失败')
}
}
function deleteMapping(item: ChannelProductMapping) {
modal.confirm({
title: '删除渠道映射',
content: `确认删除「${providerLabel(item.provider)} / ${item.shopId || '全局'} / ${item.platformSkuCode || item.platformSkuName || '-'}」这条映射?删除后该平台 SKU 将不再自动归一。`,
okText: '删除',
okButtonProps: { danger: true },
cancelText: '取消',
onOk: async () => {
try {
await deleteAdminChannelProductMapping(item.id)
message.success('渠道映射已删除')
refreshAll()
} catch (error) {
message.error(error instanceof Error ? error.message : '删除渠道映射失败')
}
},
})
}
function backfillMappings() {
modal.confirm({
title: '回填订单项商品映射',
content:
'按编码、编码 + 名称系列、编码 + 精确名称、名称系列兜底的优先级,分批匹配全部未映射订单项。',
okText: '开始回填',
cancelText: '取消',
onOk: async () => {
try {
const response = await backfillAdminProductMappings({ limit: 20000, all: true })
const { updatedCount, batches, remainingCount } = response.data
message.success(
`已回填 ${updatedCount} 条订单项映射(${batches} 批)${remainingCount > 0 ? `,剩余 ${remainingCount} 条无可用映射` : ''}`,
)
refreshAll()
} catch (error) {
message.error(error instanceof Error ? error.message : '回填商品映射失败')
}
},
})
}
function backfillQuantities() {
modal.confirm({
title: '回填归一数量',
content: '按 SKU 名称/编码解析数量,自动分批处理全部订单项;解析不到时按 1 件记录。',
okText: '开始回填',
cancelText: '取消',
onOk: async () => {
try {
const response = await backfillAdminNormalizedQuantities({ limit: 20000, all: true })
const { updatedCount, remainingCount, batches } = response.data
message.success(
`已回填 ${updatedCount} 条归一数量(${batches} 批)${remainingCount > 0 ? `,剩余 ${remainingCount} 条` : ''}`,
)
refreshAll()
} catch (error) {
message.error(error instanceof Error ? error.message : '回填归一数量失败')
}
},
})
}
const mappingDetailColumns: TableColumnsType<ChannelProductMapping> = [
{ title: '来源', dataIndex: 'provider', width: 130, render: providerLabel },
{
title: '店铺',
dataIndex: 'shopId',
width: 150,
render: (value: string) => value || <Tag>全局</Tag>,
},
{
title: '平台 SKU',
dataIndex: 'platformSkuCode',
width: 220,
render: (value: string, row) => (
<Space direction="vertical" size={0}>
<Typography.Text strong>{value || row.platformSkuName || '-'}</Typography.Text>
<Typography.Text type="secondary">
{value ? row.platformSkuName || '-' : row.platformSkuNameKey || '-'}
</Typography.Text>
</Space>
),
},
{
title: '匹配方式',
dataIndex: 'matchType',
width: 160,
render: (value: ChannelProductMapping['matchType']) => (
<Tag color={value === 'sku_code' ? 'green' : 'blue'}>{mappingMatchTypeLabel(value)}</Tag>
),
},
{ title: '倍率', dataIndex: 'quantityMultiplier', width: 70 },
{ title: '置信度', dataIndex: 'confidence', width: 85 },
{
title: '启用',
dataIndex: 'enabled',
width: 75,
render: (value: boolean) => (
<Tag color={value ? 'green' : 'default'}>{value ? '启用' : '停用'}</Tag>
),
},
{
title: '操作',
width: 140,
fixed: 'right',
render: (_, row) =>
canConfig ? (
<Space size={4}>
<Button size="small" onClick={() => openEditMapping(row)}>
编辑
</Button>
<Button size="small" danger onClick={() => deleteMapping(row)}>
删除
</Button>
</Space>
) : null,
},
]
const mappingGroupColumns: TableColumnsType<ChannelProductMappingGroup> = [
{
title: '标准商品',
dataIndex: 'canonicalName',
width: 260,
render: (value: string, row) => (
<Space size={8} align="start">
<Space direction="vertical" size={0} style={{ width: '100%' }}>
<Typography.Text strong ellipsis={{ tooltip: value }}>
{value}
</Typography.Text>
<Typography.Text type="secondary" ellipsis={{ tooltip: row.canonicalSku }}>
{row.canonicalSku} · {row.unitName}
</Typography.Text>
</Space>
</Space>
),
},
{
title: '分类',
dataIndex: 'category',
width: 120,
render: (value: string) =>
value || <Typography.Text type="secondary">未分类</Typography.Text>,
},
{
title: '覆盖范围',
width: 220,
render: (_, row) => {
const rowProviders = Array.from(new Set(row.mappings.map((item) => item.provider)))
const shops = new Set(row.mappings.map((item) => `${item.provider}:${item.shopId || ''}`))
.size
return (
<Space size={[4, 4]} wrap>
{rowProviders.map((provider) => (
<Tag key={provider}>{providerLabel(provider)}</Tag>
))}
<Tag color="blue">{shops} 个店铺键</Tag>
</Space>
)
},
},
{
title: '映射',
width: 150,
render: (_, row) => {
const enabledCount = row.mappings.filter((item) => item.enabled).length
return (
<Space size={4}>
<Tag color="blue">{row.mappings.length} 条</Tag>
<Typography.Text type="secondary">启用 {enabledCount}</Typography.Text>
</Space>
)
},
},
{
title: '匹配方式',
width: 280,
render: (_, row) => {
const matchTypes = Array.from(new Set(row.mappings.map((item) => item.matchType)))
return (
<Space size={[4, 4]} wrap>
{matchTypes.map((matchType) => (
<Tag key={matchType} color={matchType === 'sku_code' ? 'green' : 'blue'}>
{mappingMatchTypeLabel(matchType)}
</Tag>
))}
</Space>
)
},
},
{
title: '状态',
dataIndex: 'status',
width: 80,
render: (value: string) => (
<Tag color={value === 'active' ? 'green' : 'default'}>
{value === 'active' ? '启用' : '归档'}
</Tag>
),
},
{
title: '目录',
width: 90,
fixed: 'right',
render: (_, row) => {
const key = String(row.canonicalProductId)
const expanded = expandedMappingProductIds.includes(key)
return (
<Button
size="small"
type="link"
onClick={(event) => {
event.stopPropagation()
setExpandedMappingProductIds((current) =>
current.includes(key) ? current.filter((item) => item !== key) : [...current, key],
)
}}
>
{expanded ? '收起' : '展开'}
</Button>
)
},
},
]
return (
<>
<Card
title={
<Space size={6} wrap>
<Typography.Text strong>渠道映射目录</Typography.Text>
<Tag color="blue">{mappingTotal} 条映射</Tag>
<Tag>{mappingGroupTotal} 个标准商品</Tag>
</Space>
}
extra={
canConfig ? (
<Space>
<Button icon={<SyncOutlined />} onClick={backfillMappings}>
回填订单项
</Button>
<Button onClick={backfillQuantities}>回填数量</Button>
<Button type="primary" onClick={openCreateMapping}>
新建映射
</Button>
</Space>
) : null
}
>
<Space style={{ marginBottom: 16 }} wrap>
<Input
allowClear
prefix={<SearchOutlined />}
placeholder="标准商品 / 平台 SKU"
value={mappingKeyword}
onChange={(event) => {
setMappingKeyword(event.target.value)
setMappingPage(1)
setExpandedMappingProductIds([])
}}
style={{ width: 260 }}
/>
<Select
allowClear
placeholder="来源"
value={mappingProvider || undefined}
onChange={(value) => {
setMappingProvider(value || '')
setMappingPage(1)
setExpandedMappingProductIds([])
}}
options={providers.map((provider) => ({
value: provider,
label: providerLabel(provider),
}))}
style={{ width: 180 }}
/>
<Button
onClick={() =>
setExpandedMappingProductIds(
mappingGroups.map((group) => String(group.canonicalProductId)),
)
}
>
展开本页
</Button>
<Button onClick={() => setExpandedMappingProductIds([])}>收起全部</Button>
</Space>
<Table<ChannelProductMappingGroup>
tableLayout="fixed"
rowKey={(row) => String(row.canonicalProductId)}
size="small"
columns={mappingGroupColumns}
dataSource={mappingGroups}
loading={mappingsQuery.isLoading}
scroll={{ x: 1100 }}
expandable={{
expandedRowKeys: expandedMappingProductIds,
onExpandedRowsChange: (keys) =>
setExpandedMappingProductIds(keys.map((key) => String(key))),
expandRowByClick: true,
expandedRowRender: (group) => (
<Space direction="vertical" size={8} style={{ width: '100%' }}>
<Typography.Text type="secondary">
该标准商品下共有 {group.mappings.length} 条渠道映射
</Typography.Text>
<Table<ChannelProductMapping>
tableLayout="fixed"
rowKey="id"
size="small"
columns={mappingDetailColumns}
dataSource={group.mappings}
pagination={buildAdminLocalTablePagination({
pageSize: mappingDetailPageSize,
size: 'small',
onChange: (_page, pageSize) => setMappingDetailPageSize(pageSize),
})}
scroll={{ x: 980 }}
/>
</Space>
),
}}
pagination={buildAdminTablePagination({
current: mappingPage,
pageSize: mappingPageSize,
total: mappingGroupTotal,
showTotal: (total) => `共 ${total} 个标准商品`,
onChange: (page, pageSize) => {
setMappingPage(page)
setMappingPageSize(pageSize)
setExpandedMappingProductIds([])
},
})}
/>
</Card>
<Modal
title={editingMapping ? '编辑渠道映射' : '新建渠道映射'}
open={mappingModalOpen}
onCancel={() => setMappingModalOpen(false)}
onOk={() => mappingForm.submit()}
okText="保存"
cancelText="取消"
width={620}
destroyOnClose
>
<Form form={mappingForm} layout="vertical" onFinish={submitMapping}>
<Form.Item name="provider" label="来源" rules={[{ required: true }]}>
<Select
showSearch
options={providers.map((provider) => ({
value: provider,
label: providerLabel(provider),
}))}
/>
</Form.Item>
<Form.Item name="shopId" label="店铺 ID">
<Input placeholder="留空表示该来源全局映射" />
</Form.Item>
<Form.Item name="matchType" label="匹配方式" rules={[{ required: true }]}>
<Select options={MAPPING_MATCH_TYPE_OPTIONS} />
</Form.Item>
<Form.Item noStyle shouldUpdate={(prev, current) => prev.matchType !== current.matchType}>
{({ getFieldValue }) => {
const matchType =
(getFieldValue('matchType') as ChannelProductMapping['matchType'] | undefined) ||
'sku_code'
return (
<>
<Form.Item
name="platformSkuCode"
label="平台 SKU"
rules={
matchType === 'sku_name_series'
? []
: [{ required: true, message: '请输入平台 SKU' }]
}
>
<Input placeholder="平台原始 sku_code / productNo" />
</Form.Item>
<Form.Item
name="platformSkuName"
label="平台商品名"
rules={
matchType === 'sku_code'
? []
: [{ required: true, message: '该匹配方式必须填写平台商品名' }]
}
>
<Input placeholder="精确名称或数量系列文本,例如:指挥官密钥5个" />
</Form.Item>
</>
)
}}
</Form.Item>
<Form.Item
name="canonicalProductId"
label="标准商品"
rules={[{ required: true, message: '请选择标准商品' }]}
>
<Select showSearch options={productOptions} optionFilterProp="label" />
</Form.Item>
<Form.Item name="quantityMultiplier" label="数量倍率">
<InputNumber min={1} precision={0} style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="confidence" label="置信度">
<Select
options={[
{ value: 'exact', label: '精确' },
{ value: 'rule', label: '规则' },
{ value: 'manual', label: '人工' },
]}
/>
</Form.Item>
<Form.Item name="source" label="来源方式">
<Select
options={[
{ value: 'manual', label: '人工' },
{ value: 'import', label: '导入' },
{ value: 'rule', label: '规则' },
]}
/>
</Form.Item>
<Form.Item name="enabled" label="启用" valuePropName="checked">
<Switch />
</Form.Item>
<Form.Item name="note" label="备注">
<Input.TextArea rows={2} />
</Form.Item>
</Form>
</Modal>
</>
)
}