feat(fulfillment): 新增 order_site 客户绑定集成
This commit is contained in:
@@ -32,6 +32,7 @@ from .routers import (
|
||||
huya,
|
||||
login,
|
||||
platform_fulfillment,
|
||||
platform_fulfillment_integration,
|
||||
proxy,
|
||||
users,
|
||||
weibo,
|
||||
@@ -173,6 +174,7 @@ app.include_router(weibo_collab.router)
|
||||
app.include_router(douyu.router)
|
||||
app.include_router(douyu_collab.router)
|
||||
app.include_router(platform_fulfillment.router)
|
||||
app.include_router(platform_fulfillment_integration.router)
|
||||
app.include_router(yyb.router)
|
||||
app.include_router(audit.router)
|
||||
app.include_router(automation.router)
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"""order_site -> live-hub 的直播账号履约服务端集成接口。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from hmac import compare_digest
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from ..schemas import (
|
||||
PlatformFulfillmentCustomerBindingAction,
|
||||
PlatformFulfillmentCustomerSessionRequest,
|
||||
)
|
||||
from ..services.platform_fulfillment import service
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/api/integration/platform-fulfillment",
|
||||
tags=["直播账号履约集成"],
|
||||
)
|
||||
|
||||
|
||||
def require_integration_key(
|
||||
x_integration_key: str = Header("", alias="X-Integration-Key"),
|
||||
) -> None:
|
||||
expected = os.getenv("PLATFORM_FULFILLMENT_INTEGRATION_KEY", "").strip()
|
||||
if not expected:
|
||||
raise HTTPException(status_code=503, detail="直播账号履约集成密钥未配置")
|
||||
if not x_integration_key or not compare_digest(x_integration_key, expected):
|
||||
raise HTTPException(status_code=401, detail="直播账号履约集成鉴权失败")
|
||||
|
||||
|
||||
@router.post(
|
||||
"/customer-sessions/ensure", dependencies=[Depends(require_integration_key)]
|
||||
)
|
||||
def ensure_customer_session(
|
||||
req: PlatformFulfillmentCustomerSessionRequest,
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict[str, Any]:
|
||||
return service.ensure_customer_session(
|
||||
db,
|
||||
source_order_item_id=req.source_order_item_id,
|
||||
platform_order_id=req.platform_order_id,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/customer-sessions/{task_id}/binding/start",
|
||||
dependencies=[Depends(require_integration_key)],
|
||||
)
|
||||
async def start_customer_binding(
|
||||
task_id: int,
|
||||
req: PlatformFulfillmentCustomerBindingAction,
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict[str, Any]:
|
||||
return await service.customer_start_binding(
|
||||
db,
|
||||
task_id=task_id,
|
||||
force_refresh=req.force_refresh,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/customer-sessions/{task_id}/status",
|
||||
dependencies=[Depends(require_integration_key)],
|
||||
)
|
||||
def get_customer_binding_status(
|
||||
task_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict[str, Any]:
|
||||
return service.customer_refresh_binding(db, task_id=task_id)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/customer-sessions/{task_id}/binding/confirm",
|
||||
dependencies=[Depends(require_integration_key)],
|
||||
)
|
||||
async def confirm_customer_binding(
|
||||
task_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict[str, Any]:
|
||||
return await service.customer_confirm_binding(db, task_id=task_id)
|
||||
@@ -1580,6 +1580,15 @@ class PlatformFulfillmentSettingsUpdate(BaseModel):
|
||||
lease_duration_minutes: int | None = Field(..., ge=1, le=525600)
|
||||
|
||||
|
||||
class PlatformFulfillmentCustomerSessionRequest(BaseModel):
|
||||
source_order_item_id: str = Field(..., min_length=1, max_length=128)
|
||||
platform_order_id: str = Field(default="", max_length=255)
|
||||
|
||||
|
||||
class PlatformFulfillmentCustomerBindingAction(BaseModel):
|
||||
force_refresh: bool = False
|
||||
|
||||
|
||||
class DouyuTaskBatchRequest(BaseModel):
|
||||
account_ids: list[int]
|
||||
task_type: str
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -28,7 +28,7 @@ from .business_events import record_bind
|
||||
from .douyu_activity_query import query_bind_info, query_esports_bind_info
|
||||
|
||||
DOUYU_LEGACY_BIND_ACT_ALIAS = "20250213NQCYX"
|
||||
DOUYU_BIND_ROLE_POLL_SECONDS = 65
|
||||
DOUYU_BIND_ROLE_POLL_SECONDS = 600
|
||||
DOUYU_BIND_ROLE_POLL_INTERVAL = 5
|
||||
DOUYU_CONFIRM_EFFECT_POLL_TIMES = 3
|
||||
DOUYU_CONFIRM_EFFECT_POLL_INTERVAL = 3
|
||||
@@ -620,6 +620,7 @@ class BindMixin:
|
||||
f"role={current_role_name or '-'} wait={wait_time if wait_time is not None else 0}",
|
||||
)
|
||||
qr_result = client.get_bind_qr(qr_act_alias)
|
||||
qr_generated_at = datetime.now(UTC)
|
||||
result = {
|
||||
**qr_result,
|
||||
"act_alias": qr_act_alias,
|
||||
@@ -635,6 +636,10 @@ class BindMixin:
|
||||
"bind_confirmed": False,
|
||||
"bind_phase": "waiting_scan",
|
||||
"bind_polling": True,
|
||||
"qr_generated_at": qr_generated_at.isoformat(),
|
||||
"qr_expires_at": (
|
||||
qr_generated_at + timedelta(seconds=DOUYU_BIND_ROLE_POLL_SECONDS)
|
||||
).isoformat(),
|
||||
}
|
||||
account.updated_at = datetime.now(UTC)
|
||||
# 关键:先把二维码 progress 出去,前端 running 期间即可弹窗扫码。
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import uuid
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
@@ -50,6 +51,8 @@ ACTIVE_STATUSES = {
|
||||
"manual_required",
|
||||
}
|
||||
|
||||
BINDING_QR_TTL_SECONDS = int(os.getenv("PLATFORM_BINDING_QR_TTL_SECONDS", "600"))
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(UTC)
|
||||
@@ -141,6 +144,61 @@ def _lease_duration_minutes(db: Session) -> int | None:
|
||||
return get_settings(db)["leaseDurationMinutes"]
|
||||
|
||||
|
||||
def _integration_actor(db: Session) -> User:
|
||||
raw_user_id = os.getenv("PLATFORM_FULFILLMENT_INTEGRATION_ACTOR_ID", "").strip()
|
||||
query = db.query(User).filter(User.is_active.is_(True))
|
||||
if raw_user_id:
|
||||
try:
|
||||
user = query.filter(User.id == int(raw_user_id)).first()
|
||||
except ValueError:
|
||||
user = None
|
||||
else:
|
||||
user = query.filter(User.role == "super_admin").order_by(User.id.asc()).first()
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="未配置可用的直播账号履约集成操作人",
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
def _find_customer_task(
|
||||
db: Session,
|
||||
*,
|
||||
source_order_item_id: str,
|
||||
platform_order_id: str = "",
|
||||
) -> PlatformFulfillmentTask | None:
|
||||
item_id = str(source_order_item_id or "").strip()
|
||||
if not item_id:
|
||||
return None
|
||||
query = db.query(PlatformFulfillmentTask).filter(
|
||||
PlatformFulfillmentTask.source_system == "order_site",
|
||||
PlatformFulfillmentTask.source_order_item_id == item_id,
|
||||
)
|
||||
order_no = str(platform_order_id or "").strip()
|
||||
if order_no:
|
||||
query = query.filter(PlatformFulfillmentTask.platform_order_id == order_no)
|
||||
return query.first()
|
||||
|
||||
|
||||
def _binding_qr_expired(bind_task: DouyuTask, now: datetime | None = None) -> bool:
|
||||
result = bind_task.result or {}
|
||||
raw_expires_at = str(result.get("qr_expires_at") or "").strip()
|
||||
if raw_expires_at:
|
||||
try:
|
||||
expires_at = datetime.fromisoformat(raw_expires_at)
|
||||
except ValueError:
|
||||
expires_at = None
|
||||
if expires_at is not None:
|
||||
if expires_at.tzinfo is None:
|
||||
expires_at = expires_at.replace(tzinfo=UTC)
|
||||
return expires_at <= (now or _now())
|
||||
created_at = bind_task.created_at
|
||||
if created_at.tzinfo is None:
|
||||
created_at = created_at.replace(tzinfo=UTC)
|
||||
return created_at + timedelta(seconds=BINDING_QR_TTL_SECONDS) <= (now or _now())
|
||||
|
||||
|
||||
def _append_event(
|
||||
db: Session,
|
||||
task_id: int,
|
||||
@@ -435,6 +493,128 @@ def get_task_detail(db: Session, task_id: int) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _customer_task_message(task: PlatformFulfillmentTask) -> str:
|
||||
messages = {
|
||||
"mapping_missing": "商品正在准备中,请稍后重试",
|
||||
"no_eligible_account": "正在准备可用账号,请稍后重试",
|
||||
"elite_not_opened": "账号正在准备精英宝典,请稍后重试",
|
||||
"points_short": "账号正在补充积分,请稍后重试",
|
||||
"commodity_limit_reached": "当前商品暂时无法兑换,请联系客服",
|
||||
"binding_failed": "绑定失败,请刷新二维码后重试",
|
||||
"eligibility_check_failed": "状态查询异常,请稍后刷新",
|
||||
"manual_required": "当前需要人工处理,请联系客服",
|
||||
}
|
||||
return messages.get(task.issue_code, "") if task.issue_code else ""
|
||||
|
||||
|
||||
def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
|
||||
"""面向前端客户页的安全绑定快照,不包含账号、CK、积分和租约。"""
|
||||
task = _load_task(db, task_id)
|
||||
bind_task = (
|
||||
db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first()
|
||||
if task.bind_task_id
|
||||
else None
|
||||
)
|
||||
bind_result = (bind_task.result or {}) if bind_task else {}
|
||||
lease = (
|
||||
db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
|
||||
if task.lease_id
|
||||
else None
|
||||
)
|
||||
lease_ready = bool(task.account_id and lease and lease.status == "active")
|
||||
return {
|
||||
"sessionId": task.id,
|
||||
"platformOrderId": task.platform_order_id,
|
||||
"sourceOrderItemId": task.source_order_item_id,
|
||||
"productName": task.sku_name,
|
||||
"quantity": task.quantity,
|
||||
"executionStatus": task.execution_status,
|
||||
"bindingStatus": task.binding_status,
|
||||
"exchangeStatus": task.exchange_status,
|
||||
"issueCode": task.issue_code,
|
||||
"message": _customer_task_message(task),
|
||||
"accountReady": lease_ready,
|
||||
"bindTaskId": bind_task.id if bind_task else None,
|
||||
"bindTaskStatus": bind_task.status if bind_task else "",
|
||||
"bindPhase": str(bind_result.get("bind_phase") or ""),
|
||||
"qrUrl": str(bind_result.get("url") or ""),
|
||||
"qrGeneratedAt": str(bind_result.get("qr_generated_at") or ""),
|
||||
"qrExpiresAt": str(bind_result.get("qr_expires_at") or ""),
|
||||
"roleName": str(
|
||||
bind_result.get("role_name") or bind_result.get("current_role_name") or ""
|
||||
),
|
||||
"areaName": str(bind_result.get("area_name") or ""),
|
||||
"platName": str(bind_result.get("plat_name") or ""),
|
||||
"bindReadyForConfirm": bool(bind_result.get("bind_ready_for_confirm")),
|
||||
"bindConfirmed": bool(bind_result.get("bind_confirmed")),
|
||||
"completedAt": _jsonable(task.completed_at),
|
||||
"updatedAt": _jsonable(task.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def ensure_customer_session(
|
||||
db: Session,
|
||||
*,
|
||||
source_order_item_id: str,
|
||||
platform_order_id: str = "",
|
||||
) -> dict[str, Any]:
|
||||
"""按订单项幂等准备客户绑定会话;必要时同步订单并自动分配账号。"""
|
||||
task = _find_customer_task(
|
||||
db,
|
||||
source_order_item_id=source_order_item_id,
|
||||
platform_order_id=platform_order_id,
|
||||
)
|
||||
if task is None:
|
||||
sync_pending_tasks(db, limit=500)
|
||||
task = _find_customer_task(
|
||||
db,
|
||||
source_order_item_id=source_order_item_id,
|
||||
platform_order_id=platform_order_id,
|
||||
)
|
||||
if task is None:
|
||||
raise HTTPException(status_code=404, detail="订单尚未进入直播账号履约队列")
|
||||
if task.execution_status in {"completed", "cancelled"}:
|
||||
return customer_binding_out(db, task.id)
|
||||
if task.execution_status in {"pending_mapping", "ready", "manual_required"}:
|
||||
if task.issue_code == "mapping_missing":
|
||||
return customer_binding_out(db, task.id)
|
||||
actor = _integration_actor(db)
|
||||
allocate_task(db, task_id=task.id, current=actor)
|
||||
return customer_binding_out(db, task.id)
|
||||
|
||||
|
||||
async def customer_start_binding(
|
||||
db: Session,
|
||||
*,
|
||||
task_id: int,
|
||||
force_refresh: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
task = _load_task(db, task_id)
|
||||
actor = _integration_actor(db)
|
||||
if task.execution_status not in {"completed", "cancelled"} and (
|
||||
not task.account_id or not task.lease_id
|
||||
):
|
||||
allocate_task(db, task_id=task.id, current=actor)
|
||||
await start_binding(
|
||||
db,
|
||||
task_id=task.id,
|
||||
current=actor,
|
||||
force_refresh=force_refresh,
|
||||
)
|
||||
return customer_binding_out(db, task.id)
|
||||
|
||||
|
||||
def customer_refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]:
|
||||
refresh_binding(db, task_id=task_id)
|
||||
return customer_binding_out(db, task_id)
|
||||
|
||||
|
||||
async def customer_confirm_binding(db: Session, *, task_id: int) -> dict[str, Any]:
|
||||
refresh_binding(db, task_id=task_id)
|
||||
await confirm_binding(db, task_id=task_id, current=_integration_actor(db))
|
||||
return customer_binding_out(db, task_id)
|
||||
|
||||
|
||||
def list_mappings(db: Session, *, keyword: str = "") -> list[dict[str, Any]]:
|
||||
query = db.query(PlatformCommodityMapping)
|
||||
text = keyword.strip()
|
||||
@@ -740,7 +920,13 @@ def release_task_account(
|
||||
return get_task_detail(db, task.id)
|
||||
|
||||
|
||||
async def start_binding(db: Session, *, task_id: int, current: User) -> dict[str, Any]:
|
||||
async def start_binding(
|
||||
db: Session,
|
||||
*,
|
||||
task_id: int,
|
||||
current: User,
|
||||
force_refresh: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
task = _load_task(db, task_id)
|
||||
if not task.account_id or not task.lease_id:
|
||||
raise HTTPException(status_code=409, detail="请先分配账号")
|
||||
@@ -749,8 +935,23 @@ async def start_binding(db: Session, *, task_id: int, current: User) -> dict[str
|
||||
raise HTTPException(status_code=409, detail="账号租约已失效,请重新分配")
|
||||
if task.bind_task_id:
|
||||
existing = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first()
|
||||
if existing and existing.status in {"planned", "pending", "running", "success"}:
|
||||
return get_task_detail(db, task.id)
|
||||
if existing:
|
||||
result = existing.result or {}
|
||||
if bool(result.get("bind_confirmed")) or bool(
|
||||
result.get("bind_ready_for_confirm")
|
||||
):
|
||||
return get_task_detail(db, task.id)
|
||||
if existing.status in {"planned", "pending", "running"}:
|
||||
return get_task_detail(db, task.id)
|
||||
if existing.status == "success" and not _binding_qr_expired(existing):
|
||||
return get_task_detail(db, task.id)
|
||||
if not force_refresh and existing.status not in {
|
||||
"success",
|
||||
"failed",
|
||||
"error",
|
||||
"stopped",
|
||||
}:
|
||||
return get_task_detail(db, task.id)
|
||||
|
||||
batch_id = f"pfbind-{task.id}-{uuid.uuid4().hex[:8]}"
|
||||
bind_task = DouyuTask(
|
||||
|
||||
Reference in New Issue
Block a user