perf(fulfillment): 优化本地能力选号查询与索引

This commit is contained in:
yml
2026-11-23 18:53:06 +08:00
parent d5422b0ecd
commit 7e0d27927c
23 changed files with 1624 additions and 95 deletions
+61
View File
@@ -1984,6 +1984,67 @@ class TestDouyuCollabOrders:
assert collab.list_orders(self.session, ck_status=collab.CK_VALID)["total"] == 0
assert collab.summary(self.session)["ck_invalid"] == 1
def test_exact_order_search_bypasses_void_archive_and_status_filters(self):
order = collab.create_order(
self.session,
self.admin,
order_no="DY-ARCHIVED-VOID",
shop="向日葵",
draft=True,
)
order.status = collab.STATUS_VOID
order.archived_at = datetime.now(UTC)
self.session.commit()
exact = collab.list_orders(
self.session,
keyword=order.order_no,
status=collab.STATUS_DONE,
archive_scope="active",
include_void=False,
)
partial = collab.list_orders(
self.session,
keyword="ARCHIVED",
archive_scope="active",
include_void=False,
)
assert [item["id"] for item in exact["items"]] == [order.id]
assert partial["total"] == 0
def test_manual_shop_alias_preserves_original_name_and_filters_by_short_name(self):
shop = collab.create_shop(
self.session,
self.admin,
name="向日葵",
)
order = collab.create_order(
self.session,
self.admin,
order_no="DY-SHOP-ALIAS",
shop="向日葵游戏服务店",
draft=True,
)
assert order.shop == "向日葵游戏服务店"
assert order.shop_original_name == "向日葵游戏服务店"
collab.update_shop(
self.session,
self.admin,
shop,
{"aliases": ["向日葵游戏服务店"]},
)
self.session.refresh(order)
result = collab.list_orders(self.session, shop="向日葵")
assert order.shop == "向日葵"
assert order.shop_original_name == "向日葵游戏服务店"
assert [item["id"] for item in result["items"]] == [order.id]
assert result["items"][0]["shop"] == "向日葵"
assert result["items"][0]["shop_original_name"] == "向日葵游戏服务店"
def test_export_cks_reads_linked_account_and_skips_missing_cookie(self):
first = collab.create_order(
self.session,
+62
View File
@@ -216,6 +216,68 @@ def test_mark_task_commits_result_before_account_event(db, monkeypatch):
]
def test_mark_task_syncs_platform_for_standalone_confirm_bind(db, monkeypatch):
_, _, task = _fixtures(db, status="running")
task.task_type = "confirm_bind"
task.platform_task_id = None
db.commit()
runner = DouyuBatchRunnerCore(
db,
task.batch_id,
task.task_type,
close_db=False,
)
calls: list[bool] = []
monkeypatch.setattr(
runner,
"_sync_platform_fulfillment",
lambda _task_id, *, enabled: calls.append(enabled),
)
runner._mark_task(
db,
task,
"success",
"done",
{"role_name": "新角色", "bind_confirmed": True},
)
assert calls == [True]
def test_mark_task_auto_refreshes_exchange_after_elite_gift(db, monkeypatch):
_, _, task = _fixtures(db, status="running")
task.task_type = "donate_elite_gift"
db.commit()
runner = DouyuBatchRunnerCore(
db,
task.batch_id,
task.task_type,
close_db=False,
)
calls: list[bool] = []
monkeypatch.setattr(
runner,
"_sync_platform_fulfillment",
lambda *_args, **_kwargs: None,
)
monkeypatch.setattr(
runner,
"_refresh_platform_exchange_eligibility",
lambda _task_id, *, enabled: calls.append(enabled),
)
runner._mark_task(
db,
task,
"success",
"赠送成功",
{"gift_points_confirmed": True},
)
assert calls == [True]
def test_cleanup_commits_stopped_status_before_account_event(db, monkeypatch):
_, _, task = _fixtures(db, status="running")
observed: list[str] = []
+180 -1
View File
@@ -33,6 +33,7 @@ from web.backend.models import (
DouyuExternalOrder,
HuyaExternalOrder,
PlatformCommodityMapping,
PlatformFulfillmentEvent,
PlatformFulfillmentTask,
User,
WeiboAccount,
@@ -42,7 +43,7 @@ TESTS_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = TESTS_DIR.parent
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
HEAD_REVISION = "20261123_0122"
HEAD_REVISION = "20261123_0125"
# 迁移新增、但不声明在模型里的复合查询索引。
EXTRA_INDEXES = (
@@ -372,6 +373,184 @@ class TestMigrationSmoke:
with admin_engine.begin() as conn:
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
def test_0124_backfills_fulfillment_binding_confirmed_from_account(self):
creds = get_mysql_credentials()
mig_db = f"douyu_login_mig_{secrets.token_hex(4)}"
mig_url = (
f"mysql+pymysql://{quote_plus(creds['user'])}:"
f"{quote_plus(creds['password'])}@{creds['host']}:{creds['port']}/"
f"{mig_db}?charset=utf8mb4"
)
admin_engine = get_test_engine()
mig_engine = create_engine(mig_url)
original_url = database_module.DATABASE_URL
with admin_engine.begin() as conn:
conn.execute(
text(
f"CREATE DATABASE `{mig_db}` "
"CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;"
)
)
try:
database_module.DATABASE_URL = mig_url
cfg = _migration_config()
cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261123_0123")
with Session(mig_engine) as session:
user = User(
username="binding-sync-user",
password_hash="hash",
role="super_admin",
is_active=True,
)
account = Account(
username="binding-sync-account",
password="password",
email="binding-sync@example.com",
email_password="mail-password",
cookie="acf_uid=1",
role_bind_status="bound",
game_name="新角色",
game_channel="微信 · 苹果(iOS)",
status="active",
)
session.add_all([user, account])
session.flush()
lease = AccountLease(
account_id=account.id,
holder_user_id=user.id,
status="active",
purpose="platform_fulfillment",
)
session.add(lease)
session.flush()
task = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="BIND-SYNC-ORDER",
source_order_item_id="BIND-SYNC-ITEM",
platform_order_id="BIND-SYNC-PLATFORM",
internal_sku_key="绑定同步测试",
sku_name="绑定同步测试",
scope="elite",
account_id=account.id,
lease_id=lease.id,
binding_status="role_ready",
execution_status="role_ready",
)
session.add(task)
session.commit()
task_id = int(task.id)
command.upgrade(cfg, "head")
with Session(mig_engine) as session:
task = session.get(PlatformFulfillmentTask, task_id)
event = (
session.query(PlatformFulfillmentEvent)
.filter_by(
task_id=task_id,
event_type="binding_synced_from_account",
)
.one()
)
assert task.binding_status == "bound"
assert task.execution_status == "bound"
assert event.detail_json["roleName"] == "新角色"
assert event.detail_json["gameChannel"] == "微信 · 苹果(iOS)"
assert event.detail_json["backfilled"] is True
finally:
database_module.DATABASE_URL = original_url
mig_engine.dispose()
with admin_engine.begin() as conn:
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
def test_0125_preserves_shop_names_without_automatic_aliases(self):
creds = get_mysql_credentials()
mig_db = f"douyu_login_mig_{secrets.token_hex(4)}"
mig_url = (
f"mysql+pymysql://{quote_plus(creds['user'])}:"
f"{quote_plus(creds['password'])}@{creds['host']}:{creds['port']}/"
f"{mig_db}?charset=utf8mb4"
)
admin_engine = get_test_engine()
mig_engine = create_engine(mig_url)
original_url = database_module.DATABASE_URL
with admin_engine.begin() as conn:
conn.execute(
text(
f"CREATE DATABASE `{mig_db}` "
"CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;"
)
)
try:
database_module.DATABASE_URL = mig_url
cfg = _migration_config()
cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261123_0124")
now = datetime.now(UTC).replace(tzinfo=None)
with mig_engine.begin() as conn:
conn.execute(
text(
"""
INSERT INTO douyu_collab_shops (
name, sort_order, is_active, remark, created_at, updated_at
) VALUES (
'向日葵', 1, 1, '', :now, :now
)
"""
),
{"now": now},
)
conn.execute(
text(
"""
INSERT INTO douyu_external_orders (
order_no, shop, status, created_at, updated_at
) VALUES (
'DY-SHOP-MIGRATION', '向日葵游戏服务店',
'incomplete', :now, :now
)
"""
),
{"now": now},
)
command.upgrade(cfg, "head")
with mig_engine.begin() as conn:
shops = conn.execute(
text(
"""
SELECT name, aliases
FROM douyu_collab_shops
ORDER BY id
"""
)
).mappings().all()
order = conn.execute(
text(
"""
SELECT shop, shop_original_name
FROM douyu_external_orders
WHERE order_no = 'DY-SHOP-MIGRATION'
"""
)
).mappings().one()
assert [shop["name"] for shop in shops] == ["向日葵"]
aliases = (
json.loads(shops[0]["aliases"])
if isinstance(shops[0]["aliases"], str)
else list(shops[0]["aliases"] or [])
)
assert aliases == []
assert order["shop"] == "向日葵游戏服务店"
assert order["shop_original_name"] == "向日葵游戏服务店"
finally:
database_module.DATABASE_URL = original_url
mig_engine.dispose()
with admin_engine.begin() as conn:
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
def test_0105_adds_exchange_result_image_columns_and_roundtrips(self):
creds = get_mysql_credentials()
mig_db = f"douyu_login_mig_{secrets.token_hex(4)}"
+202
View File
@@ -1153,6 +1153,35 @@ class TestSnapshotSync(_Base):
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
@@ -1774,6 +1803,88 @@ class TestBindingAndCompletion(_Base):
assert task.issue_code == ""
assert task.last_error == ""
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 False
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 event.detail_json["roleName"] == "新角色"
def test_customer_start_mapping_missing_is_idempotent(self, monkeypatch):
task = self.task(mapped=False)
task.issue_code = "mapping_missing"
@@ -3009,6 +3120,97 @@ class TestBindingAndCompletion(_Base):
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()