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

643 lines
21 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.models import (
Account,
AccountLease,
AutomationJob,
DouyuGoodsSnapshot,
DouyuTask,
PlatformCommodityMapping,
PlatformFulfillmentTask,
User,
)
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.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"},
created_at=NOW,
updated_at=NOW,
)
self.session.add(row)
self.session.commit()
return row
class TestSyncAndMapping(_Base):
def test_sync_creates_pending_mapping_task(self, monkeypatch):
monkeypatch.setattr(
service,
"list_pending_manual_fulfillments",
lambda limit: [
{
"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,
"revenue_amount_fen": 9900,
"total_amount": 9900,
"paid_at": NOW,
"item_updated_at": NOW,
}
],
)
result = service.sync_pending_tasks(self.session, limit=10)
assert result["created"] == 1
task = self.session.query(PlatformFulfillmentTask).one()
assert task.execution_status == "pending_mapping"
assert task.internal_sku_key == INTERNAL_SKU
assert task.order_amount_fen == 9900
def test_sync_is_idempotent_and_applies_mapping(self, monkeypatch):
self.mapping()
monkeypatch.setattr(
service,
"list_pending_manual_fulfillments",
lambda limit: [
{
"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,
}
],
)
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 self.session.query(PlatformFulfillmentTask).count() == 1
task = self.session.query(PlatformFulfillmentTask).one()
assert task.execution_status == "ready"
assert task.commodity_id == COMMODITY
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 TestAccountSelection(_Base):
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_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_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
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"
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,
current=self.admin,
)
self.session.refresh(lease)
assert finite["leaseDurationMinutes"] == 90
assert lease.expires_at is not None
unlimited = service.update_settings(
self.session,
lease_duration_minutes=None,
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_refresh_binding_maps_role_ready(self):
task = self._allocated()
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": "测试角色"},
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"] == "测试角色"
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_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_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_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,
)