1438 lines
50 KiB
TypeScript
1438 lines
50 KiB
TypeScript
/**
|
||
* 履约渠道页:履约待办队列 + 渠道规则 + 问题队列。
|
||
*
|
||
* 设计口径(2026-10-31 v2):
|
||
* · 渠道由 L1 规则决定,不再由「有没有任务」反推;
|
||
* · 没有命中规则的新单落在「待分类」,收入进未分类桶,不产生成本噪音;
|
||
* · 第三方卡券由外部卡券库履约:不建内部任务、不发领取页,但支持平台券自动核销。
|
||
*/
|
||
import {
|
||
DeleteOutlined,
|
||
PlusOutlined,
|
||
ReloadOutlined,
|
||
SearchOutlined,
|
||
SyncOutlined,
|
||
ThunderboltOutlined,
|
||
} from '@ant-design/icons'
|
||
import {
|
||
Alert,
|
||
Button,
|
||
Card,
|
||
Form,
|
||
Input,
|
||
InputNumber,
|
||
Modal,
|
||
Segmented,
|
||
Select,
|
||
Space,
|
||
Switch,
|
||
Tabs,
|
||
Tag,
|
||
Tooltip,
|
||
Typography,
|
||
message,
|
||
} from 'antd'
|
||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||
import { useEffect, useState } from 'react'
|
||
import { useNavigate } from 'react-router'
|
||
|
||
import PercentTable from '@/components/common/PercentTable'
|
||
import FinanceSubNav from '@/components/admin/FinanceSubNav'
|
||
import VoucherConsumePolicyPanel from './panels/VoucherConsumePolicyPanel'
|
||
import {
|
||
assignChannelByInternalSku,
|
||
deletePendingChannelGroup,
|
||
deleteInternalSkuMapping,
|
||
deleteChannelRules,
|
||
forceDeleteChannelRules,
|
||
fetchChannelExceptions,
|
||
fetchChannelRules,
|
||
fetchInternalSkuMappings,
|
||
fetchPendingChannelGroups,
|
||
fetchPipelineStatus,
|
||
retryPendingCarriers,
|
||
retryPendingWorkOrderRouting,
|
||
runFinancePipeline,
|
||
unlockPendingChannelGroup,
|
||
type FinancePipelineStatus,
|
||
type InternalSkuMapping,
|
||
type InternalSkuMappingMatchType,
|
||
saveChannelRule,
|
||
saveInternalSkuMapping,
|
||
type ChannelRule,
|
||
type FulfillmentQueueBucket,
|
||
type PendingChannelGroup,
|
||
} from '@/services/admin'
|
||
import { formatRedeemAmount } from '@/utils/redeem'
|
||
import { formatDateTime } from '@/utils/date-time'
|
||
import { ADMIN_DEFAULT_PAGE_SIZE, buildAdminTablePagination } from '@/utils/admin-pagination'
|
||
|
||
const CHANNEL_OPTIONS = [
|
||
{ value: 'work_order', label: '接单平台' },
|
||
{ value: 'affiliate_dash', label: '自动发货' },
|
||
{ value: 'third_party_voucher', label: '第三方卡券' },
|
||
{ value: 'manual', label: '人工客服' },
|
||
{ value: 'on_account', label: '统一结算' },
|
||
]
|
||
|
||
const CHANNEL_COLOR: Record<string, string> = {
|
||
work_order: 'blue',
|
||
affiliate_dash: 'green',
|
||
third_party_voucher: 'purple',
|
||
manual: 'orange',
|
||
on_account: 'gold',
|
||
}
|
||
|
||
const CHANNEL_SOURCE_LABEL: Record<string, string> = {
|
||
operator: '运营配置',
|
||
manual_config: '人工 SKU 配置',
|
||
voucher: '第三方卡券',
|
||
capability: '商品能力迁移',
|
||
backfill: '历史回填',
|
||
}
|
||
|
||
const CHANNEL_SOURCE_FILTER_OPTIONS = [
|
||
...Object.entries(CHANNEL_SOURCE_LABEL).map(([value, label]) => ({ value, label })),
|
||
{ value: 'rule', label: '规则迁移' },
|
||
]
|
||
|
||
const ENABLED_FILTER_OPTIONS = [
|
||
{ value: 'true', label: '启用' },
|
||
{ value: 'false', label: '停用' },
|
||
]
|
||
|
||
const MATCH_KEY_OPTIONS = [{ value: 'internal_sku', label: '内部 SKU' }]
|
||
|
||
const PENDING_QUEUE_BUCKET_OPTIONS: Array<{
|
||
value: FulfillmentQueueBucket
|
||
label: string
|
||
}> = [
|
||
{ value: 'actionable', label: '自动处理中' },
|
||
{ value: 'configuration', label: '配置待补' },
|
||
{ value: 'operator_review', label: '人工处理' },
|
||
{ value: 'terminal', label: '售后/终止' },
|
||
]
|
||
|
||
const INTERNAL_SKU_MAPPING_TYPES: Array<{
|
||
value: InternalSkuMappingMatchType
|
||
label: string
|
||
}> = [
|
||
{ value: 'sku_code', label: '平台 SKU 编码' },
|
||
{ value: 'sku_nick', label: 'SKU 昵称' },
|
||
{ value: 'out_sku_sn', label: '外部 SKU 编码' },
|
||
{ value: 'spec', label: '规格值' },
|
||
{ value: 'sku_name', label: '商品名称' },
|
||
]
|
||
|
||
export default function AdminFulfillmentChannelPage() {
|
||
return (
|
||
<div className="page-container">
|
||
<FinanceSubNav current="/admin/fulfillment-channel" />
|
||
<Tabs
|
||
defaultActiveKey="pending"
|
||
items={[
|
||
{ key: 'pending', label: '履约待办', children: <PendingPanel /> },
|
||
{ key: 'mappings', label: 'SKU 映射', children: <InternalSkuMappingsPanel /> },
|
||
{ key: 'rules', label: '渠道规则', children: <RulesPanel /> },
|
||
{ key: 'exceptions', label: '问题队列', children: <ExceptionsPanel /> },
|
||
{ key: 'pipelines', label: '管道状态', children: <PipelinesPanel /> },
|
||
{ key: 'voucher-consume', label: '自动核销', children: <VoucherConsumePolicyPanel /> },
|
||
]}
|
||
/>
|
||
</div>
|
||
)
|
||
}
|
||
|
||
function PendingPanel() {
|
||
const queryClient = useQueryClient()
|
||
const navigate = useNavigate()
|
||
const [keyword, setKeyword] = useState('')
|
||
const [queueBucket, setQueueBucket] = useState<FulfillmentQueueBucket>('actionable')
|
||
const [page, setPage] = useState(1)
|
||
const [pageSize, setPageSize] = useState(ADMIN_DEFAULT_PAGE_SIZE)
|
||
const [selections, setSelections] = useState<Record<string, string>>({})
|
||
const [internalSkuDrafts, setInternalSkuDrafts] = useState<Record<string, string>>({})
|
||
|
||
const query = useQuery({
|
||
queryKey: ['fulfillment-pending', keyword, queueBucket, page, pageSize],
|
||
queryFn: () => fetchPendingChannelGroups({ page, pageSize, keyword, queueBucket }),
|
||
})
|
||
|
||
const assignMutation = useMutation({
|
||
mutationFn: (row: PendingChannelGroup) =>
|
||
assignChannelByInternalSku({
|
||
groupKey: row.group_key,
|
||
internalSku: row.internal_sku || '',
|
||
mappedInternalSku: row.internal_sku
|
||
? ''
|
||
: String(internalSkuDrafts[rowKey(row)] || '').trim(),
|
||
channel: selections[rowKey(row)] || '',
|
||
queueBucket,
|
||
}),
|
||
onSuccess: (result) => {
|
||
const productMessage = result.data.draftProductId ? '和标准商品' : ''
|
||
if (result.data.carrierFailed > 0) {
|
||
const firstFailure = result.data.carrierFailures?.[0]
|
||
message.warning(
|
||
`渠道${productMessage}已保存,${result.data.carrierFailed} 个订单项仍待补配置${
|
||
firstFailure?.message ? `:${firstFailure.message}` : ''
|
||
}`,
|
||
)
|
||
} else {
|
||
message.success(
|
||
`已指定 ${result.data.updated} 个订单项${productMessage ? `并创建${productMessage.slice(1)}` : ''}`,
|
||
)
|
||
}
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-pending'] })
|
||
},
|
||
onError: (error) => message.error(error instanceof Error ? error.message : '指定渠道失败'),
|
||
})
|
||
|
||
const retryWorkOrderMutation = useMutation({
|
||
mutationFn: (inputSku?: string) =>
|
||
retryPendingWorkOrderRouting(inputSku ? { internalSku: inputSku } : {}),
|
||
onSuccess: (result) => {
|
||
const data = result.data
|
||
const detail = [
|
||
`重试 ${data.scanned} 个订单项`,
|
||
`新建工单 ${data.createdWorkOrders} 个`,
|
||
`转接单平台 ${data.assigned} 个`,
|
||
].join(',')
|
||
if (data.remaining > 0) {
|
||
message.warning(`${detail},仍有 ${data.remaining} 个未匹配到接单模板`)
|
||
} else {
|
||
message.success(detail)
|
||
}
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-pending'] })
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-rules'] })
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-exceptions'] })
|
||
},
|
||
onError: (error) =>
|
||
message.error(error instanceof Error ? error.message : '重新匹配接单模板失败'),
|
||
})
|
||
|
||
const retryCarrierMutation = useMutation({
|
||
mutationFn: (input: {
|
||
row: PendingChannelGroup
|
||
retryInactiveCarrier: boolean
|
||
issueCodes: string[]
|
||
}) =>
|
||
retryPendingCarriers({
|
||
internalSku: input.row.internal_sku || '',
|
||
retryInactiveCarrier: input.retryInactiveCarrier,
|
||
issueCodes: input.issueCodes,
|
||
}),
|
||
onSuccess: (result) => {
|
||
const data = result.data
|
||
const detail = [
|
||
`扫描 ${data.scanned} 个订单项`,
|
||
`创建工单 ${data.workOrdersCreated} 个`,
|
||
`创建自动任务 ${data.affiliateTasksCreated} 个`,
|
||
`已分流 ${data.assigned} 个`,
|
||
].join(',')
|
||
if (data.remaining > 0) {
|
||
message.warning(`${detail},仍有 ${data.remaining} 个待处理`)
|
||
} else {
|
||
message.success(detail)
|
||
}
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-pending'] })
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-exceptions'] })
|
||
},
|
||
onError: (error) => message.error(error instanceof Error ? error.message : '重试履约载体失败'),
|
||
})
|
||
|
||
const unlockMutation = useMutation({
|
||
mutationFn: (row: PendingChannelGroup) =>
|
||
unlockPendingChannelGroup({
|
||
groupKey: row.group_key,
|
||
internalSku: row.internal_sku || '',
|
||
queueBucket,
|
||
}),
|
||
onSuccess: (result) => {
|
||
message.success(`已解除 ${result.data.updated} 个订单项的运营锁定`)
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-pending'] })
|
||
},
|
||
onError: (error) => message.error(error instanceof Error ? error.message : '解除运营锁定失败'),
|
||
})
|
||
|
||
const deleteMutation = useMutation({
|
||
mutationFn: (row: PendingChannelGroup) =>
|
||
deletePendingChannelGroup({ groupKey: row.group_key, queueBucket }),
|
||
onSuccess: (result) => {
|
||
const data = result.data
|
||
message.success(
|
||
`已忽略归档 ${data.archivedItems} 个待分类订单项,原始订单保留;财务事实已重算 ${data.refreshedDays} 天`,
|
||
)
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-pending'] })
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-exceptions'] })
|
||
},
|
||
onError: (error) => message.error(error instanceof Error ? error.message : '删除失败'),
|
||
})
|
||
|
||
const pipelineMutation = useMutation({
|
||
mutationFn: () => runFinancePipeline({ days: 3 }),
|
||
onSuccess: () => {
|
||
message.success('管道已执行')
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-pending'] })
|
||
},
|
||
onError: () => message.error('执行管道失败'),
|
||
})
|
||
|
||
const columns = [
|
||
{
|
||
title: '来源',
|
||
dataIndex: 'providers',
|
||
width: 120,
|
||
render: (value: string[] | undefined) => value?.join(' / ') || '-',
|
||
},
|
||
{
|
||
title: '店铺',
|
||
dataIndex: 'shops',
|
||
width: 210,
|
||
render: (_: unknown, row: PendingChannelGroup) => {
|
||
const shops =
|
||
row.shops?.length > 0
|
||
? row.shops
|
||
: (row.shop_ids || []).map((shopId) => ({ id: shopId, name: shopId }))
|
||
if (shops.length === 0) return '-'
|
||
return (
|
||
<Space direction="vertical" size={2}>
|
||
{shops.map((shop) => (
|
||
<span key={`${shop.id}-${shop.name}`}>
|
||
<Typography.Text>{shop.name}</Typography.Text>
|
||
{shop.name !== shop.id ? (
|
||
<Typography.Text type="secondary"> · {shop.id}</Typography.Text>
|
||
) : null}
|
||
</span>
|
||
))}
|
||
</Space>
|
||
)
|
||
},
|
||
},
|
||
{
|
||
title: '内部SKU',
|
||
dataIndex: 'internal_sku',
|
||
width: 220,
|
||
render: (value: string | null, row: PendingChannelGroup) => (
|
||
<Space direction="vertical" size={4}>
|
||
{value ? (
|
||
<Typography.Text>{value}</Typography.Text>
|
||
) : (
|
||
<Input
|
||
size="small"
|
||
placeholder="填写内部 SKU"
|
||
value={internalSkuDrafts[rowKey(row)] || ''}
|
||
onChange={(event) =>
|
||
setInternalSkuDrafts((current) => ({
|
||
...current,
|
||
[rowKey(row)]: event.target.value,
|
||
}))
|
||
}
|
||
/>
|
||
)}
|
||
{row.configured_channels?.length ? (
|
||
<Space size={2} wrap>
|
||
{row.configured_channels.map((channel) => (
|
||
<Tag key={channel} color={CHANNEL_COLOR[channel] || 'default'}>
|
||
{CHANNEL_OPTIONS.find((option) => option.value === channel)?.label || channel}
|
||
</Tag>
|
||
))}
|
||
</Space>
|
||
) : null}
|
||
</Space>
|
||
),
|
||
},
|
||
{
|
||
title: '平台SKU',
|
||
dataIndex: 'sku_codes',
|
||
width: 180,
|
||
render: (value: string[] | undefined) => (value?.length ? value.join(' / ') : '-'),
|
||
},
|
||
{ title: '商品名', dataIndex: 'sku_name', ellipsis: true },
|
||
{
|
||
title: '待分类原因',
|
||
dataIndex: 'pending_reasons',
|
||
width: 240,
|
||
render: (value: string[] | undefined, row: PendingChannelGroup) => {
|
||
const labels: Record<string, string> = {
|
||
no_internal_sku: '无内部SKU',
|
||
no_channel_capability: '无渠道能力',
|
||
no_carrier: '无履约载体',
|
||
routing_conflict: '渠道冲突',
|
||
}
|
||
const subreasonLabels: Record<string, string> = {
|
||
carrier_task_closed: '载体已关闭',
|
||
carrier_task_manual_review: '载体人工复核',
|
||
carrier_not_attempted: '尚未尝试补载体',
|
||
carrier_attempt_failed: '载体创建失败',
|
||
carrier_task_retry_pending: '载体失败待确认重试',
|
||
carrier_task_expired: '载体已过期',
|
||
carrier_task_user_refund: '用户已申请退款',
|
||
carrier_task_cancelled: '上游履约已取消',
|
||
manual_config_missing: '缺人工配置',
|
||
work_rule_missing: '缺接单模板',
|
||
affiliate_mapping_missing: '缺自动发货映射',
|
||
existing_carrier_conflict: '已有其它载体',
|
||
carrier_config_ambiguous: '载体配置冲突',
|
||
missing_internal_sku: '缺内部 SKU',
|
||
missing_channel: '缺渠道配置',
|
||
user_refund: '用户已申请退款',
|
||
platform_cancelled: '上游履约已取消',
|
||
carrier_manual_review: '载体人工复核',
|
||
carrier_retry_pending: '载体失败待重试',
|
||
carrier_expired: '载体已过期',
|
||
carrier_closed: '载体已关闭',
|
||
carrier_missing: '缺履约载体',
|
||
state_inconsistent: '履约状态不一致',
|
||
}
|
||
const breakdown = row.issue_breakdown || []
|
||
return (
|
||
<Space direction="vertical" size={2}>
|
||
{breakdown.length > 0 ? (
|
||
breakdown.map((issue) => (
|
||
<Typography.Text
|
||
key={issue.issue_code}
|
||
type={issue.issue_category === 'after_sales' ? 'danger' : undefined}
|
||
>
|
||
{subreasonLabels[issue.issue_code] || issue.issue_code} {issue.item_count} 项
|
||
{issue.locked_item_count > 0 ? ` · 锁定 ${issue.locked_item_count}` : ''}
|
||
</Typography.Text>
|
||
))
|
||
) : (
|
||
<>
|
||
<Typography.Text>
|
||
{value?.length
|
||
? value.map((reason) => labels[reason] || reason).join(' / ')
|
||
: '-'}
|
||
</Typography.Text>
|
||
{row.pending_subreasons?.length ? (
|
||
<Typography.Text type="secondary">
|
||
{row.pending_subreasons
|
||
.map((reason) => subreasonLabels[reason] || reason)
|
||
.join(' / ')}
|
||
</Typography.Text>
|
||
) : null}
|
||
</>
|
||
)}
|
||
{row.locked_item_count > 0 ? (
|
||
<Typography.Text type="warning">
|
||
已人工指定渠道,等待补配置 {row.locked_item_count} 项
|
||
</Typography.Text>
|
||
) : null}
|
||
</Space>
|
||
)
|
||
},
|
||
},
|
||
{ title: '订单项', dataIndex: 'item_count', width: 90 },
|
||
{
|
||
title: '收入',
|
||
dataIndex: 'revenue_fen',
|
||
width: 120,
|
||
render: (value: number) => formatRedeemAmount(value),
|
||
},
|
||
{
|
||
title: '最近出现',
|
||
dataIndex: 'last_seen_at',
|
||
width: 160,
|
||
render: (value: string) => formatDateTime(value),
|
||
},
|
||
{
|
||
title: '指定渠道',
|
||
width: 440,
|
||
render: (_: unknown, row: PendingChannelGroup) => {
|
||
const issueBreakdown = row.issue_breakdown || []
|
||
const retryableIssueCodes = issueBreakdown
|
||
.filter((issue) => issue.retryable)
|
||
.map((issue) => issue.issue_code)
|
||
const autoRetryableIssueCodes = issueBreakdown
|
||
.filter((issue) => issue.auto_retryable)
|
||
.map((issue) => issue.issue_code)
|
||
const hasConfigIssue = Number(row.config_issue_item_count || 0) > 0
|
||
const hasManualReview = Number(row.manual_review_item_count || 0) > 0
|
||
const hasAfterSales = Number(row.after_sales_item_count || 0) > 0
|
||
const hasSystemIssue = Number(row.system_issue_item_count || 0) > 0
|
||
const hasRetryable = Number(row.retryable_unlocked_item_count || 0) > 0
|
||
const hasAutoRetryable = Number(row.auto_retryable_unlocked_item_count || 0) > 0
|
||
const hasOnlyRetryableIssues =
|
||
issueBreakdown.length > 0 && issueBreakdown.every((issue) => issue.retryable)
|
||
const hasOnlyAutoRetryableIssues =
|
||
issueBreakdown.length > 0 && issueBreakdown.every((issue) => issue.auto_retryable)
|
||
const canRunScopedActions = issueBreakdown.length <= 1
|
||
const canChangeChannel = queueBucket !== 'terminal'
|
||
const hasUnlockedItems = row.locked_item_count < row.item_count
|
||
return (
|
||
<Space size={4} wrap>
|
||
<Select
|
||
size="small"
|
||
style={{ width: 180 }}
|
||
placeholder={
|
||
row.internal_sku || internalSkuDrafts[rowKey(row)] ? '选择渠道' : '先补内部 SKU'
|
||
}
|
||
options={CHANNEL_OPTIONS}
|
||
value={selections[rowKey(row)]}
|
||
onChange={(value) => setSelections((prev) => ({ ...prev, [rowKey(row)]: value }))}
|
||
/>
|
||
<Button
|
||
size="small"
|
||
type="primary"
|
||
disabled={
|
||
(!row.internal_sku && !String(internalSkuDrafts[rowKey(row)] || '').trim()) ||
|
||
!selections[rowKey(row)] ||
|
||
!canRunScopedActions ||
|
||
!canChangeChannel
|
||
}
|
||
loading={assignMutation.isPending}
|
||
onClick={() => assignMutation.mutate(row)}
|
||
>
|
||
保存渠道
|
||
</Button>
|
||
{canRunScopedActions && hasConfigIssue ? (
|
||
<Button
|
||
size="small"
|
||
disabled={!row.internal_sku}
|
||
onClick={() => {
|
||
const sku = String(row.internal_sku || '').trim()
|
||
if (!sku) return
|
||
void navigate(
|
||
`/admin/cost-center?scope=manual&tab=cost&manualSku=${encodeURIComponent(sku)}&returnTo=${encodeURIComponent('/admin/fulfillment-channel')}`,
|
||
)
|
||
}}
|
||
>
|
||
去补配置({row.config_issue_item_count})
|
||
</Button>
|
||
) : null}
|
||
{canRunScopedActions && hasManualReview ? (
|
||
<Button size="small" onClick={() => void navigate('/admin/tasks')}>
|
||
处理人工复核({row.manual_review_item_count})
|
||
</Button>
|
||
) : null}
|
||
{canRunScopedActions && hasOnlyRetryableIssues && hasRetryable && hasUnlockedItems ? (
|
||
<Button
|
||
size="small"
|
||
danger
|
||
loading={retryCarrierMutation.isPending}
|
||
onClick={() =>
|
||
Modal.confirm({
|
||
title: '确认重开履约载体',
|
||
content: `只会处理该 SKU 下 ${row.retryable_unlocked_item_count} 个未锁定、允许重试的订单项。退款、取消、人工复核和缺配置项不会被处理。已有失败或关闭任务会保留为历史。`,
|
||
okText: '确认重试',
|
||
okButtonProps: { danger: true },
|
||
cancelText: '取消',
|
||
onOk: () =>
|
||
retryCarrierMutation.mutateAsync({
|
||
row,
|
||
retryInactiveCarrier: true,
|
||
issueCodes: retryableIssueCodes,
|
||
}),
|
||
})
|
||
}
|
||
>
|
||
确认重试({row.retryable_unlocked_item_count})
|
||
</Button>
|
||
) : null}
|
||
{canRunScopedActions &&
|
||
hasOnlyAutoRetryableIssues &&
|
||
hasAutoRetryable &&
|
||
!hasAfterSales &&
|
||
!hasSystemIssue &&
|
||
row.configured_channels?.length &&
|
||
hasUnlockedItems ? (
|
||
<Tooltip title="只补建当前无活跃载体的未锁定订单,不会重开失败或关闭的旧任务">
|
||
<Button
|
||
size="small"
|
||
icon={<SyncOutlined />}
|
||
loading={retryCarrierMutation.isPending}
|
||
onClick={() =>
|
||
retryCarrierMutation.mutate({
|
||
row,
|
||
retryInactiveCarrier: false,
|
||
issueCodes: autoRetryableIssueCodes,
|
||
})
|
||
}
|
||
>
|
||
补载体({row.auto_retryable_unlocked_item_count})
|
||
</Button>
|
||
</Tooltip>
|
||
) : null}
|
||
{canRunScopedActions && row.locked_item_count > 0 ? (
|
||
<Button
|
||
size="small"
|
||
loading={unlockMutation.isPending}
|
||
onClick={() =>
|
||
Modal.confirm({
|
||
title: '解除运营锁定',
|
||
content: `将解除该分组中 ${row.locked_item_count} 个订单项的运营锁定。若渠道配置仍缺失,订单会继续留在待分类队列。`,
|
||
okText: '解除锁定',
|
||
cancelText: '取消',
|
||
onOk: () => unlockMutation.mutateAsync(row),
|
||
})
|
||
}
|
||
>
|
||
解除锁定
|
||
</Button>
|
||
) : null}
|
||
{canRunScopedActions ? (
|
||
<Tooltip title="从待办中忽略并归档,不删除原始订单">
|
||
<Button
|
||
danger
|
||
icon={<DeleteOutlined />}
|
||
loading={deleteMutation.isPending}
|
||
onClick={() =>
|
||
Modal.confirm({
|
||
title: '忽略并归档待分类记录',
|
||
content: (
|
||
<div>
|
||
<p>
|
||
将从待办中归档 <strong>{row.item_count}</strong>{' '}
|
||
个订单项,并清除已生成的
|
||
派生成本快照、分类异常;可重建的财务事实会按开放期间重算。
|
||
</p>
|
||
<p style={{ marginBottom: 0 }}>
|
||
原始订单和订单商品不会删除;已关账期间只跳过重算,不再阻止归档。
|
||
</p>
|
||
</div>
|
||
),
|
||
okText: '确认归档',
|
||
okButtonProps: { danger: true },
|
||
cancelText: '取消',
|
||
onOk: () => deleteMutation.mutateAsync(row),
|
||
})
|
||
}
|
||
/>
|
||
</Tooltip>
|
||
) : null}
|
||
</Space>
|
||
)
|
||
},
|
||
},
|
||
]
|
||
|
||
return (
|
||
<Card
|
||
title={`${
|
||
PENDING_QUEUE_BUCKET_OPTIONS.find((option) => option.value === queueBucket)?.label ||
|
||
'履约待办'
|
||
}(${query.data?.data?.total ?? 0} 个 SKU)`}
|
||
extra={
|
||
<Space>
|
||
<Input.Search
|
||
allowClear
|
||
placeholder="SKU / 商品名"
|
||
style={{ width: 220 }}
|
||
onSearch={(value) => {
|
||
setKeyword(value)
|
||
setPage(1)
|
||
}}
|
||
/>
|
||
<Button icon={<ReloadOutlined />} onClick={() => void query.refetch()}>
|
||
刷新
|
||
</Button>
|
||
<Button
|
||
icon={<SyncOutlined />}
|
||
loading={retryWorkOrderMutation.isPending}
|
||
onClick={() => retryWorkOrderMutation.mutate(undefined)}
|
||
>
|
||
重试接单匹配
|
||
</Button>
|
||
<Button
|
||
icon={<ThunderboltOutlined />}
|
||
loading={pipelineMutation.isPending}
|
||
onClick={() => pipelineMutation.mutate()}
|
||
>
|
||
立即跑一遍管道
|
||
</Button>
|
||
</Space>
|
||
}
|
||
>
|
||
<Alert
|
||
type="warning"
|
||
showIcon
|
||
style={{ marginBottom: 12 }}
|
||
message="补载体自动扫描只处理“自动处理中”。缺配置、失败重试、人工复核、售后和已终止订单分别留在对应队列,不再占用自动扫描。指定渠道会先保存渠道和草稿标准商品;忽略归档只影响派生流程,不删除原始订单。"
|
||
/>
|
||
<Segmented
|
||
block
|
||
value={queueBucket}
|
||
options={PENDING_QUEUE_BUCKET_OPTIONS.map((option) => ({
|
||
value: option.value,
|
||
label: `${option.label} ${query.data?.data?.bucketCounts?.[option.value] ?? 0}`,
|
||
}))}
|
||
onChange={(value) => {
|
||
setQueueBucket(String(value) as FulfillmentQueueBucket)
|
||
setPage(1)
|
||
setSelections({})
|
||
setInternalSkuDrafts({})
|
||
}}
|
||
style={{ marginBottom: 12 }}
|
||
/>
|
||
<PercentTable
|
||
rowKey={(row) => rowKey(row)}
|
||
size="small"
|
||
loading={query.isLoading}
|
||
dataSource={query.data?.data?.items || []}
|
||
columns={columns}
|
||
pagination={buildAdminTablePagination({
|
||
current: query.data?.data?.page || page,
|
||
pageSize: query.data?.data?.pageSize || pageSize,
|
||
total: query.data?.data?.total || 0,
|
||
onChange: (nextPage, nextPageSize) => {
|
||
setPage(nextPageSize !== pageSize ? 1 : nextPage)
|
||
setPageSize(nextPageSize)
|
||
},
|
||
})}
|
||
/>
|
||
</Card>
|
||
)
|
||
}
|
||
|
||
function InternalSkuMappingsPanel() {
|
||
const queryClient = useQueryClient()
|
||
const [form] = Form.useForm()
|
||
const [keyword, setKeyword] = useState('')
|
||
const [page, setPage] = useState(1)
|
||
const [pageSize, setPageSize] = useState(ADMIN_DEFAULT_PAGE_SIZE)
|
||
const [open, setOpen] = useState(false)
|
||
const [editing, setEditing] = useState<InternalSkuMapping | null>(null)
|
||
|
||
const query = useQuery({
|
||
queryKey: ['fulfillment-internal-sku-mappings', keyword, page, pageSize],
|
||
queryFn: () => fetchInternalSkuMappings({ keyword, page, pageSize }),
|
||
})
|
||
|
||
const saveMutation = useMutation({
|
||
mutationFn: (values: Record<string, unknown>) =>
|
||
saveInternalSkuMapping({
|
||
provider: String(values.provider || '').trim(),
|
||
shopId: String(values.shopId || '').trim(),
|
||
matchType: values.matchType as InternalSkuMappingMatchType,
|
||
matchValue: String(values.matchValue || ''),
|
||
internalSku: String(values.internalSku || ''),
|
||
priority: Number(values.priority || 100),
|
||
note: String(values.note || ''),
|
||
enabled: values.enabled !== false,
|
||
}),
|
||
onSuccess: () => {
|
||
message.success('SKU 映射已保存,后续管道将按新映射归一')
|
||
setOpen(false)
|
||
setEditing(null)
|
||
form.resetFields()
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-internal-sku-mappings'] })
|
||
},
|
||
onError: (error) => message.error(error instanceof Error ? error.message : '保存 SKU 映射失败'),
|
||
})
|
||
|
||
const deleteMutation = useMutation({
|
||
mutationFn: (id: number) => deleteInternalSkuMapping(id),
|
||
onSuccess: () => {
|
||
message.success('SKU 映射已删除')
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-internal-sku-mappings'] })
|
||
},
|
||
onError: (error) => message.error(error instanceof Error ? error.message : '删除 SKU 映射失败'),
|
||
})
|
||
|
||
function openEditor(row?: InternalSkuMapping) {
|
||
setEditing(row || null)
|
||
form.resetFields()
|
||
form.setFieldsValue(
|
||
row
|
||
? {
|
||
provider: row.provider,
|
||
shopId: row.shop_id,
|
||
matchType: row.match_type,
|
||
matchValue: row.match_value,
|
||
internalSku: row.internal_sku,
|
||
priority: row.priority,
|
||
note: row.note,
|
||
enabled: row.enabled,
|
||
}
|
||
: {
|
||
provider: '',
|
||
shopId: '',
|
||
matchType: 'sku_code',
|
||
priority: 100,
|
||
enabled: true,
|
||
},
|
||
)
|
||
setOpen(true)
|
||
}
|
||
|
||
const columns = [
|
||
{
|
||
title: '来源平台',
|
||
dataIndex: 'provider',
|
||
width: 120,
|
||
render: (value: string) => value || <Tag color="blue">全部平台</Tag>,
|
||
},
|
||
{
|
||
title: '店铺',
|
||
dataIndex: 'shop_id',
|
||
width: 150,
|
||
ellipsis: true,
|
||
render: (value: string) => value || <Tag color="blue">全部店铺</Tag>,
|
||
},
|
||
{
|
||
title: '匹配字段',
|
||
dataIndex: 'match_type',
|
||
width: 130,
|
||
render: (value: InternalSkuMappingMatchType) =>
|
||
INTERNAL_SKU_MAPPING_TYPES.find((item) => item.value === value)?.label || value,
|
||
},
|
||
{ title: '平台匹配值', dataIndex: 'match_value', ellipsis: true },
|
||
{ title: '中文内部 SKU', dataIndex: 'internal_sku', ellipsis: true },
|
||
{ title: '优先级', dataIndex: 'priority', width: 90 },
|
||
{
|
||
title: '状态',
|
||
dataIndex: 'enabled',
|
||
width: 80,
|
||
render: (value: boolean) => (value ? <Tag color="green">启用</Tag> : <Tag>停用</Tag>),
|
||
},
|
||
{
|
||
title: '操作',
|
||
width: 150,
|
||
render: (_: unknown, row: InternalSkuMapping) => (
|
||
<Space>
|
||
<Button size="small" onClick={() => openEditor(row)}>
|
||
编辑
|
||
</Button>
|
||
<Button
|
||
danger
|
||
size="small"
|
||
loading={deleteMutation.isPending}
|
||
onClick={() =>
|
||
Modal.confirm({
|
||
title: '删除 SKU 映射',
|
||
content: `${row.provider || '全部平台'} / ${row.shop_id || '全部店铺'} / ${row.match_value}`,
|
||
okText: '删除',
|
||
okButtonProps: { danger: true },
|
||
cancelText: '取消',
|
||
onOk: () => deleteMutation.mutateAsync(row.id),
|
||
})
|
||
}
|
||
>
|
||
删除
|
||
</Button>
|
||
</Space>
|
||
),
|
||
},
|
||
]
|
||
|
||
return (
|
||
<Card
|
||
title={`SKU 映射(${query.data?.data?.total ?? 0})`}
|
||
extra={
|
||
<Space>
|
||
<Input.Search
|
||
allowClear
|
||
placeholder="平台 SKU / 中文 SKU"
|
||
style={{ width: 220 }}
|
||
onSearch={(value) => {
|
||
setKeyword(value.trim())
|
||
setPage(1)
|
||
}}
|
||
/>
|
||
<Button icon={<ReloadOutlined />} onClick={() => void query.refetch()}>
|
||
刷新
|
||
</Button>
|
||
<Button type="primary" icon={<PlusOutlined />} onClick={() => openEditor()}>
|
||
新增映射
|
||
</Button>
|
||
</Space>
|
||
}
|
||
>
|
||
<Alert
|
||
type="info"
|
||
showIcon
|
||
style={{ marginBottom: 12 }}
|
||
message="平台 SKU 只在这里映射为中文内部 SKU。店铺级映射优先于平台级,平台级优先于全局;渠道配置仍然只按中文内部 SKU 全局生效。"
|
||
/>
|
||
<PercentTable
|
||
rowKey="id"
|
||
size="small"
|
||
loading={query.isFetching}
|
||
dataSource={query.data?.data?.items || []}
|
||
columns={columns}
|
||
pagination={buildAdminTablePagination({
|
||
current: query.data?.data?.page || page,
|
||
pageSize: query.data?.data?.pageSize || pageSize,
|
||
total: query.data?.data?.total || 0,
|
||
onChange: (nextPage, nextPageSize) => {
|
||
setPage(nextPageSize !== pageSize ? 1 : nextPage)
|
||
setPageSize(nextPageSize)
|
||
},
|
||
})}
|
||
/>
|
||
|
||
<Modal
|
||
title={editing ? '编辑 SKU 映射' : '新增 SKU 映射'}
|
||
open={open}
|
||
onCancel={() => {
|
||
setOpen(false)
|
||
setEditing(null)
|
||
}}
|
||
onOk={() => form.submit()}
|
||
confirmLoading={saveMutation.isPending}
|
||
destroyOnHidden
|
||
>
|
||
<Form
|
||
form={form}
|
||
layout="vertical"
|
||
initialValues={{ matchType: 'sku_code', priority: 100, enabled: true }}
|
||
onFinish={(values) => saveMutation.mutate(values)}
|
||
>
|
||
<Form.Item name="provider" label="来源平台">
|
||
<Input placeholder="留空表示全部平台" />
|
||
</Form.Item>
|
||
<Form.Item name="shopId" label="店铺 ID">
|
||
<Input placeholder="留空表示全部店铺" />
|
||
</Form.Item>
|
||
<Form.Item name="matchType" label="匹配字段" rules={[{ required: true }]}>
|
||
<Select options={INTERNAL_SKU_MAPPING_TYPES} />
|
||
</Form.Item>
|
||
<Form.Item name="matchValue" label="平台匹配值" rules={[{ required: true }]}>
|
||
<Input placeholder="例如平台 SKU、SKU 昵称或规格值" />
|
||
</Form.Item>
|
||
<Form.Item
|
||
name="internalSku"
|
||
label="中文内部 SKU"
|
||
rules={[{ required: true, message: '请输入包含中文的内部 SKU' }]}
|
||
>
|
||
<Input placeholder="例如:幸运币2个" />
|
||
</Form.Item>
|
||
<Form.Item name="priority" label="优先级" extra="数字越小越优先">
|
||
<InputNumber min={0} precision={0} style={{ width: '100%' }} />
|
||
</Form.Item>
|
||
<Form.Item name="note" label="备注">
|
||
<Input.TextArea rows={2} maxLength={300} showCount />
|
||
</Form.Item>
|
||
<Form.Item name="enabled" label="启用" valuePropName="checked">
|
||
<Switch />
|
||
</Form.Item>
|
||
</Form>
|
||
</Modal>
|
||
</Card>
|
||
)
|
||
}
|
||
|
||
function RulesPanel() {
|
||
const queryClient = useQueryClient()
|
||
const [open, setOpen] = useState(false)
|
||
const [selectedRuleIds, setSelectedRuleIds] = useState<number[]>([])
|
||
const [keyword, setKeyword] = useState('')
|
||
const [channelFilter, setChannelFilter] = useState('')
|
||
const [sourceFilter, setSourceFilter] = useState('')
|
||
const [enabledFilter, setEnabledFilter] = useState('')
|
||
const [page, setPage] = useState(1)
|
||
const [pageSize, setPageSize] = useState(ADMIN_DEFAULT_PAGE_SIZE)
|
||
const [form] = Form.useForm()
|
||
const hasActiveFilters = Boolean(keyword || channelFilter || sourceFilter || enabledFilter)
|
||
|
||
const query = useQuery({
|
||
queryKey: [
|
||
'fulfillment-rules',
|
||
keyword,
|
||
channelFilter,
|
||
sourceFilter,
|
||
enabledFilter,
|
||
page,
|
||
pageSize,
|
||
],
|
||
queryFn: () =>
|
||
fetchChannelRules({
|
||
keyword,
|
||
channel: channelFilter,
|
||
source: sourceFilter,
|
||
...(enabledFilter ? { enabled: enabledFilter === 'true' } : {}),
|
||
page,
|
||
pageSize,
|
||
}),
|
||
})
|
||
const ruleCount = query.data?.data?.total || 0
|
||
|
||
useEffect(() => {
|
||
const maxPage = Math.max(1, Math.ceil(ruleCount / pageSize))
|
||
if (page > maxPage) setPage(maxPage)
|
||
}, [page, pageSize, ruleCount])
|
||
|
||
const saveMutation = useMutation({
|
||
mutationFn: (values: Record<string, unknown>) => saveChannelRule(values as never),
|
||
onSuccess: () => {
|
||
message.success('规则已保存')
|
||
setOpen(false)
|
||
form.resetFields()
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-rules'] })
|
||
},
|
||
onError: (error) => message.error(error instanceof Error ? error.message : '保存规则失败'),
|
||
})
|
||
|
||
const deleteMutation = useMutation({
|
||
mutationFn: (ids: number[]) => deleteChannelRules(ids),
|
||
onSuccess: (result) => {
|
||
const missingHint = result.data.missingIds.length
|
||
? `,${result.data.missingIds.length} 条已不存在`
|
||
: ''
|
||
message.success(`已删除 ${result.data.deletedCount} 条渠道规则${missingHint}`)
|
||
setSelectedRuleIds([])
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-rules'] })
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-pending'] })
|
||
},
|
||
onError: (error) => message.error(error instanceof Error ? error.message : '删除规则失败'),
|
||
})
|
||
|
||
const forceDeleteMutation = useMutation({
|
||
mutationFn: (ids: number[]) => forceDeleteChannelRules(ids),
|
||
onSuccess: (result) => {
|
||
const missingHint = result.data.missingIds.length
|
||
? `,${result.data.missingIds.length} 条已不存在`
|
||
: ''
|
||
message.success(`已强制删除 ${result.data.deletedCount} 条渠道规则${missingHint}`)
|
||
setSelectedRuleIds([])
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-rules'] })
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-pending'] })
|
||
},
|
||
onError: (error) => message.error(error instanceof Error ? error.message : '强制删除规则失败'),
|
||
})
|
||
|
||
function resetFilters() {
|
||
setKeyword('')
|
||
setChannelFilter('')
|
||
setSourceFilter('')
|
||
setEnabledFilter('')
|
||
setPage(1)
|
||
setSelectedRuleIds([])
|
||
}
|
||
|
||
function confirmDeleteRules(ids: number[]) {
|
||
if (ids.length === 0) return
|
||
Modal.confirm({
|
||
title: ids.length === 1 ? '删除渠道规则' : `批量删除 ${ids.length} 条渠道规则`,
|
||
content: '删除后会立即影响新订单的渠道判定;历史订单和成本数据不会被删除。',
|
||
okText: '确认删除',
|
||
okButtonProps: { danger: true },
|
||
cancelText: '取消',
|
||
onOk: () => deleteMutation.mutateAsync(ids),
|
||
})
|
||
}
|
||
|
||
function confirmForceDeleteRules(ids: number[]) {
|
||
if (ids.length === 0) return
|
||
Modal.confirm({
|
||
title: ids.length === 1 ? '强制删除渠道规则' : `批量强制删除 ${ids.length} 条渠道规则`,
|
||
content:
|
||
'将跳过系统来源保护,只删除统一渠道规则本身。历史订单和成本数据不会被删除;对应来源后续同步时,规则仍可能重新生成。',
|
||
okText: '确认强制删除',
|
||
okButtonProps: { danger: true },
|
||
cancelText: '取消',
|
||
onOk: () => forceDeleteMutation.mutateAsync(ids),
|
||
})
|
||
}
|
||
|
||
const columns = [
|
||
{ title: '作用范围', width: 110, render: () => <Tag color="blue">全局</Tag> },
|
||
{
|
||
title: '匹配键',
|
||
dataIndex: 'match_key_type',
|
||
width: 110,
|
||
render: (v: string) => MATCH_KEY_OPTIONS.find((item) => item.value === v)?.label || v,
|
||
},
|
||
{ title: '匹配值', dataIndex: 'match_key' },
|
||
{
|
||
title: '渠道',
|
||
dataIndex: 'channel',
|
||
width: 140,
|
||
render: (value: string) => (
|
||
<Tag color={CHANNEL_COLOR[value] || 'default'}>
|
||
{CHANNEL_OPTIONS.find((item) => item.value === value)?.label || value}
|
||
</Tag>
|
||
),
|
||
},
|
||
{ title: '优先级', dataIndex: 'priority', width: 90 },
|
||
{
|
||
title: '载体参数',
|
||
width: 220,
|
||
ellipsis: true,
|
||
render: (_: unknown, row: ChannelRule) => formatCarrierParams(row),
|
||
},
|
||
{
|
||
title: '来源',
|
||
dataIndex: 'source',
|
||
width: 140,
|
||
render: (value: string) =>
|
||
CHANNEL_SOURCE_LABEL[value] || (value.startsWith('rule:') ? '规则迁移' : value || '-'),
|
||
},
|
||
{
|
||
title: '启用',
|
||
dataIndex: 'enabled',
|
||
width: 80,
|
||
render: (value: boolean) => (value ? <Tag color="green">启用</Tag> : <Tag>停用</Tag>),
|
||
},
|
||
{
|
||
title: '操作',
|
||
width: 120,
|
||
render: (_: unknown, row: ChannelRule) => {
|
||
if (!canDeleteChannelRule(row)) {
|
||
return (
|
||
<Button
|
||
danger
|
||
size="small"
|
||
loading={forceDeleteMutation.isPending}
|
||
onClick={() => confirmForceDeleteRules([row.id])}
|
||
>
|
||
强制删除
|
||
</Button>
|
||
)
|
||
}
|
||
return (
|
||
<Button
|
||
danger
|
||
size="small"
|
||
loading={deleteMutation.isPending}
|
||
onClick={() => confirmDeleteRules([row.id])}
|
||
>
|
||
删除
|
||
</Button>
|
||
)
|
||
},
|
||
},
|
||
]
|
||
|
||
return (
|
||
<Card
|
||
title={`统一渠道配置(${ruleCount})`}
|
||
extra={
|
||
<Space>
|
||
<Button
|
||
danger
|
||
icon={<DeleteOutlined />}
|
||
disabled={selectedRuleIds.length === 0}
|
||
loading={forceDeleteMutation.isPending}
|
||
onClick={() => confirmForceDeleteRules(selectedRuleIds)}
|
||
>
|
||
批量强制删除{selectedRuleIds.length ? ` (${selectedRuleIds.length})` : ''}
|
||
</Button>
|
||
<Button icon={<ReloadOutlined />} onClick={() => void query.refetch()}>
|
||
刷新
|
||
</Button>
|
||
<Button type="primary" icon={<PlusOutlined />} onClick={() => setOpen(true)}>
|
||
新增规则
|
||
</Button>
|
||
</Space>
|
||
}
|
||
>
|
||
<Typography.Paragraph type="secondary">
|
||
配置按内部 SKU 全局生效,会同时影响所有平台和店铺。每条内部 SKU 只能有一个主渠道;
|
||
其他渠道请设置 90 以上优先级作为兜底。接单平台的具体模板由统一配置中的 workRuleKey 控制。
|
||
来源为商品能力迁移、人工配置、卡券或历史回填的系统规则默认受保护;确认配置错误时可使用
|
||
「强制删除」,但对应来源后续同步时仍可能重新生成。
|
||
</Typography.Paragraph>
|
||
<Space wrap style={{ marginBottom: 12 }}>
|
||
<Input
|
||
allowClear
|
||
prefix={<SearchOutlined />}
|
||
placeholder="搜索内部 SKU、载体参数或备注"
|
||
value={keyword}
|
||
onChange={(event) => {
|
||
setKeyword(event.target.value)
|
||
setPage(1)
|
||
setSelectedRuleIds([])
|
||
}}
|
||
style={{ width: 280 }}
|
||
/>
|
||
<Select
|
||
allowClear
|
||
placeholder="全部渠道"
|
||
value={channelFilter || undefined}
|
||
onChange={(value) => {
|
||
setChannelFilter(value || '')
|
||
setPage(1)
|
||
setSelectedRuleIds([])
|
||
}}
|
||
options={CHANNEL_OPTIONS}
|
||
style={{ width: 160 }}
|
||
/>
|
||
<Select
|
||
allowClear
|
||
placeholder="全部来源"
|
||
value={sourceFilter || undefined}
|
||
onChange={(value) => {
|
||
setSourceFilter(value || '')
|
||
setPage(1)
|
||
setSelectedRuleIds([])
|
||
}}
|
||
options={CHANNEL_SOURCE_FILTER_OPTIONS}
|
||
style={{ width: 160 }}
|
||
/>
|
||
<Select
|
||
allowClear
|
||
placeholder="全部状态"
|
||
value={enabledFilter || undefined}
|
||
onChange={(value) => {
|
||
setEnabledFilter(value || '')
|
||
setPage(1)
|
||
setSelectedRuleIds([])
|
||
}}
|
||
options={ENABLED_FILTER_OPTIONS}
|
||
style={{ width: 120 }}
|
||
/>
|
||
<Button disabled={!hasActiveFilters} onClick={resetFilters}>
|
||
重置
|
||
</Button>
|
||
</Space>
|
||
<PercentTable
|
||
rowKey="id"
|
||
size="small"
|
||
loading={query.isFetching}
|
||
dataSource={query.data?.data?.items || []}
|
||
columns={columns}
|
||
rowSelection={{
|
||
selectedRowKeys: selectedRuleIds,
|
||
onChange: (keys) => setSelectedRuleIds(keys.map(Number)),
|
||
}}
|
||
pagination={buildAdminTablePagination({
|
||
current: query.data?.data?.page || page,
|
||
pageSize: query.data?.data?.pageSize || pageSize,
|
||
total: ruleCount,
|
||
onChange: (nextPage, nextPageSize) => {
|
||
setPage(nextPageSize !== pageSize ? 1 : nextPage)
|
||
setPageSize(nextPageSize)
|
||
},
|
||
})}
|
||
/>
|
||
|
||
<Modal
|
||
title="新增统一渠道配置"
|
||
open={open}
|
||
onCancel={() => setOpen(false)}
|
||
onOk={() => form.submit()}
|
||
confirmLoading={saveMutation.isPending}
|
||
>
|
||
<Form
|
||
form={form}
|
||
layout="vertical"
|
||
initialValues={{
|
||
matchKeyType: 'internal_sku',
|
||
channel: 'third_party_voucher',
|
||
priority: 10,
|
||
}}
|
||
onFinish={(values) => saveMutation.mutate(values)}
|
||
>
|
||
<Form.Item name="matchKeyType" label="匹配键" rules={[{ required: true }]}>
|
||
<Select options={MATCH_KEY_OPTIONS} />
|
||
</Form.Item>
|
||
<Form.Item name="matchKey" label="匹配值" rules={[{ required: true }]}>
|
||
<Input />
|
||
</Form.Item>
|
||
<Form.Item name="channel" label="渠道" rules={[{ required: true }]}>
|
||
<Select options={CHANNEL_OPTIONS} />
|
||
</Form.Item>
|
||
<Form.Item name="priority" label="优先级(越小越优先)">
|
||
<InputNumber min={1} max={999} style={{ width: '100%' }} />
|
||
</Form.Item>
|
||
<Form.Item name="note" label="备注">
|
||
<Input />
|
||
</Form.Item>
|
||
<Form.Item name="enabled" label="启用" valuePropName="checked" initialValue>
|
||
<Switch />
|
||
</Form.Item>
|
||
</Form>
|
||
</Modal>
|
||
</Card>
|
||
)
|
||
}
|
||
|
||
function ExceptionsPanel() {
|
||
const [reason, setReason] = useState('')
|
||
const [page, setPage] = useState(1)
|
||
const [pageSize, setPageSize] = useState(ADMIN_DEFAULT_PAGE_SIZE)
|
||
const query = useQuery({
|
||
queryKey: ['fulfillment-exceptions', reason, page, pageSize],
|
||
queryFn: () => fetchChannelExceptions({ reason, status: 'open', page, pageSize }),
|
||
})
|
||
|
||
const REASON_OPTIONS = [
|
||
{ value: '', label: '全部' },
|
||
{ value: 'routing_conflict', label: '渠道冲突' },
|
||
{ value: 'product_mapping_missing', label: '未归一' },
|
||
{ value: 'cost_missing', label: '成本缺失' },
|
||
{ value: 'manual_config_missing', label: '人工 SKU 未配置' },
|
||
{ value: 'manual_cost_missing', label: '人工未确认履约' },
|
||
{ value: 'carrier_missing', label: '缺少履约载体' },
|
||
]
|
||
|
||
const columns = [
|
||
{
|
||
title: '类型',
|
||
dataIndex: 'reason',
|
||
width: 200,
|
||
render: (value: string) => (
|
||
<Tag>{REASON_OPTIONS.find((item) => item.value === value)?.label || value}</Tag>
|
||
),
|
||
},
|
||
{ title: '范围', dataIndex: 'scope_key', ellipsis: true },
|
||
{ title: '涉及订单项', dataIndex: 'item_count', width: 110 },
|
||
{
|
||
title: '最近出现',
|
||
dataIndex: 'last_seen_at',
|
||
width: 160,
|
||
render: (value: string) => formatDateTime(value),
|
||
},
|
||
]
|
||
|
||
return (
|
||
<Card
|
||
title="问题队列(按中文内部 SKU 聚合)"
|
||
extra={
|
||
<Space>
|
||
<Select
|
||
style={{ width: 180 }}
|
||
value={reason}
|
||
options={REASON_OPTIONS}
|
||
onChange={(value) => {
|
||
setReason(value)
|
||
setPage(1)
|
||
}}
|
||
/>
|
||
<Button icon={<ReloadOutlined />} onClick={() => void query.refetch()}>
|
||
刷新
|
||
</Button>
|
||
</Space>
|
||
}
|
||
>
|
||
<PercentTable
|
||
rowKey="id"
|
||
size="small"
|
||
loading={query.isFetching}
|
||
dataSource={query.data?.data?.items || []}
|
||
columns={columns}
|
||
pagination={buildAdminTablePagination({
|
||
current: query.data?.data?.page || page,
|
||
pageSize: query.data?.data?.pageSize || pageSize,
|
||
total: query.data?.data?.total || 0,
|
||
onChange: (nextPage, nextPageSize) => {
|
||
setPage(nextPageSize !== pageSize ? 1 : nextPage)
|
||
setPageSize(nextPageSize)
|
||
},
|
||
})}
|
||
/>
|
||
</Card>
|
||
)
|
||
}
|
||
|
||
function PipelinesPanel() {
|
||
const queryClient = useQueryClient()
|
||
const query = useQuery({
|
||
queryKey: ['fulfillment-pipelines'],
|
||
queryFn: fetchPipelineStatus,
|
||
})
|
||
|
||
const runMutation = useMutation({
|
||
mutationFn: (pipeline: string) => runFinancePipeline({ pipeline }),
|
||
onSuccess: () => {
|
||
message.success('管道已执行')
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-pipelines'] })
|
||
void queryClient.invalidateQueries({ queryKey: ['fulfillment-pending'] })
|
||
},
|
||
onError: (error) => message.error(error instanceof Error ? error.message : '执行管道失败'),
|
||
})
|
||
|
||
const columns = [
|
||
{ title: '管道', dataIndex: 'label', width: 130 },
|
||
{
|
||
title: '兜底任务',
|
||
width: 150,
|
||
render: (_: unknown, row: FinancePipelineStatus) =>
|
||
row.scheduler ? (
|
||
row.scheduler.enabled ? (
|
||
<Tag color="green">已启用</Tag>
|
||
) : (
|
||
<Tag>已停用</Tag>
|
||
)
|
||
) : (
|
||
<Tag color="orange">未注册</Tag>
|
||
),
|
||
},
|
||
{
|
||
title: '上次成功',
|
||
dataIndex: 'lastSuccessAt',
|
||
width: 170,
|
||
render: (value: string | null) => (value ? formatDateTime(value) : '从未成功'),
|
||
},
|
||
{
|
||
title: '水位',
|
||
width: 200,
|
||
render: (_: unknown, row: FinancePipelineStatus) =>
|
||
row.lastStatDate
|
||
? `日期 ${row.lastStatDate}`
|
||
: row.lastItemId > 0
|
||
? `订单项 ${row.lastItemId}`
|
||
: '—',
|
||
},
|
||
{
|
||
title: '最近一次执行',
|
||
width: 260,
|
||
render: (_: unknown, row: FinancePipelineStatus) => row.scheduler?.lastMessage || '—',
|
||
},
|
||
{
|
||
title: '错误',
|
||
render: (_: unknown, row: FinancePipelineStatus) =>
|
||
row.lastError ? <Typography.Text type="danger">{row.lastError}</Typography.Text> : '—',
|
||
},
|
||
{
|
||
title: '操作',
|
||
width: 110,
|
||
render: (_: unknown, row: FinancePipelineStatus) => (
|
||
<Button
|
||
size="small"
|
||
loading={runMutation.isPending && runMutation.variables === row.pipeline}
|
||
onClick={() => runMutation.mutate(row.pipeline)}
|
||
>
|
||
立即执行
|
||
</Button>
|
||
),
|
||
},
|
||
]
|
||
|
||
return (
|
||
<Card
|
||
title="管道状态"
|
||
extra={
|
||
<Button icon={<ReloadOutlined />} onClick={() => void query.refetch()}>
|
||
刷新
|
||
</Button>
|
||
}
|
||
>
|
||
<Typography.Paragraph type="secondary">
|
||
新订单会由入库事件即时推进渠道判定和载体补建;定时任务只做漏事件兜底。 本页随后台 SSE
|
||
自动刷新,用于查看进度、排障和补跑。
|
||
</Typography.Paragraph>
|
||
<PercentTable
|
||
rowKey="pipeline"
|
||
size="small"
|
||
loading={query.isFetching}
|
||
dataSource={query.data?.data || []}
|
||
columns={columns}
|
||
pagination={false}
|
||
/>
|
||
</Card>
|
||
)
|
||
}
|
||
|
||
function rowKey(row: PendingChannelGroup) {
|
||
return row.group_key
|
||
}
|
||
|
||
function formatCarrierParams(row: ChannelRule) {
|
||
const key =
|
||
row.channel === 'affiliate_dash'
|
||
? row.config_json.affiliateSku
|
||
: row.channel === 'work_order'
|
||
? row.config_json.workRuleKey
|
||
: row.channel === 'manual'
|
||
? row.config_json.manualConfigId
|
||
: row.config_json.voucherSku
|
||
return key ? String(key) : '待补全'
|
||
}
|
||
|
||
function canDeleteChannelRule(row: ChannelRule) {
|
||
return row.source === 'operator' || row.source.startsWith('rule:')
|
||
}
|