diff --git a/tests/test_weibo_collab.py b/tests/test_weibo_collab.py index 4eaa77c..b5bd6cf 100644 --- a/tests/test_weibo_collab.py +++ b/tests/test_weibo_collab.py @@ -2,8 +2,10 @@ from __future__ import annotations +import json from datetime import UTC, datetime +import pytest from sqlalchemy.orm import Session from core.weibo import WeiboAuthError @@ -15,7 +17,11 @@ from web.backend.models import ( WeiboRechargeRecord, ) from web.backend.routers import weibo_collab as weibo_collab_router -from web.backend.schemas import WeiboCollabCkExportOut +from web.backend.schemas import ( + WeiboCollabCkExportOut, + WeiboCollabStatusBatchRequest, + WeiboCollabStatusRequest, +) from web.backend.services import weibo_collab_service as collab from web.backend.services import weibo_service @@ -42,14 +48,179 @@ def make_account(db: Session, uid: str = "4014000001") -> WeiboAccount: return account -def make_user(db: Session) -> User: - user = User(username="weibo-collab", password_hash="hash", role="super_admin") +def make_user( + db: Session, + username: str = "weibo-collab", + role: str = "super_admin", +) -> User: + user = User(username=username, password_hash="hash", role=role) db.add(user) db.commit() db.refresh(user) return user +def test_super_admin_can_force_restore_void_order(db): + user = make_user(db) + account = make_account(db) + order = collab.create_order( + db, + user, + order_no="WB-FORCE-001", + account_id=account.id, + goods_name="商品A", + required_weidou=100, + require_verified=False, + ) + order.scripted_at = datetime.now(UTC) + order.done_at = datetime.now(UTC) + db.commit() + collab.set_status(db, user, order, collab.STATUS_VOID, reason="误作废") + + result = collab.set_status( + db, + user, + order, + collab.STATUS_INCOMPLETE, + reason="复核后恢复流程", + force=True, + ) + + db.refresh(order) + assert result == {"from": collab.STATUS_VOID, "to": collab.STATUS_INCOMPLETE} + assert order.status == collab.STATUS_INCOMPLETE + assert order.void_reason == "" + assert order.scripted_at is None + assert order.done_at is None + + audit = ( + db.query(AuditLog) + .filter(AuditLog.action == "weibo:collab:status") + .order_by(AuditLog.id.desc()) + .first() + ) + assert audit is not None + detail = json.loads(audit.detail) + assert detail["force"] is True + assert detail["reason"] == "复核后恢复流程" + assert detail["previous_void_reason"] == "误作废" + + +def test_force_restore_void_requires_super_admin_and_reason(db): + admin = make_user(db, username="wb-force-admin", role="super_admin") + operator = make_user(db, username="wb-force-operator", role="operation") + account = make_account(db) + order = collab.create_order( + db, + admin, + order_no="WB-FORCE-002", + account_id=account.id, + goods_name="商品A", + required_weidou=100, + require_verified=False, + ) + collab.set_status(db, admin, order, collab.STATUS_VOID, reason="客户退款") + + with pytest.raises(collab.CollabError) as exc_info: + collab.set_status( + db, + operator, + order, + collab.STATUS_TO_RECHARGE, + reason="尝试恢复", + force=True, + ) + assert exc_info.value.status_code == 403 + assert exc_info.value.code == "force_admin_required" + + with pytest.raises(collab.CollabError) as exc_info: + collab.set_status( + db, + admin, + order, + collab.STATUS_TO_RECHARGE, + force=True, + ) + assert exc_info.value.code == "force_reason_required" + + with pytest.raises(collab.CollabError) as exc_info: + collab.set_status( + db, + admin, + order, + collab.STATUS_FAILED, + reason="不允许恢复到旁路状态", + force=True, + ) + assert exc_info.value.code == "force_target_invalid" + db.refresh(order) + assert order.status == collab.STATUS_VOID + + +def test_batch_status_router_passes_force_restore(db): + user = make_user(db, username="wb-batch-force-admin") + account = make_account(db) + order = collab.create_order( + db, + user, + order_no="WB-FORCE-BATCH-001", + shop="店铺A", + account_id=account.id, + goods_name="商品A", + required_weidou=100, + require_verified=False, + ) + collab.set_status(db, user, order, collab.STATUS_VOID, reason="误操作") + + result = weibo_collab_router.set_external_orders_status_batch( + WeiboCollabStatusBatchRequest( + ids=[order.id], + status=collab.STATUS_TO_RECHARGE, + reason="批量复核恢复", + force=True, + ), + db=db, + current=user, + ) + + db.refresh(order) + assert result["updated"] == 1 + assert order.status == collab.STATUS_TO_RECHARGE + assert order.void_reason == "" + + +def test_single_status_router_passes_force_restore(db): + user = make_user(db, username="wb-single-force-admin") + account = make_account(db) + order = collab.create_order( + db, + user, + order_no="WB-FORCE-SINGLE-001", + account_id=account.id, + goods_name="商品A", + required_weidou=100, + require_verified=False, + ) + collab.set_status(db, user, order, collab.STATUS_VOID, reason="误操作") + + result = weibo_collab_router.set_external_order_status( + order.id, + WeiboCollabStatusRequest( + status=collab.STATUS_INCOMPLETE, + reason="复核后恢复", + force=True, + expected_version=order.version, + ), + db=db, + current=user, + ) + + db.refresh(order) + assert result["status"] == collab.STATUS_INCOMPLETE + assert order.status == collab.STATUS_INCOMPLETE + assert order.void_reason == "" + + def test_create_orders_groups_and_balance_check(monkeypatch, db): user = make_user(db) account = make_account(db) diff --git a/web/backend/routers/weibo_collab.py b/web/backend/routers/weibo_collab.py index 9952606..1cfe681 100644 --- a/web/backend/routers/weibo_collab.py +++ b/web/backend/routers/weibo_collab.py @@ -498,6 +498,7 @@ def set_external_orders_status_batch( req.status, reason=req.reason, rollback=req.rollback, + force=req.force, ) except collab.CollabError as exc: raise _http_error(exc) from exc @@ -627,6 +628,7 @@ def set_external_order_status( req.status, reason=req.reason, rollback=req.rollback, + force=req.force, ) except collab.CollabError as exc: raise _http_error(exc) from exc diff --git a/web/backend/schemas.py b/web/backend/schemas.py index d2dd356..4ea52b3 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -869,6 +869,8 @@ class WeiboCollabStatusRequest(BaseModel): status: str = Field(..., min_length=1, max_length=20) reason: str = Field("", max_length=256) rollback: bool = False + # 仅超级管理员可用:从「已作废」强制恢复,必须同时填写 reason。 + force: bool = False expected_version: int | None = None @@ -877,6 +879,8 @@ class WeiboCollabStatusBatchRequest(BaseModel): status: str = Field(..., min_length=1, max_length=20) reason: str = Field("", max_length=256) rollback: bool = False + # 仅超级管理员可用;混合批次里只对 void 行生效,必须同时填写 reason。 + force: bool = False class WeiboCollabCkExportRequest(BaseModel): diff --git a/web/backend/services/weibo_collab_service.py b/web/backend/services/weibo_collab_service.py index d33a5bd..cc4d90e 100644 --- a/web/backend/services/weibo_collab_service.py +++ b/web/backend/services/weibo_collab_service.py @@ -679,6 +679,7 @@ def set_status( *, reason: str = "", rollback: bool = False, + force: bool = False, allow_check: bool = False, commit: bool = True, ) -> dict[str, Any]: @@ -693,8 +694,31 @@ def set_status( old = order.status if old == target: return {"from": old, "to": target} + force_applied = False + force_reason = "" + previous_void_reason = "" if old == STATUS_VOID: - raise CollabError("已作废订单不能直接改回流程内", code="order_void") + if not force: + raise CollabError("已作废订单不能直接改回流程内", code="order_void") + if current.role != "super_admin": + raise CollabError( + "只有超级管理员可以强制恢复已作废的订单", + status_code=403, + code="force_admin_required", + ) + if target not in STAGE_INDEX: + raise CollabError( + "已作废订单只能强制恢复到正常流程状态", + code="force_target_invalid", + ) + force_reason = _text(reason, max_length=256) + if not force_reason: + raise CollabError( + "强制恢复已作废订单必须填写原因", + code="force_reason_required", + ) + force_applied = True + previous_void_reason = order.void_reason or "" if target == STATUS_VOID: clean_reason = _text(reason, max_length=256) if not clean_reason: @@ -728,6 +752,15 @@ def set_status( code="recharge_precondition", ) now = _now() + if force_applied: + # 重新进入流程时不能沿用作废前的阶段时间和资金来源。 + order.recharged_at = None + order.funding_source = "" + order.funding_source_detail = "" + order.funding_recharge_record_id = None + order.scripted_at = None + order.exchange_started_at = None + order.done_at = None if target == STATUS_TO_RECHARGE: order.recharged_at = None order.funding_source = "" @@ -766,7 +799,14 @@ def set_status( current, order, "weibo:collab:status", - {"from": old, "to": target, "rollback": rollback, "reason": reason}, + { + "from": old, + "to": target, + "rollback": rollback, + "reason": force_reason if force_applied else reason, + "force": force_applied, + "previous_void_reason": previous_void_reason if force_applied else "", + }, ) if commit: db.commit() @@ -782,6 +822,7 @@ def set_status_batch( *, reason: str = "", rollback: bool = False, + force: bool = False, ) -> dict[str, Any]: rows = list(orders) if not rows: @@ -800,6 +841,7 @@ def set_status_batch( target, reason=reason, rollback=rollback, + force=force, allow_check=False, commit=False, ) diff --git a/web/frontend/src/api/weiboCollab.ts b/web/frontend/src/api/weiboCollab.ts index 92ff080..dd993b8 100644 --- a/web/frontend/src/api/weiboCollab.ts +++ b/web/frontend/src/api/weiboCollab.ts @@ -373,6 +373,8 @@ export const weiboCollabApi = { status: WeiboCollabStatus; reason?: string; rollback?: boolean; + /** 仅超级管理员:从「已作废」强制恢复,必须填写 reason */ + force?: boolean; expected_version?: number; }, ) => @@ -385,6 +387,8 @@ export const weiboCollabApi = { status: WeiboCollabStatus; reason?: string; rollback?: boolean; + /** 仅超级管理员:批次里的 void 行强制恢复,必须填写 reason */ + force?: boolean; }) => api.post('/weibo/external-orders/status/batch', data), verifyBatch: (ids: number[]) => api.post( diff --git a/web/frontend/src/pages/WeiboCollabPage.tsx b/web/frontend/src/pages/WeiboCollabPage.tsx index 3bafac4..50f5529 100644 --- a/web/frontend/src/pages/WeiboCollabPage.tsx +++ b/web/frontend/src/pages/WeiboCollabPage.tsx @@ -116,6 +116,10 @@ const MANUAL_STATUS_OPTIONS = STATUS_ORDER.filter( (item) => item !== 'weidou_error', ).map((value) => ({ value, label: STATUS_META[value].label })); +const FORCE_RECOVERY_OPTIONS = ( + ['incomplete', 'to_recharge', 'recharged', 'scripted', 'done'] as WeiboCollabStatus[] +).map((value) => ({ value, label: STATUS_META[value].label })); + const VERDICT_META: Record = { success: { label: '唯一命中', color: 'success' }, failed: { label: '未命中', color: 'error' }, @@ -157,6 +161,8 @@ const TIMELINE_FIELD_LABELS: Record = { records_matched: '匹配数', verdict: '兑换结论', message: '说明', + force: '强制恢复', + previous_void_reason: '原作废原因', }; function statusLabel(value: unknown): string { @@ -264,12 +270,13 @@ interface OrderFormValues { export default function WeiboCollabPage() { const { token } = theme.useToken(); - const { can } = usePermissions(); + const { can, user } = usePermissions(); const location = useLocation(); const navigate = useNavigate(); const canEdit = can('weibo:collab:edit'); const canManage = can('weibo:collab:manage'); const canExportCk = can('weibo:account:ck_export'); + const isSuperAdmin = user?.role === 'super_admin'; const [orders, setOrders] = useState([]); const [summary, setSummary] = useState(null); @@ -312,6 +319,7 @@ export default function WeiboCollabPage() { const [statusTarget, setStatusTarget] = useState('to_recharge'); const [statusReason, setStatusReason] = useState(''); const [statusRollback, setStatusRollback] = useState(false); + const [statusForce, setStatusForce] = useState(false); const [statusIds, setStatusIds] = useState([]); const [statusSaving, setStatusSaving] = useState(false); const [noteTarget, setNoteTarget] = useState(null); @@ -329,6 +337,12 @@ export default function WeiboCollabPage() { remark?: string; }>(); + const statusSelectedOrders = useMemo( + () => orders.filter((item) => statusIds.includes(item.id)), + [orders, statusIds], + ); + const statusHasVoid = statusSelectedOrders.some((item) => item.status === 'void'); + const loadBase = useCallback(async () => { try { const [summaryData, ownerRows, shopRows, goodsRows, accountData] = @@ -711,16 +725,32 @@ export default function WeiboCollabPage() { } }; - const openStatus = (ids: number[], initial?: WeiboCollabStatus) => { + const openStatus = ( + ids: number[], + initial?: WeiboCollabStatus, + force = false, + ) => { if (!ids.length) return; setStatusIds(ids); setStatusTarget(initial || 'to_recharge'); setStatusReason(''); setStatusRollback(false); + setStatusForce(Boolean(force && isSuperAdmin)); setStatusOpen(true); }; const saveStatus = async () => { + if (statusTarget === 'void' && !statusReason.trim()) { + message.warning('作废必须填写原因'); + return; + } + const forceRestore = Boolean( + isSuperAdmin && statusForce && statusHasVoid && statusTarget !== 'void', + ); + if (forceRestore && !statusReason.trim()) { + message.warning('强制恢复已作废订单必须填写原因'); + return; + } setStatusSaving(true); try { if (statusIds.length === 1) { @@ -728,7 +758,8 @@ export default function WeiboCollabPage() { await weiboCollabApi.updateStatus(statusIds[0], { status: statusTarget, reason: statusReason, - rollback: statusRollback, + rollback: forceRestore ? false : statusRollback, + force: forceRestore, expected_version: row?.version, }); } else { @@ -736,11 +767,16 @@ export default function WeiboCollabPage() { ids: statusIds, status: statusTarget, reason: statusReason, - rollback: statusRollback, + rollback: forceRestore ? false : statusRollback, + force: forceRestore, }); } setStatusOpen(false); - message.success(`已更新为「${STATUS_META[statusTarget].label}」`); + message.success( + forceRestore + ? `已强制恢复为「${STATUS_META[statusTarget].label}」` + : `已更新为「${STATUS_META[statusTarget].label}」`, + ); refreshAll(); } catch (error) { message.error(getErrorMessage(error)); @@ -1108,9 +1144,22 @@ export default function WeiboCollabPage() { > 校验 - + {row.status === 'void' ? ( + isSuperAdmin && ( + + ) + ) : ( + + )} )} {canManage && ( @@ -1670,20 +1719,59 @@ export default function WeiboCollabPage() {