feat(fulfillment): 接收并展示 order_site 客户主页截图

- 履约任务新增客户角色/平台/系统/主页截图/更新时间字段
- 迁移 0131
- order_site contractVersion=3 快照自动落客户资料
- 增加客户资料 integration 写入接口
- 工作台详情展示客户资料、平台角色比对和截图
- 补充客户资料保存/快照解析测试与对接文档
This commit is contained in:
yml
2026-11-24 21:25:14 +08:00
parent 06a226f51f
commit 6ec8248068
14 changed files with 531 additions and 2 deletions
@@ -521,6 +521,10 @@
"20261124_0130_douyu_api_max_amount.py": {
"revision": "20261124_0130",
"sha256": "fcaa64dfa069084fd6636b459b53f670376c79adf765f41646f05b6829ee9885"
},
"20261124_0131_fulfillment_customer_profile.py": {
"revision": "20261124_0131",
"sha256": "23f8780eb16a689a5f929f3f1e1865e84c0896dbde70be6bbffb0ef77d06d587"
}
}
}
@@ -0,0 +1,64 @@
"""直播账号履约保存 order_site 客户资料与主页截图。
客户领取页改为必填主页截图;order_site 通过 integration API 推送到 live-hub,
履约工作台直接展示并和绑定角色比对,不再由客服手动索要。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261124_0131"
down_revision: str | None = "20261124_0130"
branch_labels: str | None = None
depends_on: str | None = None
TABLE = "platform_fulfillment_tasks"
COLUMNS = {
"customer_role_name": sa.String(length=128),
"customer_platform": sa.String(length=16),
"customer_system": sa.String(length=16),
"customer_home_images": sa.JSON(),
"customer_profile_updated_at": sa.DateTime(),
}
def _column_exists(name: str) -> bool:
conn = op.get_bind()
count = conn.execute(
sa.text(
"SELECT COUNT(*) FROM information_schema.columns "
"WHERE table_schema = DATABASE() AND table_name = :table "
"AND column_name = :name"
),
{"table": TABLE, "name": name},
).scalar()
return bool(count)
def upgrade() -> None:
text_columns = {
"customer_role_name",
"customer_platform",
"customer_system",
}
for name, column_type in COLUMNS.items():
if _column_exists(name):
continue
op.add_column(
TABLE,
sa.Column(
name,
column_type,
nullable=name not in text_columns,
server_default="" if name in text_columns else None,
),
)
def downgrade() -> None:
for name in reversed(tuple(COLUMNS)):
if _column_exists(name):
op.drop_column(TABLE, name)
+15
View File
@@ -2467,6 +2467,21 @@ class PlatformFulfillmentTask(Base):
classification_source: Mapped[str] = mapped_column(
String(24), nullable=False, default="unknown", server_default="unknown"
)
# 客户在 order_site 领取页填写的资料。图片存 order_site 文件 URL,
# live-hub 只做展示和绑定比对,不再让客服手动索要主页截图。
customer_role_name: Mapped[str] = mapped_column(
String(128), nullable=False, default="", server_default=""
)
customer_platform: Mapped[str] = mapped_column(
String(16), nullable=False, default="", server_default=""
)
customer_system: Mapped[str] = mapped_column(
String(16), nullable=False, default="", server_default=""
)
customer_home_images: Mapped[list | None] = mapped_column(JSON, nullable=True)
customer_profile_updated_at: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
account_id: Mapped[int | None] = mapped_column(
ForeignKey("accounts.id", ondelete="SET NULL"), nullable=True, index=True
)
@@ -17,6 +17,7 @@ from ..database import get_db
from ..models import IntegrationInbox
from ..schemas import (
PlatformFulfillmentCustomerBindingAction,
PlatformFulfillmentCustomerProfileRequest,
PlatformFulfillmentCustomerSessionBatchRequest,
PlatformFulfillmentCustomerSessionRequest,
)
@@ -132,6 +133,26 @@ def ensure_customer_session(
)
@router.post(
"/customer-sessions/{task_id}/profile",
dependencies=[Depends(require_integration_key)],
)
def save_customer_profile(
task_id: int,
req: PlatformFulfillmentCustomerProfileRequest,
db: Session = Depends(get_db),
) -> dict[str, Any]:
"""接 order_site 客户领取页资料与主页截图;order_site 端保证必填。"""
return service.save_customer_profile(
db,
task_id=task_id,
customer_role_name=req.customer_role_name,
platform=req.platform,
system=req.system,
home_images=[item.model_dump() for item in req.home_images],
)
@router.post(
"/customer-sessions/{task_id}/binding/start",
dependencies=[Depends(require_integration_key)],
+15
View File
@@ -1762,6 +1762,21 @@ class PlatformFulfillmentCustomerSessionRequest(BaseModel):
platform_order_id: str = Field(default="", max_length=255)
class PlatformFulfillmentCustomerImage(BaseModel):
url: str = Field(..., min_length=1, max_length=2048)
thumbnail_url: str = Field("", max_length=2048)
object_key: str = Field("", max_length=512)
class PlatformFulfillmentCustomerProfileRequest(BaseModel):
customer_role_name: str = Field(..., min_length=1, max_length=128)
platform: str = Field(..., pattern="^(wechat|qq)$")
system: str = Field(..., pattern="^(ios|android)$")
home_images: list[PlatformFulfillmentCustomerImage] = Field(
..., min_length=1, max_length=5
)
class PlatformFulfillmentCustomerBindingAction(BaseModel):
force_refresh: bool = False
@@ -2,6 +2,7 @@
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from fastapi import HTTPException
@@ -21,7 +22,9 @@ from .repository import (
_find_customer_task,
_integration_actor,
_load_task,
_load_task_for_update,
)
from .runtime import _append_event
from .views import customer_binding_out
@@ -61,6 +64,57 @@ def ensure_customer_session(
return customer_binding_out(db, task.id)
def save_customer_profile(
db: Session,
*,
task_id: int,
customer_role_name: str,
platform: str,
system: str,
home_images: list[dict[str, str]],
commit: bool = True,
) -> dict[str, Any]:
"""保存 order_site 客户资料;至少一张主页截图由 order_site 端强制。"""
task = _load_task_for_update(db, task_id)
if task.execution_status in {"completed", "cancelled"}:
raise HTTPException(status_code=409, detail="订单已结束,不能修改客户资料")
images = []
for item in home_images[:5]:
url = str(item.get("url") or "").strip()
if not url:
continue
images.append(
{
"url": url[:2048],
"thumbnailUrl": str(item.get("thumbnail_url") or item.get("thumbnailUrl") or url)[:2048],
"objectKey": str(item.get("object_key") or item.get("objectKey") or "")[:512],
}
)
if not images:
raise HTTPException(status_code=409, detail="客户主页截图至少需要 1 张")
task.customer_role_name = str(customer_role_name or "").strip()[:128]
task.customer_platform = str(platform or "").strip()[:16]
task.customer_system = str(system or "").strip()[:16]
task.customer_home_images = images
task.customer_profile_updated_at = datetime.now(UTC)
task.updated_at = datetime.now(UTC)
_append_event(
db,
task.id,
"customer_profile_saved",
actor_type="integration",
detail={
"customerRoleName": task.customer_role_name,
"platform": task.customer_platform,
"system": task.customer_system,
"homeImageCount": len(images),
},
)
if commit:
db.commit()
return customer_binding_out(db, task.id)
async def customer_start_binding(
db: Session,
*,
@@ -42,6 +42,72 @@ _AUTO_SYNC_LOCK = threading.Lock()
_AUTO_SYNC_LAST_ATTEMPT = float("-inf")
def _apply_customer_profile(
task: PlatformFulfillmentTask,
snapshot: dict[str, Any],
) -> None:
"""order_site contractVersion=3 快照里的客户资料和主页截图。"""
keys = {
"customerRoleName",
"customer_role_name",
"homeImages",
"home_images",
}
if not keys.intersection(snapshot):
return
task.customer_role_name = str(
_snapshot_value(snapshot, "customerRoleName", "customer_role_name")
or ""
)[:128]
task.customer_platform = str(
_snapshot_value(snapshot, "customerPlatform", "customer_platform")
or ""
)[:16]
task.customer_system = str(
_snapshot_value(snapshot, "customerSystem", "customer_system")
or ""
)[:16]
raw_images = _snapshot_value(
snapshot,
"homeImages",
"home_images",
default=[],
)
images: list[dict[str, str]] = []
if isinstance(raw_images, list):
for item in raw_images[:5]:
if isinstance(item, str):
url = item.strip()
if url:
images.append({"url": url[:2048], "thumbnailUrl": url[:2048], "objectKey": ""})
continue
if not isinstance(item, dict):
continue
url = str(item.get("url") or "").strip()
if not url:
continue
images.append(
{
"url": url[:2048],
"thumbnailUrl": str(
item.get("thumbnailUrl") or item.get("thumbnail_url") or url
)[:2048],
"objectKey": str(
item.get("objectKey") or item.get("object_key") or ""
)[:512],
}
)
task.customer_home_images = images or None
task.customer_profile_updated_at = _parse_snapshot_datetime(
_snapshot_value(
snapshot,
"customerProfileUpdatedAt",
"customer_profile_updated_at",
default=None,
)
)
def _upsert_order_snapshot(
db: Session,
snapshot: dict[str, Any],
@@ -150,6 +216,7 @@ def _upsert_order_snapshot(
task.required_points,
task.issue_code,
)
_apply_customer_profile(task, snapshot)
if task.execution_status in {"completed", "cancelled"}:
task.source_snapshot_json = _jsonable(snapshot)
return task, created, False
@@ -481,6 +548,7 @@ def _sync_pending_tasks(
task.target_platform = TARGET_PLATFORM
task.scope = SCOPE_ELITE
task.source_snapshot_json = _jsonable(row)
_apply_customer_profile(task, row)
task.updated_at = _now()
if task.account_id is None and task.execution_status in {
"pending_mapping",
@@ -67,6 +67,7 @@ from .customer import (
customer_refresh_bindings,
customer_start_binding,
ensure_customer_session,
save_customer_profile,
)
from .lifecycle import (
cancel_task,
@@ -173,6 +174,7 @@ __all__ = [
"reset_task_binding",
"restore_cancelled_task",
"restore_mapping",
"save_customer_profile",
"set_mapping_enabled",
"start_binding",
"sync_active_task_from_account_binding",
@@ -506,6 +506,7 @@ def _task_out(
if include_qr and bind_task is not None
else None
),
"customerProfile": _customer_profile_out(task, account, binding),
"exchangeTaskId": exchange_task_id,
"exchangeResultImage": (
{
@@ -690,6 +691,58 @@ def _customer_binding_queue_state(
return "preparing", 1000
def _customer_profile_out(
task: PlatformFulfillmentTask,
account: Account | None,
binding,
) -> dict[str, Any] | None:
"""客户资料 + 与平台当前/确认角色的绑定比对。"""
role = str(task.customer_role_name or "").strip()
images = list(task.customer_home_images or [])
if not role and not images:
return None
platform_role = str(binding.effective_role_name or "").strip()
if not platform_role and account is not None:
platform_role = str(account.game_name or "").strip()
role_matched: bool | None = None
if role and platform_role:
role_matched = role == platform_role
channel_matched: bool | None = None
customer_channel = " ".join(
[
"微信" if task.customer_platform == "wechat" else ("QQ" if task.customer_platform == "qq" else ""),
"苹果" if task.customer_system == "ios" else ("安卓" if task.customer_system == "android" else ""),
]
).strip()
account_channel = str(
binding.effective_channel
or (account.game_channel if account is not None else "")
or ""
)
if customer_channel and account_channel:
channel_matched = all(part in account_channel for part in customer_channel.split())
if role and not platform_role:
message = "客户已填角色,平台还未识别绑定角色"
elif role_matched is True and channel_matched is not False:
message = "客户资料与平台角色一致"
elif role_matched is False or channel_matched is False:
message = "客户资料与平台角色不一致,请核对绑定"
else:
message = "客户资料已收到,等待平台识别角色"
return {
"roleName": role,
"platform": str(task.customer_platform or ""),
"system": str(task.customer_system or ""),
"homeImages": images,
"updatedAt": _jsonable(task.customer_profile_updated_at),
"platformRoleName": platform_role,
"platformChannel": account_channel,
"roleMatched": role_matched,
"channelMatched": channel_matched,
"message": message,
}
def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
"""面向前端客户页的安全绑定快照,不包含账号、CK、积分和租约。"""
task = _load_task(db, task_id)
@@ -754,6 +807,7 @@ def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
"queueLane": bind_task.queue_lane if bind_task else "",
"accepted": False,
"stateVersion": int(task.state_version or 0),
"customerProfile": _customer_profile_out(task, account, binding),
"completedAt": _jsonable(task.completed_at),
"updatedAt": _jsonable(task.updated_at),
}
+20
View File
@@ -2532,6 +2532,25 @@ export interface PlatformFulfillmentBindingEvidence {
accountLock: PlatformFulfillmentBindingLock | null;
}
export interface PlatformFulfillmentCustomerImage {
url: string;
thumbnailUrl: string;
objectKey: string;
}
export interface PlatformFulfillmentCustomerProfile {
roleName: string;
platform: string;
system: string;
homeImages: PlatformFulfillmentCustomerImage[];
updatedAt: string | null;
platformRoleName: string;
platformChannel: string;
roleMatched: boolean | null;
channelMatched: boolean | null;
message: string;
}
export interface PlatformFulfillmentTask {
id: number;
sourceSystem: string;
@@ -2582,6 +2601,7 @@ export interface PlatformFulfillmentTask {
lease: { id: number; status: string; expiresAt: string | null } | null;
bindTask: PlatformFulfillmentBindTask | null;
bindingEvidence: PlatformFulfillmentBindingEvidence | null;
customerProfile: PlatformFulfillmentCustomerProfile | null;
exchangeTaskId: number | null;
exchangeResultImage: {
objectKey: string;
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import { Alert, Button, Card, Col, DatePicker, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Row, Segmented, Select, Space, Switch, Table, Tag, Timeline, Typography } from 'antd';
import { Alert, Button, Card, Col, DatePicker, Descriptions, Drawer, Empty, Image, Input, InputNumber, Modal, QRCode, Row, Segmented, Select, Space, Switch, Table, Tag, Timeline, Typography } from 'antd';
import { CheckCircleOutlined, CopyOutlined, CreditCardOutlined, DownloadOutlined, GiftOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, ShoppingOutlined, SyncOutlined, UndoOutlined, UserSwitchOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { douyuApi, platformFulfillmentApi } from '../api/modules';
@@ -18,6 +18,22 @@ import { usePermissions } from '../hooks/usePermissions';
const { Text, Title } = Typography;
const CUSTOMER_PLATFORM_LABELS: Record<string, string> = {
wechat: '微信',
qq: 'QQ',
};
const CUSTOMER_SYSTEM_LABELS: Record<string, string> = {
ios: '苹果',
android: '安卓',
};
function customerMatchTone(profile: NonNullable<PlatformFulfillmentTask['customerProfile']>) {
if (profile.roleMatched === false || profile.channelMatched === false) return 'red';
if (profile.roleMatched === true && profile.channelMatched === true) return 'green';
return 'gold';
}
const STATUS_OPTIONS = [
{ value: '', label: '全部' },
{ value: 'pending_mapping', label: '待映射' },
@@ -1798,6 +1814,65 @@ export default function PlatformFulfillmentPage() {
</Descriptions>
</Card>
<Card size="small" title="用户资料(order_site)">
{selected.customerProfile ? (
<Space direction="vertical" size={10} style={{ width: '100%' }}>
<Descriptions bordered size="small" column={2}>
<Descriptions.Item label="客户角色" span={2}>
{selected.customerProfile.roleName || '未填写'}
</Descriptions.Item>
<Descriptions.Item label="登录方式">
{CUSTOMER_PLATFORM_LABELS[selected.customerProfile.platform] || selected.customerProfile.platform || '-'}
</Descriptions.Item>
<Descriptions.Item label="系统">
{CUSTOMER_SYSTEM_LABELS[selected.customerProfile.system] || selected.customerProfile.system || '-'}
</Descriptions.Item>
<Descriptions.Item label="平台当前角色">
{selected.customerProfile.platformRoleName || '未识别'}
</Descriptions.Item>
<Descriptions.Item label="平台渠道">
{selected.customerProfile.platformChannel || '-'}
</Descriptions.Item>
<Descriptions.Item label="绑定比对" span={2}>
<Space wrap size={6}>
<Tag color={customerMatchTone(selected.customerProfile)}>
{selected.customerProfile.message}
</Tag>
{selected.customerProfile.updatedAt ? (
<Text type="secondary">更新 {formatTime(selected.customerProfile.updatedAt)}</Text>
) : null}
</Space>
</Descriptions.Item>
</Descriptions>
{selected.customerProfile.homeImages.length ? (
<Image.PreviewGroup
items={selected.customerProfile.homeImages.map((item) => item.url)}
>
<Space wrap size={8}>
{selected.customerProfile.homeImages.map((item, index) => (
<Image
key={`${item.objectKey || item.url}-${index}`}
src={item.thumbnailUrl || item.url}
width={96}
height={96}
style={{ objectFit: 'cover', borderRadius: 6 }}
alt={`客户主页截图 ${index + 1}`}
/>
))}
</Space>
</Image.PreviewGroup>
) : (
<Text type="secondary">没有主页截图</Text>
)}
</Space>
) : (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description="客户尚未同步资料和主页截图"
/>
)}
</Card>
<Card size="small" title="账号实时状态">
{selected.account ? (
<Descriptions bordered size="small" column={2}>