Files
order_site/apps/frontend/src/pages/admin/cost-center/AffiliateSkuPanel.tsx
T

226 lines
7.6 KiB
TypeScript
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.
/**
* 自动发货 SKU Tab:上游 SKU 目录与订单项回填。
*
* 自动发货只有 affiliate-dash 一个上游渠道,SKU 固定归一为 `aff:<skuCode>`,
* 不写渠道映射,也不维护游戏分类。
*/
import { ReloadOutlined, SyncOutlined } from '@ant-design/icons'
import { Alert, App, Button, Card, Space, Switch, Tag, Typography } from 'antd'
import PercentTable from '@/components/common/PercentTable'
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> 归一,不走渠道映射;这里不维护游戏分类和商品上下架,那些只属于接单平台。"
/>
<PercentTable
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>
)
}