diff --git a/.env.example b/.env.example index dbbe361..58f2c2a 100644 --- a/.env.example +++ b/.env.example @@ -146,5 +146,12 @@ ORDER_SITE_DATABASE_URL= ORDER_SITE_LOOKUP_ENABLED=false ORDER_SITE_LOOKUP_TIMEOUT_SECONDS=3 +# order_site -> live-hub 直播账号履约服务端集成 +PLATFORM_FULFILLMENT_INTEGRATION_KEY= +# 可选:指定集成操作人;不填时使用最早创建的有效超级管理员 +# PLATFORM_FULFILLMENT_INTEGRATION_ACTOR_ID=1 +# 客户绑定二维码有效期 +PLATFORM_BINDING_QR_TTL_SECONDS=600 + # Uvicorn reload(开发模式设为 true,生产环境保持 false) UVICORN_RELOAD=false diff --git a/docker-compose.yml b/docker-compose.yml index e5772aa..6071d56 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -83,6 +83,9 @@ services: - ORDER_SITE_DATABASE_URL=${ORDER_SITE_DATABASE_URL:-} - ORDER_SITE_LOOKUP_ENABLED=${ORDER_SITE_LOOKUP_ENABLED:-false} - ORDER_SITE_LOOKUP_TIMEOUT_SECONDS=${ORDER_SITE_LOOKUP_TIMEOUT_SECONDS:-3} + - PLATFORM_FULFILLMENT_INTEGRATION_KEY=${PLATFORM_FULFILLMENT_INTEGRATION_KEY:-} + - PLATFORM_FULFILLMENT_INTEGRATION_ACTOR_ID=${PLATFORM_FULFILLMENT_INTEGRATION_ACTOR_ID:-} + - PLATFORM_BINDING_QR_TTL_SECONDS=${PLATFORM_BINDING_QR_TTL_SECONDS:-600} # 用户上传图片的桶(在线协作 / P2 资料收集共用;生产用内网 endpoint)。 # OSS_MODE=oss 才走对象存储,否则落容器内 ./data/file_storage。 - OSS_MODE=${OSS_MODE:-local} diff --git a/docs/直播账号履约工作台.md b/docs/直播账号履约工作台.md index 51ee3f3..4592db1 100644 --- a/docs/直播账号履约工作台.md +++ b/docs/直播账号履约工作台.md @@ -98,6 +98,24 @@ ORDER_SITE_LOOKUP_ENABLED=true 数据库账号必须是只读账号。跨库 SQL 只允许出现在 `web/backend/services/external_order_source.py`。 +## order_site 客户领取集成 + +`order_site` 客户页通过服务端接口调用 live-hub,不允许客户浏览器直接访问 +live-hub 管理 API。内部接口统一位于: + +```text +/api/integration/platform-fulfillment/customer-sessions/* +``` + +接口使用 `X-Integration-Key` 鉴权,密钥来自 +`PLATFORM_FULFILLMENT_INTEGRATION_KEY`。返回给 `order_site` 的客户会话只包含 +二维码、二维码有效期、绑定阶段、平台识别角色和状态提示,不包含账号、CK、 +积分、租约或限兑信息。 + +客户绑定二维码默认有效期 600 秒,可通过 +`PLATFORM_BINDING_QR_TTL_SECONDS` 调整。过期、失败或客户主动刷新时会在 +live-hub 创建新的绑定任务。 + ## 权限 - `platform_fulfillment:view` diff --git a/tests/test_platform_fulfillment_integration.py b/tests/test_platform_fulfillment_integration.py new file mode 100644 index 0000000..147965b --- /dev/null +++ b/tests/test_platform_fulfillment_integration.py @@ -0,0 +1,118 @@ +"""直播账号履约服务端集成接口测试。""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta + +import pytest +from fastapi import HTTPException + +from web.backend.models import ( + Account, + AccountLease, + DouyuTask, + PlatformFulfillmentTask, + User, +) +from web.backend.routers.platform_fulfillment_integration import require_integration_key +from web.backend.services.platform_fulfillment import service + + +def test_integration_key_is_required(monkeypatch): + monkeypatch.setenv("PLATFORM_FULFILLMENT_INTEGRATION_KEY", "secret") + + require_integration_key("secret") + with pytest.raises(HTTPException) as missing: + require_integration_key("") + with pytest.raises(HTTPException) as invalid: + require_integration_key("wrong") + + assert missing.value.status_code == 401 + assert invalid.value.status_code == 401 + + +def test_customer_binding_out_hides_internal_account_data(db): + user = User( + username="integration-actor", + password_hash="h", + role="super_admin", + is_active=True, + ) + account = Account( + username="internal-douyu-account", + password="p", + email="internal@example.com", + email_password="ep", + cookie="secret-cookie", + ) + db.add_all([user, account]) + db.flush() + lease = AccountLease( + account_id=account.id, + holder_user_id=user.id, + purpose="platform_fulfillment", + status="active", + ) + bind = DouyuTask( + batch_id="bind", + account_id=account.id, + account_assigned_to=user.id, + task_type="get_bind_qr", + handbook_scope="elite", + status="running", + message="等待扫码", + result={ + "url": "https://livenlink.example/private-qr-token", + "bind_phase": "waiting_scan", + "qr_generated_at": datetime.now(UTC).isoformat(), + "qr_expires_at": (datetime.now(UTC) + timedelta(minutes=10)).isoformat(), + }, + created_by=user.id, + ) + db.add_all([lease, bind]) + db.flush() + task = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="order-1", + source_order_item_id="item-1", + platform_order_id="DY-001", + sku_name="斗鱼精英宝典", + quantity=1, + account_id=account.id, + lease_id=lease.id, + bind_task_id=bind.id, + binding_status="qr_pending", + execution_status="waiting_bind", + ) + db.add(task) + db.commit() + + payload = service.customer_binding_out(db, task.id) + + assert payload["sessionId"] == task.id + assert payload["qrUrl"] == "https://livenlink.example/private-qr-token" + assert payload["accountReady"] is True + assert "account" not in payload + assert "cookie" not in payload + assert "points" not in payload + assert "lease" not in payload + + +def test_binding_qr_expiry_uses_customer_ttl(): + now = datetime.now(UTC) + task = DouyuTask( + batch_id="expired", + account_id=1, + account_assigned_to=1, + task_type="get_bind_qr", + handbook_scope="elite", + status="success", + message="", + result={ + "qr_expires_at": (now - timedelta(seconds=1)).isoformat(), + }, + created_by=1, + ) + task.created_at = now - timedelta(minutes=5) + + assert service._binding_qr_expired(task, now=now) is True diff --git a/web/backend/main.py b/web/backend/main.py index 3b07bd9..1b88ddc 100644 --- a/web/backend/main.py +++ b/web/backend/main.py @@ -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) diff --git a/web/backend/routers/platform_fulfillment_integration.py b/web/backend/routers/platform_fulfillment_integration.py new file mode 100644 index 0000000..14de9d4 --- /dev/null +++ b/web/backend/routers/platform_fulfillment_integration.py @@ -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) diff --git a/web/backend/schemas.py b/web/backend/schemas.py index c7c2f3d..c446330 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -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 diff --git a/web/backend/services/douyu_runner_bind.py b/web/backend/services/douyu_runner_bind.py index bf488dd..29fe0a2 100644 --- a/web/backend/services/douyu_runner_bind.py +++ b/web/backend/services/douyu_runner_bind.py @@ -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 期间即可弹窗扫码。 diff --git a/web/backend/services/platform_fulfillment/service.py b/web/backend/services/platform_fulfillment/service.py index 8561690..d8a8739 100644 --- a/web/backend/services/platform_fulfillment/service.py +++ b/web/backend/services/platform_fulfillment/service.py @@ -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(