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,224 @@
/**
* 自动发货 SKU Tab:上游 SKU 目录与订单项回填。
*
* 自动发货只有 affiliate-dash 一个上游渠道,SKU 固定归一为 `aff:<skuCode>`,
* 不写渠道映射,也不维护游戏分类。
*/
import { ReloadOutlined, SyncOutlined } from '@ant-design/icons'
import { Alert, App, Button, Card, Space, Switch, Table, Tag, Typography } from 'antd'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useState } from 'react'
import {
backfillAdminAffiliateDashSkus,
fetchAdminProductCatalog,
syncAdminAffiliateDashProducts,
updateAdminProductCatalog,
} from '@/services/admin'
import type { ProductCatalogItem } from '@/types/admin'
import { ADMIN_DEFAULT_PAGE_SIZE, buildAdminTablePagination } from '@/utils/admin-pagination'
import { formatAdminDateTime } from '@/utils/admin-time'
import { useCostCenter } from './CostCenterContext'
export function AffiliateSkuPanel() {
const { message } = App.useApp()
const queryClient = useQueryClient()
const { canConfig, refreshAll } = useCostCenter()
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(ADMIN_DEFAULT_PAGE_SIZE)
const [statusUpdatingId, setStatusUpdatingId] = useState<number | null>(null)
const [syncing, setSyncing] = useState(false)
const [backfilling, setBackfilling] = useState(false)
const productsQuery = useQuery({
queryKey: ['admin-cost-center-products', 'affiliate_dash', page, pageSize],
queryFn: () =>
fetchAdminProductCatalog({
carrierType: 'affiliate_dash',
page,
pageSize,
}),
})
const products = productsQuery.data?.data.items || []
const total = productsQuery.data?.data.pagination.total || 0
async function syncProducts() {
setSyncing(true)
try {
const result = await syncAdminAffiliateDashProducts()
message.success(
`已同步 ${result.data.productCount} 个自动发货商品(新增 ${result.data.createdCount},更新 ${result.data.updatedCount})`,
)
refreshAll()
} catch (error) {
message.error(error instanceof Error ? error.message : '同步自动发货商品失败')
} finally {
setSyncing(false)
}
}
async function backfillSkus() {
setBackfilling(true)
try {
const response = await backfillAdminAffiliateDashSkus()
const result = response.data
const factsText = result.factsRebuild
? `;已重算 ${result.factsRebuild.fromDate} ~ ${result.factsRebuild.toDate} 的销售事实`
: ''
const remainingText =
result.remainingCount > 0
? `;仍有 ${result.remainingCount} 个订单项缺少可匹配的自动发货 SKU`
: ''
message.success(
`已回填 ${result.updatedCount} 个订单项,${result.skippedCount} 个已是归一状态${factsText}${remainingText}`,
)
refreshAll()
} catch (error) {
message.error(error instanceof Error ? error.message : '回填自动发货 SKU 失败')
} finally {
setBackfilling(false)
}
}
async function toggleStatus(row: ProductCatalogItem, checked: boolean) {
if (!canConfig) return
setStatusUpdatingId(row.id)
try {
await updateAdminProductCatalog(row.id, { status: checked ? 'active' : 'archived' })
message.success(checked ? 'SKU 已启用' : 'SKU 已归档')
await queryClient.invalidateQueries({ queryKey: ['admin-cost-center-products'] })
void queryClient.invalidateQueries({ queryKey: ['admin-cost-center-overview'] })
} catch (error) {
message.error(error instanceof Error ? error.message : '更新 SKU 状态失败')
} finally {
setStatusUpdatingId(null)
}
}
return (
<Card
title={
<Space size={6} wrap>
<Typography.Text strong>自动发货 SKU</Typography.Text>
<Tag color="green">{total}</Tag>
</Space>
}
extra={
canConfig ? (
<Space>
<Button icon={<SyncOutlined />} loading={syncing} onClick={() => void syncProducts()}>
同步自动发货商品
</Button>
<Button
icon={<SyncOutlined />}
loading={backfilling}
onClick={() => void backfillSkus()}
>
回填自动发货 SKU
</Button>
<Button
icon={<ReloadOutlined />}
loading={productsQuery.isFetching}
onClick={() => void productsQuery.refetch()}
/>
</Space>
) : null
}
>
<Alert
type="info"
showIcon
style={{ marginBottom: 12 }}
message="自动发货只按上游货源 SKU 配采购成本:订单项直接按 aff:<skuCode> 归一,不走渠道映射;这里不维护游戏分类和商品上下架,那些只属于接单平台。"
/>
<Table
tableLayout="fixed"
rowKey="id"
size="small"
dataSource={products}
loading={productsQuery.isLoading}
scroll={{ x: 1080 }}
pagination={buildAdminTablePagination({
current: page,
pageSize,
total,
showTotal: (count) => `共 ${count} 个 SKU`,
onChange: (nextPage, nextPageSize) => {
setPage(nextPage)
setPageSize(nextPageSize)
},
})}
columns={[
{
title: 'SKU 名称',
dataIndex: 'canonicalName',
width: 320,
ellipsis: true,
render: (value: string, row) => (
<Space direction="vertical" size={0} style={{ width: '100%' }}>
<Typography.Text strong ellipsis={{ tooltip: value }}>
{value}
</Typography.Text>
<Typography.Text
type="secondary"
style={{ fontSize: 12 }}
ellipsis={{
tooltip: String(row.attributes?.skuCode || row.canonicalSku),
}}
>
{String(row.attributes?.skuCode || row.canonicalSku)}
</Typography.Text>
</Space>
),
},
{
title: '履约任务',
width: 110,
render: (_, row) => `${row.affiliateTaskCount} 单`,
},
{
title: '最近履约',
width: 180,
render: (_, row) =>
row.affiliateLastFulfilledAt
? formatAdminDateTime(row.affiliateLastFulfilledAt)
: '-',
},
{
title: '成本版本',
dataIndex: 'costVersionCount',
width: 110,
render: (value: number) => (value > 0 ? `${value} 个` : <Tag>未配置</Tag>),
},
{
title: '状态',
dataIndex: 'status',
width: 120,
render: (value: string, row) => (
<Space size={6}>
<Switch
size="small"
checked={value === 'active'}
loading={statusUpdatingId === row.id}
disabled={
!canConfig || (statusUpdatingId !== null && statusUpdatingId !== row.id)
}
onChange={(checked) => void toggleStatus(row, checked)}
/>
<Typography.Text
type={value === 'active' ? 'success' : 'secondary'}
style={{ fontSize: 12 }}
>
{value === 'active' ? '启用' : '归档'}
</Typography.Text>
</Space>
),
},
]}
/>
</Card>
)
}