Files
live-hub-py/tests/test_platform_fulfillment.py
T

7440 lines
272 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""直播账号履约:订单同步、映射、选号、绑码状态和人工完成。"""
from __future__ import annotations
import asyncio
import threading
from datetime import UTC, datetime, timedelta
import pytest
from fastapi import HTTPException
from sqlalchemy import event
from tests.support.db import get_test_engine, make_test_session
from web.backend.deps import require_permission
from web.backend.models import (
Account,
AccountCommodityState,
AccountEvent,
AccountLease,
AccountWorkItem,
AutomationJob,
DouyuExternalOrder,
DouyuGoodsSnapshot,
DouyuRoleApiLog,
DouyuTask,
IntegrationOutbox,
PlatformCommodityMapping,
PlatformFulfillmentEvent,
PlatformFulfillmentSetting,
PlatformFulfillmentTask,
User,
)
from web.backend.permissions import ROLE_PERMISSIONS
from web.backend.schemas import DouyuCollabOrderOut
from web.backend.services import douyu_collab_service as collab
from web.backend.services.account_sync_runner import WORK_STOREHOME_SYNC
from web.backend.services.automation.jobs import (
platform_fulfillment_lease_reaper as reaper,
)
from web.backend.services.platform_fulfillment import account_selector, service, views
from web.backend.services.platform_fulfillment.binding_status import (
_binding_failure_issue,
_binding_failure_raw_message,
)
from web.backend.services.platform_fulfillment.order_sync import _apply_customer_profile
NOW = datetime.now(UTC).replace(microsecond=0)
COMMODITY = "20260120QYOOB_bag10"
INTERNAL_SKU = "套装-兔兔白日梦"
class _Base:
def setup_method(self):
self.engine = get_test_engine()
self.session = make_test_session(self.engine)
self.admin = User(
username="pf-admin",
password_hash="h",
role="super_admin",
)
self.session.add(self.admin)
self.session.commit()
self.admin_id = self.admin.id
self.session.add(
PlatformFulfillmentSetting(
id=1,
lease_duration_minutes=None,
order_match_started_at=NOW - timedelta(days=1),
)
)
self.session.commit()
def teardown_method(self):
views.invalidate_task_list_count_cache()
self.session.close()
def complete_customer_profile(self, task: PlatformFulfillmentTask) -> None:
task.customer_role_name = "小淋笨"
task.customer_platform = "wechat"
task.customer_system = "android"
task.customer_home_images = [
{
"url": "https://example.com/game-home.png",
"thumbnailUrl": "https://example.com/game-home-thumb.png",
"objectKey": "game-home.png",
}
]
self.session.commit()
def account(
self,
name: str,
*,
points: int = 2000,
opened: bool = True,
role_available_at: datetime | None = None,
capability: bool = True,
availability: str = "available",
) -> Account:
row = Account(
username=name,
password="p",
email=f"{name}@example.com",
email_password="ep",
status="active",
ck_check_status="valid",
cookie="PHPSESSID=x",
elite_opened=opened,
points=points,
gold_balance=100,
auto_managed=True,
role_change_available_at=role_available_at,
)
self.session.add(row)
self.session.flush()
if capability:
self.session.add(
AccountCommodityState(
account_id=row.id,
platform="douyu",
scope="elite",
commodity_id=COMMODITY,
commodity_name=INTERNAL_SKU,
account_eligibility=(
"limited" if availability == "limited" else "eligible"
),
offer_state="before" if availability == "not_open" else "active",
stock_state=(
"out_of_stock" if availability == "no_stock" else "in_stock"
),
availability=availability,
observed_at=NOW,
valid_until=NOW + timedelta(hours=6),
source="test_fixture",
)
)
self.session.commit()
return row
def mapping(self, enabled: bool = True) -> PlatformCommodityMapping:
row = PlatformCommodityMapping(
target_platform="douyu",
internal_sku_key=INTERNAL_SKU,
commodity_id=COMMODITY,
goods_name=INTERNAL_SKU,
required_points=1280,
scope="elite",
enabled=enabled,
created_by=self.admin_id,
created_at=NOW,
updated_at=NOW,
)
self.session.add(row)
self.session.commit()
return row
def task(self, *, mapped: bool = True) -> PlatformFulfillmentTask:
mapping = self.mapping() if mapped else None
row = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="100",
source_order_item_id="101",
source_fulfillment_id="201",
platform_order_id="ORDER-101",
provider="91kaquan",
shop_id="shop-1",
shop_name="测试店",
sku_code=INTERNAL_SKU,
sku_name=INTERNAL_SKU,
internal_sku_key=INTERNAL_SKU,
quantity=1,
order_amount_fen=9900,
target_platform="douyu",
scope="elite",
commodity_mapping_id=mapping.id if mapping else None,
commodity_id=COMMODITY if mapping else "",
required_points=1280 if mapping else None,
binding_status="not_started",
execution_status="ready" if mapping else "pending_mapping",
exchange_status="not_started",
source_snapshot_json={"order_no": "ORDER-101"},
paid_at=NOW,
created_at=NOW,
updated_at=NOW,
)
self.session.add(row)
self.session.commit()
return row
class TestAccountAvailability(_Base):
COMMODITIES = (
"bundle-commodity-a",
"bundle-commodity-b",
"bundle-commodity-c",
)
def setup_method(self):
super().setup_method()
setting = self.session.get(PlatformFulfillmentSetting, 1)
setting.allocation_policy_json = {
"sameRoleReuseEnabled": True,
"preserveBundlePool": True,
"bundleRules": [
{
"id": "availability-bundle",
"name": "三商品全资格",
"enabled": True,
"mode": "prefer_all",
"commodityIds": list(self.COMMODITIES),
}
],
}
self.session.commit()
def commodity_account(
self,
name: str,
commodity_ids: tuple[str, ...],
*,
role_available_at: datetime | None = None,
) -> Account:
account = Account(
username=name,
password="p",
email=f"{name}@example.com",
email_password="ep",
status="active",
ck_check_status="valid",
cookie="PHPSESSID=x",
elite_opened=True,
points=3000,
auto_managed=True,
role_change_available_at=role_available_at,
)
self.session.add(account)
self.session.flush()
for commodity_id in commodity_ids:
self.session.add(
AccountCommodityState(
account_id=account.id,
platform="douyu",
scope="elite",
commodity_id=commodity_id,
commodity_name=commodity_id,
account_eligibility="eligible",
offer_state="active",
stock_state="in_stock",
availability="available",
observed_at=NOW,
valid_until=NOW + timedelta(hours=6),
source="test_fixture",
)
)
self.session.commit()
return account
def test_counts_allocatable_bundle_and_unique_accounts(self):
self.commodity_account("availability-full", self.COMMODITIES)
leased = self.commodity_account("availability-leased", self.COMMODITIES)
self.commodity_account(
"availability-role-cooldown",
self.COMMODITIES,
role_available_at=NOW + timedelta(days=1),
)
self.commodity_account(
"availability-single",
(self.COMMODITIES[0],),
)
exchanged = self.commodity_account(
"availability-exchanged",
(self.COMMODITIES[0],),
)
self.session.add(
AccountLease(
account_id=leased.id,
holder_user_id=self.admin_id,
purpose="platform_fulfillment",
status="active",
)
)
self.session.add(
AccountEvent(
account_id=exchanged.id,
event_type="exchange",
category="business",
occurred_at=NOW - timedelta(days=10),
subject_type="commodity",
subject_key=self.COMMODITIES[0],
source="test_fixture",
)
)
self.session.commit()
result = service.get_account_availability(
self.session,
commodity_ids=list(self.COMMODITIES),
now=NOW,
)
assert result["uniqueAllocatable"] == 2
for commodity_id in self.COMMODITIES:
item = result["items"][commodity_id]
assert item["bundleCommodityCount"] == 3
assert item["fullBundleAllocatable"] == 1
assert item["roleCooldown"] == 1
assert item["leased"] == 1
assert result["items"][self.COMMODITIES[0]]["allocatable"] == 2
assert result["items"][self.COMMODITIES[1]]["allocatable"] == 1
assert result["items"][self.COMMODITIES[2]]["allocatable"] == 1
def test_availability_permission_excludes_support(self):
checker = require_permission("platform_fulfillment:admin")
support = User(
username="availability-support",
password_hash="h",
role="support",
is_active=True,
)
operator = User(
username="availability-operator",
password_hash="h",
role="operation",
is_active=True,
)
with pytest.raises(HTTPException) as exc_info:
checker(current_user=support)
assert exc_info.value.status_code == 403
assert checker(current_user=operator) is operator
class TestWorkbenchReadPath(_Base):
def mapped_task(self, mapping: PlatformCommodityMapping, index: int):
task = self.task(mapped=False)
task.source_order_item_id = f"workbench-{index}"
task.platform_order_id = f"WORKBENCH-{index}"
task.commodity_mapping_id = mapping.id
task.commodity_id = mapping.commodity_id
task.required_points = mapping.required_points
task.execution_status = "ready"
self.session.commit()
return task
def test_all_queue_includes_mapped_and_unmapped_tasks(self):
views.invalidate_task_list_count_cache()
self.task()
unmapped = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="all-unmapped",
source_order_item_id="all-unmapped",
platform_order_id="ALL-UNMAPPED",
internal_sku_key="all-unmapped",
execution_status="pending_mapping",
binding_status="not_started",
exchange_status="not_started",
paid_at=NOW,
created_at=NOW,
updated_at=NOW,
)
self.session.add(unmapped)
self.session.commit()
default_result = service.list_tasks(self.session, page_size=100)
all_result = service.list_tasks(
self.session,
queue_bucket="all",
page_size=100,
)
assert default_result["pagination"]["total"] == 1
assert all_result["pagination"]["total"] == 2
def test_pending_mapping_queue_shows_unmapped_tasks(self):
views.invalidate_task_list_count_cache()
task = self.task(mapped=False)
result = service.list_tasks(
self.session,
queue_bucket="pending_mapping",
page_size=100,
)
assert [item["id"] for item in result["items"]] == [task.id]
assert result["items"][0]["executionStatus"] == "pending_mapping"
def test_task_list_count_uses_short_ttl_cache_until_invalidated(self):
views.invalidate_task_list_count_cache()
mapping = self.mapping()
self.mapped_task(mapping, 1)
first = service.list_tasks(self.session, page_size=100)
assert first["pagination"]["total"] == 1
self.mapped_task(mapping, 2)
cached = service.list_tasks(self.session, page_size=100)
assert cached["pagination"]["total"] == 1
views.invalidate_task_list_count_cache()
refreshed = service.list_tasks(self.session, page_size=100)
assert refreshed["pagination"]["total"] == 2
def test_task_list_loads_relations_in_batches(self):
mapping = self.mapping()
for index in range(5):
self.mapped_task(mapping, index)
views.invalidate_task_list_count_cache()
queries: list[str] = []
def count_query(
_conn,
_cursor,
statement,
_parameters,
_context,
_executemany,
):
queries.append(statement)
event.listen(self.engine, "before_cursor_execute", count_query)
try:
result = service.list_tasks(self.session, page_size=100)
finally:
event.remove(self.engine, "before_cursor_execute", count_query)
assert len(result["items"]) == 5
# COUNT + 分页 + 固定 6 组关联数据,不再随行数增长成 N+1。
assert len(queries) <= 10
class TestSyncAndMapping(_Base):
def test_sync_skips_external_orders_when_no_mapping_is_configured(
self, monkeypatch
):
monkeypatch.setattr(
service.order_sync,
"list_pending_manual_fulfillments",
lambda **_kwargs: (_ for _ in ()).throw(
AssertionError("没有映射时不应查询 order_site")
),
)
result = service.sync_pending_tasks(self.session, limit=10)
assert result["fetched"] == 0
assert result["created"] == 0
assert result["configuredSkuCount"] == 0
assert self.session.query(PlatformFulfillmentTask).count() == 0
def test_sync_is_idempotent_and_applies_mapping(self, monkeypatch):
self.mapping()
cutoff = NOW - timedelta(days=1)
captured_keys: list[str] = []
captured_cutoff: list[datetime | None] = []
def _rows(
*,
limit: int,
internal_sku_keys: list[str],
paid_at_from: datetime | None,
):
del limit
captured_keys.extend(internal_sku_keys)
captured_cutoff.append(paid_at_from)
return [
{
"source_order_id": "100",
"source_order_item_id": "101",
"source_fulfillment_id": "201",
"platform_order_id": "ORDER-101",
"provider": "91kaquan",
"shop_id": "shop-1",
"shop_name": "测试店",
"sku_code": INTERNAL_SKU,
"sku_name": INTERNAL_SKU,
"internal_sku_key": INTERNAL_SKU,
"quantity": 1,
"revenue_amount_fen": 9900,
"total_amount": 9900,
"paid_at": NOW,
"item_updated_at": NOW,
}
]
monkeypatch.setattr(
service.order_sync,
"list_pending_manual_fulfillments",
_rows,
)
first = service.sync_pending_tasks(self.session, limit=10)
second = service.sync_pending_tasks(self.session, limit=10)
assert first["created"] == 1
assert second["created"] == 0
assert captured_keys == [INTERNAL_SKU, INTERNAL_SKU]
assert captured_cutoff == [cutoff, cutoff]
assert self.session.query(PlatformFulfillmentTask).count() == 1
task = self.session.query(PlatformFulfillmentTask).one()
assert task.execution_status == "ready"
assert task.commodity_id == COMMODITY
assert task.paid_at == NOW
def test_list_only_returns_tasks_that_have_a_commodity_mapping(self):
legacy = self.task(mapped=False)
mapping = self.mapping()
mapped = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="102",
source_order_item_id="103",
source_fulfillment_id="203",
platform_order_id="ORDER-103",
provider="91kaquan",
shop_id="shop-1",
shop_name="测试店",
sku_code=INTERNAL_SKU,
sku_name=INTERNAL_SKU,
internal_sku_key=INTERNAL_SKU,
quantity=1,
order_amount_fen=9900,
target_platform="douyu",
scope="elite",
commodity_mapping_id=mapping.id,
commodity_id=COMMODITY,
required_points=1280,
binding_status="not_started",
execution_status="ready",
exchange_status="not_started",
source_snapshot_json={"order_no": "ORDER-103"},
paid_at=NOW,
created_at=NOW,
updated_at=NOW,
)
self.session.add(mapped)
self.session.commit()
listed = service.list_tasks(self.session)
assert [item["id"] for item in listed["items"]] == [mapped.id]
assert listed["pagination"]["total"] == 1
assert legacy.id != mapped.id
def test_list_searches_assigned_douyu_account_identity(self):
task = self.task()
account = self.account("douyu-search-account")
account.nickname = "斗鱼昵称-搜索"
account.uid = "90000123"
task.account_id = account.id
self.session.commit()
for keyword in ("douyu-search-account", "斗鱼昵称-搜索", "90000123"):
listed = service.list_tasks(self.session, keyword=keyword)
assert listed["pagination"]["total"] == 1
assert listed["items"][0]["id"] == task.id
assert listed["items"][0]["account"]["id"] == account.id
def test_list_hides_tasks_paid_before_order_match_cutoff(self):
mapping = self.mapping()
task = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="104",
source_order_item_id="105",
source_fulfillment_id="205",
platform_order_id="ORDER-105",
sku_code=INTERNAL_SKU,
sku_name=INTERNAL_SKU,
internal_sku_key=INTERNAL_SKU,
quantity=1,
target_platform="douyu",
scope="elite",
commodity_mapping_id=mapping.id,
commodity_id=COMMODITY,
required_points=1280,
binding_status="not_started",
execution_status="ready",
exchange_status="not_started",
paid_at=NOW - timedelta(hours=2),
created_at=NOW,
updated_at=NOW,
)
self.session.add(task)
self.session.commit()
service.update_settings(
self.session,
lease_duration_minutes=None,
order_match_started_at=NOW - timedelta(hours=1),
current=self.admin,
)
listed = service.list_tasks(self.session)
assert listed["pagination"]["total"] == 0
def test_list_order_is_stable_by_paid_time_not_updated_at(self):
first = self.task()
second = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="108",
source_order_item_id="109",
source_fulfillment_id="209",
platform_order_id="ORDER-109",
provider="91kaquan",
shop_id="shop-1",
shop_name="测试店",
sku_code=INTERNAL_SKU,
sku_name=INTERNAL_SKU,
internal_sku_key=INTERNAL_SKU,
quantity=1,
order_amount_fen=9900,
target_platform="douyu",
scope="elite",
commodity_mapping_id=first.commodity_mapping_id,
commodity_id=COMMODITY,
required_points=1280,
binding_status="not_started",
execution_status="ready",
exchange_status="not_started",
paid_at=NOW + timedelta(minutes=1),
created_at=NOW,
updated_at=NOW,
)
self.session.add(second)
self.session.commit()
# 模拟 worker 重试:旧订单的 updated_at 变得更新,但列表顺序不能跳。
first.updated_at = NOW + timedelta(minutes=10)
self.session.commit()
listed = service.list_tasks(self.session)
assert [item["id"] for item in listed["items"]] == [second.id, first.id]
def test_list_includes_recent_paid_task_created_before_order_match_cutoff(self):
mapping = self.mapping()
task = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="106",
source_order_item_id="107",
source_fulfillment_id="207",
platform_order_id="ORDER-107",
sku_code=INTERNAL_SKU,
sku_name=INTERNAL_SKU,
internal_sku_key=INTERNAL_SKU,
quantity=1,
target_platform="douyu",
scope="elite",
commodity_mapping_id=mapping.id,
commodity_id=COMMODITY,
required_points=1280,
binding_status="not_started",
execution_status="ready",
exchange_status="not_started",
paid_at=NOW,
created_at=NOW - timedelta(hours=2),
updated_at=NOW,
)
self.session.add(task)
self.session.commit()
service.update_settings(
self.session,
lease_duration_minutes=None,
order_match_started_at=NOW - timedelta(hours=1),
current=self.admin,
)
listed = service.list_tasks(self.session)
assert [item["id"] for item in listed["items"]] == [task.id]
def test_customer_session_ignores_task_before_order_match_cutoff(
self,
monkeypatch,
):
task = self.task()
assert task.paid_at is not None
service.update_settings(
self.session,
lease_duration_minutes=None,
order_match_started_at=task.paid_at + timedelta(minutes=1),
current=self.admin,
)
monkeypatch.setattr(
service.order_sync,
"lookup_pending_manual_fulfillment",
lambda *_args, **_kwargs: None,
)
with pytest.raises(HTTPException) as exc_info:
service.ensure_customer_session(
self.session,
source_order_item_id=task.source_order_item_id,
platform_order_id=task.platform_order_id,
)
assert exc_info.value.status_code == 404
def test_upsert_mapping_advances_existing_task(self):
task = self.task(mapped=False)
self.session.add(
DouyuGoodsSnapshot(
commodity_id=COMMODITY,
name=INTERNAL_SKU,
score=1280,
)
)
self.session.commit()
service.upsert_mapping(
self.session,
internal_sku_key=INTERNAL_SKU,
commodity_id=COMMODITY,
goods_name="",
required_points=None,
enabled=True,
current=self.admin,
)
self.session.refresh(task)
assert task.execution_status == "ready"
assert task.commodity_id == COMMODITY
assert task.required_points == 1280
assert task.sale_mode == "unknown"
assert task.campaign_key == "douyu-current"
assert task.classification_source == "unknown"
def test_mapping_sale_mode_is_snapshotted_and_drives_presale_queue(self):
task = self.task(mapped=False)
self.session.add(
DouyuGoodsSnapshot(
commodity_id=COMMODITY,
name=INTERNAL_SKU,
score=1280,
)
)
self.session.commit()
available_from = NOW + timedelta(days=1)
mapping = service.create_mapping(
self.session,
internal_sku_key=INTERNAL_SKU,
campaign_key="douyu-2026-12-return",
campaign_name="12 月返场",
commodity_id=COMMODITY,
goods_name=INTERNAL_SKU,
required_points=1280,
sale_mode="presale",
available_from=available_from,
available_until=available_from + timedelta(days=7),
released_at=None,
enabled=True,
current=self.admin,
)
self.session.refresh(task)
detail = service.get_task_detail(self.session, task.id)
assert mapping["saleMode"] == "presale"
assert mapping["availabilityState"] == "waiting_release"
assert task.sale_mode == "presale"
assert task.campaign_key == "douyu-2026-12-return"
assert task.classification_source == "mapping"
assert detail["task"]["queueBucket"] == "presale_waiting"
assert detail["task"]["availabilityState"] == "waiting_release"
def test_mapping_crud_archive_and_delete_guard(self):
task = self.task(mapped=False)
self.session.commit()
created = service.create_mapping(
self.session,
internal_sku_key=INTERNAL_SKU,
campaign_key="douyu-2026-12-direct",
campaign_name="12 月现货",
commodity_id=COMMODITY,
goods_name=INTERNAL_SKU,
required_points=1280,
sale_mode="direct",
available_from=NOW,
available_until=NOW + timedelta(days=30),
released_at=NOW,
enabled=True,
current=self.admin,
)
updated = service.update_mapping(
self.session,
mapping_id=created["id"],
internal_sku_key=INTERNAL_SKU,
campaign_key="douyu-2026-12-direct",
campaign_name="12 月现货修正",
commodity_id=COMMODITY,
goods_name="套装-兔兔白日梦(斗鱼)",
required_points=1280,
sale_mode="direct",
available_from=NOW,
available_until=NOW + timedelta(days=30),
released_at=NOW,
enabled=True,
current=self.admin,
)
assert updated["campaignName"] == "12 月现货修正"
assert updated["version"] == 2
with pytest.raises(HTTPException, match="只能归档"):
service.delete_mapping(self.session, mapping_id=created["id"])
archived = service.archive_mapping(
self.session,
mapping_id=created["id"],
current=self.admin,
)
self.session.refresh(task)
assert archived["archivedAt"] is not None
assert task.execution_status == "pending_mapping"
class TestFulfillmentCollabSync(_Base):
def _task_with_account(
self,
*,
execution_status: str = "ready",
) -> PlatformFulfillmentTask:
task = self.task()
account = self.account("collab-sync-account")
task.account_id = account.id
task.execution_status = execution_status
self.session.commit()
return task
def test_manual_sync_creates_projected_collab_order(self):
task = self._task_with_account()
self.complete_customer_profile(task)
mapping = self.session.query(PlatformCommodityMapping).one()
mapping.goods_name = "套装-兔兔白日梦(斗鱼)"
self.session.add(
DouyuGoodsSnapshot(
commodity_id=COMMODITY,
name="不应覆盖显式映射",
score=999,
)
)
bind_task = DouyuTask(
batch_id="collab-sync-bind",
account_id=task.account_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"role_name": "已确认角色",
"bind_confirmed": True,
"area_name": "微信",
"plat_name": "苹果(iOS)",
},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
self.session.commit()
order, action = collab.sync_platform_fulfillment_order(
self.session,
self.admin,
task,
)
assert action == "created"
assert order.order_no == task.platform_order_id
assert order.source_type == "platform_fulfillment"
assert order.source_task_id == task.id
assert order.source_order_id == task.source_order_id
assert order.source_order_item_id == task.source_order_item_id
assert order.source_platform_order_id == task.platform_order_id
assert order.last_synced_at is not None
assert order.shop == task.shop_name
assert order.gift_name == "套装-兔兔白日梦(斗鱼)"
assert order.commodity_id == COMMODITY
assert order.required_points == 1280
assert order.account_id == task.account_id
assert order.account_username == "collab-sync-account"
assert order.home_images == ["https://example.com/game-home.png"]
assert order.bind_game_role == "已确认角色"
assert order.bind_game_channel == "微信 / 苹果(iOS)"
assert order.status == collab.STATUS_INCOMPLETE
payload = DouyuCollabOrderOut.model_validate(
collab.serialize_one(self.session, order)
).model_dump()
assert payload["source_task_id"] == task.id
assert payload["source_platform_order_id"] == task.platform_order_id
assert payload["home_image_urls"] == ["https://example.com/game-home.png"]
assert payload["home_image_thumb_urls"] == ["https://example.com/game-home.png"]
assert (
self.session.query(AccountEvent)
.filter(AccountEvent.event_type == "collab_synced")
.count()
== 1
)
lease = self.session.query(AccountLease).one()
assert lease.purpose == "douyu_collab"
def test_platform_sync_replaces_account_and_role_after_reallocation(self):
"""履约单释放后重选账号,台账必须清掉首单角色并投影新账号。"""
task = self._task_with_account()
old_account = self.session.get(Account, task.account_id)
old_bind = DouyuTask(
batch_id="collab-old-account-bind",
account_id=old_account.id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"role_name": "旧角色",
"bind_confirmed": True,
"area_name": "微信",
"plat_name": "苹果(iOS)",
},
created_by=self.admin_id,
)
self.session.add(old_bind)
self.session.flush()
task.bind_task_id = old_bind.id
task.binding_status = "bound"
task.execution_status = "bound"
self.session.commit()
order, _ = collab.sync_platform_fulfillment_order(
self.session,
self.admin,
task,
)
assert order.account_id == old_account.id
assert order.bind_game_role == "旧角色"
replacement = self.account("collab-replacement-account")
replacement.role_bind_status = "bound"
replacement.game_name = "新角色"
replacement.game_channel = "手Q · 安卓(android)"
task.account_id = replacement.id
task.bind_task_id = None
task.binding_status = "not_started"
task.execution_status = "allocated"
self.session.commit()
reallocated, _ = collab.sync_platform_fulfillment_order(
self.session,
self.admin,
task,
)
assert reallocated.account_id == replacement.id
assert reallocated.account_username == replacement.username
assert reallocated.bind_game_role == ""
assert reallocated.bind_game_channel == ""
assert reallocated.bind_snapshot_at is None
new_bind = DouyuTask(
batch_id="collab-new-account-bind",
account_id=replacement.id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"role_name": "新角色",
"bind_confirmed": True,
"area_name": "手Q",
"plat_name": "安卓(android)",
},
created_by=self.admin_id,
)
self.session.add(new_bind)
self.session.flush()
task.bind_task_id = new_bind.id
task.binding_status = "bound"
task.execution_status = "bound"
self.session.commit()
rebound, _ = collab.sync_platform_fulfillment_order(
self.session,
self.admin,
task,
)
assert rebound.account_id == replacement.id
assert rebound.bind_game_role == "新角色"
assert rebound.bind_game_channel == "手Q / 安卓(android)"
assert rebound.bind_snapshot_at is not None
def test_manual_sync_does_not_clear_account_added_in_collab(self):
task = self.task()
order, _ = collab.sync_platform_fulfillment_order(
self.session,
self.admin,
task,
)
account = self.account("manual-collab-account")
order.account_id = account.id
order.account_username = account.username
self.session.commit()
synced, _ = collab.sync_platform_fulfillment_order(
self.session,
self.admin,
task,
)
assert synced.account_id == account.id
assert synced.account_username == account.username
def test_manual_sync_backfills_customer_home_images(self):
task = self._task_with_account()
order, _ = collab.sync_platform_fulfillment_order(
self.session,
self.admin,
task,
)
assert not order.home_images
self.complete_customer_profile(task)
synced, action = collab.sync_platform_fulfillment_order(
self.session,
self.admin,
task,
)
assert action == "updated"
assert synced.home_images == ["https://example.com/game-home.png"]
def test_manual_sync_is_idempotent_and_preserves_human_fields(self):
task = self._task_with_account()
order, _ = collab.sync_platform_fulfillment_order(
self.session,
self.admin,
task,
)
other_owner = User(
username="collab-owner",
password_hash="h",
role="operator",
)
self.session.add(other_owner)
self.session.commit()
order.owner_id = other_owner.id
order.fish_fin_balance = 321
order.points_balance = 654
order.points_check_message = "人工核账快照"
order.remark = "客服人工备注"
order.order_no = f"PF{task.id}"
self.session.commit()
synced, action = collab.sync_platform_fulfillment_order(
self.session,
self.admin,
task,
)
assert action == "updated"
assert self.session.query(DouyuExternalOrder).count() == 1
assert synced.id == order.id
assert synced.order_no == task.platform_order_id
assert synced.owner_id == other_owner.id
assert synced.fish_fin_balance == 321
assert synced.points_balance == 654
assert synced.points_check_message == "人工核账快照"
assert synced.remark == "客服人工备注"
def test_manual_sync_links_existing_collab_order_with_real_order_no(self):
task = self.task()
manual = DouyuExternalOrder(
order_no=task.platform_order_id,
shop="人工先建单",
owner_id=self.admin.id,
remark="人工备注保留",
status="to_recharge",
created_by=self.admin.id,
updated_by=self.admin.id,
)
self.session.add(manual)
self.session.commit()
synced, action = collab.sync_platform_fulfillment_order(
self.session,
self.admin,
task,
)
assert action == "updated"
assert synced.id == manual.id
assert synced.order_no == task.platform_order_id
assert synced.source_type == "platform_fulfillment"
assert synced.source_task_id == task.id
assert synced.remark == "人工备注保留"
def test_manual_sync_preserves_existing_collab_account_and_role(self):
task = self.task()
task_account = self.account("task-account")
manual_account = self.account("manual-account")
task.account_id = task_account.id
manual = DouyuExternalOrder(
order_no=task.platform_order_id,
account_id=manual_account.id,
account_username=manual_account.username,
bind_game_role="人工绑定角色",
bind_game_channel="手工渠道",
status="to_recharge",
)
self.session.add(manual)
self.session.commit()
synced, action = collab.sync_platform_fulfillment_order(
self.session,
self.admin,
task,
)
assert action == "updated"
assert synced.id == manual.id
assert synced.account_id == manual_account.id
assert synced.account_username == manual_account.username
assert synced.bind_game_role == "人工绑定角色"
assert synced.bind_game_channel == "手工渠道"
assert synced.status == "to_recharge"
def test_manual_sync_maps_only_safe_terminal_statuses(self):
task = self._task_with_account()
order, _ = collab.sync_platform_fulfillment_order(
self.session,
self.admin,
task,
)
order.status = collab.STATUS_TO_RECHARGE
self.session.commit()
task.execution_status = "completed"
task.completed_at = NOW
self.session.commit()
order, _ = collab.sync_platform_fulfillment_order(
self.session,
self.admin,
task,
)
assert order.status == collab.STATUS_DONE
assert order.done_at == NOW
cancelled = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="200",
source_order_item_id="201",
source_fulfillment_id="301",
platform_order_id="ORDER-201",
sku_code=INTERNAL_SKU,
sku_name=INTERNAL_SKU,
internal_sku_key=INTERNAL_SKU,
commodity_mapping_id=task.commodity_mapping_id,
commodity_id=COMMODITY,
required_points=1280,
execution_status="cancelled",
paid_at=NOW,
created_at=NOW,
updated_at=NOW,
)
self.session.add(cancelled)
self.session.commit()
cancelled_order, action = collab.sync_platform_fulfillment_order(
self.session,
self.admin,
cancelled,
)
assert action == "created"
assert cancelled_order.status == collab.STATUS_VOID
assert cancelled_order.void_reason == "直播履约任务已取消"
def test_manual_sync_batch_reports_created_and_missing(self):
first = self.task()
second = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="300",
source_order_item_id="301",
source_fulfillment_id="401",
platform_order_id="ORDER-301",
sku_code=INTERNAL_SKU,
sku_name=INTERNAL_SKU,
internal_sku_key=INTERNAL_SKU,
commodity_mapping_id=first.commodity_mapping_id,
commodity_id=COMMODITY,
required_points=1280,
execution_status="ready",
paid_at=NOW,
created_at=NOW,
updated_at=NOW,
)
self.session.add(second)
self.session.commit()
result = collab.sync_platform_fulfillment_orders(
self.session,
self.admin,
task_ids=[first.id, second.id, 99999999],
)
assert result["requested"] == 3
assert result["created"] == 2
assert result["updated"] == 0
assert result["skipped"] == 1
assert result["failed"] == 0
assert [item["action"] for item in result["items"]] == [
"created",
"created",
"skipped",
]
def test_task_list_exposes_linked_collab_order(self):
task = self._task_with_account()
order, _ = collab.sync_platform_fulfillment_order(
self.session,
self.admin,
task,
)
listed = service.list_tasks(self.session)
assert listed["items"][0]["collabOrder"] == {
"id": order.id,
"orderNo": order.order_no,
"status": collab.STATUS_INCOMPLETE,
"lastSyncedAt": order.last_synced_at,
}
class TestDouyuOperationTimeline(_Base):
def test_operation_start_and_result_are_written_once(self):
task = self.task()
account = self.account("operation-timeline-account")
task.account_id = account.id
self.session.commit()
douyu_task = DouyuTask(
batch_id="platform-operation",
account_id=account.id,
account_assigned_to=account.assigned_to,
task_type="create_gold_qr",
handbook_scope="elite",
status="planned",
created_by=self.admin_id,
platform_task_id=task.id,
)
self.session.add(douyu_task)
self.session.commit()
service.record_douyu_operation_started(
self.session,
task,
current=self.admin,
batch_id=douyu_task.batch_id,
task_type=douyu_task.task_type,
douyu_task_ids=[douyu_task.id],
payload={"amount": 18},
)
service.record_douyu_operation_result(
self.session,
douyu_task,
status="success",
message="充值鱼翅成功",
)
service.record_douyu_operation_result(
self.session,
douyu_task,
status="success",
message="充值鱼翅成功",
)
self.session.commit()
detail = service.get_task_detail(self.session, task.id)
operation_events = [
event
for event in detail["events"]
if event["eventType"].startswith("douyu_operation_")
]
assert [event["eventType"] for event in operation_events] == [
"douyu_operation_succeeded",
"douyu_operation_started",
]
assert operation_events[0]["detail"]["douyuTaskId"] == douyu_task.id
assert operation_events[1]["detail"]["batchId"] == douyu_task.batch_id
def test_binding_failure_event_uses_raw_confirm_error_classification(self):
task = self.task()
account = self.account("operation-customer-cooldown")
task.account_id = account.id
self.session.commit()
douyu_task = DouyuTask(
batch_id="platform-customer-cooldown",
account_id=account.id,
account_assigned_to=account.assigned_to,
task_type="confirm_bind",
handbook_scope="elite",
status="failed",
message="斗鱼账号当前绑定角色(旧角色)未到可换绑时间",
result={
"issue_code": "account_role_cooldown",
"bind_phase": "confirm_failed",
"role_name": "客户角色",
"confirm_error": "该账号未到可换绑时间,请使用其他账号",
"confirm_error_code": -200001,
},
created_by=self.admin_id,
platform_task_id=task.id,
)
self.session.add(douyu_task)
self.session.commit()
service.record_douyu_operation_result(
self.session,
douyu_task,
status="failed",
message=douyu_task.message,
)
self.session.commit()
event = (
self.session.query(PlatformFulfillmentEvent)
.filter(
PlatformFulfillmentEvent.task_id == task.id,
PlatformFulfillmentEvent.event_type == "douyu_operation_failed",
)
.one()
)
assert event.detail_json["issueCode"] == "customer_role_cooldown"
assert "待绑定游戏账号(客户角色)" in event.detail_json["message"]
class TestSnapshotSync(_Base):
def snapshot(self, **overrides):
payload = {
"sourceOrderId": "100",
"sourceOrderItemId": "101",
"sourceFulfillmentId": "201",
"platformOrderId": "ORDER-101",
"provider": "91kaquan",
"shopId": "shop-1",
"shopName": "测试店",
"orderStatus": "paid",
"payStatus": "paid",
"skuCode": INTERNAL_SKU,
"skuName": INTERNAL_SKU,
"internalSkuKey": INTERNAL_SKU,
"quantity": 1,
"revenueAmountFen": 9900,
"orderCreatedAt": NOW.isoformat(),
"paidAt": NOW.isoformat(),
"fulfillmentStatus": "assigned",
"fulfillmentChannel": "manual",
"configEnabled": True,
"douyuFulfillmentEnabled": True,
}
payload.update(overrides)
return payload
def test_order_snapshot_creates_task_without_external_database_read(
self, monkeypatch
):
self.mapping()
monkeypatch.setattr(
service.order_sync,
"lookup_pending_manual_fulfillment",
lambda *_args, **_kwargs: (_ for _ in ()).throw(
AssertionError("新快照契约不应回查 order_site")
),
)
result = service.sync_order_snapshot(
self.session,
{
"eventType": "platform_fulfillment.order_snapshot",
"contractVersion": 2,
"data": self.snapshot(),
},
)
task = self.session.query(PlatformFulfillmentTask).one()
assert result["created"] == 1
assert task.execution_status == "ready"
assert task.next_allocate_at is not None
assert task.state_version == 1
detail = service.get_task_detail(self.session, task.id)
assert detail["task"]["goodsName"] == INTERNAL_SKU
outbox = self.session.query(IntegrationOutbox).one()
assert outbox.payload_json["items"][0]["stateVersion"] == 1
def test_snapshot_before_clean_cutover_creates_legacy_task(self):
self.mapping()
setting = self.session.get(PlatformFulfillmentSetting, 1)
setting.clean_flow_started_at = NOW
self.session.commit()
service.sync_order_snapshot(
self.session,
{"data": self.snapshot(paidAt=(NOW - timedelta(hours=1)).isoformat())},
)
task = self.session.query(PlatformFulfillmentTask).one()
assert task.flow_version == 1
assert (
service.list_tasks(self.session, flow_version=2)["pagination"]["total"] == 0
)
assert (
service.list_tasks(self.session, flow_version=1)["pagination"]["total"] == 1
)
def test_legacy_task_is_frozen_against_snapshot_transitions(self):
task = self.task()
task.flow_version = 1
self.session.commit()
service.sync_order_snapshot(
self.session,
{
"data": self.snapshot(
orderStatus="refunded", douyuFulfillmentEnabled=False
)
},
)
self.session.refresh(task)
assert task.flow_version == 1
assert task.execution_status == "ready"
assert task.issue_code == ""
assert task.source_snapshot_json["orderStatus"] == "refunded"
def test_snapshot_after_clean_cutover_creates_clean_task(self):
self.mapping()
setting = self.session.get(PlatformFulfillmentSetting, 1)
setting.clean_flow_started_at = NOW - timedelta(hours=1)
self.session.commit()
service.sync_order_snapshot(self.session, {"data": self.snapshot()})
task = self.session.query(PlatformFulfillmentTask).one()
assert task.flow_version == 2
def test_legacy_list_ignores_order_match_cutoff(self):
task = self.task()
task.flow_version = 1
task.paid_at = NOW - timedelta(days=10)
self.session.commit()
listed = service.list_tasks(self.session, flow_version=1)
assert listed["pagination"]["total"] == 1
assert listed["items"][0]["flowVersion"] == 1
def test_duplicate_snapshot_keeps_allocated_task_state(self):
self.mapping()
account = self.account("snapshot-allocated")
service.sync_order_snapshot(self.session, {"data": self.snapshot()})
task = self.session.query(PlatformFulfillmentTask).one()
service.allocate_task(
self.session,
task_id=task.id,
current=self.admin,
)
service.sync_order_snapshot(self.session, {"data": self.snapshot()})
self.session.refresh(task)
assert task.execution_status == "allocated"
assert task.account_id == account.id
assert task.lease_id is not None
assert task.next_allocate_at is None
assert task.exchange_status == "eligible"
assert task.issue_code == ""
def test_duplicate_snapshot_preserves_allocation_retry(self):
self.mapping()
service.sync_order_snapshot(self.session, {"data": self.snapshot()})
task = self.session.query(PlatformFulfillmentTask).one()
retry_at = NOW + timedelta(seconds=45)
task.issue_code = "no_eligible_account"
task.last_error = "当前没有可用账号"
task.next_allocate_at = retry_at
self.session.commit()
service.sync_order_snapshot(self.session, {"data": self.snapshot()})
self.session.refresh(task)
assert task.execution_status == "ready"
assert task.issue_code == "no_eligible_account"
assert task.last_error == "当前没有可用账号"
assert task.next_allocate_at == retry_at
def test_legacy_event_only_reads_the_specified_order_item(self, monkeypatch):
self.mapping()
requested: list[str] = []
def lookup(item_id: str):
requested.append(item_id)
return self.snapshot()
monkeypatch.setattr(
service.order_sync,
"lookup_pending_manual_fulfillment",
lookup,
)
result = service.sync_order_item_ids(self.session, ["101"])
assert requested == ["101"]
assert result["created"] == 1
assert self.session.query(PlatformFulfillmentTask).count() == 1
def test_terminal_snapshot_cancels_task_and_increments_state_version(self):
self.mapping()
service.sync_order_snapshot(self.session, {"data": self.snapshot()})
service.sync_order_snapshot(
self.session,
{"data": self.snapshot(orderStatus="refunded")},
)
task = self.session.query(PlatformFulfillmentTask).one()
assert task.execution_status == "cancelled"
assert task.state_version == 2
assert task.next_allocate_at is None
def test_valid_snapshot_restores_source_cancelled_task(self):
self.mapping()
service.sync_order_snapshot(self.session, {"data": self.snapshot()})
service.sync_order_snapshot(
self.session,
{"data": self.snapshot(douyuFulfillmentEnabled=False)},
)
task = self.session.query(PlatformFulfillmentTask).one()
assert task.execution_status == "cancelled"
assert task.issue_code == "source_cancelled"
service.sync_order_snapshot(self.session, {"data": self.snapshot()})
self.session.refresh(task)
assert task.execution_status == "ready"
assert task.issue_code == ""
assert task.last_error == ""
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="source_order_restored")
.count()
== 1
)
def test_unpaid_snapshot_does_not_enter_live_fulfillment(self):
self.mapping()
result = service.sync_order_snapshot(
self.session,
{"data": self.snapshot(payStatus="unpaid")},
)
assert result["created"] == 0
assert result["ignored"] == 1
assert self.session.query(PlatformFulfillmentTask).count() == 0
class TestAccountSelection(_Base):
def test_capability_candidate_query_selects_only_selection_columns(self):
query = account_selector._capability_candidate_query(
self.session,
commodity_id=COMMODITY,
required_points=1280,
now=NOW,
)
assert query is not None
selected = {
str(description["name"]) for description in query.column_descriptions
}
assert {
"account_id",
"account_username",
"account_points",
"account_elite_opened",
"state_offer_state",
"state_observed_at",
} <= selected
assert {
"account_cookie",
"account_overview_snapshot",
"account_ck_check_result",
"state_raw_json",
"state_schedule_json",
}.isdisjoint(selected)
def test_manual_allocation_request_only_marks_task_due(self):
task = self.task()
old_retry_at = task.next_allocate_at
detail = service.prepare_manual_allocation(
self.session,
task_id=task.id,
current=self.admin,
)
self.session.refresh(task)
assert detail["task"]["account"] is None
assert task.next_allocate_at is not None
assert old_retry_at is None or task.next_allocate_at >= old_retry_at
def test_manual_allocation_allows_rebind_after_released_binding_failure(self):
task = self.task()
task.execution_status = "manual_required"
task.binding_status = "failed"
task.issue_code = "binding_failed"
task.last_error = "绑定二维码已过期"
self.session.commit()
detail = service.prepare_manual_allocation(
self.session,
task_id=task.id,
current=self.admin,
)
self.session.refresh(task)
assert detail["task"]["executionStatus"] == "ready"
assert task.execution_status == "ready"
assert task.binding_status == "not_started"
assert task.issue_code == ""
assert task.next_allocate_at is not None
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_retry_requested")
.count()
== 1
)
def test_capability_match_uses_local_index_without_live_probe(self):
account = self.account("capability-fast", capability=False)
task = self.task()
self.session.add(
AccountCommodityState(
account_id=account.id,
platform="douyu",
scope="elite",
commodity_id=COMMODITY,
commodity_name=INTERNAL_SKU,
account_eligibility="eligible",
offer_state="active",
stock_state="in_stock",
availability="available",
observed_at=NOW,
valid_until=NOW + timedelta(minutes=15),
source="overview",
)
)
self.session.commit()
detail = service.allocate_task(
self.session,
task_id=task.id,
current=self.admin,
)
assert detail["task"]["account"]["id"] == account.id
assert detail["task"]["executionStatus"] == "allocated"
def test_allocation_reports_role_cooldown_without_fast_retry_loop(self):
self.account(
"capability-role-cooldown",
points=2000,
role_available_at=NOW + timedelta(days=2),
)
task = self.task()
detail = service.allocate_task(
self.session,
task_id=task.id,
current=self.admin,
)
self.session.refresh(task)
assert detail["task"]["account"] is None
assert detail["task"]["issueCode"] == "account_role_cooldown"
assert task.next_allocate_at is not None
assert task.next_allocate_at >= NOW + timedelta(minutes=4)
event = (
self.session.query(PlatformFulfillmentEvent)
.filter(PlatformFulfillmentEvent.event_type == "account_allocation_failed")
.order_by(PlatformFulfillmentEvent.id.desc())
.first()
)
assert event.detail_json["retryReason"] == "account_role_cooldown"
assert event.detail_json["availabilityCounts"]["account:eligible"] == 1
assert event.detail_json["availabilityCounts"]["account:roleCooldown"] == 1
def test_missing_capability_does_not_fall_back_to_live_scan(self):
self.account("live-fallback", capability=False)
task = self.task()
detail = service.allocate_task(
self.session,
task_id=task.id,
current=self.admin,
)
assert detail["task"]["account"] is None
assert detail["task"]["executionStatus"] == "ready"
assert detail["task"]["issueCode"] == "capability_cache_miss"
work_item = self.session.query(AccountWorkItem).one()
assert work_item.work_type == WORK_STOREHOME_SYNC
assert work_item.priority == 20
def test_legacy_mode_env_cannot_enable_live_scan(self, monkeypatch):
monkeypatch.setenv("PLATFORM_FULFILLMENT_MATCH_MODE", "legacy")
self.account("forced-local-selection", capability=False)
task = self.task()
detail = service.allocate_task(
self.session,
task_id=task.id,
current=self.admin,
)
assert detail["task"]["account"] is None
assert detail["task"]["executionStatus"] == "ready"
assert detail["task"]["issueCode"] == "capability_cache_miss"
def test_live_candidates_exclude_support_assigned_accounts(self):
support = User(
username="pool-support",
password_hash="h",
role="support",
is_active=True,
)
self.session.add(support)
self.session.flush()
invalid = Account(
username="old-invalid",
password="p",
email="invalid@example.com",
email_password="ep",
status="invalid",
ck_check_status="invalid",
ck_checked_at=NOW - timedelta(days=2),
cookie="PHPSESSID=invalid",
auto_managed=True,
)
valid = Account(
username="support-valid",
password="p",
email="valid@example.com",
email_password="ep",
status="active",
ck_check_status="valid",
ck_checked_at=NOW - timedelta(days=1),
cookie="PHPSESSID=valid",
elite_opened=True,
points=2000,
auto_managed=True,
assigned_to=support.id,
)
self.session.add_all([invalid, valid])
self.session.commit()
rows = account_selector.live_candidate_accounts(
self.session,
required_points=1680,
)
assert [row.id for row in rows] == [invalid.id]
def test_points_short_is_soft_and_does_not_block_allocation(self):
account = self.account("points-short", points=100)
task = self.task()
detail = service.allocate_task(
self.session,
task_id=task.id,
current=self.admin,
)
assert detail["task"]["account"]["id"] == account.id
assert detail["task"]["executionStatus"] == "allocated"
assert detail["task"]["exchangeStatus"] == "points_short"
assert detail["task"]["issueCode"] == "points_short"
def test_elite_not_opened_is_soft_and_does_not_block_allocation(self):
account = self.account("elite-closed", opened=False)
task = self.task()
detail = service.allocate_task(
self.session,
task_id=task.id,
current=self.admin,
)
assert detail["task"]["account"]["id"] == account.id
assert detail["task"]["executionStatus"] == "allocated"
assert detail["task"]["exchangeStatus"] == "not_opened"
assert detail["task"]["issueCode"] == "elite_not_opened"
def test_presale_not_open_allows_allocation_and_advance_binding(self):
account = self.account("presale-future", availability="not_open")
task = self.task()
task.sale_mode = "presale"
self.session.commit()
detail = service.allocate_task(
self.session,
task_id=task.id,
current=self.admin,
)
assert detail["task"]["account"]["id"] == account.id
assert detail["task"]["executionStatus"] == "allocated"
assert detail["task"]["exchangeStatus"] == "waiting_release"
assert detail["task"]["issueCode"] == "commodity_not_open"
def test_presale_allocates_eligible_account_even_when_official_stock_is_zero(self):
account = self.account("presale-no-stock", capability=False)
self.session.add(
AccountCommodityState(
account_id=account.id,
platform="douyu",
scope="elite",
commodity_id=COMMODITY,
commodity_name=INTERNAL_SKU,
account_eligibility="eligible",
offer_state="before",
stock_state="out_of_stock",
availability="no_stock",
observed_at=NOW,
valid_until=NOW + timedelta(hours=1),
available_from=NOW + timedelta(days=4),
available_until=NOW + timedelta(days=10),
source="storehome_sync",
)
)
task = self.task()
task.sale_mode = "presale"
self.session.commit()
detail = service.allocate_task(
self.session,
task_id=task.id,
current=self.admin,
)
assert detail["task"]["account"]["id"] == account.id
assert detail["task"]["executionStatus"] == "allocated"
assert detail["task"]["exchangeStatus"] == "waiting_release"
def test_direct_sale_allows_allocation_and_advance_binding_when_not_open(self):
account = self.account("direct-future", availability="not_open")
task = self.task()
task.sale_mode = "direct"
self.session.commit()
detail = service.allocate_task(
self.session,
task_id=task.id,
current=self.admin,
)
assert detail["task"]["account"]["id"] == account.id
assert detail["task"]["executionStatus"] == "allocated"
assert detail["task"]["exchangeStatus"] == "waiting_release"
assert detail["task"]["issueCode"] == "commodity_not_open"
def test_capability_pool_includes_future_not_open_for_presale_only(self):
account = self.account("capability-future", capability=False)
self.session.add(
AccountCommodityState(
account_id=account.id,
platform="douyu",
scope="elite",
commodity_id=COMMODITY,
commodity_name=INTERNAL_SKU,
account_eligibility="eligible",
offer_state="before",
stock_state="in_stock",
availability="not_open",
blocking_reason="限时兑换未开始",
observed_at=NOW,
valid_until=NOW + timedelta(minutes=15),
available_from=NOW + timedelta(days=4),
available_until=NOW + timedelta(days=10),
source="storehome_sync",
)
)
self.session.commit()
assert (
account_selector.capability_candidate_accounts(
self.session,
commodity_id=COMMODITY,
required_points=1280,
now=NOW,
)
== []
)
assert [
row.id
for row in account_selector.capability_candidate_accounts(
self.session,
commodity_id=COMMODITY,
required_points=1280,
now=NOW,
allow_before_open=True,
)
] == [account.id]
def test_eligible_account_excludes_cooldown_and_uses_least_points(self):
self.account("small", points=1300)
self.account("large", points=9000)
self.account(
"cooldown",
points=1400,
role_available_at=NOW + timedelta(days=1),
)
candidates = account_selector.eligible_accounts(
self.session,
commodity_id=COMMODITY,
required_points=1280,
now=NOW,
)
assert [row.username for row in candidates] == ["small", "large"]
def test_active_collab_order_blocks_all_automatic_candidate_pools(self):
account = self.account(
"active-collab-candidate",
points=2000,
capability=False,
)
self.session.add(
AccountCommodityState(
account_id=account.id,
platform="douyu",
scope="elite",
commodity_id=COMMODITY,
commodity_name=INTERNAL_SKU,
account_eligibility="eligible",
offer_state="active",
stock_state="in_stock",
availability="available",
observed_at=NOW,
valid_until=NOW + timedelta(hours=1),
)
)
order = DouyuExternalOrder(
order_no="DY-ACTIVE-CANDIDATE",
account_id=account.id,
account_username=account.username,
status=collab.STATUS_TO_RECHARGE,
owner_id=self.admin.id,
created_by=self.admin.id,
)
self.session.add(order)
self.session.commit()
assert (
account_selector.eligible_accounts(
self.session,
commodity_id=COMMODITY,
required_points=1280,
now=NOW,
)
== []
)
assert (
account_selector.live_candidate_accounts(
self.session,
required_points=1280,
commodity_id=COMMODITY,
)
== []
)
assert (
account_selector.capability_candidate_accounts(
self.session,
commodity_id=COMMODITY,
required_points=1280,
now=NOW,
)
== []
)
order.status = collab.STATUS_DONE
self.session.commit()
assert [
row.account_id
for row in account_selector.eligible_accounts(
self.session,
commodity_id=COMMODITY,
required_points=1280,
now=NOW,
)
] == [account.id]
assert [
row.id
for row in account_selector.live_candidate_accounts(
self.session,
required_points=1280,
commodity_id=COMMODITY,
)
] == [account.id]
assert [
row.id
for row in account_selector.capability_candidate_accounts(
self.session,
commodity_id=COMMODITY,
required_points=1280,
now=NOW,
)
] == [account.id]
def test_lease_is_unique_per_account(self):
account = self.account("leased")
candidate = account_selector.eligible_accounts(
self.session,
commodity_id=COMMODITY,
required_points=1280,
now=NOW,
)[0]
first = account_selector.lease_account(
self.session,
candidate=candidate,
holder_user_id=self.admin_id,
task_id=1,
commodity_id=COMMODITY,
now=NOW,
)
second = account_selector.lease_account(
self.session,
candidate=candidate,
holder_user_id=self.admin_id,
task_id=2,
commodity_id=COMMODITY,
now=NOW,
)
assert first is not None
assert second is None
assert (
self.session.query(AccountLease).filter_by(account_id=account.id).count()
== 1
)
def test_allocate_and_release_task(self):
account = self.account("allocated")
task = self.task()
detail = service.allocate_task(
self.session,
task_id=task.id,
current=self.admin,
)
assert detail["task"]["account"]["id"] == account.id
assert detail["task"]["executionStatus"] == "allocated"
lease = self.session.query(AccountLease).one()
assert lease.purpose == "platform_fulfillment"
assert lease.status == "active"
assert lease.expires_at is None
acquired = (
self.session.query(AccountEvent)
.filter(
AccountEvent.account_id == account.id,
AccountEvent.event_type == "lease_acquired",
)
.one()
)
assert acquired.detail["task_id"] == task.id
released = service.release_task_account(
self.session,
task_id=task.id,
current=self.admin,
)
assert released["task"]["executionStatus"] == "ready"
self.session.refresh(lease)
assert lease.status == "released"
released_event = (
self.session.query(AccountEvent)
.filter(
AccountEvent.account_id == account.id,
AccountEvent.event_type == "lease_released",
)
.one()
)
assert released_event.detail["lease_id"] == lease.id
def test_lease_settings_support_unlimited_and_finite_duration(self):
self.account("settings-account")
task = self.task()
service.allocate_task(self.session, task_id=task.id, current=self.admin)
lease = self.session.query(AccountLease).one()
assert lease.expires_at is None
finite = service.update_settings(
self.session,
lease_duration_minutes=90,
order_match_started_at=NOW - timedelta(days=1),
current=self.admin,
)
self.session.refresh(lease)
assert finite["leaseDurationMinutes"] == 90
assert finite["orderMatchStartedAt"] is not None
assert lease.expires_at is not None
unlimited = service.update_settings(
self.session,
lease_duration_minutes=None,
order_match_started_at=NOW - timedelta(days=1),
current=self.admin,
)
self.session.refresh(lease)
assert unlimited["leaseDurationMinutes"] is None
assert lease.expires_at is None
def test_lease_policy_is_applied_by_task_state(self):
self.account("state-policy-account")
task = self.task()
service.allocate_task(self.session, task_id=task.id, current=self.admin)
lease = self.session.query(AccountLease).one()
task = self.session.get(PlatformFulfillmentTask, task.id)
service.update_settings(
self.session,
lease_duration_minutes=60,
completed_release_delay_minutes=30,
manual_completed_release_delay_minutes=120,
presale_waiting_release_ttl_minutes=None,
manual_required_lease_ttl_minutes=90,
order_match_started_at=NOW - timedelta(days=1),
current=self.admin,
)
self.session.refresh(lease)
assert lease.expires_at is not None
task.sale_mode = "presale"
task.execution_status = "bound"
task.exchange_status = "waiting_release"
self.session.commit()
service.update_settings(
self.session,
lease_duration_minutes=60,
completed_release_delay_minutes=30,
manual_completed_release_delay_minutes=120,
presale_waiting_release_ttl_minutes=None,
manual_required_lease_ttl_minutes=90,
order_match_started_at=NOW - timedelta(days=1),
current=self.admin,
)
self.session.refresh(lease)
assert lease.expires_at is None
task.execution_status = "manual_required"
task.exchange_status = "points_short"
self.session.commit()
service.update_settings(
self.session,
lease_duration_minutes=60,
completed_release_delay_minutes=30,
manual_completed_release_delay_minutes=120,
presale_waiting_release_ttl_minutes=None,
manual_required_lease_ttl_minutes=90,
order_match_started_at=NOW - timedelta(days=1),
current=self.admin,
)
self.session.refresh(lease)
assert lease.expires_at is not None
task.execution_status = "completed"
task.exchange_status = "manual_done"
self.session.commit()
service.update_settings(
self.session,
lease_duration_minutes=60,
completed_release_delay_minutes=30,
manual_completed_release_delay_minutes=120,
presale_waiting_release_ttl_minutes=None,
manual_required_lease_ttl_minutes=90,
order_match_started_at=NOW - timedelta(days=1),
current=self.admin,
)
self.session.refresh(lease)
assert lease.status == "active"
assert lease.expires_at is not None
class TestBindingAndCompletion(_Base):
def _allocated(self):
self.account("bind-account")
task = self.task()
service.allocate_task(self.session, task_id=task.id, current=self.admin)
self.session.refresh(task)
return task
def test_start_binding_clears_stale_binding_failure(self, monkeypatch):
task = self._allocated()
failed_bind_task = DouyuTask(
batch_id="bind-failed",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="failed",
message="绑定任务失败",
result={},
created_by=self.admin_id,
)
self.session.add(failed_bind_task)
self.session.flush()
task.bind_task_id = failed_bind_task.id
task.binding_status = "failed"
task.execution_status = "manual_required"
task.issue_code = "binding_failed"
task.last_error = "绑定失败,请刷新二维码后重试"
self.session.commit()
monkeypatch.setattr(
service.binding,
"enqueue_execution_job",
lambda _db, **_kwargs: None,
)
asyncio.run(
service.start_binding(
self.session,
task_id=task.id,
current=self.admin,
force_refresh=True,
)
)
self.session.refresh(task)
assert task.binding_status == "preparing"
assert task.execution_status == "waiting_bind"
assert task.issue_code == ""
assert task.last_error == ""
def test_customer_profile_updates_active_bind_expected_role(self):
task = self._allocated()
bind_task = DouyuTask(
batch_id="late-customer-profile",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="running",
platform_task_id=task.id,
result={"expected_role_name": "", "bind_polling": True},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "waiting_bind"
task.execution_status = "waiting_bind"
self.session.commit()
service.save_customer_profile(
self.session,
task_id=task.id,
customer_role_name="丛未停息的雨",
platform="qq",
system="ios",
home_images=[{"url": "https://example.com/home.png"}],
)
self.session.refresh(bind_task)
assert bind_task.result["expected_role_name"] == "丛未停息的雨"
assert bind_task.result["expected_role_required"] is True
def test_standalone_account_confirmation_syncs_active_fulfillment_task(self):
task = self._allocated()
old_bind_task = DouyuTask(
batch_id="bind-old-role",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"role_name": "新角色",
"current_role_name": "新角色",
"baseline_role_name": "历史角色",
"baseline_is_bound_act": True,
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "历史角色",
"is_bound_act": True,
"need_bind_act": True,
},
"need_bind_act": True,
"is_bound_act": False,
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
self.session.add(old_bind_task)
self.session.flush()
task.bind_task_id = old_bind_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
account = self.session.get(Account, task.account_id)
account.role_bind_status = "bound"
account.game_name = "历史角色"
account.game_channel = "微信 · 苹果(iOS)"
confirm_task = DouyuTask(
batch_id="confirm-from-elite-workbench",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="success",
result={
"role_name": "新角色",
"is_bound_act": True,
"bind_confirmed": True,
"bind_phase": "confirmed",
},
created_by=self.admin_id,
)
self.session.add(confirm_task)
self.session.commit()
pre_sync_detail = service.get_task_detail(self.session, task.id)
assert pre_sync_detail["task"]["bindTask"]["roleName"] == "新角色"
assert pre_sync_detail["task"]["bindTask"]["bindReadyForConfirm"] is True
account.game_name = "新角色"
account.role_bind_status = "bound"
self.session.commit()
synced = service.sync_task_from_binding_runner(
self.session,
douyu_task_id=confirm_task.id,
)
self.session.refresh(task)
detail = service.get_task_detail(self.session, task.id)
event = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(
task_id=task.id,
event_type="binding_synced_from_account",
)
.one()
)
assert synced == 1
assert task.binding_status == "bound"
assert task.execution_status == "bound"
assert detail["task"]["bindTask"]["roleName"] == "新角色"
assert detail["task"]["bindTask"]["bindReadyForConfirm"] is False
assert detail["task"]["bindTask"]["bindConfirmed"] is True
assert task.bind_task_id == confirm_task.id
assert event.detail_json["roleName"] == "新角色"
def test_account_bound_does_not_confirm_unconfirmed_confirmation_task(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.role_bind_status = "bound"
account.game_name = "账号当前角色"
task.binding_status = "role_ready"
task.execution_status = "role_ready"
confirm_task = DouyuTask(
batch_id="unconfirmed-confirm-task",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="success",
result={
"role_name": "账号当前角色",
"is_bound_act": True,
"bind_confirmed": False,
"bind_phase": "waiting_role",
},
created_by=self.admin_id,
)
self.session.add(confirm_task)
self.session.commit()
synced = service.sync_task_from_binding_runner(
self.session,
douyu_task_id=confirm_task.id,
)
self.session.refresh(task)
assert synced == 0
assert task.binding_status == "role_ready"
assert task.execution_status == "role_ready"
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(
task_id=task.id,
event_type="binding_synced_from_account",
)
.count()
== 0
)
def test_bind_qr_success_does_not_promote_existing_account_binding(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.role_bind_status = "bound"
account.game_name = "历史角色"
account.game_channel = "微信 · 苹果(iOS)"
bind_task = DouyuTask(
batch_id="bind-pending-current-order",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"act_alias": "cjm",
"role_name": "本次待确认角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"baseline_role_name": "历史角色",
"baseline_is_bound_act": True,
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "历史角色",
"is_bound_act": True,
"need_bind_act": True,
},
"need_bind_act": False,
"is_bound_act": False,
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
self.session.commit()
synced = service.sync_task_from_binding_runner(
self.session,
douyu_task_id=bind_task.id,
)
self.session.refresh(task)
detail = service.get_task_detail(self.session, task.id)
assert synced == 1
assert task.bind_task_id == bind_task.id
assert task.binding_status == "role_ready"
assert task.execution_status == "role_ready"
assert detail["task"]["bindTask"]["roleName"] == "本次待确认角色"
assert detail["task"]["bindTask"]["bindReadyForConfirm"] is True
assert detail["task"]["bindTask"]["bindConfirmed"] is False
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(
task_id=task.id,
event_type="binding_synced_from_account",
)
.count()
== 0
)
def test_standalone_pending_bind_task_links_to_active_fulfillment_task(self):
task = self._allocated()
old_bind_task = DouyuTask(
batch_id="bind-old-pending",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"role_name": "旧待确认角色",
"current_role_name": "历史角色",
"baseline_role_name": "历史角色",
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "历史角色",
"is_bound_act": True,
"need_bind_act": True,
},
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
self.session.add(old_bind_task)
self.session.flush()
task.bind_task_id = old_bind_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
latest_bind_task = DouyuTask(
batch_id="account-workbench-new-pending",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"role_name": "最新待确认角色",
"current_role_name": "历史角色",
"baseline_role_name": "历史角色",
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "历史角色",
"is_bound_act": True,
"need_bind_act": True,
},
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
self.session.add(latest_bind_task)
self.session.commit()
synced = service.sync_task_from_binding_runner(
self.session,
douyu_task_id=latest_bind_task.id,
)
self.session.refresh(task)
detail = service.get_task_detail(self.session, task.id)
assert synced == 1
assert task.bind_task_id == latest_bind_task.id
assert task.binding_status == "role_ready"
assert detail["task"]["bindTask"]["roleName"] == "最新待确认角色"
event = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(
task_id=task.id,
event_type="binding_pending_task_linked",
)
.one()
)
assert event.detail_json["previousBindTaskId"] == old_bind_task.id
assert event.detail_json["bindTaskId"] == latest_bind_task.id
def test_observation_never_settles_fulfillment_task(self):
"""查询任务只能展示账号当前角色,不能证明本单已确认。"""
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "续梦乖"
account.role_bind_status = "bound"
pending_task = DouyuTask(
batch_id="pending-for-observation",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"role_name": "布丁贩卖机",
"area_name": "微信",
"plat_name": "苹果(iOS)",
"baseline_role_name": "续梦乖",
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "续梦乖",
"is_bound_act": True,
"need_bind_act": True,
},
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
self.session.add(pending_task)
self.session.flush()
task.bind_task_id = pending_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
observed_roles = ["续梦乖", "布丁贩卖机"]
observations = []
for index, role_name in enumerate(observed_roles):
observation = DouyuTask(
batch_id=f"observe-{index}",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="query_game_name",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"role_name": role_name,
"area_name": "手Q",
"plat_name": "安卓(android)",
"is_bound_act": True,
"bind_confirmed": True,
"bind_phase": "confirmed",
},
created_by=self.admin_id,
)
self.session.add(observation)
observations.append(observation)
self.session.commit()
for observation in observations:
assert (
service.sync_task_from_binding_runner(
self.session,
douyu_task_id=observation.id,
)
== 0
)
assert service.reconcile_binding_observations(self.session) == 0
self.session.refresh(task)
assert task.binding_status == "role_ready"
assert task.execution_status == "role_ready"
assert task.bind_task_id == pending_task.id
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_confirmed")
.count()
== 0
)
def test_target_matching_observation_repairs_stale_pending_role(self):
"""租期内后续查询已绑定客户目标时,必须收敛旧的瞬时 cjm 角色。"""
task = self._allocated()
task.customer_role_name = "丛未停息的雨"
account = self.session.get(Account, task.account_id)
account.game_name = "丛未停息的雨"
account.game_channel = "手Q · 苹果(iOS)"
account.role_bind_status = "bound"
pending_task = DouyuTask(
batch_id="stale-transient-pending",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"role_name": "TuT小玉",
"baseline_role_name": "真心似有若无",
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "真心似有若无",
"is_bound_act": True,
"need_bind_act": True,
},
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
self.session.add(pending_task)
self.session.flush()
task.bind_task_id = pending_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
observation = DouyuTask(
batch_id="confirmed-target-observation",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="query_game_name",
handbook_scope="elite",
status="success",
platform_task_id=None,
result={
"act_alias": "20260120QYOOB",
"action_act_aliases": ["20260120QYOOB"],
"role_name": "丛未停息的雨",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"is_bound_act": True,
"bind_confirmed": True,
"bind_phase": "confirmed",
},
created_by=self.admin_id,
)
self.session.add(observation)
self.session.commit()
detail = service.refresh_binding(self.session, task_id=task.id)
self.session.refresh(task)
event = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(
task_id=task.id,
event_type="binding_confirmed_from_observation",
)
.one()
)
assert task.binding_status == "bound"
assert task.execution_status == "bound"
assert task.bind_task_id == observation.id
assert detail["task"]["bindTask"]["roleName"] == "丛未停息的雨"
assert detail["task"]["bindTask"]["bindConfirmed"] is True
assert event.detail_json["previousBindTaskId"] == pending_task.id
assert event.detail_json["targetRoleName"] == "丛未停息的雨"
def test_startup_reconcile_prioritizes_role_ready_tasks(self):
"""大量历史订单占用 limit 时,role_ready 自愈不能被饿死。"""
older = self._allocated()
older.source_order_item_id = "older-active-order"
older.binding_status = "failed"
older.execution_status = "manual_required"
self.session.commit()
task = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="priority-active-order",
source_order_item_id="priority-active-order",
source_fulfillment_id="priority-active-order",
platform_order_id="PRIORITY-ACTIVE-ORDER",
provider="91kaquan",
shop_id="shop-1",
shop_name="测试店",
sku_code=INTERNAL_SKU,
sku_name=INTERNAL_SKU,
internal_sku_key=INTERNAL_SKU,
quantity=1,
order_amount_fen=9900,
target_platform="douyu",
scope="elite",
commodity_mapping_id=older.commodity_mapping_id,
commodity_id=older.commodity_id,
required_points=older.required_points,
customer_role_name="丛未停息的雨",
account_id=older.account_id,
lease_id=older.lease_id,
binding_status="role_ready",
execution_status="role_ready",
exchange_status="not_started",
source_snapshot_json={"order_no": "PRIORITY-ACTIVE-ORDER"},
paid_at=NOW,
created_at=NOW,
updated_at=NOW,
)
self.session.add(task)
self.session.flush()
account = self.session.get(Account, task.account_id)
account.game_name = "丛未停息的雨"
account.game_channel = "手Q · 苹果(iOS)"
account.role_bind_status = "bound"
pending_task = DouyuTask(
batch_id="priority-stale-pending",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"role_name": "TuT小玉",
"baseline_role_name": "真心似有若无",
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
self.session.add(pending_task)
self.session.flush()
task.bind_task_id = pending_task.id
observation = DouyuTask(
batch_id="priority-confirmed-observation",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="query_game_name",
handbook_scope="elite",
status="success",
platform_task_id=None,
result={
"act_alias": "20260120QYOOB",
"action_act_aliases": ["20260120QYOOB"],
"role_name": "丛未停息的雨",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"is_bound_act": True,
"bind_confirmed": True,
"bind_phase": "confirmed",
},
created_by=self.admin_id,
)
self.session.add(observation)
self.session.commit()
reconciled = service.reconcile_binding_observations(self.session, limit=1)
self.session.refresh(task)
assert reconciled == 1
assert task.binding_status == "bound"
assert task.execution_status == "bound"
assert task.bind_task_id == observation.id
def test_startup_recovers_lost_confirm_callback(self):
"""确认任务已成功落库但回调丢失时,启动对账能收敛为 bound。"""
task = self._allocated()
task.binding_status = "confirming"
task.execution_status = "binding_confirming"
confirm_task = DouyuTask(
batch_id="lost-confirm-callback",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"role_name": "目标角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"bind_confirmed": True,
"bind_phase": "confirmed",
},
created_by=self.admin_id,
)
self.session.add(confirm_task)
self.session.flush()
task.bind_task_id = confirm_task.id
self.session.commit()
reconciled = service.reconcile_binding_observations(self.session)
self.session.refresh(task)
assert reconciled == 1
assert task.binding_status == "bound"
assert task.execution_status == "bound"
assert task.bind_task_id == confirm_task.id
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_confirmed")
.count()
== 1
)
def test_unlinked_confirm_requires_matching_target_role(self):
"""精英宝典工作台的无归属确认任务必须和本单目标角色一致。"""
task = self._allocated()
qr_task = DouyuTask(
batch_id="unlinked-target-qr",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"role_name": "本单目标角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"current_role_name": "历史角色",
"baseline_role_name": "历史角色",
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "历史角色",
"is_bound_act": True,
"need_bind_act": True,
},
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
mismatched = DouyuTask(
batch_id="unlinked-mismatched-confirm",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="success",
result={
"role_name": "别的角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"bind_confirmed": True,
"bind_phase": "confirmed",
},
created_by=self.admin_id,
)
self.session.add(mismatched)
self.session.commit()
synced = service.sync_task_from_binding_runner(
self.session,
douyu_task_id=mismatched.id,
)
self.session.refresh(task)
rejection = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_sync_rejected")
.one()
)
assert synced == 0
assert task.binding_status == "role_ready"
assert task.bind_task_id == qr_task.id
assert rejection.detail_json["reason"] == "target_mismatch"
assert rejection.detail_json["confirmedRoleName"] == "别的角色"
assert rejection.detail_json["targetRoleName"] == "本单目标角色"
def test_unlinked_confirm_created_before_lease_is_rejected(self):
"""上一个租约遗留的确认任务不能结算当前订单。"""
task = self._allocated()
qr_task = DouyuTask(
batch_id="outside-lease-qr",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"role_name": "当前目标角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"current_role_name": "历史角色",
"baseline_role_name": "历史角色",
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "历史角色",
"is_bound_act": True,
"need_bind_act": True,
},
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
old_confirm = DouyuTask(
batch_id="outside-lease-confirm",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="success",
result={
"role_name": "当前目标角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"bind_confirmed": True,
"bind_phase": "confirmed",
},
created_by=self.admin_id,
created_at=NOW - timedelta(days=1),
)
self.session.add_all([qr_task, old_confirm])
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
self.session.commit()
synced = service.sync_task_from_binding_runner(
self.session,
douyu_task_id=old_confirm.id,
)
self.session.refresh(task)
rejection = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_sync_rejected")
.one()
)
assert synced == 0
assert task.binding_status == "role_ready"
assert rejection.detail_json["reason"] == "source_outside_lease"
def test_bound_task_ignores_late_unlinked_bind_failure(self):
"""已绑定订单不能被账号工作台迟到的失败任务打成人工处理。"""
task = self._allocated()
task.binding_status = "bound"
task.execution_status = "exchanging"
task.exchange_status = "checking"
self.session.commit()
late_failed = DouyuTask(
batch_id="late-workbench-failure",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="failed",
message="换绑冷却",
result={"bind_phase": "change_waiting"},
created_by=self.admin_id,
)
self.session.add(late_failed)
self.session.commit()
synced = service.sync_task_from_binding_runner(
self.session,
douyu_task_id=late_failed.id,
)
self.session.refresh(task)
assert synced == 0
assert task.binding_status == "bound"
assert task.execution_status == "exchanging"
assert task.issue_code == ""
def test_esports_binding_task_does_not_touch_elite_fulfillment(self):
"""电竞/和平小店任务与精英履约互不投影。"""
task = self._allocated()
esports_task = DouyuTask(
batch_id="esports-cross-scope",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_esports_bind",
handbook_scope="esports",
status="success",
platform_task_id=None,
result={
"role_name": "电竞角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"esports_bound": True,
"bind_confirmed": True,
"bind_phase": "confirmed",
},
created_by=self.admin_id,
)
self.session.add(esports_task)
self.session.commit()
synced = service.sync_task_from_binding_runner(
self.session,
douyu_task_id=esports_task.id,
)
self.session.refresh(task)
assert synced == 0
assert task.binding_status == "not_started"
assert task.bind_task_id is None
def test_workbench_binding_tasks_are_owned_by_active_fulfillment_order(self):
"""已租给履约订单的账号,工作台绑定任务在创建时就写入订单归属。"""
from web.backend.services.douyu_service import create_douyu_planned_tasks
task = self._allocated()
qr_batch, qr_count = create_douyu_planned_tasks(
self.session,
[task.account_id],
"get_bind_qr",
"elite",
self.admin_id,
enqueue_execution=False,
)
qr_task = (
self.session.query(DouyuTask).filter(DouyuTask.batch_id == qr_batch).one()
)
assert qr_count == 1
assert qr_task.platform_task_id == task.id
qr_task.status = "success"
qr_task.result = {
"role_name": "工作台扫码角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"current_role_name": "历史角色",
"baseline_role_name": "历史角色",
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "历史角色",
"is_bound_act": True,
"need_bind_act": True,
},
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
}
self.session.commit()
assert (
service.sync_task_from_binding_runner(
self.session,
douyu_task_id=qr_task.id,
)
== 1
)
self.session.refresh(task)
assert task.binding_status == "role_ready"
assert task.bind_task_id == qr_task.id
confirm_batch, _ = create_douyu_planned_tasks(
self.session,
[task.account_id],
"confirm_bind",
"elite",
self.admin_id,
enqueue_execution=False,
)
confirm_task = (
self.session.query(DouyuTask)
.filter(DouyuTask.batch_id == confirm_batch)
.one()
)
assert confirm_task.platform_task_id == task.id
confirm_task.status = "success"
confirm_task.result = {
"role_name": "工作台扫码角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"bind_confirmed": True,
"bind_phase": "confirmed",
}
self.session.commit()
assert (
service.sync_task_from_binding_runner(
self.session,
douyu_task_id=confirm_task.id,
)
== 1
)
self.session.refresh(task)
assert task.binding_status == "bound"
assert task.bind_task_id == confirm_task.id
def test_owned_confirm_with_mismatched_role_is_rejected(self):
"""带订单归属的确认任务如果绑了别的角色,也不能结算订单。"""
task = self._allocated()
qr_task = DouyuTask(
batch_id="owned-target-qr",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"role_name": "本单目标角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"current_role_name": "历史角色",
"baseline_role_name": "历史角色",
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "历史角色",
"is_bound_act": True,
"need_bind_act": True,
},
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
confirm_task = DouyuTask(
batch_id="owned-mismatched-confirm",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"role_name": "别的角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"bind_confirmed": True,
"bind_phase": "confirmed",
},
created_by=self.admin_id,
)
self.session.add(confirm_task)
self.session.commit()
synced = service.sync_task_from_binding_runner(
self.session,
douyu_task_id=confirm_task.id,
)
self.session.refresh(task)
rejection = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_sync_rejected")
.one()
)
assert synced == 1
assert task.binding_status == "role_ready"
assert task.bind_task_id == confirm_task.id
assert "别的角色" in (task.last_error or "")
assert "本单目标角色" in (task.last_error or "")
assert rejection.detail_json["reason"] == "target_mismatch"
def _role_lock_event(self, account, role_name, *, occurred_at=None):
self.session.add(
AccountEvent(
account_id=account.id,
event_type="bind_ok",
category="business",
occurred_at=occurred_at or NOW,
subject_type="elite_role",
subject_key=role_name,
detail={
"scope": "elite",
"role_name": role_name,
"act_alias": "20260120QYOOB",
"rebind": True,
"confirmed": True,
},
source="test",
actor_type="system",
)
)
def _role_lock_pending_task(self, task, role_name):
return DouyuTask(
batch_id=f"role-lock-qr-{task.id}",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"role_name": role_name,
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"current_role_name": "旧角色",
"baseline_role_name": "旧角色",
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "旧角色",
"is_bound_act": True,
"need_bind_act": True,
},
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
def test_pending_role_locked_to_other_account_goes_manual(self):
task = self._allocated()
lock_account = self.account("role-lock-holder", capability=False)
lock_account.game_name = "跨账号角色"
lock_account.role_bind_status = "bound"
self.session.add(
AccountLease(
account_id=lock_account.id,
holder_user_id=self.admin_id,
scope="elite",
purpose="douyu_collab",
batch_id="collab:role-lock",
status="active",
)
)
self._role_lock_event(lock_account, "跨账号角色")
self.session.commit()
qr_task = self._role_lock_pending_task(task, "跨账号角色")
self.session.add(qr_task)
self.session.commit()
synced = service.sync_task_from_binding_runner(
self.session,
douyu_task_id=qr_task.id,
)
self.session.refresh(task)
event = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_role_locked_elsewhere")
.one()
)
assert synced == 1
assert task.binding_status == "failed"
assert task.execution_status == "manual_required"
assert task.issue_code == "customer_role_bound_elsewhere"
assert "role-lock-holder" in task.last_error
assert "预售台账" in task.last_error
assert event.detail_json["roleLockAccountId"] == lock_account.id
assert event.detail_json["roleLockAccountName"] == "role-lock-holder"
assert event.detail_json["roleLockLeasePurpose"] == "douyu_collab"
assert event.detail_json["sourceTaskId"] == qr_task.id
assert (
self.session.query(DouyuTask).filter_by(task_type="confirm_bind").count()
== 0
)
# 人工状态下刷新不能把它推回 role_ready。
service.refresh_binding(self.session, task_id=task.id)
self.session.refresh(task)
assert task.binding_status == "failed"
assert task.execution_status == "manual_required"
assert task.issue_code == "customer_role_bound_elsewhere"
def test_pending_role_bound_to_same_account_is_allowed(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "同账号角色"
account.role_bind_status = "bound"
self._role_lock_event(account, "同账号角色")
qr_task = self._role_lock_pending_task(task, "同账号角色")
self.session.add(qr_task)
self.session.commit()
service.sync_task_from_binding_runner(
self.session,
douyu_task_id=qr_task.id,
)
self.session.refresh(task)
assert task.binding_status == "role_ready"
assert task.execution_status == "role_ready"
assert task.issue_code == ""
def test_role_lock_older_than_seven_days_is_allowed(self):
task = self._allocated()
lock_account = self.account("old-role-holder", capability=False)
lock_account.game_name = "旧锁角色"
lock_account.role_bind_status = "bound"
self._role_lock_event(
lock_account,
"旧锁角色",
occurred_at=NOW - timedelta(days=8),
)
qr_task = self._role_lock_pending_task(task, "旧锁角色")
self.session.add(qr_task)
self.session.commit()
service.sync_task_from_binding_runner(
self.session,
douyu_task_id=qr_task.id,
)
self.session.refresh(task)
assert task.binding_status == "role_ready"
assert task.execution_status == "role_ready"
def test_confirm_rejects_role_locked_to_other_account(self):
task = self._allocated()
lock_account = self.account("confirm-lock-holder", capability=False)
lock_account.game_name = "确认锁角色"
lock_account.role_bind_status = "bound"
self._role_lock_event(lock_account, "确认锁角色")
qr_task = self._role_lock_pending_task(task, "确认锁角色")
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
self.session.commit()
confirm_count = (
self.session.query(DouyuTask).filter_by(task_type="confirm_bind").count()
)
detail = service.confirm_binding_sync(
self.session,
task_id=task.id,
current=self.admin,
)
self.session.refresh(task)
assert (
self.session.query(DouyuTask).filter_by(task_type="confirm_bind").count()
== confirm_count
)
assert detail["task"]["bindingStatus"] == "failed"
assert detail["task"]["issueCode"] == "customer_role_bound_elsewhere"
assert task.binding_status == "failed"
assert task.execution_status == "manual_required"
def test_startup_reconcile_locks_legacy_role_ready_order(self):
task = self._allocated()
lock_account = self.account("startup-lock-holder", capability=False)
lock_account.game_name = "启动锁角色"
lock_account.role_bind_status = "bound"
self._role_lock_event(lock_account, "启动锁角色")
qr_task = self._role_lock_pending_task(task, "启动锁角色")
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
self.session.commit()
reconciled = service.reconcile_binding_observations(self.session)
self.session.refresh(task)
assert reconciled == 1
assert task.binding_status == "failed"
assert task.execution_status == "manual_required"
assert task.issue_code == "customer_role_bound_elsewhere"
def test_binding_evidence_separates_qyoob_cjm_and_locks(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "旧账号角色"
account.role_bind_status = "bound"
lock_account = self.account("evidence-role-holder", capability=False)
self._role_lock_event(lock_account, "新扫角色")
# 当前分配的账号 7 天内绑过旧角色:账号侧锁
self._role_lock_event(account, "旧账号角色")
qr_task = DouyuTask(
batch_id="evidence-qr",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"act_alias": "cjm",
"query_act_alias": "cjm",
"role_name": "新扫角色",
"current_role_name": "旧账号角色",
"baseline_role_name": "旧账号角色",
"action_act_aliases": ["20260120QYOOB"],
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
"bind_decision": {
"alias": "cjm",
"role_name": "新扫角色",
"reason": "role_changed",
"confirmable": True,
"actionable_alias": False,
},
"bind_candidates": [
{
"act_alias": "cjm",
"role_name": "新扫角色",
"is_bound_act": False,
"is_bound_role": True,
"reason": "role_changed",
"confirmable": True,
"actionable_alias": False,
},
{
"act_alias": "20260120QYOOB",
"role_name": "旧账号角色",
"is_bound_act": True,
"is_bound_role": True,
"reason": "already_bound",
"confirmable": False,
"actionable_alias": True,
},
],
},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
detail = service.get_task_detail(self.session, task.id)
evidence = detail["task"]["bindingEvidence"]
assert evidence is not None
assert evidence["actionAliases"] == ["20260120QYOOB"]
assert evidence["actionCurrent"]["roleName"] == "旧账号角色"
assert evidence["actionCurrent"]["bindAct"] is True
assert evidence["actionPending"] is None
assert evidence["legacyLatest"]["roleName"] == "新扫角色"
assert evidence["selectedAlias"] == "cjm"
assert evidence["selectedActionable"] is False
assert evidence["targetRole"] == ""
assert evidence["scannedRole"] == ""
assert evidence["confirmable"] is False
assert evidence["samePair"] is False
assert evidence["roleLock"] is None
assert evidence["accountLock"] is None
def test_binding_evidence_marks_same_account_same_role(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "同对角色"
account.role_bind_status = "bound"
qr_task = DouyuTask(
batch_id="evidence-same-pair",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"act_alias": "cjm",
"role_name": "同对角色",
"current_role_name": "同对角色",
"baseline_role_name": "同对角色",
"action_act_aliases": ["20260120QYOOB"],
"bind_ready_for_confirm": False,
"bind_confirmed": False,
"bind_phase": "waiting_scan",
"bind_decision": {
"alias": "cjm",
"role_name": "同对角色",
"reason": "same_role_stale",
"confirmable": False,
"actionable_alias": False,
},
"bind_candidates": [
{
"act_alias": "cjm",
"role_name": "同对角色",
"is_bound_act": False,
"is_bound_role": True,
"reason": "same_role_stale",
"confirmable": False,
"actionable_alias": False,
},
{
"act_alias": "20260120QYOOB",
"role_name": "同对角色",
"is_bound_act": True,
"is_bound_role": True,
"reason": "already_bound",
"confirmable": False,
"actionable_alias": True,
},
],
},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
detail = service.get_task_detail(self.session, task.id)
evidence = detail["task"]["bindingEvidence"]
assert evidence is not None
assert evidence["samePair"] is True
assert evidence["actionCurrent"]["roleName"] == "同对角色"
assert evidence["legacyLatest"]["roleName"] == "同对角色"
assert evidence["targetRole"] == "同对角色"
assert evidence["confirmable"] is False
def test_task_detail_includes_binding_role_api_logs(self):
task = self._allocated()
qr_task = DouyuTask(
batch_id="role-log-qr",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={"bind_ready_for_confirm": True, "bind_phase": "role_ready"},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
self.session.add(
DouyuRoleApiLog(
account_id=task.account_id,
task_id=qr_task.id,
scope="elite",
stage="binding_poll.legacy_changed",
source="douyu_task.get_bind_qr",
act_alias="cjm",
role_name="雨佑佑",
area_name="手Q",
plat_name="苹果(iOS)",
is_bound_act=False,
is_bound_role=True,
need_bind_act=False,
need_bind_role=True,
change_role_wait_time=0,
response_json={"error": 0, "msg": "请求正常"},
created_at=NOW,
)
)
self.session.commit()
detail = service.get_task_detail(self.session, task.id)
assert detail["bindingLogs"]
log = detail["bindingLogs"][0]
assert log["stage"] == "binding_poll.legacy_changed"
assert log["actAlias"] == "cjm"
assert log["roleName"] == "雨佑佑"
assert log["bindAct"] is False
assert log["error"] == 0
assert log["message"] == "请求正常"
def test_binding_evidence_does_not_treat_baseline_as_scanned(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "兔稚儿"
account.role_bind_status = "bound"
qr_task = DouyuTask(
batch_id="evidence-baseline-only",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="running",
platform_task_id=task.id,
result={
"act_alias": "cjm",
"role_name": "",
"current_role_name": "兔稚儿",
"baseline_role_name": "兔稚儿",
"baseline_is_bound_act": True,
"action_act_aliases": ["20260120QYOOB"],
"bind_ready_for_confirm": False,
"bind_confirmed": False,
"bind_phase": "waiting_scan",
"bind_decision": {
"alias": "cjm",
"role_name": "",
"reason": "no_role",
"confirmable": False,
"actionable_alias": False,
},
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "兔稚儿",
"is_bound_act": True,
"is_bound_role": True,
"need_bind_act": True,
"need_bind_role": True,
},
},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
detail = service.get_task_detail(self.session, task.id)
evidence = detail["task"]["bindingEvidence"]
assert evidence is not None
assert evidence["scannedRole"] == ""
assert evidence["samePair"] is False
assert evidence["baselineRole"] == "兔稚儿"
assert evidence["accountCurrentRole"] == "兔稚儿"
assert evidence["actionCurrent"]["roleName"] == "兔稚儿"
assert evidence["decisionReason"] == "no_role"
def test_operator_confirm_uses_scanned_role_without_form(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "旧角色"
account.role_bind_status = "bound"
qr_task = DouyuTask(
batch_id="operator-confirm-qr",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"act_alias": "cjm",
"role_name": "新角色",
"current_role_name": "旧角色",
"baseline_role_name": "旧角色",
"action_act_aliases": ["20260120QYOOB"],
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
"bind_decision": {
"alias": "cjm",
"role_name": "新角色",
"reason": "role_changed",
"confirmable": True,
"actionable_alias": False,
},
},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
detail = service.operator_confirm_binding_sync(
self.session,
task_id=task.id,
current=self.admin,
)
confirm_task = (
self.session.query(DouyuTask)
.filter_by(task_type="confirm_bind", platform_task_id=task.id)
.one()
)
assert confirm_task.result["expected_role_name"] == "新角色"
assert detail["task"]["bindingStatus"] in {"role_ready", "confirming"}
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_manually_confirmed")
.count()
== 0
)
def test_customer_profile_snapshot_is_applied_to_task(self):
task = self._allocated()
_apply_customer_profile(
task,
{
"customerRoleName": "小淋笨",
"customerPlatform": "wechat",
"customerSystem": "android",
"homeImages": [
{
"url": "https://order.example.com/a.png",
"thumbnailUrl": "https://order.example.com/a-thumb.png",
"objectKey": "douyu-homepage-screenshot/a.png",
}
],
"customerProfileUpdatedAt": "2026-11-24T12:00:00.000Z",
},
)
assert task.customer_role_name == "小淋笨"
assert task.customer_platform == "wechat"
assert task.customer_system == "android"
assert task.customer_home_images[0]["objectKey"].endswith("a.png")
assert task.customer_profile_updated_at is not None
def test_customer_profile_with_home_image_is_saved_and_compared(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "小淋笨"
account.game_channel = "微信 · 安卓(android)"
self.session.commit()
detail = service.save_customer_profile(
self.session,
task_id=task.id,
customer_role_name="小淋笨",
platform="wechat",
system="android",
home_images=[
{
"url": "https://example.com/customer-home.png",
"thumbnail_url": "https://example.com/customer-home-thumb.png",
"object_key": "collect-material/customer-home.png",
}
],
)
self.session.refresh(task)
profile = detail["customerProfile"]
assert task.customer_role_name == "小淋笨"
assert task.customer_home_images[0]["url"].endswith("customer-home.png")
assert profile["roleMatched"] is True
assert profile["channelMatched"] is True
assert profile["homeImages"][0]["thumbnailUrl"].endswith("thumb.png")
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="customer_profile_saved")
.count()
== 1
)
def test_customer_profile_matches_online_qq_channel_label(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "手Q角色"
account.game_channel = "手Q · 苹果(iOS)"
self.session.commit()
detail = service.save_customer_profile(
self.session,
task_id=task.id,
customer_role_name="手Q角色",
platform="qq",
system="ios",
home_images=[{"url": "https://example.com/qq-home.png"}],
)
assert detail["customerProfile"]["channelMatched"] is True
def test_confirm_role_disappeared_is_not_customer_cooldown(self):
result = {
"bind_phase": "confirm_failed",
"expected_role_name": "再说就一坨儿",
"bind_candidates": [
{"act_alias": "cjm", "role_name": ""},
{"act_alias": "20260120QYOOB", "role_name": "小无恩"},
],
}
task = DouyuTask(
message="待确认角色已变化,未找到: 再说就一坨儿",
result=result,
)
assert _binding_failure_issue(task, result) == "role_changed"
assert "扫码角色已失效" in _binding_failure_raw_message("role_changed", result)
def test_customer_profile_requires_home_image(self):
task = self._allocated()
with pytest.raises(HTTPException) as exc_info:
service.save_customer_profile(
self.session,
task_id=task.id,
customer_role_name="小淋笨",
platform="wechat",
system="android",
home_images=[],
)
assert exc_info.value.status_code == 409
assert "主页截图" in str(exc_info.value.detail)
def test_cjm_only_transient_role_waits_for_action_alias_sync(self):
task = self._allocated()
qr_task = DouyuTask(
batch_id="cjm-only-pending",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"act_alias": "cjm",
"role_name": "cjm新角色",
"current_role_name": "旧角色",
"baseline_role_name": "旧角色",
"action_act_aliases": ["20260120QYOOB"],
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
"bind_decision": {
"alias": "cjm",
"role_name": "cjm新角色",
"reason": "role_changed",
"confirmable": True,
"actionable_alias": False,
},
"bind_candidates": [
{
"act_alias": "cjm",
"role_name": "cjm新角色",
"is_bound_act": False,
"is_bound_role": True,
"reason": "role_changed",
"confirmable": True,
"actionable_alias": False,
},
{
"act_alias": "20260120QYOOB",
"role_name": "旧角色",
"is_bound_act": True,
"is_bound_role": True,
"reason": "already_bound",
"confirmable": False,
"actionable_alias": True,
},
],
},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
# 客户页 readiness 与确认接口必须读同一层事实:
# 平台任务还在 qr_pending 时不能显示“可确认”。
assert (
views.customer_binding_out(self.session, task.id)["bindReadyForConfirm"]
is False
)
service.refresh_binding(self.session, task_id=task.id)
self.session.refresh(task)
detail = service.get_task_detail(self.session, task.id)
evidence = detail["task"]["bindingEvidence"]
assert task.binding_status == "qr_pending"
assert task.execution_status == "waiting_bind"
assert evidence["targetRole"] == ""
assert evidence["confirmable"] is False
assert evidence["scannedRole"] == ""
assert (
views.customer_binding_out(self.session, task.id)["bindReadyForConfirm"]
is False
)
assert evidence["legacyLatest"]["roleName"] == "cjm新角色"
assert evidence["actionCurrent"]["roleName"] == "旧角色"
assert (
self.session.query(DouyuTask).filter_by(task_type="confirm_bind").count()
== 0
)
def _same_pair_qr_task(self, task, include_legacy: bool = True):
candidates = [
{
"act_alias": "20260120QYOOB",
"role_name": "同对角色",
"is_bound_act": True,
"is_bound_role": True,
"reason": "already_bound",
"confirmable": False,
"actionable_alias": True,
}
]
if include_legacy:
candidates.insert(
0,
{
"act_alias": "cjm",
"role_name": "同对角色",
"is_bound_act": False,
"is_bound_role": True,
"reason": "same_role_stale",
"confirmable": False,
"actionable_alias": False,
},
)
return DouyuTask(
batch_id=f"reuse-qr-{task.id}",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"act_alias": "cjm" if include_legacy else "20260120QYOOB",
"role_name": "同对角色",
"current_role_name": "同对角色",
"baseline_role_name": "同对角色",
"action_act_aliases": ["20260120QYOOB"],
"bind_ready_for_confirm": False,
"bind_confirmed": False,
"bind_phase": "waiting_scan",
"bind_decision": {
"alias": "cjm" if include_legacy else "20260120QYOOB",
"role_name": "同对角色",
"reason": "same_role_stale" if include_legacy else "already_bound",
"confirmable": False,
"actionable_alias": not include_legacy,
},
"bind_candidates": candidates,
},
created_by=self.admin_id,
)
def test_same_account_same_role_is_reused_as_bound(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "同对角色"
account.role_bind_status = "bound"
qr_task = self._same_pair_qr_task(task, include_legacy=True)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
service.refresh_binding(self.session, task_id=task.id)
self.session.refresh(task)
event = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_reused_existing_pair")
.one()
)
assert task.binding_status == "bound"
assert task.execution_status == "bound"
assert task.bind_task_id == qr_task.id
assert event.detail_json["roleName"] == "同对角色"
assert event.detail_json["reason"] == "same_account_same_role"
assert (
self.session.query(DouyuTask).filter_by(task_type="confirm_bind").count()
== 0
)
def test_already_bound_without_scan_does_not_reuse(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "同对角色"
account.role_bind_status = "bound"
qr_task = self._same_pair_qr_task(task, include_legacy=False)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
service.refresh_binding(self.session, task_id=task.id)
self.session.refresh(task)
assert task.binding_status == "qr_pending"
assert task.execution_status == "waiting_bind"
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_reused_existing_pair")
.count()
== 0
)
def test_pending_role_blocked_by_account_seven_day_lock(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "账号旧角色"
account.role_bind_status = "bound"
self._role_lock_event(account, "账号上一角色")
qr_task = self._role_lock_pending_task(task, "本次新角色")
self.session.add(qr_task)
self.session.commit()
service.sync_task_from_binding_runner(
self.session,
douyu_task_id=qr_task.id,
)
self.session.refresh(task)
event = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_account_locked_elsewhere")
.one()
)
assert task.binding_status == "failed"
assert task.execution_status == "manual_required"
assert task.issue_code == "account_role_bound_elsewhere"
assert "账号上一角色" in task.last_error
assert event.detail_json["accountRoleName"] == "账号上一角色"
assert event.detail_json["sourceTaskId"] == qr_task.id
def test_account_seven_day_lock_older_than_seven_days_allows_binding(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "账号旧角色"
account.role_bind_status = "bound"
self._role_lock_event(
account,
"账号上一角色",
occurred_at=NOW - timedelta(days=8),
)
qr_task = self._role_lock_pending_task(task, "本次新角色")
self.session.add(qr_task)
self.session.commit()
service.sync_task_from_binding_runner(
self.session,
douyu_task_id=qr_task.id,
)
self.session.refresh(task)
assert task.binding_status == "role_ready"
assert task.execution_status == "role_ready"
def test_refresh_binding_attaches_latest_pending_account_workbench_role(self):
task = self._allocated()
old_bind_task = DouyuTask(
batch_id="refresh-old-pending",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={"role_name": "旧待确认角色", "bind_ready_for_confirm": True},
created_by=self.admin_id,
)
latest_bind_task = DouyuTask(
batch_id="refresh-latest-pending",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"role_name": "最新待确认角色",
"current_role_name": "历史角色",
"baseline_role_name": "历史角色",
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "历史角色",
"is_bound_act": True,
"need_bind_act": True,
},
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
self.session.add_all([old_bind_task, latest_bind_task])
self.session.flush()
task.bind_task_id = old_bind_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
self.session.commit()
detail = service.refresh_binding(self.session, task_id=task.id)
self.session.refresh(task)
assert task.bind_task_id == latest_bind_task.id
assert detail["task"]["bindTask"]["roleName"] == "最新待确认角色"
assert detail["task"]["bindTask"]["bindReadyForConfirm"] is True
def test_customer_start_mapping_missing_is_idempotent(self, monkeypatch):
task = self.task(mapped=False)
task.issue_code = "mapping_missing"
self.session.commit()
monkeypatch.setattr(
service,
"allocate_task",
lambda **_kwargs: (_ for _ in ()).throw(
AssertionError("mapping_missing must not allocate synchronously")
),
)
for _ in range(5):
payload = asyncio.run(
service.customer_start_binding(self.session, task_id=task.id)
)
assert payload["accepted"] is False
assert payload["queueState"] == "mapping_missing"
self.session.refresh(task)
assert task.account_id is None
assert task.bind_task_id is None
def test_customer_start_queues_allocation_without_sync_network(self, monkeypatch):
task = self.task()
self.complete_customer_profile(task)
calls: list[list[int]] = []
monkeypatch.setattr(
"web.backend.services.platform_fulfillment.auto_allocator.wake_auto_allocator",
lambda task_ids=None: calls.append(list(task_ids or [])),
)
monkeypatch.setattr(
service,
"allocate_task",
lambda **_kwargs: (_ for _ in ()).throw(
AssertionError("binding start must not allocate in the request")
),
)
payload = asyncio.run(
service.customer_start_binding(self.session, task_id=task.id)
)
assert payload["accepted"] is True
assert payload["queueState"] == "allocation_queued"
assert calls == [[task.id]]
def test_customer_start_creates_one_binding_task_and_links_platform(
self, monkeypatch
):
task = self._allocated()
self.complete_customer_profile(task)
monkeypatch.setattr(
service.binding,
"enqueue_execution_job",
lambda _db, **_kwargs: None,
)
first = asyncio.run(
service.customer_start_binding(self.session, task_id=task.id)
)
second = asyncio.run(
service.customer_start_binding(self.session, task_id=task.id)
)
assert first["accepted"] is True
assert second["accepted"] is False
bind_tasks = (
self.session.query(DouyuTask)
.filter(
DouyuTask.platform_task_id == task.id,
DouyuTask.task_type == "get_bind_qr",
)
.all()
)
assert len(bind_tasks) == 1
assert bind_tasks[0].result["expected_role_required"] is True
assert bind_tasks[0].result["expected_role_name"]
self.session.refresh(task)
assert task.bind_task_id == bind_tasks[0].id
def test_customer_started_binding_does_not_capture_request_loop(self, monkeypatch):
task = self._allocated()
self.complete_customer_profile(task)
captured: dict[str, object] = {}
monkeypatch.setattr(
service.binding,
"enqueue_execution_job",
lambda _db, **kwargs: captured.update(kwargs),
)
asyncio.run(service.customer_start_binding(self.session, task_id=task.id))
assert captured["job_type"] == "douyu_binding"
assert captured["batch_id"].startswith(f"pfbind-{task.id}-")
def test_admin_binding_requires_game_home_profile(self):
task = self._allocated()
with pytest.raises(HTTPException) as exc_info:
service.ensure_customer_profile_for_binding(self.session, task_id=task.id)
assert exc_info.value.status_code == 409
self.complete_customer_profile(task)
service.ensure_customer_profile_for_binding(self.session, task_id=task.id)
def test_customer_start_requires_game_home_profile(self):
task = self._allocated()
with pytest.raises(HTTPException) as exc_info:
asyncio.run(service.customer_start_binding(self.session, task_id=task.id))
assert exc_info.value.status_code == 409
assert "游戏主页截图" in str(exc_info.value.detail)
def test_concurrent_start_binding_creates_one_task(self, monkeypatch):
task = self._allocated()
monkeypatch.setattr(
service.binding,
"enqueue_execution_job",
lambda _db, **_kwargs: None,
)
barrier = threading.Barrier(2)
errors: list[BaseException] = []
first_session = make_test_session(self.engine)
first_admin = first_session.get(User, self.admin_id)
assert first_admin is not None
other_session = make_test_session(self.engine)
other_admin = other_session.get(User, self.admin_id)
assert other_admin is not None
def start(db, current):
try:
barrier.wait(timeout=3)
asyncio.run(
service.start_binding(
db,
task_id=task.id,
current=current,
)
)
except BaseException as exc: # noqa: BLE001 - surfaced below
errors.append(exc)
first = threading.Thread(target=start, args=(first_session, first_admin))
second = threading.Thread(target=start, args=(other_session, other_admin))
first.start()
second.start()
first.join(timeout=10)
second.join(timeout=10)
first_session.close()
other_session.close()
assert not first.is_alive()
assert not second.is_alive()
assert errors == []
verify = make_test_session(self.engine)
try:
bind_tasks = (
verify.query(DouyuTask)
.filter(
DouyuTask.platform_task_id == task.id,
DouyuTask.task_type == "get_bind_qr",
)
.all()
)
assert len(bind_tasks) == 1
finally:
verify.close()
def test_confirm_binding_pins_expected_role_for_two_role_snapshot(
self, monkeypatch
):
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-two-roles",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
message="已识别待确认角色",
result={
"role_name": "我是火星人2222",
"current_role_name": "狗鼻子弗尼亚bd",
"bind_ready_for_confirm": True,
"bind_confirmed": False,
},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
self.session.commit()
monkeypatch.setattr(
service.binding,
"enqueue_execution_job",
lambda _db, **_kwargs: None,
)
asyncio.run(
service.confirm_binding(
self.session,
task_id=task.id,
current=self.admin,
)
)
confirm_task = (
self.session.query(DouyuTask)
.filter(DouyuTask.task_type == "confirm_bind")
.order_by(DouyuTask.id.desc())
.first()
)
assert confirm_task is not None
assert confirm_task.result["expected_role_name"] == "我是火星人2222"
assert confirm_task.result["baseline_role_name"] == "狗鼻子弗尼亚bd"
def test_reset_binding_clears_failed_state_and_keeps_account(self):
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-reset",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="failed",
message="该游戏角色仍在换绑冷却期",
result={"bind_phase": "confirm_failed"},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "failed"
task.execution_status = "manual_required"
task.exchange_status = "not_started"
task.issue_code = "customer_role_cooldown"
task.last_error = "该游戏角色仍在换绑冷却期"
self.session.commit()
account_id = task.account_id
lease_id = task.lease_id
detail = service.reset_task_binding(
self.session,
task_id=task.id,
current=self.admin,
reason="客服核对后重置角色资料",
)
self.session.refresh(task)
assert detail["task"]["executionStatus"] == "allocated"
assert task.account_id == account_id
assert task.lease_id == lease_id
assert task.bind_task_id is None
assert task.binding_status == "not_started"
assert task.issue_code == ""
assert task.last_error == ""
event = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_reset")
.one()
)
assert event.detail_json["customerProfileReset"] is True
outbox = (
self.session.query(IntegrationOutbox)
.order_by(IntegrationOutbox.id.desc())
.first()
)
assert outbox is not None
assert outbox.payload_json["items"][0]["customerProfileReset"] is True
def test_reset_binding_rejects_running_bind_task(self):
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-running",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="running",
message="等待客户扫码",
result={"url": "https://example.com/qr"},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "failed"
task.execution_status = "waiting_bind"
self.session.commit()
with pytest.raises(HTTPException) as exc_info:
service.reset_task_binding(
self.session,
task_id=task.id,
current=self.admin,
)
assert exc_info.value.status_code == 409
assert "仍在执行" in str(exc_info.value.detail)
def test_cancel_permission_excludes_support(self):
assert "platform_fulfillment:cancel" in ROLE_PERMISSIONS["operation"]
assert "platform_fulfillment:cancel" in ROLE_PERMISSIONS["super_admin"]
assert "platform_fulfillment:cancel" not in ROLE_PERMISSIONS["support"]
assert "platform_fulfillment:view" in ROLE_PERMISSIONS["support"]
assert "platform_fulfillment:use" in ROLE_PERMISSIONS["support"]
checker = require_permission("platform_fulfillment:cancel")
support = User(
username="cancel-support",
password_hash="h",
role="support",
is_active=True,
)
operator = User(
username="cancel-operator",
password_hash="h",
role="operation",
is_active=True,
)
with pytest.raises(HTTPException) as exc_info:
checker(current_user=support)
assert exc_info.value.status_code == 403
assert checker(current_user=operator) is operator
def test_restore_permission_is_super_admin_only(self):
assert "platform_fulfillment:restore" in ROLE_PERMISSIONS["super_admin"]
assert "platform_fulfillment:restore" not in ROLE_PERMISSIONS["operation"]
assert "platform_fulfillment:restore" not in ROLE_PERMISSIONS["support"]
checker = require_permission("platform_fulfillment:restore")
operator = User(
username="restore-operator",
password_hash="h",
role="operation",
is_active=True,
)
admin = User(
username="restore-admin",
password_hash="h",
role="super_admin",
is_active=True,
)
with pytest.raises(HTTPException) as exc_info:
checker(current_user=operator)
assert exc_info.value.status_code == 403
assert checker(current_user=admin) is admin
def test_restore_manual_cancel_requeues_task_and_restores_collab(self, monkeypatch):
task = self.task()
service.cancel_task(
self.session,
task_id=task.id,
current=self.admin,
reason="客服误点取消",
)
collab_order = DouyuExternalOrder(
order_no=task.platform_order_id,
source_type="platform_fulfillment",
source_task_id=task.id,
status="void",
void_reason="直播履约任务已取消",
)
self.session.add(collab_order)
self.session.commit()
monkeypatch.setattr(
service.lifecycle,
"lookup_pending_manual_fulfillment",
lambda _item_id: {
"order_status": "paid",
"pay_status": "paid",
"fulfillment_issue_code": "",
},
)
detail = service.restore_cancelled_task(
self.session,
task_id=task.id,
current=self.admin,
reason="核对订单仍有效,恢复误取消任务",
)
self.session.refresh(task)
self.session.refresh(collab_order)
assert detail["task"]["executionStatus"] == "ready"
assert task.account_id is None
assert task.lease_id is None
assert task.next_allocate_at is not None
assert collab_order.status == "incomplete"
assert collab_order.void_reason == ""
restored = next(
event for event in detail["events"] if event["eventType"] == "task_restored"
)
assert restored["actorName"] == "pf-admin"
assert restored["detail"]["reason"] == "核对订单仍有效,恢复误取消任务"
def test_restore_rejects_source_cancelled_task(self):
task = self.task()
task.execution_status = "cancelled"
task.issue_code = "source_cancelled"
self.session.commit()
with pytest.raises(HTTPException) as exc_info:
service.restore_cancelled_task(
self.session,
task_id=task.id,
current=self.admin,
reason="尝试恢复来源取消任务",
)
assert exc_info.value.status_code == 409
assert "来源订单已取消" in str(exc_info.value.detail)
def test_restore_rejects_active_external_collab(self, monkeypatch):
task = self.task()
service.cancel_task(
self.session,
task_id=task.id,
current=self.admin,
reason="客服误点取消",
)
account = self.account("active-collab-account")
self.session.add(
DouyuExternalOrder(
order_no=task.platform_order_id,
source_type="platform_fulfillment",
source_task_id=task.id,
account_id=account.id,
account_username=account.username,
bind_game_role="人工已绑定",
status="to_recharge",
)
)
self.session.commit()
monkeypatch.setattr(
service.lifecycle,
"lookup_pending_manual_fulfillment",
lambda _item_id: {
"order_status": "paid",
"pay_status": "paid",
"fulfillment_issue_code": "",
},
)
with pytest.raises(HTTPException) as exc_info:
service.restore_cancelled_task(
self.session,
task_id=task.id,
current=self.admin,
reason="尝试恢复已人工处理订单",
)
assert exc_info.value.status_code == 409
assert "关联预售单已在人工处理" in str(exc_info.value.detail)
def test_restore_rejects_terminal_source_order(self, monkeypatch):
task = self.task()
service.cancel_task(
self.session,
task_id=task.id,
current=self.admin,
reason="客服误点取消",
)
monkeypatch.setattr(
service.lifecycle,
"lookup_pending_manual_fulfillment",
lambda _item_id: {
"order_status": "refunded",
"pay_status": "paid",
"fulfillment_issue_code": "",
},
)
with pytest.raises(HTTPException) as exc_info:
service.restore_cancelled_task(
self.session,
task_id=task.id,
current=self.admin,
reason="核对订单是否可恢复",
)
assert exc_info.value.status_code == 409
assert "不能恢复" in str(exc_info.value.detail)
def test_cancel_releases_account_and_terminal_state_cannot_be_refreshed_back(
self, monkeypatch
):
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-cancel",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="running",
message="等待客户扫码",
result={"url": "https://example.com/qr"},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
account_id = task.account_id
lease_id = task.lease_id
stopped: list[str] = []
monkeypatch.setattr(
service.lifecycle,
"stop_douyu_batches",
lambda batch_ids: stopped.extend(batch_ids) or len(batch_ids),
)
detail = service.cancel_task(
self.session,
task_id=task.id,
current=self.admin,
reason="运营取消并释放账号",
)
self.session.refresh(task)
self.session.refresh(bind_task)
lease = self.session.query(AccountLease).filter_by(id=lease_id).one()
assert detail["task"]["executionStatus"] == "cancelled"
cancel_event = next(
event
for event in detail["events"]
if event["eventType"] == "task_cancelled"
)
assert cancel_event["actorName"] == "pf-admin"
assert cancel_event["actorRole"] == "super_admin"
assert cancel_event["actorRoleLabel"] == "超级管理员"
assert task.account_id is None
assert task.lease_id is None
assert task.bind_task_id is None
assert task.binding_status == "not_started"
assert task.exchange_status == "not_started"
assert account_id is not None
assert lease.status == "released"
assert bind_task.status == "stopped"
assert stopped == ["bind-cancel"]
refreshed = service.refresh_binding(self.session, task_id=task.id)
assert refreshed["task"]["executionStatus"] == "cancelled"
self.session.refresh(task)
assert task.execution_status == "cancelled"
def test_release_to_manual_releases_lease_without_reallocating(self):
task = self._allocated()
account_id = task.account_id
lease_id = task.lease_id
detail = service.release_task_to_manual(
self.session,
task_id=task.id,
current=self.admin,
reason="以外部单协作人工处理为准",
)
self.session.refresh(task)
lease = self.session.query(AccountLease).filter_by(id=lease_id).one()
assert detail["task"]["executionStatus"] == "manual_required"
assert task.account_id is None
assert task.lease_id is None
assert task.next_allocate_at is None
assert task.issue_code == "manual_required"
assert task.last_error == "以外部单协作人工处理为准"
assert lease.status == "released"
assert lease.release_reason == "platform_fulfillment_manual"
event = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="released_to_manual")
.one()
)
assert event.detail_json["releasedAccountId"] == account_id
assert event.detail_json["releasedLeaseId"] == lease_id
def test_release_to_manual_hands_lease_to_active_collab_order(self):
task = self._allocated()
lease_id = task.lease_id
order, _ = collab.sync_platform_fulfillment_order(
self.session,
self.admin,
task,
)
assert order.status == collab.STATUS_INCOMPLETE
lease = self.session.query(AccountLease).filter_by(id=lease_id).one()
assert lease.purpose == "platform_fulfillment"
detail = service.release_task_to_manual(
self.session,
task_id=task.id,
current=self.admin,
reason="以斗鱼预售台账的人工处理为准",
)
self.session.refresh(task)
self.session.refresh(lease)
assert detail["task"]["executionStatus"] == "manual_required"
assert task.account_id is None
assert task.lease_id is None
assert lease.status == "active"
assert lease.purpose == "douyu_collab"
assert lease.expires_at is None
assert lease.batch_id == f"collab:{lease.account_id}"
assert self.session.query(AccountLease).count() == 1
def test_refresh_binding_maps_role_ready(self, monkeypatch):
notified: list[int] = []
monkeypatch.setattr(
service.binding,
"_emit_order_site_binding_state",
lambda _db, task_id: notified.append(task_id) or True,
)
task = self._allocated()
notified.clear()
bind_task = DouyuTask(
batch_id="bind-1",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"url": "https://example.com/qr",
"act_alias": "20260120QYOOB",
"role_name": "测试角色",
"need_bind_act": True,
"baseline_role_name": "测试角色",
"baseline_is_bound_act": True,
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "测试角色",
"is_bound_act": True,
"need_bind_act": True,
},
"bind_ready_for_confirm": True,
},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "preparing"
task.execution_status = "waiting_bind"
self.session.commit()
detail = service.refresh_binding(self.session, task_id=task.id)
assert detail["task"]["bindingStatus"] == "role_ready"
assert detail["task"]["bindTask"]["roleName"] == "测试角色"
assert notified == [task.id]
def test_refresh_qr_reuses_unexpired_qr_and_keeps_account(self):
task = self._allocated()
account_id = int(task.account_id or 0)
bind_task = DouyuTask(
batch_id="bind-valid-qr",
account_id=account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"url": "https://example.com/current-qr",
"qr_expires_at": (NOW + timedelta(minutes=5)).isoformat(),
},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
detail = asyncio.run(
service.start_binding(
self.session,
task_id=task.id,
current=self.admin,
force_refresh=True,
)
)
self.session.refresh(task)
assert task.bind_task_id == bind_task.id
assert task.account_id == account_id
assert detail["task"]["bindTask"]["id"] == bind_task.id
def test_refresh_expired_qr_reuses_same_account(self, monkeypatch):
task = self._allocated()
account_id = int(task.account_id or 0)
old_bind_task = DouyuTask(
batch_id="bind-expired-qr",
account_id=account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"url": "https://example.com/expired-qr",
"qr_expires_at": (NOW - timedelta(minutes=1)).isoformat(),
},
created_by=self.admin_id,
)
self.session.add(old_bind_task)
self.session.flush()
task.bind_task_id = old_bind_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
monkeypatch.setattr(
service.binding,
"enqueue_execution_job",
lambda _db, **_kwargs: None,
)
asyncio.run(
service.start_binding(
self.session,
task_id=task.id,
current=self.admin,
force_refresh=True,
)
)
self.session.refresh(task)
assert task.account_id == account_id
assert task.bind_task_id != old_bind_task.id
refreshed_task = self.session.get(DouyuTask, task.bind_task_id)
assert refreshed_task is not None
assert refreshed_task.account_id == account_id
assert refreshed_task.task_type == "get_bind_qr"
def test_refresh_binding_ignores_legacy_same_role_pending(self):
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-stale-same-role",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"url": "https://example.com/old-qr",
"role_name": "少和我较劲",
"current_role_name": "少和我较劲",
"baseline_role_name": "少和我较劲",
"need_bind_act": False,
"is_bound_act": False,
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
self.session.commit()
detail = service.refresh_binding(self.session, task_id=task.id)
self.session.refresh(task)
assert task.bind_task_id is None
assert task.binding_status == "not_started"
assert task.execution_status == "allocated"
assert detail["task"]["bindTask"] is None
event = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_stale_role_ignored")
.one()
)
assert event.detail_json["roleName"] == "少和我较劲"
def test_refresh_binding_keeps_same_role_after_pending_transition(self):
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-new-same-role",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"url": "https://example.com/new-qr",
"act_alias": "20260120QYOOB",
"role_name": "少和我较劲",
"current_role_name": "少和我较劲",
"baseline_role_name": "少和我较劲",
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "少和我较劲",
"is_bound_act": True,
},
"need_bind_act": True,
"is_bound_act": False,
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "waiting_bind"
task.execution_status = "waiting_bind"
self.session.commit()
detail = service.refresh_binding(self.session, task_id=task.id)
assert detail["task"]["bindingStatus"] == "role_ready"
assert detail["task"]["bindTask"]["roleName"] == "少和我较劲"
assert detail["task"]["bindTask"]["bindReadyForConfirm"] is True
def test_confirmed_binding_is_not_reported_as_waiting_for_confirmation(self):
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-confirmed",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="success",
result={
"role_name": "洋崽想要躺鸡",
"need_bind_act": True,
"is_bound_act": True,
"bind_ready_for_confirm": True,
"bind_confirmed": True,
"bind_phase": "confirmed",
},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "bound"
task.execution_status = "bound"
self.session.commit()
live = service.customer_binding_out(self.session, task.id)
detail = service.get_task_detail(self.session, task.id)
assert live["roleName"] == "洋崽想要躺鸡"
assert live["bindConfirmed"] is True
assert live["bindReadyForConfirm"] is False
assert detail["task"]["bindTask"]["bindReadyForConfirm"] is False
def test_refresh_binding_clears_stale_failure_when_qr_is_pending(self):
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-qr-after-failure",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="running",
result={"url": "https://example.com/new-qr"},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "failed"
task.execution_status = "manual_required"
task.issue_code = "binding_failed"
task.last_error = "绑定失败,请刷新二维码后重试"
self.session.commit()
detail = service.refresh_binding(self.session, task_id=task.id)
assert detail["task"]["bindingStatus"] == "qr_pending"
assert detail["task"]["executionStatus"] == "waiting_bind"
assert detail["task"]["issueCode"] == ""
assert detail["task"]["lastError"] == ""
def test_refresh_binding_classifies_customer_role_cooldown(self):
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-customer-cooldown",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="failed",
message="待绑定游戏账号(测试角色)未到换绑时间,请重新换账号扫码绑定",
result={
"bind_phase": "confirm_failed",
"issue_code": "account_role_cooldown",
"role_name": "测试角色",
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"confirm_error": "该账号未到可换绑时间,请使用其他账号",
"confirm_error_code": -200001,
},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "failed"
task.execution_status = "manual_required"
task.issue_code = "account_role_cooldown"
task.last_error = (
"斗鱼账号当前绑定角色(测试角色)未到可换绑时间,请更换斗鱼账号或稍后重试"
)
self.session.add_all(
[
PlatformFulfillmentEvent(
task_id=task.id,
event_type="douyu_operation_failed",
actor_type="system",
detail_json={
"douyuTaskId": bind_task.id,
"message": task.last_error,
},
),
PlatformFulfillmentEvent(
task_id=task.id,
event_type="binding_failed",
actor_type="system",
detail_json={
"bindTaskId": bind_task.id,
"issueCode": "account_role_cooldown",
"rawError": task.last_error,
},
),
]
)
self.session.commit()
historical = service.get_task_detail(self.session, task_id=task.id)
assert historical["task"]["issueCode"] == "customer_role_cooldown"
assert "游戏角色" in historical["task"]["lastError"]
operation_event = next(
event
for event in historical["events"]
if event["eventType"] == "douyu_operation_failed"
)
binding_event = next(
event
for event in historical["events"]
if event["eventType"] == "binding_failed"
)
assert "待绑定游戏账号" in operation_event["detail"]["message"]
assert operation_event["detail"]["issueCode"] == "customer_role_cooldown"
assert "待绑定游戏账号" in binding_event["detail"]["rawError"]
assert binding_event["detail"]["issueCode"] == "customer_role_cooldown"
historical_live = service.customer_binding_out(self.session, task.id)
assert historical_live["issueCode"] == "customer_role_cooldown"
assert "游戏角色" in historical_live["message"]
detail = service.refresh_binding(self.session, task_id=task.id)
assert detail["task"]["issueCode"] == "customer_role_cooldown"
assert detail["task"]["bindingStatus"] == "failed"
assert detail["task"]["executionStatus"] == "manual_required"
assert "截图" in detail["task"]["lastError"]
assert "联系客服" in detail["task"]["lastError"]
self.session.refresh(task)
assert task.issue_code == "customer_role_cooldown"
live = service.customer_binding_out(self.session, task.id)
assert live["issueCode"] == "customer_role_cooldown"
assert "游戏角色" in live["message"]
assert live["bindingStatus"] == "failed"
assert live["executionStatus"] == "manual_required"
assert live["bindReadyForConfirm"] is False
assert live["bindConfirmed"] is False
def test_refresh_binding_classifies_account_role_cooldown(self):
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-account-cooldown",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="failed",
message="当前角色 暂不能换绑,剩余 3天",
result={
"bind_phase": "change_waiting",
"change_role_wait_time": 259200,
},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "preparing"
task.execution_status = "waiting_bind"
self.session.commit()
detail = service.refresh_binding(self.session, task_id=task.id)
assert detail["task"]["issueCode"] == "account_role_cooldown"
assert detail["task"]["executionStatus"] == "manual_required"
assert "截图" in detail["task"]["lastError"]
live = service.customer_binding_out(self.session, task.id)
assert live["bindReadyForConfirm"] is False
def test_refresh_binding_uses_structured_platform_cooldown_issue(self):
"""2026-11-22 HAR:中文消息即使像角色冷却,也以 -200001 结构化码为准。"""
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-platform-cooldown-error-code",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="failed",
message="待绑定游戏账号(测试角色)未到换绑时间,请重新换账号扫码绑定",
result={
"bind_phase": "confirm_failed",
"issue_code": "account_role_cooldown",
"confirm_error": "该平台账号未到可换绑时间,请使用其他平台账号",
"confirm_error_code": -200001,
"bind_ready_for_confirm": False,
},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
self.session.commit()
detail = service.refresh_binding(self.session, task_id=task.id)
assert detail["task"]["issueCode"] == "account_role_cooldown"
assert detail["task"]["executionStatus"] == "manual_required"
assert "斗鱼账号" in detail["task"]["lastError"]
def test_list_hides_qr_but_detail_returns_it(self):
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-qr",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="running",
result={"url": "https://example.com/private-qr"},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
listed = service.list_tasks(self.session)
detail = service.get_task_detail(self.session, task.id)
assert listed["items"][0]["bindTask"]["qrUrl"] == ""
assert detail["task"]["bindTask"]["qrUrl"] == "https://example.com/private-qr"
def test_manual_completion_requires_bound_and_keeps_review_window(self):
task = self._allocated()
task.binding_status = "bound"
task.execution_status = "bound"
task.exchange_status = "eligible"
self.session.commit()
detail = service.complete_manual_exchange(
self.session,
task_id=task.id,
current=self.admin,
note="人工兑换完成",
)
assert detail["task"]["executionStatus"] == "completed"
assert detail["task"]["exchangeStatus"] == "manual_done"
lease = self.session.query(AccountLease).one()
assert lease.status == "active"
assert lease.expires_at is not None
job = AutomationJob(key=reaper.JOB_KEY, batch_size=100)
result = reaper.run_platform_fulfillment_lease_reaper(
self.session,
job,
now=lease.expires_at + timedelta(seconds=1),
)
self.session.refresh(lease)
assert result["expired"] == 1
assert lease.status == "expired"
def test_manual_completion_zero_delay_releases_immediately(self):
task = self._allocated()
task.binding_status = "bound"
task.execution_status = "bound"
task.exchange_status = "eligible"
self.session.commit()
service.update_settings(
self.session,
lease_duration_minutes=None,
completed_release_delay_minutes=30,
manual_completed_release_delay_minutes=0,
presale_waiting_release_ttl_minutes=None,
manual_required_lease_ttl_minutes=None,
order_match_started_at=NOW - timedelta(days=1),
current=self.admin,
)
service.complete_manual_exchange(
self.session,
task_id=task.id,
current=self.admin,
note="立即释放",
)
lease = self.session.query(AccountLease).one()
assert lease.status == "released"
assert lease.release_reason == "lease_policy:manual_completed"
def test_points_short_after_binding_keeps_account_and_stays_bound(
self, monkeypatch
):
task = self._allocated()
account = (
self.session.query(Account).filter(Account.id == task.account_id).one()
)
task.binding_status = "bound"
task.execution_status = "bound"
self.session.commit()
monkeypatch.setattr(
service.lifecycle,
"probe_account",
lambda *_args, **_kwargs: {
"probe_id": "points-short",
"session": {"status": "valid", "message": "有效"},
"elite": {
"status": "ok",
"raw": {"manual_type": 1},
"manual_type": 1,
"manual_score": 100,
"opened": True,
},
"eligibility": {
"points": 100,
"points_response": {"points": 100},
"limited_ids": [],
"limited_goods": [],
},
"roles": {},
"errors": {},
},
)
detail = service.refresh_exchange_eligibility(
self.session,
task_id=task.id,
current=self.admin,
)
assert detail["task"]["executionStatus"] == "bound"
assert detail["task"]["exchangeStatus"] == "points_short"
assert detail["task"]["account"]["id"] == account.id
def test_presale_refresh_after_binding_shows_waiting_release(self, monkeypatch):
task = self._allocated()
task.binding_status = "bound"
task.execution_status = "bound"
task.sale_mode = "presale"
self.session.commit()
start_at = NOW + timedelta(days=4)
end_at = NOW + timedelta(days=10)
monkeypatch.setattr(
service.lifecycle,
"probe_account",
lambda *_args, **_kwargs: {
"probe_id": "presale-waiting",
"session": {"status": "valid", "message": "有效"},
"elite": {
"status": "ok",
"raw": {"manual_type": 1},
"manual_type": 1,
"manual_score": 2000,
"opened": True,
},
"eligibility": {
"points": 2000,
"points_response": {"points": 2000},
"limited_ids": [],
"limited_goods": [],
"storehome_goods": [
{
"commodityId": COMMODITY,
"commodityName": INTERNAL_SKU,
"status": "0",
"timeLimited": 1,
"startTime": str(int(start_at.timestamp())),
"endTime": str(int(end_at.timestamp())),
}
],
},
"roles": {},
"errors": {},
},
)
detail = service.refresh_exchange_eligibility(
self.session,
task_id=task.id,
current=self.admin,
)
assert detail["task"]["executionStatus"] == "bound"
assert detail["task"]["exchangeStatus"] == "waiting_release"
assert detail["task"]["issueCode"] == "commodity_not_open"
def test_expired_elite_is_not_currently_opened(self, monkeypatch):
task = self._allocated()
account = (
self.session.query(Account).filter(Account.id == task.account_id).one()
)
task.binding_status = "bound"
task.execution_status = "bound"
self.session.commit()
monkeypatch.setattr(
service.lifecycle,
"probe_account",
lambda *_args, **_kwargs: {
"probe_id": "expired-elite",
"session": {"status": "valid", "message": "有效"},
"elite": {
"status": "ok",
"raw": {"manual_type": 1, "expire_time": 1},
"manual_type": 1,
"manual_score": 2000,
"expire_time": 1,
"opened": False,
},
"eligibility": {
"points": 2000,
"points_response": {"points": 2000},
"limited_ids": [],
"limited_goods": [],
},
"roles": {},
"errors": {},
},
)
detail = service.refresh_exchange_eligibility(
self.session,
task_id=task.id,
current=self.admin,
)
self.session.refresh(account)
assert account.elite_opened is False
assert account.elite_expire_time == 1
assert detail["task"]["exchangeStatus"] == "not_opened"
assert detail["task"]["issueCode"] == "elite_not_opened"
def test_account_change_auto_refreshes_active_exchange_projection(
self,
monkeypatch,
):
task = self._allocated()
account = self.session.get(Account, task.account_id)
task.binding_status = "bound"
task.execution_status = "bound"
task.exchange_status = "points_short"
task.issue_code = "points_short"
account.points = 2000
account.elite_opened = True
self.session.commit()
monkeypatch.setattr(
service.lifecycle,
"probe_account",
lambda *_args, **_kwargs: {
"probe_id": "auto-eligible",
"session": {"status": "valid", "message": "有效"},
"elite": {
"status": "ok",
"raw": {"manual_type": 1},
"manual_type": 1,
"manual_score": 2000,
"opened": True,
},
"eligibility": {
"points": 2000,
"points_response": {"points": 2000},
"limited_ids": [],
"limited_goods": [],
"storehome_goods": [],
},
"roles": {},
"errors": {},
},
)
detail = service.refresh_active_exchange_eligibility_for_account(
self.session,
account_id=int(account.id),
scope="elite",
actor_id=int(self.admin.id),
)
assert detail is not None
assert detail["task"]["executionStatus"] == "bound"
assert detail["task"]["exchangeStatus"] == "eligible"
assert detail["task"]["issueCode"] == ""
def test_auto_exchange_refresh_failure_keeps_bound_task_unchanged(
self,
monkeypatch,
):
task = self._allocated()
account = self.session.get(Account, task.account_id)
task.binding_status = "bound"
task.execution_status = "bound"
task.exchange_status = "points_short"
task.issue_code = "points_short"
self.session.commit()
monkeypatch.setattr(
service.lifecycle,
"probe_account",
lambda *_args, **_kwargs: (_ for _ in ()).throw(
RuntimeError("暂时查询失败")
),
)
detail = service.refresh_active_exchange_eligibility_for_account(
self.session,
account_id=int(account.id),
scope="elite",
actor_id=int(self.admin.id),
)
self.session.refresh(task)
event = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(
task_id=task.id,
event_type="eligibility_auto_refresh_failed",
)
.one()
)
assert detail is not None
assert task.execution_status == "bound"
assert task.exchange_status == "points_short"
assert task.issue_code == "points_short"
assert "暂时查询失败" in event.detail_json["error"]
def test_expired_lease_moves_unfinished_task_to_manual(self):
task = self._allocated()
lease = self.session.query(AccountLease).one()
lease.expires_at = NOW - timedelta(minutes=1)
self.session.commit()
job = AutomationJob(key=reaper.JOB_KEY, batch_size=100)
result = reaper.run_platform_fulfillment_lease_reaper(
self.session,
job,
now=NOW,
)
self.session.refresh(task)
assert result["expired"] == 1
assert task.execution_status == "manual_required"
assert task.issue_code == "lease_expired"
def test_clean_binding_failed_lease_is_held_without_expiry(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.role_bind_status = "unbound"
bind_task = DouyuTask(
batch_id="bind-timeout-cleanup",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="failed",
message="绑定二维码已过期,未识别到新扫码角色",
result={"bind_phase": "role_timeout"},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
service.refresh_binding(self.session, task_id=task.id)
lease = self.session.query(AccountLease).one()
self.session.refresh(task)
assert task.issue_code == "binding_failed"
assert task.flow_version == 2
assert lease.expires_at is None
def test_reaper_does_not_release_clean_binding_failed_lease(self):
task = self._allocated()
lease = self.session.query(AccountLease).one()
account = self.session.get(Account, task.account_id)
account.role_bind_status = "unbound"
task.execution_status = "manual_required"
task.binding_status = "failed"
task.issue_code = "binding_failed"
task.updated_at = NOW - timedelta(hours=3)
lease.expires_at = None
self.session.commit()
job = AutomationJob(key=reaper.JOB_KEY, batch_size=100)
result = reaper.run_platform_fulfillment_lease_reaper(
self.session,
job,
now=NOW,
)
self.session.refresh(task)
self.session.refresh(lease)
assert result["stale_binding_recovered"] == 0
assert result["expired"] == 0
assert lease.status == "active"
assert task.account_id is not None
assert task.lease_id is not None
assert task.issue_code == "binding_failed"
def test_unlimited_lease_is_ignored_by_reaper(self):
task = self._allocated()
lease = self.session.query(AccountLease).one()
lease.expires_at = None
self.session.commit()
job = AutomationJob(key=reaper.JOB_KEY, batch_size=100)
result = reaper.run_platform_fulfillment_lease_reaper(
self.session,
job,
now=NOW + timedelta(days=365),
)
self.session.refresh(task)
assert result["expired"] == 0
assert task.execution_status == "allocated"
def test_reaper_releases_orphan_active_lease_from_task_retry(self):
task = self._allocated()
orphan_account = self.account("orphan-retry-account")
orphan_lease = AccountLease(
account_id=orphan_account.id,
holder_user_id=self.admin_id,
purpose="platform_fulfillment",
status="active",
batch_id=f"pf:{task.id}",
commodity_id=task.commodity_id,
)
self.session.add(orphan_lease)
self.session.commit()
job = AutomationJob(key=reaper.JOB_KEY, batch_size=100)
result = reaper.run_platform_fulfillment_lease_reaper(
self.session,
job,
now=NOW,
)
self.session.refresh(orphan_lease)
task_lease = (
self.session.query(AccountLease)
.filter(AccountLease.id == task.lease_id)
.one()
)
assert result["orphan_released"] == 1
assert orphan_lease.status == "released"
assert task_lease.status == "active"
assert task.account_id is not None
def test_expired_platform_lease_hands_off_to_active_collab(self):
task = self._allocated()
lease = self.session.query(AccountLease).one()
collab.sync_platform_fulfillment_order(
self.session,
self.admin,
task,
)
lease.expires_at = NOW - timedelta(minutes=1)
self.session.commit()
job = AutomationJob(key=reaper.JOB_KEY, batch_size=100)
result = reaper.run_platform_fulfillment_lease_reaper(
self.session,
job,
now=NOW,
)
self.session.refresh(task)
self.session.refresh(lease)
assert result["expired"] == 0
assert result["affected_tasks"] == 1
assert task.execution_status == "manual_required"
assert task.account_id is None
assert task.lease_id is None
assert task.issue_code == "lease_expired_collab_handoff"
assert lease.status == "active"
assert lease.purpose == "douyu_collab"
assert lease.expires_at is None
def test_completion_rejects_limited_exchange(self):
task = self._allocated()
task.binding_status = "bound"
task.execution_status = "manual_required"
task.exchange_status = "limited"
self.session.commit()
with pytest.raises(HTTPException):
service.complete_manual_exchange(
self.session,
task_id=task.id,
current=self.admin,
)
def test_empty_baseline_stripped_bind_candidates_reconciles_to_role_ready(self):
"""历史无 baseline 且 bind_candidates 被裁剪的扫码任务,刷新/对账后应收敛为待确认。"""
task = self._allocated()
task.customer_role_name = "欧美真心"
account = self.session.get(Account, task.account_id)
account.game_name = "曲奇小诺゛"
account.role_bind_status = "bound"
qr_task = DouyuTask(
batch_id="stripped-pending-qr",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
message="已识别角色: 欧美真心,待确认绑定",
platform_task_id=task.id,
result={
"act_alias": "20260120QYOOB",
"action_act_aliases": ["20260120QYOOB"],
"baseline_role_name": "",
"baseline_is_bound_act": False,
"before_bind_info": {},
"expected_role_name": "欧美真心",
"expected_role_required": True,
"role_name": "欧美真心",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
"url": "https://livelink.example/qr",
"bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "欧美真心",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"is_bound_act": False,
"is_bound_role": True,
"need_bind_act": True,
"need_bind_role": True,
},
"bind_decision": {
"alias": "20260120QYOOB",
"role_name": "欧美真心",
"actionable_alias": True,
"confirmable": True,
"reason": "existing_actionable_pending",
},
"bind_candidates": [
{
"act_alias": "cjm",
"role_name": "欧美真心",
"is_bound_act": False,
},
{
"act_alias": "20260120QYOOB",
"role_name": "欧美真心",
"is_bound_act": False,
},
],
"bind_candidate_decisions": [
{
"alias": "20260120QYOOB",
"role_name": "欧美真心",
"is_bound_act": False,
"is_bound_role": True,
"need_bind_act": True,
"need_bind_role": True,
"actionable_alias": True,
"confirmable": True,
"reason": "existing_actionable_pending",
}
],
},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
reconciled = service.reconcile_binding_observations(self.session)
self.session.commit()
detail = service.get_task_detail(self.session, task.id)
item = detail["task"]
assert reconciled >= 1
assert item["bindingStatus"] == "role_ready"
assert item["executionStatus"] == "role_ready"
assert item["bindTask"]["roleName"] == "欧美真心"
assert item["bindTask"]["bindReadyForConfirm"] is True
assert item["bindingEvidence"]["scannedRole"] == "欧美真心"
assert item["bindingEvidence"]["baselineRole"] == ""
assert item["bindingEvidence"]["confirmable"] is True
assert item["bindingEvidence"]["actionPending"]["needBindAct"] is True
assert item["bindingEvidence"]["actionPending"]["channel"] == "手Q / 苹果(iOS)"
def test_current_confirm_bind_with_mismatched_customer_role_is_rejected(self):
"""即使 bind_task_id 已指向 confirm_bind,确认出非客户目标角色也必须拒绝。"""
task = self._allocated()
task.customer_role_name = "客户指定角色"
confirm_task = DouyuTask(
batch_id="current-mismatched-confirm",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"act_alias": "20260120QYOOB",
"action_act_aliases": ["20260120QYOOB"],
"role_name": "账号旧角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"bind_confirmed": True,
"bind_phase": "confirmed",
},
created_by=self.admin_id,
)
self.session.add(confirm_task)
self.session.flush()
task.bind_task_id = confirm_task.id
task.binding_status = "confirming"
task.execution_status = "binding_confirming"
self.session.commit()
synced = service.sync_task_from_binding_runner(
self.session,
douyu_task_id=confirm_task.id,
)
self.session.refresh(task)
rejection = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_sync_rejected")
.one()
)
assert synced == 1
assert task.binding_status != "bound"
assert task.binding_status == "role_ready"
assert task.execution_status == "role_ready"
assert "账号旧角色" in (task.last_error or "")
assert "客户指定角色" in (task.last_error or "")
assert rejection.detail_json["reason"] == "target_mismatch"
def test_refresh_absorbs_newer_owned_confirm_and_operator_can_fix_special_role_name(
self,
):
"""精英宝典确认后应吸收最新角色;特殊字符名可直接复制并修正后结算。"""
task = self._allocated()
task.customer_role_name = "狞王ゞ"
task.customer_platform = "wechat"
task.customer_system = "android"
qr_task = DouyuTask(
batch_id="older-qr-still-polling",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="running",
platform_task_id=task.id,
result={"url": "https://livelink.example/qr", "bind_polling": True},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
account = self.session.get(Account, task.account_id)
account.role_bind_status = "bound"
account.game_name = "゚狙王゜"
account.game_channel = "微信 · 安卓(android)"
confirm_task = DouyuTask(
batch_id="elite-workbench-confirmed-special-name",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"role_name": "゚狙王゜",
"area_name": "微信",
"plat_name": "安卓(android)",
"bind_confirmed": True,
"bind_phase": "confirmed",
},
created_by=self.admin_id,
)
self.session.add(confirm_task)
self.session.commit()
detail = service.refresh_binding(self.session, task_id=task.id)
self.session.refresh(task)
assert task.bind_task_id == confirm_task.id
assert detail["task"]["bindingStatus"] == "role_ready"
assert detail["task"]["executionStatus"] == "role_ready"
assert detail["task"]["customerProfile"]["platformRoleName"] == "゚狙王゜"
assert "゚狙王゜" in (task.last_error or "")
assert "狞王ゞ" in (task.last_error or "")
updated = service.update_customer_profile_by_operator(
self.session,
task_id=task.id,
current=self.admin,
customer_role_name=detail["task"]["customerProfile"]["platformRoleName"],
platform="wechat",
system="android",
reopen_binding=False,
)
self.session.refresh(task)
assert task.customer_role_name == "゚狙王゜"
assert task.binding_status == "bound"
assert task.execution_status == "bound"
assert task.last_error == ""
assert updated["task"]["bindingStatus"] == "bound"
def test_refresh_recovers_old_qr_timeout_with_newer_owned_confirm(self):
"""旧二维码已超时失败时,更晚且归属本单的成功确认仍应恢复待确认。"""
task = self._allocated()
task.customer_role_name = "狞王ゞ"
task.customer_platform = "wechat"
task.customer_system = "android"
qr_task = DouyuTask(
batch_id="timed-out-qr-before-confirm",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="failed",
platform_task_id=task.id,
result={"bind_phase": "role_timeout"},
message="等待扫码绑定超时",
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "failed"
task.execution_status = "manual_required"
task.issue_code = "binding_failed"
task.last_error = "等待扫码绑定超时"
account = self.session.get(Account, task.account_id)
account.role_bind_status = "bound"
account.game_name = "゚狙王゜"
account.game_channel = "微信 · 安卓(android)"
confirm_task = DouyuTask(
batch_id="late-confirm-after-qr-timeout",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"role_name": "゚狙王゜",
"area_name": "微信",
"plat_name": "安卓(android)",
"bind_confirmed": True,
"bind_phase": "confirmed",
},
created_by=self.admin_id,
)
self.session.add(confirm_task)
self.session.commit()
detail = service.refresh_binding(self.session, task_id=task.id)
self.session.refresh(task)
assert task.bind_task_id == confirm_task.id
assert detail["task"]["bindingStatus"] == "role_ready"
assert detail["task"]["executionStatus"] == "role_ready"
assert task.issue_code == ""
assert "゚狙王゜" in (task.last_error or "")
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_sync_rejected")
.filter(
PlatformFulfillmentEvent.detail_json["sourceTaskId"].as_integer()
== int(confirm_task.id)
)
.count()
== 1
)
def test_save_customer_profile_immediately_reconciles_existing_qr_candidates(self):
"""先出码扫码、后提交客户资料时,保存资料应立即把订单收敛到 role_ready。"""
task = self._allocated()
task.customer_role_name = ""
qr_task = DouyuTask(
batch_id="profile-late-qr",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"act_alias": "20260120QYOOB",
"action_act_aliases": ["20260120QYOOB"],
"expected_role_name": "",
"expected_role_required": True,
"role_name": "后补角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
"url": "https://livelink.example/qr",
"bind_candidates": [
{
"act_alias": "20260120QYOOB",
"role_name": "后补角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"is_bound_act": False,
"is_bound_role": True,
"need_bind_act": True,
"need_bind_role": True,
}
],
},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
out = service.save_customer_profile(
self.session,
task_id=task.id,
customer_role_name="后补角色",
platform="qq",
system="ios",
home_images=[{"url": "https://img.example/1.png"}],
)
self.session.refresh(task)
assert task.binding_status == "role_ready"
assert task.execution_status == "role_ready"
assert out["bindingStatus"] == "role_ready"
assert out["roleName"] == "后补角色"
assert out["bindReadyForConfirm"] is True
def test_unlinked_workbench_qr_with_wrong_role_is_not_attached(self):
"""工作台无归属扫码任务若角色与客户目标不一致,绝不能挂到订单上。"""
task = self._allocated()
task.customer_role_name = "客户目标角色"
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
workbench_qr = DouyuTask(
batch_id="workbench-wrong-role",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"act_alias": "20260120QYOOB",
"action_act_aliases": ["20260120QYOOB"],
"role_name": "工作台别的号角色",
"area_name": "微信",
"plat_name": "安卓(android)",
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
"bind_candidates": [
{
"act_alias": "20260120QYOOB",
"role_name": "工作台别的号角色",
"is_bound_act": False,
"is_bound_role": True,
"need_bind_act": True,
"need_bind_role": True,
}
],
},
created_by=self.admin_id,
)
self.session.add(workbench_qr)
self.session.commit()
reconciled = service.reconcile_binding_observations(self.session)
self.session.refresh(task)
assert reconciled == 0
assert task.binding_status == "qr_pending"
assert task.bind_task_id is None
def test_waiting_scan_preflight_same_pair_with_different_customer_role_does_not_reuse(
self,
):
"""发码预检阶段 cjm 残留旧角色且与客户提交角色不同时,绝不能提前误标为 bound。"""
task = self._allocated()
task.customer_role_name = "妳总固执任性"
account = self.session.get(Account, task.account_id)
account.game_name = "强者不屑质疑"
account.role_bind_status = "bound"
qr_task = DouyuTask(
batch_id="preflight-old-cjm",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="running",
platform_task_id=task.id,
result={
"act_alias": "20260120QYOOB",
"action_act_aliases": ["20260120QYOOB"],
"expected_role_name": "妳总固执任性",
"expected_role_required": True,
"current_role_name": "强者不屑质疑",
"baseline_role_name": "强者不屑质疑",
"role_name": "",
"bind_ready_for_confirm": False,
"bind_confirmed": False,
"bind_phase": "waiting_scan",
"url": "https://livelink.example/qr",
"bind_candidates": [
{
"act_alias": "cjm",
"role_name": "强者不屑质疑",
"is_bound_act": False,
"is_bound_role": True,
"need_bind_act": False,
},
{
"act_alias": "20260120QYOOB",
"role_name": "强者不屑质疑",
"is_bound_act": True,
"is_bound_role": True,
"need_bind_act": True,
},
],
},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "preparing"
task.execution_status = "waiting_bind"
self.session.commit()
service.sync_task_from_binding_runner(self.session, douyu_task_id=qr_task.id)
detail = service.get_task_detail(self.session, task.id)
self.session.refresh(task)
assert task.binding_status == "qr_pending"
assert task.execution_status == "waiting_bind"
assert detail["task"]["bindingEvidence"]["scannedRole"] == ""
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_reused_existing_pair")
.count()
== 0
)
def test_reconcile_reverts_false_same_pair_reuse_and_promotes_scanned_role(self):
"""已被历史同对复用误锁为 bound 但尚未兑换的订单,重启对账后应自动回退并推进真实扫码角色。"""
task = self._allocated()
task.customer_role_name = "妳总固执任性"
account = self.session.get(Account, task.account_id)
account.game_name = "强者不屑质疑"
account.role_bind_status = "bound"
qr_task = DouyuTask(
batch_id="false-reuse-qr",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"act_alias": "cjm",
"action_act_aliases": ["20260120QYOOB"],
"expected_role_name": "妳总固执任性",
"expected_role_required": True,
"current_role_name": "强者不屑质疑",
"baseline_role_name": "强者不屑质疑",
"role_name": "妳总固执任性",
"area_name": "手Q",
"plat_name": "安卓(android)",
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
"url": "https://livelink.example/qr",
"bind_candidates": [
{
"act_alias": "cjm",
"role_name": "妳总固执任性",
"area_name": "手Q",
"plat_name": "安卓(android)",
"is_bound_act": False,
"is_bound_role": True,
"need_bind_act": False,
},
{
"act_alias": "20260120QYOOB",
"role_name": "强者不屑质疑",
"area_name": "微信",
"plat_name": "安卓(android)",
"is_bound_act": True,
"is_bound_role": True,
"need_bind_act": True,
},
],
},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "bound"
task.execution_status = "bound"
self.session.add(
PlatformFulfillmentEvent(
task_id=task.id,
event_type="binding_reused_existing_pair",
actor_type="system",
actor_id="",
detail_json={
"roleName": "强者不屑质疑",
"sourceTaskId": qr_task.id,
"reason": "same_account_same_role",
},
)
)
self.session.commit()
reconciled = service.reconcile_binding_observations(self.session)
self.session.refresh(task)
assert reconciled >= 1
assert task.binding_status == "role_ready"
assert task.execution_status == "role_ready"
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_false_reuse_reverted")
.count()
== 1
)
def test_operator_update_customer_profile_reopens_failed_and_syncs_pending(self):
"""工作台修改客户资料:可修正名字/区服/系统并重置失败态,也会同步当前绑定任务与 Outbox。"""
task = self._allocated()
self.complete_customer_profile(task)
task.customer_role_name = "妎䏓"
task.customer_platform = "qq"
task.customer_system = "ios"
qr_task = DouyuTask(
batch_id="edit-profile-failed",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="failed",
platform_task_id=task.id,
message="绑定二维码已过期:期间扫到「妎朊」,与填写角色「妎䏓」不一致",
result={"expected_role_name": "妎䏓", "expected_role_required": True},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "failed"
task.execution_status = "manual_required"
task.issue_code = "binding_failed"
task.last_error = "已扫到角色「妎朊」,与下单填写的「妎䏓」不一致"
self.session.commit()
detail = service.update_customer_profile_by_operator(
self.session,
task_id=task.id,
current=self.admin,
customer_role_name="妎朊",
platform="qq",
system="ios",
reopen_binding=True,
)
self.session.refresh(task)
assert task.customer_role_name == "妎朊"
assert task.binding_status == "not_started"
assert task.execution_status == "allocated"
assert task.bind_task_id is None
assert task.issue_code == ""
assert task.last_error == ""
assert detail["task"]["customerProfile"]["roleName"] == "妎朊"
updated_events = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="customer_profile_updated")
.all()
)
assert len(updated_events) == 1
assert updated_events[0].detail_json["previousRoleName"] == "妎䏓"
assert updated_events[0].detail_json["customerRoleName"] == "妎朊"
assert updated_events[0].detail_json["reopenedBinding"] is True
# 已绑定订单不允许直接修改资料
task.binding_status = "bound"
task.execution_status = "bound"
self.session.commit()
with pytest.raises(HTTPException) as exc:
service.update_customer_profile_by_operator(
self.session,
task_id=task.id,
current=self.admin,
customer_role_name="新角色",
platform="wechat",
system="android",
)
assert exc.value.status_code == 409
def test_mismatched_scanned_role_is_recorded_in_timeline_and_evidence(self):
"""扫码扫到与下单填写不一致的角色时,应写入时间线并在失败提示/证据中透出。"""
task = self._allocated()
self.complete_customer_profile(task)
task.customer_role_name = "妎䏓"
qr_task = DouyuTask(
batch_id="mismatch-qr",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="running",
platform_task_id=task.id,
result={
"url": "https://livelink.example/qr",
"expected_role_name": "妎䏓",
"expected_role_required": True,
"last_mismatched_role": {
"act_alias": "cjm",
"role_name": "妎朊",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"expected_role_name": "妎䏓",
"observed_at": NOW.isoformat(),
},
"mismatched_roles": [
{
"act_alias": "cjm",
"role_name": "妎朊",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"expected_role_name": "妎䏓",
"observed_at": NOW.isoformat(),
}
],
},
created_by=self.admin_id,
)
self.session.add(qr_task)
self.session.flush()
task.bind_task_id = qr_task.id
task.binding_status = "qr_pending"
task.execution_status = "waiting_bind"
self.session.commit()
# 轮询期间记录一次不匹配事件(重复同步应去重)
service.sync_task_from_binding_runner(self.session, douyu_task_id=qr_task.id)
service.sync_task_from_binding_runner(self.session, douyu_task_id=qr_task.id)
mismatch_events = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_scanned_role_mismatch")
.all()
)
assert len(mismatch_events) == 1
assert mismatch_events[0].detail_json["scannedRoleName"] == "妎朊"
assert mismatch_events[0].detail_json["expectedRoleName"] == "妎䏓"
detail = service.get_task_detail(self.session, task.id)
assert detail["task"]["bindingEvidence"]["scannedRole"] == ""
assert detail["task"]["bindingEvidence"]["mismatchedRole"]["roleName"] == "妎朊"
# 超时失败时明确提示曾扫到的不匹配角色
qr_task.status = "failed"
qr_task.message = "绑定二维码已过期:期间扫到「妎朊」,与填写角色「妎䏓」不一致"
self.session.commit()
service.sync_task_from_binding_runner(self.session, douyu_task_id=qr_task.id)
self.session.refresh(task)
assert task.binding_status == "failed"
assert "妎朊" in task.last_error
assert "妎䏓" in task.last_error
def test_verify_task_binding_records_success_and_reverts_mismatch(
self, monkeypatch
):
"""确认绑定后复核斗鱼:一致时记复核通过;斗鱼未绑定或角色不一致时回退转人工。"""
from web.backend.services.platform_fulfillment import binding as pf_binding
task = self._allocated()
self.complete_customer_profile(task)
task.customer_role_name = "越伤痛"
confirm_task = DouyuTask(
batch_id="verify-confirm",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={"role_name": "越伤痛", "bind_confirmed": True},
created_by=self.admin_id,
)
self.session.add(confirm_task)
self.session.flush()
task.bind_task_id = confirm_task.id
task.binding_status = "bound"
task.execution_status = "bound"
self.session.commit()
monkeypatch.setattr(pf_binding, "activity_client", lambda *_a, **_kw: object())
monkeypatch.setattr(
pf_binding,
"resolve_elite_role",
lambda _client, _cfg: {
"status": "bound",
"role_name": "越伤痛",
"area_name": "手Q",
"plat_name": "安卓(android)",
"game_channel": "手Q / 安卓(android)",
"source_alias": "20260120QYOOB",
"bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "越伤痛",
"is_bound_act": True,
"is_bound_role": True,
},
"bind_infos": [
{
"act_alias": "20260120QYOOB",
"role_name": "越伤痛",
"area_name": "手Q",
"plat_name": "安卓(android)",
"is_bound_act": True,
"is_bound_role": True,
"need_bind_act": True,
"need_bind_role": True,
}
],
"errors": [],
},
)
detail = service.verify_task_binding_sync(
self.session,
task_id=task.id,
current=self.admin,
automatic=True,
)
self.session.refresh(task)
assert task.binding_status == "bound"
assert detail["events"][0]["eventType"] == "binding_verified"
assert (
self.session.query(DouyuRoleApiLog)
.filter_by(account_id=task.account_id, stage="fulfillment.verify_binding")
.count()
== 1
)
# 若复核发现斗鱼当前其实绑在别的旧角色上,应回退为人工处理
monkeypatch.setattr(
pf_binding,
"resolve_elite_role",
lambda _client, _cfg: {
"status": "bound",
"role_name": "清耆白清万入识",
"area_name": "手Q",
"plat_name": "安卓(android)",
"game_channel": "手Q / 安卓(android)",
"source_alias": "20260120QYOOB",
"bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "清耆白清万入识",
"is_bound_act": True,
"is_bound_role": True,
},
"bind_infos": [
{
"act_alias": "20260120QYOOB",
"role_name": "清耆白清万入识",
"is_bound_act": True,
"is_bound_role": True,
"need_bind_act": True,
"need_bind_role": True,
}
],
"errors": [],
},
)
service.verify_task_binding_sync(
self.session,
task_id=task.id,
current=self.admin,
automatic=False,
)
self.session.refresh(task)
assert task.binding_status == "failed"
assert task.execution_status == "manual_required"
assert task.issue_code == "role_changed"
assert "清耆白清万入识" in task.last_error
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="binding_verify_failed")
.count()
== 1
)
def test_workbench_blocks_rebind_and_goods_on_bound_or_collab_accounts(self):
"""已绑定履约单与预售台账占用期间,禁止工作台无归属绑码/换绑,且履约期禁兑换。"""
from web.backend.models import DouyuExternalOrder
from web.backend.services.douyu_service import (
DouyuLeaseConflictError,
create_douyu_planned_tasks,
)
task = self._allocated()
task.binding_status = "bound"
task.execution_status = "bound"
self.session.commit()
for blocked_type in (
"get_bind_qr",
"confirm_bind",
"lock_goods",
"pay_locked_order",
"exchange_goods",
):
with pytest.raises(DouyuLeaseConflictError):
create_douyu_planned_tasks(
self.session,
[task.account_id],
blocked_type,
"elite",
self.admin_id,
enqueue_execution=False,
)
# 只读查询仍允许从工作台发起
_, query_count = create_douyu_planned_tasks(
self.session,
[task.account_id],
"query_points",
"elite",
self.admin_id,
enqueue_execution=False,
)
assert query_count == 1
collab_account = Account(
username="collab-occupied-acc",
password="pw",
email="collab@example.com",
email_password="epw",
cookie="acf_uid=9090; acf_nickname=collab",
status="active",
)
self.session.add(collab_account)
self.session.flush()
collab_lease = AccountLease(
account_id=collab_account.id,
holder_user_id=self.admin_id,
scope="elite",
purpose="douyu_collab",
batch_id=f"collab:{collab_account.id}",
status="active",
)
self.session.add(collab_lease)
self.session.add(
DouyuExternalOrder(
order_no="DY-WORKBENCH-BLOCK-1",
shop="店铺A",
owner_id=self.admin_id,
account_id=collab_account.id,
account_username=collab_account.username,
gift_name="礼包A",
bind_game_role="原绑定角色",
status="to_recharge",
created_by=self.admin_id,
)
)
self.session.commit()
for blocked_bind_type in ("get_bind_qr", "confirm_bind"):
with pytest.raises(DouyuLeaseConflictError):
create_douyu_planned_tasks(
self.session,
[collab_account.id],
blocked_bind_type,
"elite",
self.admin_id,
enqueue_execution=False,
)
# 预售台账账号仍可由人工从工作台查积分或做兑换,不被绑定拦截误伤
_, collab_query_count = create_douyu_planned_tasks(
self.session,
[collab_account.id],
"query_points",
"elite",
self.admin_id,
enqueue_execution=False,
)
assert collab_query_count == 1
def test_workbench_force_exchange_requires_permission_and_matching_role(self):
"""超管/运营可在核对账号与非空角色一致后强制锁单/兑换,并只在履约时间线留痕。"""
from fastapi import HTTPException
from web.backend.models import DouyuGoodsSnapshot
from web.backend.routers.douyu import _prepare_task_batch
from web.backend.schemas import DouyuTaskBatchRequest
task = self._allocated()
task.binding_status = "bound"
task.execution_status = "bound"
task.customer_role_name = "客户目标角色"
account = self.session.get(Account, task.account_id)
account.game_name = ""
account.role_bind_status = "bound"
self.session.add(
DouyuGoodsSnapshot(
commodity_id="bag-force-1",
name="套装-花椰椰",
score=988,
raw={"name": "套装-花椰椰"},
)
)
support_user = User(
username="pf-support",
password_hash="h",
role="support",
is_active=True,
)
op_user = User(
username="pf-op",
password_hash="h",
role="operation",
is_active=True,
)
self.session.add_all([support_user, op_user])
self.session.commit()
req_exchange = DouyuTaskBatchRequest(
account_ids=[account.id],
task_type="exchange_goods",
handbook_scope="elite",
payload={"commodity_id": "bag-force-1"},
)
req_force = DouyuTaskBatchRequest(
account_ids=[account.id],
task_type="exchange_goods",
handbook_scope="elite",
payload={"commodity_id": "bag-force-1"},
force_occupied=True,
)
# 客服即使有自己名下账号并带 douyu:task,也无权在占用期间强制发放
account.assigned_to = support_user.id
self.session.commit()
with pytest.raises(HTTPException) as exc_sup_409:
_prepare_task_batch(req_exchange, self.session, support_user)
assert exc_sup_409.value.status_code == 409
with pytest.raises(HTTPException) as exc_sup_403:
_prepare_task_batch(req_force, self.session, support_user)
assert exc_sup_403.value.status_code == 403
account.assigned_to = None
self.session.commit()
# 运营但账号尚未获取到游戏角色名 -> 严格拒绝并提示先一键获取游戏名
with pytest.raises(HTTPException) as exc_empty_role:
_prepare_task_batch(req_exchange, self.session, op_user)
assert exc_empty_role.value.status_code == 409
assert "一键获取游戏名" in exc_empty_role.value.detail
with pytest.raises(HTTPException) as exc_empty_force:
_prepare_task_batch(req_force, self.session, op_user)
assert exc_empty_force.value.status_code == 409
assert "一键获取游戏名" in exc_empty_force.value.detail
# 角色与履约目标角色不一致 -> 拒绝
account.game_name = "别的错误角色"
self.session.commit()
with pytest.raises(HTTPException) as exc_mismatch:
_prepare_task_batch(req_force, self.session, op_user)
assert exc_mismatch.value.status_code == 409
assert "不一致" in exc_mismatch.value.detail
# 禁止强制绑码/换绑
req_bind_force = DouyuTaskBatchRequest(
account_ids=[account.id],
task_type="get_bind_qr",
handbook_scope="elite",
force_occupied=True,
)
with pytest.raises(HTTPException) as exc_bind:
_prepare_task_batch(req_bind_force, self.session, op_user)
assert exc_bind.value.status_code == 400
# 角色一致后:首次返回 requires_force_confirmation,二次确认提交成功且保持履约状态
account.game_name = "客户目标角色"
self.session.commit()
preview = _prepare_task_batch(req_exchange, self.session, op_user)
assert preview["requires_force_confirmation"] is True
assert preview["occupied_accounts"][0]["account_role"] == "客户目标角色"
assert preview["occupied_accounts"][0]["customer_role_name"] == "客户目标角色"
created = _prepare_task_batch(req_force, self.session, op_user)
assert created["success"] is True
assert created["count"] == 1
douyu_task = (
self.session.query(DouyuTask)
.filter(DouyuTask.batch_id == created["batch_id"])
.one()
)
assert douyu_task.result["payload"]["force_occupied"] is True
assert douyu_task.result["payload"]["force_expected_role"] == "客户目标角色"
self.session.refresh(task)
assert task.execution_status == "bound"
assert task.binding_status == "bound"
evt = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(task_id=task.id, event_type="workbench_force_exchange")
.one()
)
assert evt.detail_json["operatorUsername"] == "pf-op"
assert evt.detail_json["accountRole"] == "客户目标角色"
assert evt.detail_json["goodsName"] == "套装-花椰椰"
TRIO_BAG412 = "20260120QYOOB_bag412"
TRIO_BAG413 = "20260120QYOOB_bag413"
TRIO_BAG414 = "20260120QYOOB_bag414"
class TestAllocationPolicyAndSameRoleReuse(_Base):
def _add_commodity_state(
self,
account: Account,
commodity_id: str,
*,
eligibility: str = "eligible",
availability: str = "available",
) -> None:
self.session.add(
AccountCommodityState(
account_id=account.id,
platform="douyu",
scope="elite",
commodity_id=commodity_id,
commodity_name=commodity_id,
account_eligibility=eligibility,
offer_state="active",
stock_state="in_stock",
availability=availability,
observed_at=NOW,
valid_until=NOW + timedelta(hours=6),
source="test_fixture",
)
)
def _create_commodity_task(
self,
*,
commodity_id: str,
order_suffix: str,
role_name: str = "",
required_points: int = 8000,
) -> PlatformFulfillmentTask:
mapping = (
self.session.query(PlatformCommodityMapping)
.filter_by(commodity_id=commodity_id)
.first()
)
if mapping is None:
mapping = PlatformCommodityMapping(
target_platform="douyu",
internal_sku_key=f"sku-{commodity_id}",
commodity_id=commodity_id,
goods_name=f"商品-{commodity_id}",
required_points=required_points,
scope="elite",
enabled=True,
created_by=self.admin_id,
created_at=NOW,
updated_at=NOW,
)
self.session.add(mapping)
self.session.flush()
task = PlatformFulfillmentTask(
source_system="order_site",
source_order_id=f"ord-{order_suffix}",
source_order_item_id=f"item-{order_suffix}",
source_fulfillment_id=f"ff-{order_suffix}",
platform_order_id=f"ORDER-{order_suffix}",
provider="91kaquan",
shop_id="shop-1",
shop_name="测试店",
sku_code=mapping.internal_sku_key,
sku_name=mapping.goods_name,
internal_sku_key=mapping.internal_sku_key,
quantity=1,
order_amount_fen=9900,
target_platform="douyu",
scope="elite",
commodity_mapping_id=mapping.id,
commodity_id=commodity_id,
required_points=required_points,
customer_role_name=role_name,
customer_platform="wechat" if role_name else "",
customer_system="android" if role_name else "",
binding_status="not_started",
execution_status="ready",
exchange_status="not_started",
source_snapshot_json={"order_no": f"ORDER-{order_suffix}"},
paid_at=NOW,
created_at=NOW,
updated_at=NOW,
)
self.session.add(task)
self.session.commit()
return task
def test_trio_bundle_requires_all_three_and_ordinary_preserves_bundle_pool(self):
# 只有部分资格(缺 bag414)
partial = self.account("partial-trio", points=8000, capability=False)
self._add_commodity_state(partial, TRIO_BAG412, eligibility="eligible")
self._add_commodity_state(partial, TRIO_BAG413, eligibility="eligible")
self._add_commodity_state(partial, TRIO_BAG414, eligibility="limited")
# 仅普通商品有资格(无三皮肤全资格)
ordinary_only = self.account("ordinary-only", points=8000, capability=False)
self._add_commodity_state(ordinary_only, COMMODITY, eligibility="eligible")
# 具备三皮肤全资格 + 普通商品资格
full_trio = self.account("full-trio", points=8000, capability=False)
self._add_commodity_state(full_trio, TRIO_BAG412, eligibility="eligible")
self._add_commodity_state(full_trio, TRIO_BAG413, eligibility="eligible")
self._add_commodity_state(full_trio, TRIO_BAG414, eligibility="eligible")
self._add_commodity_state(full_trio, COMMODITY, eligibility="eligible")
self.session.commit()
# 普通单应避开 full-trio,把全资格账号池留给三皮肤联合订单
ordinary_task = self._create_commodity_task(
commodity_id=COMMODITY,
order_suffix="ord-1",
required_points=1280,
)
ordinary_detail = service.allocate_task(
self.session,
task_id=ordinary_task.id,
current=self.admin,
)
assert ordinary_detail["task"]["account"]["id"] == ordinary_only.id
# 购买三皮肤之一必须匹配三者全部可兑的账号
trio_task = self._create_commodity_task(
commodity_id=TRIO_BAG412,
order_suffix="trio-1",
role_name="联合玩家",
)
trio_detail = service.allocate_task(
self.session,
task_id=trio_task.id,
current=self.admin,
)
assert trio_detail["task"]["account"]["id"] == full_trio.id
# 当全资格账号均已被占用,只剩 partial-trio 时,必须阻止误选并标明联合缺口
second_trio = self._create_commodity_task(
commodity_id=TRIO_BAG413,
order_suffix="trio-2",
role_name="另一个玩家",
)
failed = service.allocate_task(
self.session,
task_id=second_trio.id,
current=self.admin,
)
assert failed["task"]["account"] is None
assert failed["task"]["issueCode"] == "bundle_co_eligibility_missing"
def test_bundle_prefer_all_and_settings_policy_persistence(self):
saved = service.update_settings(
self.session,
lease_duration_minutes=None,
order_match_started_at=NOW - timedelta(days=1),
allocation_policy={
"sameRoleReuseEnabled": True,
"preserveBundlePool": False,
"priorityOrder": [
"bundle_match",
"same_role_reuse",
"resource_ready",
"points_asc",
"ck_freshness",
"preserve_bundle_pool",
],
"bundleRules": [
{
"id": "soft-duo",
"name": "两件套优先全部可兑",
"enabled": True,
"mode": "prefer_all",
"commodityIds": [TRIO_BAG412, TRIO_BAG413],
}
],
},
current=self.admin,
)
assert saved["allocationPolicy"]["preserveBundlePool"] is False
assert saved["allocationPolicy"]["priorityOrder"][0] == "bundle_match"
assert saved["allocationPolicy"]["bundleRules"][0]["mode"] == "prefer_all"
fetched = service.get_settings(self.session)
assert fetched["allocationPolicy"]["bundleRules"][0]["commodityIds"] == [
TRIO_BAG412,
TRIO_BAG413,
]
partial = self.account("prefer-partial", points=8000, capability=False)
self._add_commodity_state(partial, TRIO_BAG412, eligibility="eligible")
full = self.account("prefer-full", points=9000, capability=False)
self._add_commodity_state(full, TRIO_BAG412, eligibility="eligible")
self._add_commodity_state(full, TRIO_BAG413, eligibility="eligible")
self.session.commit()
# Full 可用时 prefer_all 优先 full
t1 = self._create_commodity_task(
commodity_id=TRIO_BAG412,
order_suffix="pref-1",
role_name="玩家A",
)
d1 = service.allocate_task(self.session, task_id=t1.id, current=self.admin)
assert d1["task"]["account"]["id"] == full.id
# Full 已被占用后,prefer_all 允许降级命中 partial
t2 = self._create_commodity_task(
commodity_id=TRIO_BAG412,
order_suffix="pref-2",
role_name="玩家B",
)
d2 = service.allocate_task(self.session, task_id=t2.id, current=self.admin)
assert d2["task"]["account"]["id"] == partial.id
def test_same_role_multi_skin_shares_account_lease_and_propagates_bound(self):
trio_acc = self.account("shared-trio-acc", points=24000, capability=False)
for cid in (TRIO_BAG412, TRIO_BAG413, TRIO_BAG414):
self._add_commodity_state(trio_acc, cid, eligibility="eligible")
backup_acc = self.account("backup-trio-acc", points=24000, capability=False)
for cid in (TRIO_BAG412, TRIO_BAG413, TRIO_BAG414):
self._add_commodity_state(backup_acc, cid, eligibility="eligible")
self.session.commit()
task1 = self._create_commodity_task(
commodity_id=TRIO_BAG412,
order_suffix="same-1",
role_name="同角色三连下单",
)
task2 = self._create_commodity_task(
commodity_id=TRIO_BAG413,
order_suffix="same-2",
role_name="同角色三连下单",
)
task3 = self._create_commodity_task(
commodity_id=TRIO_BAG414,
order_suffix="same-3",
role_name="同角色三连下单",
)
d1 = service.allocate_task(self.session, task_id=task1.id, current=self.admin)
d2 = service.allocate_task(self.session, task_id=task2.id, current=self.admin)
d3 = service.allocate_task(self.session, task_id=task3.id, current=self.admin)
acc_id = d1["task"]["account"]["id"]
assert d2["task"]["account"]["id"] == acc_id
assert d3["task"]["account"]["id"] == acc_id
assert self.session.query(AccountLease).count() == 1
assert sorted(d3["task"].get("sharedLeaseTaskIds") or []) == sorted(
[task1.id, task2.id]
)
d1_latest = service.get_task_detail(self.session, task1.id)
assert sorted(d1_latest["task"].get("sharedLeaseTaskIds") or []) == sorted(
[task2.id, task3.id]
)
# 首单完成绑定确认 -> 同角色共享任务自动传播为 bound
confirm_task = DouyuTask(
batch_id="shared-confirm-1",
account_id=acc_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="success",
platform_task_id=task1.id,
result={
"role_name": "同角色三连下单",
"area_name": "微信",
"plat_name": "安卓",
"is_bound_act": True,
"bind_confirmed": True,
"bind_phase": "confirmed",
},
created_by=self.admin_id,
)
self.session.add(confirm_task)
self.session.flush()
task1.bind_task_id = confirm_task.id
task1.binding_status = "role_ready"
task1.execution_status = "role_ready"
self.session.commit()
synced = service.sync_task_from_binding_runner(
self.session,
douyu_task_id=confirm_task.id,
)
assert synced >= 1
for sibling in (task1, task2, task3):
self.session.refresh(sibling)
assert sibling.binding_status == "bound"
assert sibling.execution_status == "bound"
# 取消 task2 仅摘除 task2 自己,共享租约必须仍为 active
service.cancel_task(
self.session,
task_id=task2.id,
current=self.admin,
reason="退单其中一个皮肤",
)
lease = self.session.query(AccountLease).one()
assert lease.status == "active"
self.session.refresh(task2)
assert task2.lease_id is None
# 同角色若再下一单完全相同的 commodity_id(bag412),不能复用同一账号
dup_task = self._create_commodity_task(
commodity_id=TRIO_BAG412,
order_suffix="same-dup",
role_name="同角色三连下单",
)
d_dup = service.allocate_task(
self.session,
task_id=dup_task.id,
current=self.admin,
)
assert d_dup["task"]["account"]["id"] != acc_id
def test_lease_reaper_cleans_null_task_orphan_and_preserves_shared_lease(self):
acc1 = self.account("reap-acc-1", points=2000)
acc2 = self.account("reap-acc-2", points=2000)
task1 = self._create_commodity_task(
commodity_id=COMMODITY,
order_suffix="reap-1",
required_points=1280,
)
task2 = self._create_commodity_task(
commodity_id=COMMODITY,
order_suffix="reap-2",
required_points=1280,
)
# 孤儿租约:原 task1 的 account_id/lease_id 已为 NULL(回归 NULL != id 漏网 bug)
orphan_lease = AccountLease(
account_id=acc1.id,
holder_user_id=self.admin_id,
scope="elite",
purpose="platform_fulfillment",
batch_id=f"pf:{task1.id}",
status="active",
)
# 共享租约:batch_id 仍指着已置空的 task1,但 task2 正在持有它
shared_lease = AccountLease(
account_id=acc2.id,
holder_user_id=self.admin_id,
scope="elite",
purpose="platform_fulfillment",
batch_id=f"pf:{task1.id}",
status="active",
)
self.session.add_all([orphan_lease, shared_lease])
self.session.flush()
task2.account_id = acc2.id
task2.lease_id = shared_lease.id
task2.execution_status = "allocated"
self.session.commit()
job = AutomationJob(key=reaper.JOB_KEY, batch_size=100)
result = reaper.run_platform_fulfillment_lease_reaper(
self.session,
job,
now=NOW + timedelta(minutes=5),
)
self.session.refresh(orphan_lease)
self.session.refresh(shared_lease)
assert result["orphan_released"] == 1
assert orphan_lease.status == "released"
assert shared_lease.status == "active"
def test_manual_reason_preserves_specific_issue_codes(self):
task = self._create_commodity_task(
commodity_id=COMMODITY,
order_suffix="reason-1",
required_points=1280,
)
task.execution_status = "manual_required"
task.binding_status = "failed"
for issue in (
"customer_role_cooldown",
"account_role_cooldown",
"customer_role_bound_elsewhere",
"account_role_bound_elsewhere",
"role_changed",
"lease_expired",
):
task.issue_code = issue
self.session.commit()
detail = service.get_task_detail(self.session, task.id)
assert detail["task"]["manualReason"] == issue
def test_late_customer_profile_merges_preallocated_sibling_and_releases_old_lease(
self,
):
acc1 = self.account("late-merge-1", points=24000, capability=False)
acc2 = self.account("late-merge-2", points=24000, capability=False)
for acc in (acc1, acc2):
for cid in (TRIO_BAG412, TRIO_BAG413, TRIO_BAG414):
self._add_commodity_state(acc, cid, eligibility="eligible")
self.session.commit()
# 先连下两单且当时均未填客户角色名,auto_allocator 分别预分配不同账号
t1 = self._create_commodity_task(
commodity_id=TRIO_BAG413,
order_suffix="late-1",
role_name="",
)
t2 = self._create_commodity_task(
commodity_id=TRIO_BAG414,
order_suffix="late-2",
role_name="",
)
d1 = service.allocate_task(self.session, task_id=t1.id, current=self.admin)
d2 = service.allocate_task(self.session, task_id=t2.id, current=self.admin)
assert d1["task"]["account"]["id"] != d2["task"]["account"]["id"]
old_t2_lease_id = d2["task"]["lease"]["id"]
# 买家随后补交同一角色名:第二单自动释放空号并合并共享第一单的账号与租约
service.save_customer_profile(
self.session,
task_id=t1.id,
customer_role_name="迟填多单老板",
platform="wechat",
system="android",
home_images=[{"url": "https://example.com/late-1.png"}],
)
service.save_customer_profile(
self.session,
task_id=t2.id,
customer_role_name="迟填多单老板",
platform="wechat",
system="android",
home_images=[{"url": "https://example.com/late-2.png"}],
)
self.session.refresh(t1)
self.session.refresh(t2)
old_lease = self.session.get(AccountLease, old_t2_lease_id)
assert t2.account_id == t1.account_id
assert t2.lease_id == t1.lease_id
assert old_lease.status == "released"
def test_sibling_bound_and_role_lock_redirect_merges_preallocated_orders_to_bound(
self,
):
acc1 = self.account("merge-bound-1", points=24000, capability=False)
acc2 = self.account("merge-bound-2", points=24000, capability=False)
acc3 = self.account("merge-bound-3", points=24000, capability=False)
for acc in (acc1, acc2, acc3):
for cid in (TRIO_BAG412, TRIO_BAG413, TRIO_BAG414):
self._add_commodity_state(acc, cid, eligibility="eligible")
self.session.commit()
t1 = self._create_commodity_task(
commodity_id=TRIO_BAG413,
order_suffix="merge-1",
role_name="小李腰不准",
)
t2 = self._create_commodity_task(
commodity_id=TRIO_BAG414,
order_suffix="merge-2",
role_name="",
)
t3 = self._create_commodity_task(
commodity_id=TRIO_BAG412,
order_suffix="merge-3",
role_name="",
)
# 确保三单初始各拿不同账号,且 t2 已填好角色但尚未完成扫码(qr_pending)
d1 = service.allocate_task(self.session, task_id=t1.id, current=self.admin)
d2 = service.allocate_task(self.session, task_id=t2.id, current=self.admin)
d3 = service.allocate_task(self.session, task_id=t3.id, current=self.admin)
assert (
len(
{
d1["task"]["account"]["id"],
d2["task"]["account"]["id"],
d3["task"]["account"]["id"],
}
)
== 3
)
t2_old_qr = DouyuTask(
batch_id="t2-old-qr",
account_id=d2["task"]["account"]["id"],
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="running",
platform_task_id=t2.id,
result={"url": "https://example.test/old-qr", "bind_phase": "qr_pending"},
created_by=self.admin_id,
)
self.session.add(t2_old_qr)
self.session.flush()
t2.customer_role_name = "小李腰不准"
t2.bind_task_id = t2_old_qr.id
t2.binding_status = "qr_pending"
t2.execution_status = "waiting_bind"
self.session.commit()
# 场景 A:主单 t1 确认绑定 -> 跨账号的未绑定兄弟单 t2 自动停旧码、释放旧租约并合并为 bound
confirm_t1 = DouyuTask(
batch_id="t1-confirm",
account_id=d1["task"]["account"]["id"],
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="success",
platform_task_id=t1.id,
result={
"role_name": "小李腰不准",
"area_name": "微信",
"plat_name": "安卓",
"is_bound_act": True,
"bind_confirmed": True,
"bind_phase": "confirmed",
},
created_by=self.admin_id,
)
self.session.add(confirm_t1)
self.session.flush()
t1.bind_task_id = confirm_t1.id
t1.binding_status = "role_ready"
t1.execution_status = "role_ready"
self.session.commit()
service.sync_task_from_binding_runner(self.session, douyu_task_id=confirm_t1.id)
self.session.refresh(t1)
self.session.refresh(t2)
self.session.refresh(t2_old_qr)
assert t2.account_id == t1.account_id
assert t2.lease_id == t1.lease_id
assert t2.binding_status == "bound"
assert t2.execution_status == "bound"
assert t2_old_qr.status == "stopped"
# 场景 B:t3 连客户资料角色都没预先匹配,直接扫码扫出「小李腰不准」撞 7 天锁 ->
# 不应转 manual_required,而是直接改挂合并到 acc1 并标 bound
acc1_row = self.session.get(Account, t1.account_id)
acc1_row.role_bind_status = "bound"
acc1_row.game_name = "小李腰不准"
self.session.add(
AccountEvent(
account_id=acc1_row.id,
event_type="bind_ok",
category="account",
title="绑定成功",
subject_type="elite_role",
subject_key="小李腰不准",
source="test",
actor_type="system",
occurred_at=NOW,
)
)
t3_old_acc = d3["task"]["account"]["id"]
t3_old_lease_id = d3["task"]["lease"]["id"]
t3_qr = DouyuTask(
batch_id="t3-scan-locked-role",
account_id=t3_old_acc,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
platform_task_id=t3.id,
result={
"act_alias": "20260120QYOOB",
"role_name": "小李腰不准",
"current_role_name": "小李腰不准",
"baseline_role_name": "旧角色",
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "旧角色",
"is_bound_act": True,
"need_bind_act": True,
},
"area_name": "微信",
"plat_name": "安卓",
"is_bound_act": False,
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
self.session.add(t3_qr)
self.session.flush()
t3.bind_task_id = t3_qr.id
t3.binding_status = "qr_pending"
t3.execution_status = "waiting_bind"
self.session.commit()
service.sync_task_from_binding_runner(self.session, douyu_task_id=t3_qr.id)
self.session.refresh(t3)
t3_old_lease = self.session.get(AccountLease, t3_old_lease_id)
assert t3.account_id == t1.account_id
assert t3.lease_id == t1.lease_id
assert t3.binding_status == "bound"
assert t3.execution_status == "bound"
assert t3.issue_code != "customer_role_bound_elsewhere"
assert t3_old_lease.status == "released"
def test_bundle_missing_co_eligibility_not_masked_by_offer_before(self):
partial = self.account("partial-before", points=8000, capability=False)
self._add_commodity_state(partial, TRIO_BAG412, eligibility="eligible")
self._add_commodity_state(partial, TRIO_BAG413, eligibility="eligible")
self._add_commodity_state(partial, TRIO_BAG414, eligibility="limited")
partial_row = (
self.session.query(AccountCommodityState)
.filter_by(account_id=partial.id, commodity_id=TRIO_BAG412)
.one()
)
partial_row.offer_state = "before"
partial_row.availability = "not_open"
partial_row.available_from = NOW + timedelta(days=3)
expired = self.account("expired-trio", points=8000, capability=False)
for cid in (TRIO_BAG412, TRIO_BAG413, TRIO_BAG414):
self._add_commodity_state(expired, cid, eligibility="eligible")
row = (
self.session.query(AccountCommodityState)
.filter_by(account_id=expired.id, commodity_id=cid)
.one()
)
row.valid_until = NOW - timedelta(minutes=10)
task = self._create_commodity_task(
commodity_id=TRIO_BAG412,
order_suffix="trio-before-gap",
role_name="联合缺口玩家",
)
task.sale_mode = "presale"
self.session.commit()
detail = service.allocate_task(
self.session,
task_id=task.id,
current=self.admin,
)
assert detail["task"]["account"] is None
assert detail["task"]["executionStatus"] == "ready"
assert detail["task"]["issueCode"] == "bundle_co_eligibility_missing"
queued = (
self.session.query(AccountWorkItem)
.filter(
AccountWorkItem.account_id == expired.id,
AccountWorkItem.work_type == WORK_STOREHOME_SYNC,
)
.all()
)
assert queued
def test_reallocate_same_role_respects_bundle_requirements_and_before_open(self):
acc_partial = self.account("rebind-partial", points=24000, capability=False)
self._add_commodity_state(acc_partial, TRIO_BAG412, eligibility="eligible")
self._add_commodity_state(acc_partial, TRIO_BAG413, eligibility="eligible")
self._add_commodity_state(acc_partial, TRIO_BAG414, eligibility="limited")
acc_full = self.account("rebind-full", points=24000, capability=False)
for cid in (TRIO_BAG412, TRIO_BAG413, TRIO_BAG414):
self._add_commodity_state(acc_full, cid, eligibility="eligible")
row = (
self.session.query(AccountCommodityState)
.filter_by(account_id=acc_full.id, commodity_id=cid)
.one()
)
row.offer_state = "before"
row.availability = "not_open"
row.available_from = NOW + timedelta(days=3)
acc_other = self.account("rebind-other", points=24000, capability=False)
self._add_commodity_state(acc_other, TRIO_BAG414, eligibility="eligible")
self._add_commodity_state(acc_other, TRIO_BAG412, eligibility="eligible")
self._add_commodity_state(acc_other, TRIO_BAG413, eligibility="eligible")
t_partial = self._create_commodity_task(
commodity_id=TRIO_BAG412,
order_suffix="rebind-partial",
role_name="玩家甲",
)
t_partial.account_id = acc_partial.id
t_partial.binding_status = "bound"
t_partial.execution_status = "bound"
lease_partial = AccountLease(
account_id=acc_partial.id,
holder_user_id=self.admin_id,
purpose="platform_fulfillment",
batch_id=f"pf:{t_partial.id}",
status="active",
expires_at=NOW + timedelta(days=7),
)
self.session.add(lease_partial)
self.session.flush()
t_partial.lease_id = lease_partial.id
t_full = self._create_commodity_task(
commodity_id=TRIO_BAG412,
order_suffix="rebind-full",
role_name="玩家乙",
)
lease_full = AccountLease(
account_id=acc_full.id,
holder_user_id=self.admin_id,
purpose="platform_fulfillment",
batch_id=f"pf:{t_full.id}",
status="active",
expires_at=NOW + timedelta(days=7),
)
self.session.add(lease_full)
self.session.flush()
t_full.account_id = acc_full.id
t_full.lease_id = lease_full.id
t_full.binding_status = "bound"
t_full.execution_status = "bound"
t_target_partial = self._create_commodity_task(
commodity_id=TRIO_BAG414,
order_suffix="rebind-target-partial",
role_name="玩家甲",
)
t_target_partial.sale_mode = "direct"
t_target_partial.account_id = acc_other.id
t_target = self._create_commodity_task(
commodity_id=TRIO_BAG414,
order_suffix="rebind-target",
role_name="玩家乙",
)
t_target.sale_mode = "direct"
t_target.account_id = acc_other.id
self.session.commit()
assert not service.allocation.try_reallocate_task_to_same_role(
self.session,
task=t_target_partial,
current=self.admin,
role_name="玩家甲",
preferred_account_id=acc_partial.id,
)
assert service.allocation.try_reallocate_task_to_same_role(
self.session,
task=t_target,
current=self.admin,
role_name="玩家乙",
preferred_account_id=acc_full.id,
)
self.session.refresh(t_target)
assert t_target.account_id == acc_full.id
assert t_target.binding_status == "bound"
assert t_target.exchange_status == "waiting_release"