merge: 合并 main 并保留寄卖内部匹配与客户退款

This commit is contained in:
2026-11-05 18:02:47 +08:00
105 changed files with 7248 additions and 665 deletions
@@ -2,8 +2,10 @@ import {
ArrowDownOutlined,
ArrowUpOutlined,
DeleteOutlined,
DownOutlined,
PlusOutlined,
ReloadOutlined,
RightOutlined,
SaveOutlined,
SearchOutlined,
} from '@ant-design/icons'
@@ -41,6 +43,7 @@ import {
retryAdminOrderServiceAutoPublishJob,
saveAdminOrderServiceProfile,
type AdminOrderServiceAutoPublishJob,
type AdminOrderServiceCategory,
type AdminOrderServiceProfile,
type OrderServiceField,
type OrderServiceMaterialConfirmation,
@@ -81,6 +84,11 @@ type OrderServiceFormValues = {
statusSteps: OrderServiceStatusSteps
}
type OrderServiceCategoryNode = {
category: AdminOrderServiceCategory
children: AdminOrderServiceCategory[]
}
const DEFAULT_SCREENSHOTS: ScreenshotForm = {
enabled: true,
required: true,
@@ -245,6 +253,7 @@ export default function OrderServicePanel() {
const [form] = Form.useForm<OrderServiceFormValues>()
const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(null)
const [categoryKeyword, setCategoryKeyword] = useState('')
const [expandedCategoryIds, setExpandedCategoryIds] = useState<Set<number>>(() => new Set())
const [fields, setFields] = useState<OrderServiceField[]>([])
const [guideImage, setGuideImage] = useState<UploadedFile | Record<string, unknown> | null>(null)
const [saving, setSaving] = useState(false)
@@ -268,22 +277,56 @@ export default function OrderServicePanel() {
[profiles],
)
const normalizedKeyword = categoryKeyword.trim().toLowerCase()
const filteredCategories = useMemo(
() =>
categories.filter((item) => {
if (!normalizedKeyword) return true
return (
item.name.toLowerCase().includes(normalizedKeyword) ||
item.categoryKey.toLowerCase().includes(normalizedKeyword)
)
}),
[categories, normalizedKeyword],
const categoryTree = useMemo<OrderServiceCategoryNode[]>(() => {
const childrenByParent = new Map<number, AdminOrderServiceCategory[]>()
const roots: AdminOrderServiceCategory[] = []
for (const category of categories) {
if (category.parentId) {
const children = childrenByParent.get(category.parentId) || []
children.push(category)
childrenByParent.set(category.parentId, children)
} else {
roots.push(category)
}
}
const matches = (category: AdminOrderServiceCategory) =>
!normalizedKeyword ||
category.name.toLowerCase().includes(normalizedKeyword) ||
category.categoryKey.toLowerCase().includes(normalizedKeyword)
return roots.flatMap((category) => {
const children = childrenByParent.get(category.categoryId) || []
if (!normalizedKeyword) return [{ category, children }]
if (matches(category)) return [{ category, children }]
const matchedChildren = children.filter(matches)
return matchedChildren.length > 0 ? [{ category, children: matchedChildren }] : []
})
}, [categories, normalizedKeyword])
const filteredCategoryCount = categoryTree.reduce(
(total, node) => total + 1 + node.children.length,
0,
)
const configuredCount = categories.filter((item) =>
profileByCategoryId.has(item.categoryId),
).length
const configuredCount = new Set(
profiles.filter((item) => item.status !== 'archived').map((item) => item.categoryId),
).size
const selectedCategory = categories.find((item) => item.categoryId === selectedCategoryId) || null
const profile = (selectedCategoryId ? profileByCategoryId.get(selectedCategoryId) : null) || null
const ownProfile =
(selectedCategoryId ? profileByCategoryId.get(selectedCategoryId) : null) || null
const parentCategory = selectedCategory?.parentId
? categories.find((item) => item.categoryId === selectedCategory.parentId) || null
: null
const parentProfileCandidate = parentCategory
? profileByCategoryId.get(parentCategory.categoryId) || null
: null
const parentProfile =
parentProfileCandidate?.currentVersionNo && parentProfileCandidate.status !== 'archived'
? parentProfileCandidate
: null
const profile = ownProfile || parentProfile
const inheritsParentProfile = !ownProfile && Boolean(parentProfile)
const runtimeInheritsParent =
Boolean(parentProfile) &&
(!ownProfile || ownProfile.status === 'archived' || !ownProfile.currentVersionNo)
const guideFiles = useMemo(() => {
const image = resolveGuideImage(guideImage)
return image ? [image] : []
@@ -311,7 +354,10 @@ export default function OrderServicePanel() {
function applyProfile(nextProfile: AdminOrderServiceProfile | null) {
form.setFieldsValue({
name: nextProfile?.name || selectedCategory?.name || '',
name:
inheritsParentProfile && selectedCategory
? selectedCategory.name
: nextProfile?.name || selectedCategory?.name || '',
title: nextProfile?.title || '',
description: nextProfile?.description || '',
guideImageDescription: nextProfile?.guideImageDescription || '',
@@ -436,7 +482,11 @@ export default function OrderServicePanel() {
successText: values.successText,
postSubmitText: values.postSubmitText,
})
message.success('草稿已保存;点击“发布新版本”后才会影响新工单')
message.success(
inheritsParentProfile
? '已创建二级分类独立草稿;发布后优先使用该配置'
: '草稿已保存;点击“发布新版本”后才会影响新工单',
)
await refresh()
} catch (error) {
message.error(error instanceof Error ? error.message : '保存失败')
@@ -446,13 +496,13 @@ export default function OrderServicePanel() {
}
async function handlePublish() {
if (!profile) {
message.warning('请先保存配置草稿')
if (!ownProfile) {
message.warning('当前分类继承父级配置,请先保存二级分类独立草稿')
return
}
setPublishing(true)
try {
const response = await publishAdminOrderServiceProfile(profile.id)
const response = await publishAdminOrderServiceProfile(ownProfile.id)
const backfilled = Number(response.data.backfilledPendingOrders || 0)
message.success(
backfilled > 0
@@ -468,10 +518,10 @@ export default function OrderServicePanel() {
}
async function handleArchive() {
if (!profile) return
if (!ownProfile) return
setPublishing(true)
try {
await archiveAdminOrderServiceProfile(profile.id)
await archiveAdminOrderServiceProfile(ownProfile.id)
message.success('配置已归档;已有工单快照不受影响')
await refresh()
} catch (error) {
@@ -571,7 +621,7 @@ export default function OrderServicePanel() {
<Space size={6}>
<Text strong>接单分类</Text>
<Text type="secondary">
{filteredCategories.length}/{categories.length}
{filteredCategoryCount}/{categories.length}
</Text>
</Space>
<Input
@@ -584,34 +634,97 @@ export default function OrderServicePanel() {
/>
</div>
<div className="order-service-category-list">
{filteredCategories.map((category) => {
{categoryTree.map(({ category, children }) => {
const rowProfile = profileByCategoryId.get(category.categoryId)
const status = resolveProfileStatus(rowProfile)
const expanded =
Boolean(normalizedKeyword) || expandedCategoryIds.has(category.categoryId)
return (
<button
key={category.categoryId}
type="button"
className={`order-service-category-item${
category.categoryId === selectedCategoryId ? ' is-active' : ''
}`}
onClick={() => setSelectedCategoryId(category.categoryId)}
>
<span className="order-service-category-main">
<span className="order-service-category-name">{category.name}</span>
</span>
<span className="order-service-category-meta">
<span className="order-service-category-key">
{category.categoryKey}
{category.status === 'active' ? '' : ' · 已停用'}
<div className="order-service-category-group" key={category.categoryId}>
<button
type="button"
className={`order-service-category-item${
category.categoryId === selectedCategoryId ? ' is-active' : ''
}`}
onClick={() => {
setSelectedCategoryId(category.categoryId)
if (children.length === 0) return
setExpandedCategoryIds((current) => {
const next = new Set(current)
if (next.has(category.categoryId)) {
next.delete(category.categoryId)
} else {
next.add(category.categoryId)
}
return next
})
}}
>
<span className="order-service-category-main">
{children.length > 0 ? (
<span className="order-service-category-toggle">
{expanded ? <DownOutlined /> : <RightOutlined />}
</span>
) : (
<span className="order-service-category-toggle is-empty" />
)}
<span className="order-service-category-name">{category.name}</span>
{children.length > 0 ? (
<Tag className="order-service-category-count">
{children.length} 个二级
</Tag>
) : null}
</span>
<span className={`order-service-status-pill is-${status.tone}`}>
{status.label}
<span className="order-service-category-meta">
<span className="order-service-category-key">
{category.categoryKey}
{category.status === 'active' ? '' : ' · 已停用'}
</span>
<span className={`order-service-status-pill is-${status.tone}`}>
{status.label}
</span>
</span>
</span>
</button>
</button>
{expanded ? (
<div className="order-service-subcategory-list">
{children.map((child) => {
const childProfile = profileByCategoryId.get(child.categoryId)
const childStatus = resolveInheritedProfileStatus(
childProfile,
rowProfile,
)
return (
<button
key={child.categoryId}
type="button"
className={`order-service-category-item is-child${
child.categoryId === selectedCategoryId ? ' is-active' : ''
}`}
onClick={() => setSelectedCategoryId(child.categoryId)}
>
<span className="order-service-category-main">
<span className="order-service-category-name">{child.name}</span>
</span>
<span className="order-service-category-meta">
<span className="order-service-category-key">
{child.categoryKey}
{child.status === 'active' ? '' : ' · 已停用'}
</span>
<span
className={`order-service-status-pill is-${childStatus.tone}`}
>
{childStatus.label}
</span>
</span>
</button>
)
})}
</div>
) : null}
</div>
)
})}
{filteredCategories.length === 0 ? (
{categoryTree.length === 0 ? (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="没有匹配分类" />
) : null}
</div>
@@ -627,21 +740,39 @@ export default function OrderServicePanel() {
<Tag color={selectedCategory.status === 'active' ? 'green' : 'default'}>
{selectedCategory.status === 'active' ? '启用' : '停用'}
</Tag>
<Tag color={profile?.status === 'published' ? 'green' : 'orange'}>
{profile?.status === 'published'
? `线上 v${profile.currentVersionNo || 1}`
: profile?.currentVersionNo
? `线上 v${profile.currentVersionNo} · 有草稿`
: '尚未发布'}
<Tag
color={
ownProfile?.status === 'published'
? 'green'
: inheritsParentProfile
? 'blue'
: 'orange'
}
>
{ownProfile
? resolveProfileStatus(ownProfile).label
: inheritsParentProfile
? `继承「${parentCategory?.name || '父级'}」v${parentProfile?.currentVersionNo}`
: '尚未配置'}
</Tag>
{ownProfile && runtimeInheritsParent ? (
<Tag color="gold">
线上继承「{parentCategory?.name || '父级'}」v
{parentProfile?.currentVersionNo}
</Tag>
) : null}
</Space>
<Text type="secondary">分类标识:{selectedCategory.categoryKey}</Text>
</div>
<Space size={8} wrap>
<Button loading={publishing} onClick={() => void handlePublish()}>
<Button
disabled={!ownProfile}
loading={publishing}
onClick={() => void handlePublish()}
>
发布新版本
</Button>
{profile ? (
{ownProfile ? (
<Button danger loading={publishing} onClick={() => void handleArchive()}>
归档
</Button>
@@ -651,9 +782,17 @@ export default function OrderServicePanel() {
<Alert
className="order-service-tip"
type="info"
type={runtimeInheritsParent ? 'warning' : 'info'}
showIcon
message="一个分类复用一套资料配置,接单模板通过“所属分类”自动关联。"
message={
inheritsParentProfile
? `当前二级分类没有独立配置,线上直接继承一级分类「${parentCategory?.name || '父级'}」的已发布模板。修改并保存后会创建二级分类独立草稿。`
: ownProfile && runtimeInheritsParent
? `当前二级分类草稿尚未发布,线上仍继承一级分类「${parentCategory?.name || '父级'}」的已发布模板。`
: selectedCategory.parentId
? '二级分类优先使用独立配置;没有独立已发布配置时自动继承一级分类模板。'
: '一级分类作为默认模板,其下二级分类未独立配置时会自动继承。'
}
/>
<Form form={form} layout="vertical" onFinish={handleSave}>
@@ -1204,6 +1343,33 @@ function resolveProfileStatus(profile: AdminOrderServiceProfile | undefined) {
return { label: '已归档', tone: 'muted' }
}
function resolveInheritedProfileStatus(
profile: AdminOrderServiceProfile | undefined,
parentProfile: AdminOrderServiceProfile | undefined,
) {
if (profile) {
const status = resolveProfileStatus(profile)
if (profile.status === 'archived' && parentProfile?.currentVersionNo) {
return { label: `已归档 · 继承 v${parentProfile.currentVersionNo}`, tone: 'muted' }
}
if (
!profile.currentVersionNo &&
profile.status !== 'archived' &&
parentProfile?.currentVersionNo
) {
return { label: `草稿 · 继承 v${parentProfile.currentVersionNo}`, tone: 'warning' }
}
return status
}
if (parentProfile?.currentVersionNo && parentProfile.status !== 'archived') {
return {
label: `继承 v${parentProfile.currentVersionNo}`,
tone: 'inherited',
}
}
return { label: '未配置', tone: 'muted' }
}
function OrderServiceSectionTitle({
index,
title,
@@ -0,0 +1,387 @@
import { ReloadOutlined, SaveOutlined } from '@ant-design/icons'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
Button,
InputNumber,
Select,
Space,
Switch,
Tag,
Tooltip,
Typography,
message,
type TableColumnsType,
} from 'antd'
import { useEffect, useMemo, useState } from 'react'
import PercentTable from '@/components/common/PercentTable'
import {
fetchVoucherConsumeJobs,
fetchVoucherConsumePolicy,
retryVoucherConsumeJob,
saveVoucherConsumePolicy,
type VoucherChannelConsumePolicy,
type VoucherConsumeChannel,
type VoucherConsumeJob,
type VoucherConsumeMode,
type VoucherConsumePolicy,
type VoucherConsumeProvider,
} from '@/services/admin'
import { formatDateTime } from '@/utils/date-time'
const PROVIDER_LABEL: Record<VoucherConsumeProvider, string> = {
kuaishou_industry: '快手电子凭证',
douyin_mashida: '抖音码速达',
}
const CHANNEL_LABEL: Record<VoucherConsumeChannel, string> = {
affiliate_dash: '自动发货',
work_order: '接单工单',
manual: '人工客服',
on_account: '统一结算',
third_party_voucher: '第三方卡券',
}
const MODE_OPTIONS: Record<
VoucherConsumeChannel,
Array<{ value: VoucherConsumeMode; label: string }>
> = {
affiliate_dash: [
{ value: 'after_order_received', label: '收到订单后' },
{ value: 'after_link_generated', label: '领取链接生成后' },
{ value: 'after_task_created', label: '履约任务创建后' },
{ value: 'manual', label: '人工核销' },
],
work_order: [
{ value: 'after_order_received', label: '收到订单后' },
{ value: 'after_work_order_published_or_assigned', label: '发布或指派后' },
{ value: 'after_work_order_published', label: '仅发布后' },
{ value: 'after_work_order_assigned', label: '仅指派后' },
{ value: 'after_task_created', label: '履约任务创建后' },
{ value: 'manual', label: '人工核销' },
],
manual: [
{ value: 'after_order_received', label: '收到订单后' },
{ value: 'after_task_created', label: '人工任务创建后' },
{ value: 'manual', label: '人工核销' },
],
third_party_voucher: [
{ value: 'after_order_received', label: '收到订单后' },
{ value: 'manual', label: '人工核销' },
],
on_account: [
{ value: 'after_order_received', label: '收到订单后' },
{ value: 'manual', label: '人工核销' },
],
}
type PolicyRow = {
key: string
provider: VoucherConsumeProvider
channel: VoucherConsumeChannel
policy: VoucherChannelConsumePolicy
}
const JOB_STATUS: Record<string, { color: string; label: string }> = {
pending: { color: 'gold', label: '待执行' },
processing: { color: 'processing', label: '执行中' },
succeeded: { color: 'green', label: '成功' },
failed: { color: 'red', label: '失败' },
cancelled: { color: 'default', label: '已取消' },
}
export default function VoucherConsumePolicyPanel() {
const queryClient = useQueryClient()
const [draft, setDraft] = useState<VoucherConsumePolicy | null>(null)
const policyQuery = useQuery({
queryKey: ['voucher-consume-policy'],
queryFn: fetchVoucherConsumePolicy,
})
const jobsQuery = useQuery({
queryKey: ['voucher-consume-jobs'],
queryFn: () => fetchVoucherConsumeJobs({ page: 1, pageSize: 20 }),
refetchInterval: 10_000,
})
useEffect(() => {
const policy = policyQuery.data?.data
if (policy) {
setDraft(structuredClone(policy))
}
}, [policyQuery.data])
const saveMutation = useMutation({
mutationFn: (policy: VoucherConsumePolicy) => saveVoucherConsumePolicy(policy),
onSuccess: (response) => {
setDraft(structuredClone(response.data))
message.success('核销策略已保存')
void queryClient.invalidateQueries({ queryKey: ['voucher-consume-policy'] })
},
onError: (error) => {
message.error(error instanceof Error ? error.message : '保存核销策略失败')
},
})
const retryMutation = useMutation({
mutationFn: retryVoucherConsumeJob,
onSuccess: () => {
message.success('核销任务已重新排队')
void queryClient.invalidateQueries({ queryKey: ['voucher-consume-jobs'] })
},
onError: (error) => {
message.error(error instanceof Error ? error.message : '重试核销任务失败')
},
})
const rows = useMemo(() => buildPolicyRows(draft), [draft])
function updateChannel(
provider: VoucherConsumeProvider,
channel: VoucherConsumeChannel,
patch: Partial<VoucherChannelConsumePolicy>,
) {
setDraft((current) => {
if (!current) return current
return {
...current,
platforms: {
...current.platforms,
[provider]: {
...current.platforms[provider],
channels: {
...current.platforms[provider].channels,
[channel]: {
...current.platforms[provider].channels[channel],
...patch,
},
},
},
},
}
})
}
function updatePlatformEnabled(provider: VoucherConsumeProvider, enabled: boolean) {
setDraft((current) => {
if (!current) return current
return {
...current,
platforms: {
...current.platforms,
[provider]: {
...current.platforms[provider],
enabled,
},
},
}
})
}
const policyColumns: TableColumnsType<PolicyRow> = [
{
title: '平台',
dataIndex: 'provider',
width: 150,
render: (provider: VoucherConsumeProvider) => PROVIDER_LABEL[provider],
},
{
title: '履约渠道',
dataIndex: 'channel',
width: 140,
render: (channel: VoucherConsumeChannel) => CHANNEL_LABEL[channel],
},
{
title: '自动核销',
width: 100,
render: (_, row) => (
<Switch
size="small"
checked={row.policy.enabled}
onChange={(enabled) => updateChannel(row.provider, row.channel, { enabled })}
/>
),
},
{
title: '触发时间',
width: 220,
render: (_, row) => (
<Select
value={row.policy.mode}
options={MODE_OPTIONS[row.channel]}
disabled={!row.policy.enabled}
onChange={(mode) => updateChannel(row.provider, row.channel, { mode })}
style={{ width: '100%' }}
/>
),
},
{
title: '延迟',
width: 130,
render: (_, row) => (
<InputNumber
min={0}
max={3600}
precision={0}
value={row.policy.delaySeconds}
disabled={!row.policy.enabled}
onChange={(value) =>
updateChannel(row.provider, row.channel, {
delaySeconds: Math.max(0, Number(value || 0)),
})
}
addonAfter="秒"
style={{ width: '100%' }}
/>
),
},
]
const jobColumns: TableColumnsType<VoucherConsumeJob> = [
{ title: '任务', dataIndex: 'id', width: 80 },
{
title: '平台',
dataIndex: 'provider',
width: 140,
render: (provider: VoucherConsumeProvider) => PROVIDER_LABEL[provider],
},
{
title: '渠道',
dataIndex: 'channel',
width: 110,
render: (channel: VoucherConsumeChannel) => CHANNEL_LABEL[channel],
},
{
title: '订单号',
dataIndex: 'platform_order_id',
width: 170,
render: (value: string) => value || '-',
},
{
title: '计划时间',
dataIndex: 'due_at',
width: 170,
render: (value: string) => formatDateTime(value),
},
{
title: '状态',
dataIndex: 'status',
width: 100,
render: (status: string) => {
const current = JOB_STATUS[status] || { color: 'default', label: status }
return <Tag color={current.color}>{current.label}</Tag>
},
},
{
title: '尝试',
width: 80,
render: (_, row) => `${row.attempt_count}/${row.max_attempts}`,
},
{
title: '错误',
dataIndex: 'last_error',
render: (value: string) =>
value ? (
<Tooltip title={value}>
<Typography.Text ellipsis style={{ maxWidth: 260 }}>
{value}
</Typography.Text>
</Tooltip>
) : (
'-'
),
},
{
title: '',
width: 80,
render: (_, row) =>
row.status === 'failed' || row.status === 'cancelled' ? (
<Button
size="small"
onClick={() => retryMutation.mutate(row.id)}
loading={retryMutation.isPending}
>
重试
</Button>
) : null,
},
]
return (
<Space direction="vertical" size={16} className="full-width">
<Space size={20} wrap>
<Space size={8}>
<Typography.Text strong>总开关</Typography.Text>
<Switch
checked={draft?.enabled !== false}
onChange={(enabled) =>
setDraft((current) => (current ? { ...current, enabled } : current))
}
/>
</Space>
{(['kuaishou_industry', 'douyin_mashida'] as const).map((provider) => (
<Space key={provider} size={8}>
<Typography.Text>{PROVIDER_LABEL[provider]}</Typography.Text>
<Switch
checked={draft?.platforms[provider].enabled !== false}
disabled={draft?.enabled === false}
onChange={(enabled) => updatePlatformEnabled(provider, enabled)}
/>
</Space>
))}
<Button
type="primary"
icon={<SaveOutlined />}
disabled={!draft}
loading={saveMutation.isPending}
onClick={() => draft && saveMutation.mutate(draft)}
>
保存
</Button>
</Space>
<PercentTable
rowKey={(row) => row.key}
size="small"
columns={policyColumns}
dataSource={rows}
pagination={false}
loading={policyQuery.isLoading}
/>
<Space className="full-width" style={{ justifyContent: 'space-between' }}>
<Typography.Title level={5} style={{ margin: 0 }}>
最近核销任务
</Typography.Title>
<Button
icon={<ReloadOutlined />}
onClick={() => void queryClient.invalidateQueries({ queryKey: ['voucher-consume-jobs'] })}
>
刷新
</Button>
</Space>
<PercentTable
rowKey="id"
size="small"
columns={jobColumns}
dataSource={jobsQuery.data?.data.items || []}
loading={jobsQuery.isLoading}
pagination={false}
scroll={{ x: 1100 }}
/>
</Space>
)
}
function buildPolicyRows(policy: VoucherConsumePolicy | null): PolicyRow[] {
if (!policy) return []
return (Object.keys(policy.platforms) as VoucherConsumeProvider[]).flatMap((provider) =>
(Object.keys(policy.platforms[provider].channels) as VoucherConsumeChannel[]).map(
(channel) => ({
key: `${provider}:${channel}`,
provider,
channel,
policy: policy.platforms[provider].channels[channel],
}),
),
)
}
@@ -71,9 +71,11 @@ import {
fetchAdminWorkerProductNameSuffix,
fetchAdminWorkerUsers,
fetchAdminWorkOrders,
executeAdminCustomerRefund,
markAdminWorkOrderProblem,
markAdminWorkOrderShareProblem,
pinAdminWorkOrder,
previewAdminCustomerRefund,
publishAdminWorkOrder,
reduceAdminWorkOrderShareQuantity,
reopenAdminCancelledWorkOrder,
@@ -86,6 +88,7 @@ import {
updateAdminWorkOrderNote,
updateAdminWorkOrderSharing,
} from '@/services/admin'
import type { CustomerRefundPreview } from '@/services/admin/worker-platform'
import {
checkWorkOrderConsignmentMatches,
fulfillWorkOrderWithConsignment,
@@ -205,6 +208,11 @@ type CancelSharingPartFormValues = {
reason?: string
}
type CustomerRefundFormValues = {
reason: string
note?: string
}
/** 工单 `material.consignment`(寄售履约信息);没有寄售履约信息时返回 null。 */
function getConsignmentFulfillment(row: WorkOrder): ConsignmentFulfillmentInfo | null {
const consignment = asRecord((row.material as Record<string, unknown> | undefined)?.consignment)
@@ -306,6 +314,9 @@ export default function WorkOrdersPanel() {
const canCancelOrder = sessionPermissions
? sessionPermissions.includes('worker_order.cancel')
: hasAdminPermission('worker_order.cancel')
const canCustomerRefund = sessionPermissions
? sessionPermissions.includes('worker_order.customer_refund')
: hasAdminPermission('worker_order.customer_refund')
const canCancelShare = sessionPermissions
? sessionPermissions.includes('worker_order.cancel_share')
: hasAdminPermission('worker_order.cancel_share')
@@ -381,6 +392,12 @@ export default function WorkOrdersPanel() {
const [noteOrder, setNoteOrder] = useState<WorkOrder | null>(null)
const [deductOrder, setDeductOrder] = useState<WorkOrder | null>(null)
const [cancelOrder, setCancelOrder] = useState<WorkOrder | null>(null)
const [customerRefundOrder, setCustomerRefundOrder] = useState<WorkOrder | null>(null)
const [customerRefundPreview, setCustomerRefundPreview] = useState<CustomerRefundPreview | null>(
null,
)
const [customerRefundLoading, setCustomerRefundLoading] = useState(false)
const [customerRefundSubmitting, setCustomerRefundSubmitting] = useState(false)
const [problemForm] = Form.useForm()
const [resolutionForm] = Form.useForm()
const [materialForm] = Form.useForm<MaterialFormValues>()
@@ -395,6 +412,7 @@ export default function WorkOrdersPanel() {
const [cancelSharingForm] = Form.useForm<CancelSharingFormValues>()
const [cancelSharingPartForm] = Form.useForm<CancelSharingPartFormValues>()
const [deductForm] = Form.useForm<{ amount?: number; note?: string }>()
const [customerRefundForm] = Form.useForm<CustomerRefundFormValues>()
const [editForm] = Form.useForm<{
productName?: string
platformOrderId?: string
@@ -695,6 +713,46 @@ export default function WorkOrdersPanel() {
cancelForm.setFieldsValue({ action: 'return_to_hall', reason: '' })
}
async function openCustomerRefundModal(row: WorkOrder) {
setCustomerRefundOrder(row)
setCustomerRefundPreview(null)
customerRefundForm.setFieldsValue({ reason: '客户退款', note: '' })
setCustomerRefundLoading(true)
try {
const response = await previewAdminCustomerRefund(row.workOrderId)
setCustomerRefundPreview(response.data)
} catch (error) {
setCustomerRefundOrder(null)
message.error(error instanceof Error ? error.message : '客户退款预检失败')
} finally {
setCustomerRefundLoading(false)
}
}
async function submitCustomerRefund(values: CustomerRefundFormValues) {
if (!customerRefundOrder || !customerRefundPreview?.canExecute) return
setCustomerRefundSubmitting(true)
try {
const response = await executeAdminCustomerRefund(customerRefundOrder.workOrderId, values)
message.success(
response.data.idempotent
? '该客户退款已处理,无需重复操作'
: `客户退款已完成,退款 ${formatMoney(customerRefundPreview.remainingFen)}`,
)
setCustomerRefundOrder(null)
setCustomerRefundPreview(null)
customerRefundForm.resetFields()
await refreshAll()
void queryClient.invalidateQueries({ queryKey: ['admin-redeem-certificates'] })
void queryClient.invalidateQueries({ queryKey: ['admin-kuaishou-industry-vouchers'] })
void queryClient.invalidateQueries({ queryKey: ['fulfillment-pending'] })
} catch (error) {
message.error(error instanceof Error ? error.message : '客户退款失败')
} finally {
setCustomerRefundSubmitting(false)
}
}
function applyMaterialPaste(text: string) {
if (!materialOrder) return
const recognized = parseWorkerMaterialText(text)
@@ -729,9 +787,11 @@ export default function WorkOrdersPanel() {
workerId: assignWorkerId,
}),
(response) =>
response.data.voucherConsume.voucherCount > 0
? '电子凭证已自动核销,订单已指派给打手'
: '已指派打手',
!response.data.voucherConsume.ok
? '订单已指派,但自动核销未安排成功'
: response.data.voucherConsume.queuedCount > 0
? '订单已指派,自动核销任务已排队'
: '已指派打手',
)
if (!succeeded) return
setAssignOrder(null)
@@ -1020,10 +1080,10 @@ export default function WorkOrdersPanel() {
() => publishAdminWorkOrder(row.workOrderId),
(response) =>
!response.data.voucherConsume.ok
? '订单已发布,但电子凭证核销未完成'
? '订单已发布,但自动核销未安排成功'
: response.data.hallVisible
? response.data.voucherConsume.voucherCount > 0
? '订单已发布,电子凭证已顺带核销'
? response.data.voucherConsume.queuedCount > 0
? '订单已发布,自动核销任务已排队'
: '订单已展示在大厅'
: '订单已进入大厅等待队列',
)
@@ -2001,6 +2061,27 @@ export default function WorkOrdersPanel() {
内部库存匹配
</Button>
) : null}
{canCustomerRefund &&
[
'pending_material',
'unassigned',
'open',
'in_progress',
'pending_acceptance',
'problem',
].includes(String(row.rawStatus || row.status || '')) ? (
<Button
danger
icon={<RollbackOutlined />}
loading={
customerRefundLoading && customerRefundOrder?.workOrderId === row.workOrderId
}
onClick={() => void openCustomerRefundModal(row)}
title="同意平台用户退款,并关闭工单、资料、领取链接和待核销任务"
>
客户退款
</Button>
) : null}
{row.capabilities?.canCancel && (canReturnToHall || canCancelOrder) ? (
<Button danger icon={<UndoOutlined />} onClick={() => openCancelModal(row)}>
撤单
@@ -3125,6 +3206,80 @@ export default function WorkOrdersPanel() {
</Form>
</Modal>
<Modal
title={`客户退款 · ${getDisplayOrderNo(customerRefundOrder)}`}
open={Boolean(customerRefundOrder)}
onCancel={() => {
setCustomerRefundOrder(null)
setCustomerRefundPreview(null)
customerRefundForm.resetFields()
}}
onOk={() => customerRefundForm.submit()}
okText="同意退款并关闭订单"
okButtonProps={{
danger: true,
disabled: customerRefundLoading || !customerRefundPreview?.canExecute,
}}
confirmLoading={customerRefundSubmitting}
destroyOnHidden
width={620}
>
{customerRefundLoading ? (
<Alert type="info" showIcon message="正在查询平台用户售后单..." />
) : customerRefundPreview ? (
<Space direction="vertical" size={14} style={{ width: '100%' }}>
<Alert
type="warning"
showIcon
message="该操作会同意平台用户退款,并关闭订单下全部工单、资料提交、领取链接和待核销任务。"
description="订单、退款、成本与资金流水会保留用于审计;存在已验收或已结算内容时系统会拒绝执行。"
/>
<Descriptions bordered size="small" column={1}>
<Descriptions.Item label="平台">
{customerRefundPreview.platform} / {customerRefundPreview.provider}
</Descriptions.Item>
<Descriptions.Item label="平台订单号">
{customerRefundPreview.platformOrderId}
</Descriptions.Item>
<Descriptions.Item label="平台售后单号">
{customerRefundPreview.externalAfterSaleId}
</Descriptions.Item>
<Descriptions.Item label="退款金额">
{formatMoney(customerRefundPreview.remainingFen)}
</Descriptions.Item>
<Descriptions.Item label="关闭范围">
{customerRefundPreview.workOrderCount} 个工单 / {customerRefundPreview.itemCount}{' '}
个订单项
</Descriptions.Item>
</Descriptions>
{customerRefundPreview.notes.length > 0 ? (
<Alert
type={customerRefundPreview.canExecute ? 'warning' : 'error'}
showIcon
message={customerRefundPreview.canExecute ? '处理提示' : '预检未通过'}
description={customerRefundPreview.notes.join(';')}
/>
) : null}
<Form
form={customerRefundForm}
layout="vertical"
onFinish={(values) => void submitCustomerRefund(values)}
>
<Form.Item
label="退款原因"
name="reason"
rules={[{ required: true, message: '请填写退款原因' }]}
>
<Input maxLength={200} />
</Form.Item>
<Form.Item label="处理备注" name="note">
<Input.TextArea rows={3} maxLength={500} showCount />
</Form.Item>
</Form>
</Space>
) : null}
</Modal>
<Modal
title={`撤单处理 · ${getDisplayOrderNo(cancelOrder)}`}
open={Boolean(cancelOrder)}
@@ -3347,7 +3502,7 @@ export default function WorkOrdersPanel() {
>
<Space direction="vertical" size={12} className="full-width">
<Typography.Paragraph type="secondary">
指派后订单直接进入该打手的「我的订单」,不再出现在抢单大厅;有关联电子凭证时会先自动核销,再按订单规则冻结打手押金。核销后取消指派不会恢复电子凭证。
指派后订单直接进入该打手的「我的订单」,不再出现在抢单大厅;有关联电子凭证时会按核销策略安排延迟核销,并按订单规则冻结打手押金。
</Typography.Paragraph>
<Select
style={{ width: '100%' }}