fix(fulfillment): 使用真实订单号并支持协作单跳转
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
"""把已同步协作单的临时 PF 单号回填为真实平台订单号。
|
||||
|
||||
只回填平台订单号非空、长度符合列限制、且不会与现有协作单或其它履约任务
|
||||
撞号的记录。存在冲突的数据保持原样,后续手动同步会明确报冲突。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261118_0095"
|
||||
down_revision: str | None = "20261118_0094"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.get_bind().execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE douyu_external_orders AS orders
|
||||
JOIN platform_fulfillment_tasks AS tasks
|
||||
ON tasks.id = orders.source_task_id
|
||||
JOIN (
|
||||
SELECT TRIM(platform_order_id) AS order_no
|
||||
FROM platform_fulfillment_tasks
|
||||
WHERE LENGTH(TRIM(platform_order_id)) BETWEEN 1 AND 64
|
||||
GROUP BY TRIM(platform_order_id)
|
||||
HAVING COUNT(*) = 1
|
||||
) AS unique_source
|
||||
ON unique_source.order_no = TRIM(tasks.platform_order_id)
|
||||
LEFT JOIN douyu_external_orders AS conflict
|
||||
ON conflict.order_no = TRIM(tasks.platform_order_id)
|
||||
AND conflict.id <> orders.id
|
||||
SET orders.order_no = TRIM(tasks.platform_order_id),
|
||||
orders.source_platform_order_id = TRIM(tasks.platform_order_id),
|
||||
orders.updated_at = UTC_TIMESTAMP()
|
||||
WHERE orders.source_type = 'platform_fulfillment'
|
||||
AND orders.order_no <> TRIM(tasks.platform_order_id)
|
||||
AND conflict.id IS NULL
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# 临时 PF 单号没有保留,无法可靠恢复;业务上真实订单号才是正确来源。
|
||||
pass
|
||||
@@ -714,6 +714,19 @@ def _platform_fulfillment_gift(
|
||||
return name, commodity_id, required_points
|
||||
|
||||
|
||||
def _platform_fulfillment_order_no(task: PlatformFulfillmentTask) -> str:
|
||||
"""外部协作单直接使用 order_site 的真实平台订单号。"""
|
||||
order_no = _text(task.platform_order_id)
|
||||
if not order_no:
|
||||
raise CollabError("履约任务缺少平台订单号", code="platform_order_no_required")
|
||||
if len(order_no) > 64:
|
||||
raise CollabError(
|
||||
"平台订单号超过协作单号长度限制",
|
||||
code="platform_order_no_too_long",
|
||||
)
|
||||
return order_no
|
||||
|
||||
|
||||
def _apply_platform_fulfillment_binding(
|
||||
db: Session,
|
||||
order: DouyuExternalOrder,
|
||||
@@ -785,7 +798,28 @@ def sync_platform_fulfillment_order(
|
||||
.filter(DouyuExternalOrder.source_task_id == task.id)
|
||||
.first()
|
||||
)
|
||||
order_no = _platform_fulfillment_order_no(task)
|
||||
created = order is None
|
||||
order_by_no = (
|
||||
db.query(DouyuExternalOrder)
|
||||
.filter(DouyuExternalOrder.order_no == order_no)
|
||||
.first()
|
||||
)
|
||||
if order is not None and order_by_no is not None and order_by_no.id != order.id:
|
||||
raise CollabError(
|
||||
f"平台订单号 {order_no} 已关联其他履约任务",
|
||||
code="order_no_conflict",
|
||||
)
|
||||
if order is None and order_by_no is not None:
|
||||
if order_by_no.source_task_id not in (None, task.id):
|
||||
raise CollabError(
|
||||
f"平台订单号 {order_no} 已关联其他履约任务",
|
||||
code="order_no_conflict",
|
||||
)
|
||||
# 手工先建过同一真实订单号时,直接接管为来源单,保留人工字段。
|
||||
order = order_by_no
|
||||
created = False
|
||||
|
||||
now = _now()
|
||||
account = (
|
||||
db.query(Account).filter(Account.id == task.account_id).first()
|
||||
@@ -795,17 +829,6 @@ def sync_platform_fulfillment_order(
|
||||
gift_name, commodity_id, required_points = _platform_fulfillment_gift(db, task)
|
||||
|
||||
if order is None:
|
||||
order_no = f"PF{task.id}"
|
||||
occupied = (
|
||||
db.query(DouyuExternalOrder)
|
||||
.filter(DouyuExternalOrder.order_no == order_no)
|
||||
.first()
|
||||
)
|
||||
if occupied is not None:
|
||||
raise CollabError(
|
||||
f"协作单号 {order_no} 已被其他订单占用",
|
||||
code="order_no_conflict",
|
||||
)
|
||||
order = DouyuExternalOrder(
|
||||
order_no=order_no,
|
||||
source_type=SOURCE_TYPE_PLATFORM_FULFILLMENT,
|
||||
@@ -819,6 +842,7 @@ def sync_platform_fulfillment_order(
|
||||
)
|
||||
db.add(order)
|
||||
|
||||
order.order_no = order_no
|
||||
order.source_type = SOURCE_TYPE_PLATFORM_FULFILLMENT
|
||||
order.source_task_id = int(task.id)
|
||||
order.source_order_id = _text(task.source_order_id, max_length=64)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import {
|
||||
Alert,
|
||||
App,
|
||||
@@ -198,6 +198,7 @@ const EMPTY_FORM: OrderFormState = {
|
||||
|
||||
export default function DouyuCollabPage() {
|
||||
const navigate = useNavigate();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const { modal } = App.useApp();
|
||||
const { can, user } = usePermissions();
|
||||
const canView = can('douyu:collab:view');
|
||||
@@ -255,6 +256,8 @@ export default function DouyuCollabPage() {
|
||||
const [detailMetrics, setDetailMetrics] = useState<DouyuCollabMetric[]>([]);
|
||||
const [detailTimeline, setDetailTimeline] = useState<DouyuCollabTimeline[]>([]);
|
||||
const [detailLoading, setDetailLoading] = useState(false);
|
||||
const handledQueryOrderIdRef = useRef(0);
|
||||
const queryOrderId = Number(searchParams.get('orderId') || 0);
|
||||
|
||||
const [statusTarget, setStatusTarget] = useState<DouyuCollabOrder | null>(null);
|
||||
const [batchStatusOpen, setBatchStatusOpen] = useState(false);
|
||||
@@ -720,15 +723,20 @@ export default function DouyuCollabPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const openDetail = async (order: DouyuCollabOrder) => {
|
||||
setDetail(order);
|
||||
const openDetail = useCallback(async (target: DouyuCollabOrder | number) => {
|
||||
const orderId = typeof target === 'number' ? target : target.id;
|
||||
if (typeof target === 'number') {
|
||||
setDetail(null);
|
||||
} else {
|
||||
setDetail(target);
|
||||
}
|
||||
setDetailOpen(true);
|
||||
setDetailLoading(true);
|
||||
try {
|
||||
const [metrics, timeline, latest] = await Promise.all([
|
||||
douyuCollabApi.metrics(order.id),
|
||||
douyuCollabApi.timeline(order.id),
|
||||
douyuCollabApi.getOrder(order.id),
|
||||
douyuCollabApi.metrics(orderId),
|
||||
douyuCollabApi.timeline(orderId),
|
||||
douyuCollabApi.getOrder(orderId),
|
||||
]);
|
||||
setDetailMetrics(metrics);
|
||||
setDetailTimeline(timeline);
|
||||
@@ -738,7 +746,24 @@ export default function DouyuCollabPage() {
|
||||
} finally {
|
||||
setDetailLoading(false);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!canView || !Number.isInteger(queryOrderId) || queryOrderId <= 0) return;
|
||||
if (handledQueryOrderIdRef.current === queryOrderId) return;
|
||||
handledQueryOrderIdRef.current = queryOrderId;
|
||||
void openDetail(queryOrderId);
|
||||
}, [canView, openDetail, queryOrderId]);
|
||||
|
||||
const closeDetail = useCallback(() => {
|
||||
setDetailOpen(false);
|
||||
if (searchParams.has('orderId')) {
|
||||
const next = new URLSearchParams(searchParams);
|
||||
next.delete('orderId');
|
||||
setSearchParams(next, { replace: true });
|
||||
}
|
||||
handledQueryOrderIdRef.current = 0;
|
||||
}, [searchParams, setSearchParams]);
|
||||
|
||||
const openStatus = (order: DouyuCollabOrder) => {
|
||||
setStatusTarget(order);
|
||||
@@ -2186,7 +2211,7 @@ export default function DouyuCollabPage() {
|
||||
<Drawer
|
||||
title={detail ? `协作单 ${detail.order_no}` : '协作单详情'}
|
||||
open={detailOpen}
|
||||
onClose={() => setDetailOpen(false)}
|
||||
onClose={closeDetail}
|
||||
width={760}
|
||||
extra={
|
||||
detail && canEdit ? (
|
||||
@@ -2323,6 +2348,8 @@ export default function DouyuCollabPage() {
|
||||
/>
|
||||
</div>
|
||||
</Space>
|
||||
) : detailLoading ? (
|
||||
<Text type="secondary">加载中…</Text>
|
||||
) : null}
|
||||
</Drawer>
|
||||
</Space>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import dayjs from 'dayjs';
|
||||
import type { Dayjs } from 'dayjs';
|
||||
import { Alert, Button, Card, DatePicker, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Segmented, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd';
|
||||
@@ -260,6 +261,7 @@ function canResetBinding(task: PlatformFulfillmentTask) {
|
||||
|
||||
export default function PlatformFulfillmentPage() {
|
||||
const user = getUser();
|
||||
const navigate = useNavigate();
|
||||
const { can } = usePermissions(user);
|
||||
const [status, setStatus] = useState('');
|
||||
const [keyword, setKeyword] = useState('');
|
||||
@@ -270,6 +272,7 @@ export default function PlatformFulfillmentPage() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [syncing, setSyncing] = useState(false);
|
||||
const [collabSyncing, setCollabSyncing] = useState(false);
|
||||
const [rowCollabSyncingId, setRowCollabSyncingId] = useState<number | null>(null);
|
||||
const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
|
||||
const [selectedId, setSelectedId] = useState<number | null>(null);
|
||||
const [detail, setDetail] = useState<PlatformFulfillmentDetail | null>(null);
|
||||
@@ -398,16 +401,19 @@ export default function PlatformFulfillmentPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const syncCollab = async () => {
|
||||
const taskIds = selectedRowKeys.map(Number).filter((value) => Number.isInteger(value));
|
||||
if (taskIds.length === 0) {
|
||||
message.warning('请先勾选要同步的履约任务');
|
||||
return;
|
||||
const performCollabSync = async (taskIds: number[], rowTaskId?: number) => {
|
||||
if (rowTaskId) {
|
||||
setRowCollabSyncingId(rowTaskId);
|
||||
} else {
|
||||
setCollabSyncing(true);
|
||||
}
|
||||
setCollabSyncing(true);
|
||||
try {
|
||||
const result = await platformFulfillmentApi.syncCollab(taskIds);
|
||||
const summary = `外部协作同步完成:新增 ${result.created},更新 ${result.updated}`;
|
||||
const syncedOrderNo =
|
||||
result.items.find((item) => item.action === 'created' || item.action === 'updated')?.orderNo || '';
|
||||
const summary = `外部协作同步完成:新增 ${result.created},更新 ${result.updated}${
|
||||
taskIds.length === 1 && syncedOrderNo ? `,订单 ${syncedOrderNo}` : ''
|
||||
}`;
|
||||
if (result.failed || result.skipped) {
|
||||
message.warning(`${summary},跳过 ${result.skipped},失败 ${result.failed}`);
|
||||
const problems = result.items.filter(
|
||||
@@ -432,16 +438,29 @@ export default function PlatformFulfillmentPage() {
|
||||
} else {
|
||||
message.success(summary);
|
||||
}
|
||||
setSelectedRowKeys([]);
|
||||
if (!rowTaskId) setSelectedRowKeys([]);
|
||||
await loadTasks();
|
||||
if (selectedId) await loadDetail(selectedId, true);
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setCollabSyncing(false);
|
||||
if (rowTaskId) {
|
||||
setRowCollabSyncingId(null);
|
||||
} else {
|
||||
setCollabSyncing(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const syncCollab = async () => {
|
||||
const taskIds = selectedRowKeys.map(Number).filter((value) => Number.isInteger(value));
|
||||
if (taskIds.length === 0) {
|
||||
message.warning('请先勾选要同步的履约任务');
|
||||
return;
|
||||
}
|
||||
await performCollabSync(taskIds);
|
||||
};
|
||||
|
||||
const runTaskAction = async (action: () => Promise<PlatformFulfillmentDetail>) => {
|
||||
try {
|
||||
const result = await action();
|
||||
@@ -740,7 +759,21 @@ export default function PlatformFulfillmentPage() {
|
||||
<Tag color={task.collabOrder.status === 'done' ? 'success' : 'blue'}>
|
||||
{collabStatusLabel(task.collabOrder.status)}
|
||||
</Tag>
|
||||
<Text copyable={{ text: task.collabOrder.orderNo }}>{task.collabOrder.orderNo}</Text>
|
||||
<Space size={2}>
|
||||
{can('douyu:collab:view') ? (
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
style={{ height: 'auto', padding: 0 }}
|
||||
onClick={() => navigate(`/douyu/collab?orderId=${task.collabOrder?.id}`)}
|
||||
>
|
||||
{task.collabOrder.orderNo}
|
||||
</Button>
|
||||
) : (
|
||||
<Text>{task.collabOrder.orderNo}</Text>
|
||||
)}
|
||||
<Text copyable={{ text: task.collabOrder.orderNo }} />
|
||||
</Space>
|
||||
</Space>
|
||||
) : (
|
||||
<Text type="secondary">未同步</Text>
|
||||
@@ -761,6 +794,20 @@ export default function PlatformFulfillmentPage() {
|
||||
<Button size="small" onClick={() => setSelectedId(task.id)}>
|
||||
详情
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
type={task.collabOrder ? 'default' : 'primary'}
|
||||
icon={<LinkOutlined />}
|
||||
loading={rowCollabSyncingId === task.id}
|
||||
disabled={
|
||||
!can('platform_fulfillment:use') ||
|
||||
collabSyncing ||
|
||||
(rowCollabSyncingId !== null && rowCollabSyncingId !== task.id)
|
||||
}
|
||||
onClick={() => void performCollabSync([task.id], task.id)}
|
||||
>
|
||||
同步外部单协作
|
||||
</Button>
|
||||
{task.executionStatus === 'pending_mapping' ? (
|
||||
<Button size="small" type="primary" icon={<LinkOutlined />} disabled={!can('platform_fulfillment:admin')} onClick={() => void openMapping(task)}>
|
||||
配置映射
|
||||
@@ -771,11 +818,6 @@ export default function PlatformFulfillmentPage() {
|
||||
人工重试选号
|
||||
</Button>
|
||||
) : null}
|
||||
{task.executionStatus === 'allocated' ? (
|
||||
<Button size="small" type="primary" icon={<QrcodeOutlined />} onClick={() => void runTaskAction(() => platformFulfillmentApi.startBinding(task.id))}>
|
||||
生成二维码
|
||||
</Button>
|
||||
) : null}
|
||||
{['waiting_bind', 'binding_confirming'].includes(task.executionStatus) ? (
|
||||
<Button size="small" icon={<ReloadOutlined />} onClick={() => void runTaskAction(() => platformFulfillmentApi.refreshBinding(task.id))}>
|
||||
刷新绑定
|
||||
@@ -858,7 +900,11 @@ export default function PlatformFulfillmentPage() {
|
||||
<Button
|
||||
icon={<LinkOutlined />}
|
||||
loading={collabSyncing}
|
||||
disabled={!can('platform_fulfillment:use') || selectedRowKeys.length === 0}
|
||||
disabled={
|
||||
!can('platform_fulfillment:use') ||
|
||||
selectedRowKeys.length === 0 ||
|
||||
rowCollabSyncingId !== null
|
||||
}
|
||||
onClick={() => void syncCollab()}
|
||||
>
|
||||
同步外部单协作{selectedRowKeys.length > 0 ? `(${selectedRowKeys.length})` : ''}
|
||||
|
||||
Reference in New Issue
Block a user