Avoid automatic allocation of accounts with active external collaboration, require explicit manual takeover of platform leases, and add Douyu account identity search.
2278 lines
78 KiB
Python
2278 lines
78 KiB
Python
"""直播账号履约:订单同步、映射、选号、绑码状态和人工完成。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from datetime import UTC, datetime, timedelta
|
|
from unittest.mock import patch
|
|
|
|
import pytest
|
|
from fastapi import HTTPException
|
|
|
|
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,
|
|
AutomationJob,
|
|
DouyuExternalOrder,
|
|
DouyuGoodsSnapshot,
|
|
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.automation.jobs import (
|
|
platform_fulfillment_lease_reaper as reaper,
|
|
)
|
|
from web.backend.services.douyu_account_state import DouyuLiveAccountState
|
|
from web.backend.services.douyu_activity_query import DouyuEligibilityResult
|
|
from web.backend.services.platform_fulfillment import account_selector, service
|
|
|
|
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()
|
|
self.refresh_patch = patch.object(
|
|
service,
|
|
"refresh_douyu_account_state",
|
|
side_effect=self._live_state,
|
|
)
|
|
self.refresh_mock = self.refresh_patch.start()
|
|
|
|
def teardown_method(self):
|
|
self.refresh_patch.stop()
|
|
self.session.close()
|
|
|
|
@staticmethod
|
|
def _live_state(_db, account, **_kwargs):
|
|
return DouyuLiveAccountState(
|
|
account_id=account.id,
|
|
account_name=account.username,
|
|
checked_at=NOW,
|
|
ck_verdict="valid",
|
|
ck_message="有效",
|
|
elite_opened=True,
|
|
points=account.points or 2000,
|
|
limited_ids=frozenset(),
|
|
role_change_available_at=account.role_change_available_at,
|
|
)
|
|
|
|
def account(
|
|
self,
|
|
name: str,
|
|
*,
|
|
points: int = 2000,
|
|
opened: bool = True,
|
|
role_available_at: datetime | None = None,
|
|
) -> 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.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 TestSyncAndMapping(_Base):
|
|
def test_sync_skips_external_orders_when_no_mapping_is_configured(
|
|
self, monkeypatch
|
|
):
|
|
monkeypatch.setattr(
|
|
service,
|
|
"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,
|
|
"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,
|
|
"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
|
|
|
|
|
|
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()
|
|
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.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 (
|
|
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_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_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
|
|
|
|
|
|
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,
|
|
"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
|
|
outbox = self.session.query(IntegrationOutbox).one()
|
|
assert outbox.payload_json["items"][0]["stateVersion"] == 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, "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_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_match_checks_only_selected_candidate(self, monkeypatch):
|
|
account = self.account("capability-fast")
|
|
task = self.task()
|
|
self.session.add(
|
|
AccountCommodityState(
|
|
account_id=account.id,
|
|
platform="douyu",
|
|
scope="elite",
|
|
commodity_id=COMMODITY,
|
|
commodity_name=INTERNAL_SKU,
|
|
availability="available",
|
|
observed_at=NOW,
|
|
valid_until=NOW + timedelta(minutes=15),
|
|
source="overview",
|
|
)
|
|
)
|
|
self.session.commit()
|
|
monkeypatch.setenv("PLATFORM_FULFILLMENT_MATCH_MODE", "capability")
|
|
|
|
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"
|
|
self.refresh_mock.assert_called_once()
|
|
|
|
def test_hybrid_falls_back_to_live_scan_when_capability_candidate_fails(
|
|
self,
|
|
monkeypatch,
|
|
):
|
|
capability_account = self.account("capability-stale")
|
|
live_account = self.account("live-fallback")
|
|
task = self.task()
|
|
self.session.add(
|
|
AccountCommodityState(
|
|
account_id=capability_account.id,
|
|
platform="douyu",
|
|
scope="elite",
|
|
commodity_id=COMMODITY,
|
|
availability="available",
|
|
observed_at=NOW,
|
|
valid_until=NOW + timedelta(minutes=15),
|
|
source="overview",
|
|
)
|
|
)
|
|
self.session.commit()
|
|
|
|
def live_state(_db, account, **_kwargs):
|
|
return DouyuLiveAccountState(
|
|
account_id=account.id,
|
|
account_name=account.username,
|
|
checked_at=NOW,
|
|
ck_verdict="valid",
|
|
ck_message="有效",
|
|
elite_opened=True,
|
|
points=2000,
|
|
limited_ids=(
|
|
frozenset({COMMODITY})
|
|
if account.id == capability_account.id
|
|
else frozenset()
|
|
),
|
|
role_change_available_at=None,
|
|
)
|
|
|
|
self.refresh_mock.side_effect = live_state
|
|
monkeypatch.setenv("PLATFORM_FULFILLMENT_MATCH_MODE", "hybrid")
|
|
|
|
detail = service.allocate_task(
|
|
self.session,
|
|
task_id=task.id,
|
|
current=self.admin,
|
|
)
|
|
|
|
assert detail["task"]["account"]["id"] == live_account.id
|
|
assert self.refresh_mock.call_count == 2
|
|
|
|
def test_allocation_refreshes_live_state_instead_of_cached_filters(self):
|
|
account = Account(
|
|
username="live-refresh-account",
|
|
password="p",
|
|
email="live@example.com",
|
|
email_password="ep",
|
|
status="imported",
|
|
ck_check_status="",
|
|
cookie="PHPSESSID=live",
|
|
elite_opened=None,
|
|
points=None,
|
|
gold_balance=100,
|
|
auto_managed=True,
|
|
)
|
|
self.session.add(account)
|
|
self.session.commit()
|
|
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"
|
|
self.refresh_mock.assert_called()
|
|
|
|
def test_live_candidates_include_support_accounts_and_prefer_valid_cache(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] == [valid.id, 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)
|
|
self.refresh_mock.side_effect = lambda _db, row, **_kwargs: (
|
|
DouyuLiveAccountState(
|
|
account_id=row.id,
|
|
account_name=row.username,
|
|
checked_at=NOW,
|
|
ck_verdict="valid",
|
|
ck_message="有效",
|
|
elite_opened=False,
|
|
points=2000,
|
|
limited_ids=frozenset(),
|
|
role_change_available_at=None,
|
|
)
|
|
)
|
|
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_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)
|
|
self.session.add(
|
|
AccountCommodityState(
|
|
account_id=account.id,
|
|
platform="douyu",
|
|
scope="elite",
|
|
commodity_id=COMMODITY,
|
|
commodity_name=INTERNAL_SKU,
|
|
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
|
|
|
|
|
|
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, "start_douyu_batch", lambda **_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_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, "start_douyu_batch", lambda **_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,
|
|
"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,
|
|
"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,
|
|
"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,
|
|
"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,
|
|
"_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",
|
|
"role_name": "测试角色",
|
|
"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_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",
|
|
"role_name": "测试角色",
|
|
"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()
|
|
|
|
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"]
|
|
live = service.customer_binding_out(self.session, task.id)
|
|
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_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_releases_lease(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 == "released"
|
|
|
|
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,
|
|
"query_exchange_eligibility",
|
|
lambda *_args, **_kwargs: DouyuEligibilityResult(
|
|
elite_user_info={"manual_type": 1},
|
|
points=100,
|
|
points_response={"points": 100},
|
|
limited_goods=[],
|
|
limited_ids=frozenset(),
|
|
),
|
|
)
|
|
|
|
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_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,
|
|
"query_exchange_eligibility",
|
|
lambda *_args, **_kwargs: DouyuEligibilityResult(
|
|
elite_user_info={"manual_type": 1, "expire_time": 1},
|
|
points=2000,
|
|
points_response={"points": 2000},
|
|
limited_goods=[],
|
|
limited_ids=frozenset(),
|
|
),
|
|
)
|
|
|
|
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_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_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_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,
|
|
)
|