perf(fulfillment): 优化本地能力选号查询与索引
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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
@@ -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)}"
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -489,6 +489,18 @@
|
||||
"20261123_0122_execution_jobs_recharge_guard.py": {
|
||||
"revision": "20261123_0122",
|
||||
"sha256": "e3549ea76a9da00d1e6e01e11d25fbb6fca3cce64b26223a8f0352a6fbec4c7d"
|
||||
},
|
||||
"20261123_0123_capability_candidate_index.py": {
|
||||
"revision": "20261123_0123",
|
||||
"sha256": "4fc8ed0659f92a141ff383b5a5925e8b3e73aff7540b523198742971dc9b628b"
|
||||
},
|
||||
"20261123_0124_fulfillment_account_binding_sync.py": {
|
||||
"revision": "20261123_0124",
|
||||
"sha256": "33de2a57c88cfbea3219544cacaf8ff10d708639dde22322adb28ea7a2610d25"
|
||||
},
|
||||
"20261123_0125_douyu_collab_shop_aliases.py": {
|
||||
"revision": "20261123_0125",
|
||||
"sha256": "ff11ab9c735043d95504c1d52ddfeb8db04068a8027e0e1253ec45330f227bad"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""add covering index for fulfillment capability candidates.
|
||||
|
||||
Revision ID: 20261123_0123
|
||||
Revises: 20261123_0122
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261123_0123"
|
||||
down_revision: str | None = "20261123_0122"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
INDEX_NAME = "ix_account_commodity_candidate"
|
||||
REPLACED_INDEX_NAME = "ix_account_commodity_eligibility"
|
||||
|
||||
|
||||
def _indexes() -> set[str]:
|
||||
return {
|
||||
str(index["name"])
|
||||
for index in sa.inspect(op.get_bind()).get_indexes(
|
||||
"account_commodity_states"
|
||||
)
|
||||
if index.get("name")
|
||||
}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
indexes = _indexes()
|
||||
if INDEX_NAME not in indexes:
|
||||
op.create_index(
|
||||
INDEX_NAME,
|
||||
"account_commodity_states",
|
||||
[
|
||||
"platform",
|
||||
"scope",
|
||||
"commodity_id",
|
||||
"account_eligibility",
|
||||
"offer_state",
|
||||
"valid_until",
|
||||
"account_id",
|
||||
"last_exchange_at",
|
||||
"observed_at",
|
||||
],
|
||||
)
|
||||
if REPLACED_INDEX_NAME in indexes:
|
||||
op.drop_index(
|
||||
REPLACED_INDEX_NAME,
|
||||
table_name="account_commodity_states",
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
indexes = _indexes()
|
||||
if REPLACED_INDEX_NAME not in indexes:
|
||||
op.create_index(
|
||||
REPLACED_INDEX_NAME,
|
||||
"account_commodity_states",
|
||||
[
|
||||
"platform",
|
||||
"scope",
|
||||
"commodity_id",
|
||||
"account_eligibility",
|
||||
"offer_state",
|
||||
"valid_until",
|
||||
"account_id",
|
||||
],
|
||||
)
|
||||
if INDEX_NAME in indexes:
|
||||
op.drop_index(INDEX_NAME, table_name="account_commodity_states")
|
||||
@@ -0,0 +1,104 @@
|
||||
"""backfill active fulfillment bindings confirmed through the account workbench.
|
||||
|
||||
Revision ID: 20261123_0124
|
||||
Revises: 20261123_0123
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261123_0124"
|
||||
down_revision: str | None = "20261123_0123"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
rows = bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
SELECT
|
||||
t.id AS task_id,
|
||||
a.id AS account_id,
|
||||
a.username,
|
||||
a.nickname,
|
||||
a.game_name,
|
||||
a.game_channel,
|
||||
a.role_change_available_at
|
||||
FROM platform_fulfillment_tasks AS t
|
||||
JOIN accounts AS a ON a.id = t.account_id
|
||||
JOIN account_leases AS l ON l.id = t.lease_id
|
||||
WHERE t.scope = 'elite'
|
||||
AND t.binding_status IN ('role_ready', 'confirming')
|
||||
AND t.execution_status NOT IN ('completed', 'cancelled')
|
||||
AND l.status = 'active'
|
||||
AND a.role_bind_status = 'bound'
|
||||
"""
|
||||
)
|
||||
).mappings().all()
|
||||
now = datetime.now(UTC).replace(tzinfo=None)
|
||||
for row in rows:
|
||||
task_id = int(row["task_id"])
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE platform_fulfillment_tasks
|
||||
SET binding_status = 'bound',
|
||||
execution_status = 'bound',
|
||||
issue_code = '',
|
||||
last_error = '',
|
||||
updated_at = :now
|
||||
WHERE id = :task_id
|
||||
"""
|
||||
),
|
||||
{"task_id": task_id, "now": now},
|
||||
)
|
||||
detail = {
|
||||
"accountId": int(row["account_id"]),
|
||||
"accountName": str(row["nickname"] or row["username"] or ""),
|
||||
"roleName": str(row["game_name"] or ""),
|
||||
"gameChannel": str(row["game_channel"] or ""),
|
||||
"roleChangeAvailableAt": (
|
||||
row["role_change_available_at"].isoformat()
|
||||
if row["role_change_available_at"]
|
||||
else None
|
||||
),
|
||||
"sourceTaskId": None,
|
||||
"backfilled": True,
|
||||
}
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
INSERT INTO platform_fulfillment_events (
|
||||
task_id,
|
||||
event_type,
|
||||
actor_type,
|
||||
actor_id,
|
||||
detail_json,
|
||||
created_at
|
||||
) VALUES (
|
||||
:task_id,
|
||||
'binding_synced_from_account',
|
||||
'system',
|
||||
'',
|
||||
:detail_json,
|
||||
:created_at
|
||||
)
|
||||
"""
|
||||
),
|
||||
{
|
||||
"task_id": task_id,
|
||||
"detail_json": json.dumps(detail, ensure_ascii=False),
|
||||
"created_at": now,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""业务数据回填不回退,避免把已确认的账号重新标成待确认。"""
|
||||
@@ -0,0 +1,58 @@
|
||||
"""add manually maintained douyu collab shop aliases and original shop names.
|
||||
|
||||
Revision ID: 20261123_0125
|
||||
Revises: 20261123_0124
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261123_0125"
|
||||
down_revision: str | None = "20261123_0124"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
|
||||
def _columns(table: str) -> set[str]:
|
||||
return {
|
||||
str(column["name"])
|
||||
for column in sa.inspect(op.get_bind()).get_columns(table)
|
||||
}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
if "aliases" not in _columns("douyu_collab_shops"):
|
||||
op.add_column(
|
||||
"douyu_collab_shops",
|
||||
sa.Column("aliases", sa.JSON(), nullable=True),
|
||||
)
|
||||
if "shop_original_name" not in _columns("douyu_external_orders"):
|
||||
op.add_column(
|
||||
"douyu_external_orders",
|
||||
sa.Column(
|
||||
"shop_original_name",
|
||||
sa.String(length=128),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
)
|
||||
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE douyu_external_orders
|
||||
SET shop_original_name = shop
|
||||
WHERE shop_original_name = ''
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
if "shop_original_name" in _columns("douyu_external_orders"):
|
||||
op.drop_column("douyu_external_orders", "shop_original_name")
|
||||
if "aliases" in _columns("douyu_collab_shops"):
|
||||
op.drop_column("douyu_collab_shops", "aliases")
|
||||
@@ -884,6 +884,8 @@ class DouyuCollabShop(Base):
|
||||
name: Mapped[str] = mapped_column(
|
||||
String(64), unique=True, nullable=False, index=True
|
||||
)
|
||||
# 各平台同步过来的完整店铺名/历史别名,统一映射到上面的规范简称。
|
||||
aliases: Mapped[list | None] = mapped_column(JSON, nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
|
||||
is_active: Mapped[bool] = mapped_column(
|
||||
Boolean, default=True, server_default="1", index=True
|
||||
@@ -947,6 +949,10 @@ class DouyuExternalOrder(Base):
|
||||
shop: Mapped[str] = mapped_column(
|
||||
String(64), default="", server_default="", index=True
|
||||
)
|
||||
# 同步来源的原始完整店铺名;shop 存规范简称,筛选和展示不丢原值。
|
||||
shop_original_name: Mapped[str] = mapped_column(
|
||||
String(128), default="", server_default=""
|
||||
)
|
||||
owner_id: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("users.id"), nullable=True, index=True
|
||||
)
|
||||
@@ -2118,7 +2124,7 @@ class AccountCommodityState(Base):
|
||||
"account_id",
|
||||
),
|
||||
Index(
|
||||
"ix_account_commodity_eligibility",
|
||||
"ix_account_commodity_candidate",
|
||||
"platform",
|
||||
"scope",
|
||||
"commodity_id",
|
||||
@@ -2126,6 +2132,8 @@ class AccountCommodityState(Base):
|
||||
"offer_state",
|
||||
"valid_until",
|
||||
"account_id",
|
||||
"last_exchange_at",
|
||||
"observed_at",
|
||||
),
|
||||
Index(
|
||||
"ix_account_commodity_account",
|
||||
|
||||
@@ -86,6 +86,7 @@ def _shop_out(shop) -> dict:
|
||||
return {
|
||||
"id": int(shop.id),
|
||||
"name": shop.name,
|
||||
"aliases": list(shop.aliases or []),
|
||||
"sort_order": int(shop.sort_order or 0),
|
||||
"is_active": bool(shop.is_active),
|
||||
"remark": shop.remark or "",
|
||||
@@ -750,7 +751,13 @@ def create_collab_shop(
|
||||
current: User = Depends(require_permission("douyu:collab:edit")),
|
||||
):
|
||||
try:
|
||||
shop = collab.create_shop(db, current, name=req.name, remark=req.remark)
|
||||
shop = collab.create_shop(
|
||||
db,
|
||||
current,
|
||||
name=req.name,
|
||||
aliases=req.aliases,
|
||||
remark=req.remark,
|
||||
)
|
||||
except collab.CollabError as exc:
|
||||
raise _http_error(exc) from exc
|
||||
_publish_change(current, scope="shops", action="shop.create")
|
||||
|
||||
@@ -2608,11 +2608,13 @@ class HuyaExternalOrderAuditOut(BaseModel):
|
||||
|
||||
class DouyuCollabShopCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=64)
|
||||
aliases: list[str] = Field(default_factory=list)
|
||||
remark: str = Field("", max_length=255)
|
||||
|
||||
|
||||
class DouyuCollabShopUpdate(BaseModel):
|
||||
name: str | None = Field(None, min_length=1, max_length=64)
|
||||
aliases: list[str] | None = None
|
||||
sort_order: int | None = None
|
||||
is_active: bool | None = None
|
||||
remark: str | None = Field(None, max_length=255)
|
||||
@@ -2621,6 +2623,7 @@ class DouyuCollabShopUpdate(BaseModel):
|
||||
class DouyuCollabShopOut(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
aliases: list[str] = Field(default_factory=list)
|
||||
sort_order: int = 0
|
||||
is_active: bool = True
|
||||
remark: str = ""
|
||||
@@ -2705,7 +2708,7 @@ class DouyuCollabAccountLookupOut(BaseModel):
|
||||
|
||||
class DouyuCollabOrderCreate(BaseModel):
|
||||
order_no: str = Field(..., min_length=1, max_length=64)
|
||||
shop: str = Field("", max_length=64)
|
||||
shop: str = Field("", max_length=128)
|
||||
owner_id: int | None = None
|
||||
account_username: str = Field("", max_length=128)
|
||||
gift_name: str = Field("", max_length=128)
|
||||
@@ -2720,7 +2723,7 @@ class DouyuCollabOrderCreate(BaseModel):
|
||||
|
||||
class DouyuCollabOrderUpdate(BaseModel):
|
||||
order_no: str | None = Field(None, max_length=64)
|
||||
shop: str | None = Field(None, max_length=64)
|
||||
shop: str | None = Field(None, max_length=128)
|
||||
owner_id: int | None = None
|
||||
account_username: str | None = Field(None, max_length=128)
|
||||
gift_name: str | None = Field(None, max_length=128)
|
||||
@@ -2876,6 +2879,7 @@ class DouyuCollabOrderOut(BaseModel):
|
||||
id: int
|
||||
order_no: str
|
||||
shop: str = ""
|
||||
shop_original_name: str = ""
|
||||
owner_id: int | None = None
|
||||
owner_name: str = ""
|
||||
source_type: str = "manual"
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy import and_, func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
ARCHIVE_SCOPES: tuple[str, ...] = ("active", "archived", "all")
|
||||
@@ -25,14 +25,33 @@ def apply_order_visibility(
|
||||
void_status: str = "void",
|
||||
) -> Any:
|
||||
"""给协作台账查询统一追加归档和作废过滤。"""
|
||||
return query.filter(
|
||||
order_visibility_expr(
|
||||
model,
|
||||
archive_scope=archive_scope,
|
||||
include_void=include_void,
|
||||
void_status=void_status,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def order_visibility_expr(
|
||||
model: Any,
|
||||
*,
|
||||
archive_scope: str,
|
||||
include_void: bool,
|
||||
void_status: str = "void",
|
||||
):
|
||||
"""归档/作废可见性表达式,可嵌入精确订单号搜索的 OR 条件。"""
|
||||
scope = normalize_archive_scope(archive_scope)
|
||||
filters = []
|
||||
if scope == "active":
|
||||
query = query.filter(model.archived_at.is_(None))
|
||||
filters.append(model.archived_at.is_(None))
|
||||
elif scope == "archived":
|
||||
query = query.filter(model.archived_at.isnot(None))
|
||||
filters.append(model.archived_at.isnot(None))
|
||||
if not include_void:
|
||||
query = query.filter(model.status != void_status)
|
||||
return query
|
||||
filters.append(model.status != void_status)
|
||||
return and_(*filters)
|
||||
|
||||
|
||||
def count_archived(db: Session, model: Any) -> int:
|
||||
|
||||
@@ -19,7 +19,7 @@ from typing import Any
|
||||
from unicodedata import normalize as unicode_normalize
|
||||
|
||||
from loguru import logger
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy import and_, func, or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.douyu import DouyuActivityClient
|
||||
@@ -56,7 +56,10 @@ from .account_sync_runner import WORK_STOREHOME_SYNC
|
||||
from .account_work_queue import enqueue_account_work
|
||||
from .audit_service import record_account_action, record_audit
|
||||
from .business_events import record_account_query
|
||||
from .collab_common import apply_order_visibility, count_archived
|
||||
from .collab_common import (
|
||||
count_archived,
|
||||
order_visibility_expr,
|
||||
)
|
||||
from .cookie_check_service import check_douyu_cookie
|
||||
from .douyu_account_probe import (
|
||||
ROLE_BOUND,
|
||||
@@ -80,6 +83,7 @@ from .douyu_goods_service import (
|
||||
)
|
||||
from .file_service import build_file_url
|
||||
from .platform_fulfillment.account_selector import (
|
||||
CapabilityAccount,
|
||||
acquire_account_lease,
|
||||
active_lease_for_account,
|
||||
capability_candidate_accounts,
|
||||
@@ -651,7 +655,7 @@ def recommend_accounts(
|
||||
),
|
||||
)
|
||||
now = _now()
|
||||
candidates_by_id: dict[int, Account] = {}
|
||||
candidates_by_id: dict[int, Account | CapabilityAccount] = {}
|
||||
if cid:
|
||||
for account in capability_candidate_accounts(
|
||||
db,
|
||||
@@ -1488,6 +1492,8 @@ def create_order(
|
||||
)
|
||||
|
||||
images = normalize_images(home_images)
|
||||
shop_original_name = _text(shop, max_length=128)
|
||||
shop_name = resolve_shop_name(db, shop_original_name)
|
||||
explicit_points = _to_int(required_points)
|
||||
name, cid, points = _resolve_gift(
|
||||
db,
|
||||
@@ -1497,7 +1503,8 @@ def create_order(
|
||||
)
|
||||
order = DouyuExternalOrder(
|
||||
order_no=order_text,
|
||||
shop=_text(shop, max_length=64),
|
||||
shop=shop_name[:64],
|
||||
shop_original_name=shop_original_name,
|
||||
owner_id=owner_user_id,
|
||||
account_username=_text(account_username, max_length=128),
|
||||
gift_name=name,
|
||||
@@ -1818,7 +1825,10 @@ def sync_platform_fulfillment_order(
|
||||
order.last_synced_at = now
|
||||
order.updated_by = current.id
|
||||
order.updated_at = now
|
||||
order.shop = _text(task.shop_name or task.shop_id, max_length=64)
|
||||
shop_original_name = _text(task.shop_name or task.shop_id, max_length=128)
|
||||
ensure_shops_registered(db, current, [shop_original_name])
|
||||
order.shop = resolve_shop_name(db, shop_original_name)[:64]
|
||||
order.shop_original_name = shop_original_name
|
||||
order.gift_name = gift_name
|
||||
order.commodity_id = commodity_id
|
||||
order.required_points = required_points
|
||||
@@ -2017,6 +2027,8 @@ def update_order(
|
||||
raise CollabError(
|
||||
"订单号已存在", status_code=409, code="order_no_exists"
|
||||
)
|
||||
elif field == "shop":
|
||||
new = _text(payload[field], max_length=128)
|
||||
else:
|
||||
new = _text(payload[field], max_length=512 if field == "remark" else 128)
|
||||
pending[field] = new
|
||||
@@ -2041,6 +2053,9 @@ def update_order(
|
||||
|
||||
for field, new in pending.items():
|
||||
setattr(order, field, new)
|
||||
if "shop" in pending:
|
||||
order.shop_original_name = str(pending["shop"] or "")
|
||||
order.shop = resolve_shop_name(db, order.shop_original_name)[:64]
|
||||
if "account_username" in payload and (
|
||||
order.account_id is None
|
||||
or not order.bind_game_role
|
||||
@@ -2976,23 +2991,89 @@ def query_activity_batch(
|
||||
return results
|
||||
|
||||
|
||||
def _normalize_shop_aliases(values: Any) -> list[str]:
|
||||
if not isinstance(values, (list, tuple, set)):
|
||||
return []
|
||||
aliases: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for raw in values:
|
||||
alias = _text(raw, max_length=128)
|
||||
if not alias or alias in seen:
|
||||
continue
|
||||
seen.add(alias)
|
||||
aliases.append(alias)
|
||||
return aliases
|
||||
|
||||
|
||||
def _shop_match_values(shop: DouyuCollabShop) -> list[str]:
|
||||
return [str(shop.name or ""), *list(shop.aliases or [])]
|
||||
|
||||
|
||||
def resolve_shop_name(db: Session, raw_name: str) -> str:
|
||||
"""按店铺管理中人工维护的别名映射规范简称;未知名称原样保留。"""
|
||||
name = _text(raw_name, max_length=128)
|
||||
if not name:
|
||||
return ""
|
||||
for shop in db.query(DouyuCollabShop).all():
|
||||
if name in _shop_match_values(shop):
|
||||
return str(shop.name)
|
||||
return name
|
||||
|
||||
|
||||
def _reproject_shop_orders(
|
||||
db: Session,
|
||||
shop: DouyuCollabShop,
|
||||
*,
|
||||
previous_name: str,
|
||||
previous_aliases: list[str],
|
||||
) -> None:
|
||||
"""店铺名称或手工别名变化后,重新计算受影响订单的展示简称。"""
|
||||
current_aliases = list(shop.aliases or [])
|
||||
match_values = {
|
||||
previous_name,
|
||||
str(shop.name or ""),
|
||||
*previous_aliases,
|
||||
*current_aliases,
|
||||
}
|
||||
match_values.discard("")
|
||||
if not match_values:
|
||||
return
|
||||
rows = (
|
||||
db.query(DouyuExternalOrder)
|
||||
.filter(
|
||||
or_(
|
||||
DouyuExternalOrder.shop.in_(match_values),
|
||||
DouyuExternalOrder.shop_original_name.in_(match_values),
|
||||
)
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for order in rows:
|
||||
original_name = order.shop_original_name or order.shop or ""
|
||||
resolved = resolve_shop_name(db, original_name)[:64]
|
||||
if order.shop == previous_name and original_name in (previous_name, shop.name):
|
||||
resolved = str(shop.name)[:64]
|
||||
order.shop = resolved
|
||||
|
||||
|
||||
def ensure_shops_registered(
|
||||
db: Session, current: User | None, names: list[str]
|
||||
) -> None:
|
||||
seen: set[str] = set()
|
||||
for raw in names:
|
||||
name = _text(raw, max_length=64)
|
||||
name = _text(raw, max_length=128)
|
||||
if not name or name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
exists = (
|
||||
db.query(DouyuCollabShop.id).filter(DouyuCollabShop.name == name).first()
|
||||
exists = any(
|
||||
name in _shop_match_values(shop)
|
||||
for shop in db.query(DouyuCollabShop).all()
|
||||
)
|
||||
if exists:
|
||||
continue
|
||||
db.add(
|
||||
DouyuCollabShop(
|
||||
name=name,
|
||||
name=name[:64],
|
||||
created_by=current.id if current else None,
|
||||
updated_by=current.id if current else None,
|
||||
)
|
||||
@@ -3016,7 +3097,12 @@ def get_shop(db: Session, shop_id: int) -> DouyuCollabShop:
|
||||
|
||||
|
||||
def create_shop(
|
||||
db: Session, current: User, *, name: str, remark: str = ""
|
||||
db: Session,
|
||||
current: User,
|
||||
*,
|
||||
name: str,
|
||||
aliases: Any = None,
|
||||
remark: str = "",
|
||||
) -> DouyuCollabShop:
|
||||
clean = _text(name, max_length=64)
|
||||
if not clean:
|
||||
@@ -3026,6 +3112,7 @@ def create_shop(
|
||||
raise CollabError("店铺已存在", status_code=409, code="shop_exists")
|
||||
shop = DouyuCollabShop(
|
||||
name=clean,
|
||||
aliases=_normalize_shop_aliases(aliases),
|
||||
remark=_text(remark, max_length=255),
|
||||
created_by=current.id,
|
||||
updated_by=current.id,
|
||||
@@ -3043,8 +3130,10 @@ def update_shop(
|
||||
payload: Mapping[str, Any],
|
||||
) -> DouyuCollabShop:
|
||||
old_name = shop.name
|
||||
old_aliases = list(shop.aliases or [])
|
||||
old = {
|
||||
"name": shop.name,
|
||||
"aliases": old_aliases,
|
||||
"sort_order": shop.sort_order,
|
||||
"is_active": shop.is_active,
|
||||
"remark": shop.remark,
|
||||
@@ -3064,6 +3153,8 @@ def update_shop(
|
||||
if duplicate:
|
||||
raise CollabError("店铺已存在", status_code=409, code="shop_exists")
|
||||
shop.name = name
|
||||
if "aliases" in payload:
|
||||
shop.aliases = _normalize_shop_aliases(payload.get("aliases"))
|
||||
if "sort_order" in payload:
|
||||
shop.sort_order = _to_int(payload.get("sort_order")) or 0
|
||||
if "is_active" in payload:
|
||||
@@ -3071,9 +3162,15 @@ def update_shop(
|
||||
if "remark" in payload:
|
||||
shop.remark = _text(payload.get("remark"), max_length=255)
|
||||
shop.updated_by = current.id
|
||||
if shop.name != old_name:
|
||||
db.query(DouyuExternalOrder).filter(DouyuExternalOrder.shop == old_name).update(
|
||||
{DouyuExternalOrder.shop: shop.name}, synchronize_session=False
|
||||
if (
|
||||
shop.name != old_name
|
||||
or list(shop.aliases or []) != old_aliases
|
||||
):
|
||||
_reproject_shop_orders(
|
||||
db,
|
||||
shop,
|
||||
previous_name=old_name,
|
||||
previous_aliases=old_aliases,
|
||||
)
|
||||
record_audit(
|
||||
db,
|
||||
@@ -3084,6 +3181,7 @@ def update_shop(
|
||||
"old": old,
|
||||
"new": {
|
||||
"name": shop.name,
|
||||
"aliases": list(shop.aliases or []),
|
||||
"sort_order": shop.sort_order,
|
||||
"is_active": shop.is_active,
|
||||
"remark": shop.remark,
|
||||
@@ -3446,6 +3544,7 @@ def serialize_order(
|
||||
"id": int(order.id),
|
||||
"order_no": order.order_no,
|
||||
"shop": order.shop or "",
|
||||
"shop_original_name": order.shop_original_name or order.shop or "",
|
||||
"owner_id": order.owner_id,
|
||||
"owner_name": users.get(int(order.owner_id), "") if order.owner_id else "",
|
||||
"source_type": order.source_type or "manual",
|
||||
@@ -3550,17 +3649,61 @@ def _apply_order_filters(
|
||||
keyword: str = "",
|
||||
ck_status: str = "",
|
||||
):
|
||||
query = apply_order_visibility(
|
||||
query,
|
||||
DouyuExternalOrder,
|
||||
archive_scope=archive_scope,
|
||||
include_void=include_void,
|
||||
void_status=STATUS_VOID,
|
||||
)
|
||||
search = _text(keyword)
|
||||
exact_search_filter = None
|
||||
if search:
|
||||
exact_search_filter = or_(
|
||||
DouyuExternalOrder.order_no == search,
|
||||
DouyuExternalOrder.source_platform_order_id == search,
|
||||
DouyuExternalOrder.source_order_id == search,
|
||||
DouyuExternalOrder.source_order_item_id == search,
|
||||
)
|
||||
pattern = f"%{search}%"
|
||||
fuzzy_search_filter = or_(
|
||||
DouyuExternalOrder.order_no.ilike(pattern),
|
||||
DouyuExternalOrder.account_username.ilike(pattern),
|
||||
DouyuExternalOrder.account_nickname.ilike(pattern),
|
||||
DouyuExternalOrder.bind_game_role.ilike(pattern),
|
||||
DouyuExternalOrder.shop.ilike(pattern),
|
||||
DouyuExternalOrder.remark.ilike(pattern),
|
||||
DouyuExternalOrder.source_order_id.ilike(pattern),
|
||||
DouyuExternalOrder.source_order_item_id.ilike(pattern),
|
||||
DouyuExternalOrder.source_platform_order_id.ilike(pattern),
|
||||
)
|
||||
query = query.filter(
|
||||
or_(
|
||||
exact_search_filter,
|
||||
and_(
|
||||
order_visibility_expr(
|
||||
DouyuExternalOrder,
|
||||
archive_scope=archive_scope,
|
||||
include_void=include_void,
|
||||
void_status=STATUS_VOID,
|
||||
),
|
||||
fuzzy_search_filter,
|
||||
),
|
||||
)
|
||||
)
|
||||
else:
|
||||
query = query.filter(
|
||||
order_visibility_expr(
|
||||
DouyuExternalOrder,
|
||||
archive_scope=archive_scope,
|
||||
include_void=include_void,
|
||||
void_status=STATUS_VOID,
|
||||
)
|
||||
)
|
||||
if _text(status):
|
||||
query = query.filter(DouyuExternalOrder.status == _text(status))
|
||||
status_filter = DouyuExternalOrder.status == _text(status)
|
||||
query = query.filter(
|
||||
or_(status_filter, exact_search_filter)
|
||||
if exact_search_filter is not None
|
||||
else status_filter
|
||||
)
|
||||
if _text(shop):
|
||||
query = query.filter(DouyuExternalOrder.shop == _text(shop))
|
||||
query = query.filter(
|
||||
DouyuExternalOrder.shop == resolve_shop_name(db, _text(shop))
|
||||
)
|
||||
if owner_id is not None:
|
||||
query = query.filter(DouyuExternalOrder.owner_id == int(owner_id))
|
||||
if _text(gift_name):
|
||||
@@ -3580,22 +3723,6 @@ def _apply_order_filters(
|
||||
Account.ck_check_status.in_(("", CK_UNVERIFIED)),
|
||||
)
|
||||
)
|
||||
search = _text(keyword)
|
||||
if search:
|
||||
pattern = f"%{search}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
DouyuExternalOrder.order_no.ilike(pattern),
|
||||
DouyuExternalOrder.account_username.ilike(pattern),
|
||||
DouyuExternalOrder.account_nickname.ilike(pattern),
|
||||
DouyuExternalOrder.bind_game_role.ilike(pattern),
|
||||
DouyuExternalOrder.shop.ilike(pattern),
|
||||
DouyuExternalOrder.remark.ilike(pattern),
|
||||
DouyuExternalOrder.source_order_id.ilike(pattern),
|
||||
DouyuExternalOrder.source_order_item_id.ilike(pattern),
|
||||
DouyuExternalOrder.source_platform_order_id.ilike(pattern),
|
||||
)
|
||||
)
|
||||
return query
|
||||
|
||||
|
||||
|
||||
@@ -43,6 +43,16 @@ if TYPE_CHECKING:
|
||||
DOUYU_PAYMENT_POLL_SECONDS = 600
|
||||
DOUYU_PAYMENT_POLL_INTERVAL = 5
|
||||
|
||||
AUTO_EXCHANGE_ELIGIBILITY_TASK_TYPES = frozenset(
|
||||
{
|
||||
"create_gold_qr",
|
||||
"donate_elite_gift",
|
||||
"create_elite_qr",
|
||||
"confirm_bind",
|
||||
"query_game_name",
|
||||
}
|
||||
)
|
||||
|
||||
# 走代理的任务类型:写操作/消耗类(兑换、锁单、支付、开通、充值、送礼)。
|
||||
# 查询/刷新/绑定/扫码等读操作始终直连——它们不怕 IP 频控,走代理只会浪费代理额度。
|
||||
DOUYU_PROXY_TASK_TYPES = {
|
||||
@@ -255,6 +265,40 @@ class DouyuBatchRunnerCore:
|
||||
"[douyu] 同步直播账号履约状态失败: task_id={}", douyu_task_id
|
||||
)
|
||||
|
||||
def _refresh_platform_exchange_eligibility(
|
||||
self,
|
||||
douyu_task_id: int,
|
||||
*,
|
||||
enabled: bool,
|
||||
) -> None:
|
||||
"""账号积分/宝典变化后,自动刷新当前履约任务的兑换投影。"""
|
||||
if not enabled:
|
||||
return
|
||||
try:
|
||||
from ..database import WorkerSessionLocal
|
||||
from .platform_fulfillment.service import (
|
||||
refresh_active_exchange_eligibility_for_account,
|
||||
)
|
||||
|
||||
refresh_db = WorkerSessionLocal()
|
||||
try:
|
||||
task = refresh_db.get(DouyuTask, int(douyu_task_id))
|
||||
if task is None or task.status != "success":
|
||||
return
|
||||
refresh_active_exchange_eligibility_for_account(
|
||||
refresh_db,
|
||||
account_id=int(task.account_id),
|
||||
scope=str(task.handbook_scope or "elite"),
|
||||
actor_id=int(task.created_by),
|
||||
)
|
||||
finally:
|
||||
refresh_db.close()
|
||||
except Exception: # noqa: BLE001 - 自动刷新不能覆盖任务执行结果
|
||||
logger.exception(
|
||||
"[douyu] 自动刷新直播履约兑换资格失败: task_id={}",
|
||||
douyu_task_id,
|
||||
)
|
||||
|
||||
def _sync_platform_fulfillment_operation(
|
||||
self,
|
||||
db: Session,
|
||||
@@ -285,8 +329,13 @@ class DouyuBatchRunnerCore:
|
||||
message: str,
|
||||
result: dict | None = None,
|
||||
) -> None:
|
||||
from .platform_fulfillment.service import requires_account_binding_sync
|
||||
|
||||
task_id = int(task.id)
|
||||
has_platform_task = task.platform_task_id is not None
|
||||
sync_platform_fulfillment = has_platform_task or requires_account_binding_sync(
|
||||
task.task_type
|
||||
)
|
||||
task.status = status
|
||||
task.message = message[:512]
|
||||
if status in {"success", "failed", "error", "stopped"}:
|
||||
@@ -352,7 +401,17 @@ class DouyuBatchRunnerCore:
|
||||
logger.exception(
|
||||
"[douyu] 写入账号任务结果事件失败: task_id={}", task.id
|
||||
)
|
||||
self._sync_platform_fulfillment(task_id, enabled=has_platform_task)
|
||||
self._sync_platform_fulfillment(
|
||||
task_id,
|
||||
enabled=sync_platform_fulfillment,
|
||||
)
|
||||
self._refresh_platform_exchange_eligibility(
|
||||
task_id,
|
||||
enabled=(
|
||||
status == "success"
|
||||
and task.task_type in AUTO_EXCHANGE_ELIGIBILITY_TASK_TYPES
|
||||
),
|
||||
)
|
||||
|
||||
def _schedule_payment_poll(
|
||||
self,
|
||||
|
||||
@@ -64,8 +64,38 @@ class AccountCandidate:
|
||||
class CapabilityCandidate:
|
||||
"""一个新鲜能力快照及其对应账号,供本地零外部请求选号。"""
|
||||
|
||||
account: Account
|
||||
state: AccountCommodityState
|
||||
account: CapabilityAccount
|
||||
state: CapabilityState
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CapabilityAccount:
|
||||
"""能力选号实际需要的账号字段,不加载 CK / JSON 等大列。"""
|
||||
|
||||
id: int
|
||||
username: str
|
||||
nickname: str
|
||||
uid: str
|
||||
points: int | None
|
||||
gold_balance: int | None
|
||||
points_expire_at: datetime | None
|
||||
role_change_available_at: datetime | None
|
||||
elite_opened: bool | None
|
||||
role_bind_status: str
|
||||
ck_check_status: str
|
||||
game_name: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CapabilityState:
|
||||
"""选号排序之后才需要的能力快照详情。"""
|
||||
|
||||
account_eligibility: str
|
||||
offer_state: str
|
||||
observed_at: datetime | None
|
||||
available_from: datetime | None
|
||||
valid_until: datetime | None
|
||||
blocking_reason: str
|
||||
|
||||
|
||||
def _now(now: datetime | None = None) -> datetime:
|
||||
@@ -251,7 +281,24 @@ def _capability_candidate_query(
|
||||
allow_before_open=allow_before_open,
|
||||
)
|
||||
return (
|
||||
db.query(Account, AccountCommodityState)
|
||||
db.query(
|
||||
Account.id.label("account_id"),
|
||||
Account.username.label("account_username"),
|
||||
Account.nickname.label("account_nickname"),
|
||||
Account.uid.label("account_uid"),
|
||||
Account.points.label("account_points"),
|
||||
Account.gold_balance.label("account_gold_balance"),
|
||||
Account.points_expire_at.label("account_points_expire_at"),
|
||||
Account.role_change_available_at.label(
|
||||
"account_role_change_available_at"
|
||||
),
|
||||
Account.elite_opened.label("account_elite_opened"),
|
||||
Account.role_bind_status.label("account_role_bind_status"),
|
||||
Account.ck_check_status.label("account_ck_check_status"),
|
||||
Account.game_name.label("account_game_name"),
|
||||
AccountCommodityState.offer_state.label("state_offer_state"),
|
||||
AccountCommodityState.observed_at.label("state_observed_at"),
|
||||
)
|
||||
.join(
|
||||
AccountCommodityState,
|
||||
AccountCommodityState.account_id == Account.id,
|
||||
@@ -315,10 +362,67 @@ def capability_candidate_rows(
|
||||
)
|
||||
if query is None:
|
||||
return []
|
||||
return [
|
||||
CapabilityCandidate(account=account, state=state)
|
||||
for account, state in query.all()
|
||||
]
|
||||
rows = query.all()
|
||||
if not rows:
|
||||
return []
|
||||
account_ids = [int(row.account_id) for row in rows]
|
||||
state_rows = (
|
||||
db.query(
|
||||
AccountCommodityState.account_id,
|
||||
AccountCommodityState.account_eligibility,
|
||||
AccountCommodityState.offer_state,
|
||||
AccountCommodityState.observed_at,
|
||||
AccountCommodityState.available_from,
|
||||
AccountCommodityState.valid_until,
|
||||
AccountCommodityState.blocking_reason,
|
||||
)
|
||||
.filter(
|
||||
AccountCommodityState.account_id.in_(account_ids),
|
||||
AccountCommodityState.platform == "douyu",
|
||||
AccountCommodityState.scope == scope,
|
||||
AccountCommodityState.commodity_id == commodity_id.strip(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
states = {
|
||||
int(row.account_id): CapabilityState(
|
||||
account_eligibility=str(row.account_eligibility or ""),
|
||||
offer_state=str(row.offer_state or ""),
|
||||
observed_at=row.observed_at,
|
||||
available_from=row.available_from,
|
||||
valid_until=row.valid_until,
|
||||
blocking_reason=str(row.blocking_reason or ""),
|
||||
)
|
||||
for row in state_rows
|
||||
}
|
||||
candidates: list[CapabilityCandidate] = []
|
||||
for row in rows:
|
||||
account_id = int(row.account_id)
|
||||
state = states.get(account_id)
|
||||
if state is None:
|
||||
continue
|
||||
candidates.append(
|
||||
CapabilityCandidate(
|
||||
account=CapabilityAccount(
|
||||
id=account_id,
|
||||
username=str(row.account_username or ""),
|
||||
nickname=str(row.account_nickname or ""),
|
||||
uid=str(row.account_uid or ""),
|
||||
points=row.account_points,
|
||||
gold_balance=row.account_gold_balance,
|
||||
points_expire_at=row.account_points_expire_at,
|
||||
role_change_available_at=(
|
||||
row.account_role_change_available_at
|
||||
),
|
||||
elite_opened=row.account_elite_opened,
|
||||
role_bind_status=str(row.account_role_bind_status or ""),
|
||||
ck_check_status=str(row.account_ck_check_status or ""),
|
||||
game_name=str(row.account_game_name or ""),
|
||||
),
|
||||
state=state,
|
||||
)
|
||||
)
|
||||
return candidates
|
||||
|
||||
|
||||
def capability_candidate_accounts(
|
||||
@@ -330,7 +434,7 @@ def capability_candidate_accounts(
|
||||
limit: int = 20,
|
||||
now: datetime | None = None,
|
||||
allow_before_open: bool = False,
|
||||
) -> list[Account]:
|
||||
) -> list[CapabilityAccount]:
|
||||
"""从新鲜的商品能力索引读取候选账号,不产生外部请求。"""
|
||||
return [
|
||||
candidate.account
|
||||
@@ -680,6 +784,7 @@ __all__ = [
|
||||
"EXCHANGE_COOLDOWN_DAYS",
|
||||
"VALIDATION_LEASE_MINUTES",
|
||||
"AccountCandidate",
|
||||
"CapabilityAccount",
|
||||
"acquire_account_lease",
|
||||
"active_lease_for_account",
|
||||
"capability_candidate_accounts",
|
||||
|
||||
@@ -44,6 +44,20 @@ from .runtime import (
|
||||
)
|
||||
from .views import get_task_detail
|
||||
|
||||
BINDING_SYNC_TASK_TYPES = frozenset(
|
||||
{
|
||||
"get_bind_qr",
|
||||
"query_game_name",
|
||||
"confirm_bind",
|
||||
"prepare_esports_bind",
|
||||
"query_esports_game_name",
|
||||
"confirm_esports_bind",
|
||||
"prepare_xpd_bind",
|
||||
"query_xpd_game_name",
|
||||
"confirm_xpd_bind",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def start_binding_sync(
|
||||
db: Session,
|
||||
@@ -277,7 +291,86 @@ def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int:
|
||||
]
|
||||
for task_id in task_ids:
|
||||
refresh_binding(db, task_id=task_id)
|
||||
return len(task_ids)
|
||||
douyu_task = db.get(DouyuTask, int(douyu_task_id))
|
||||
if douyu_task is None or douyu_task.task_type not in BINDING_SYNC_TASK_TYPES:
|
||||
return len(task_ids)
|
||||
return len(task_ids) + sync_active_task_from_account_binding(
|
||||
db,
|
||||
account_id=int(douyu_task.account_id),
|
||||
scope=str(douyu_task.handbook_scope or ""),
|
||||
source_task_id=int(douyu_task.id),
|
||||
)
|
||||
|
||||
|
||||
def sync_active_task_from_account_binding(
|
||||
db: Session,
|
||||
*,
|
||||
account_id: int,
|
||||
scope: str,
|
||||
source_task_id: int | None = None,
|
||||
) -> int:
|
||||
"""账号权威绑定已确认时,把当前活跃履约任务同步到 bound。
|
||||
|
||||
精英宝典工作台发出的确认任务不挂在履约任务上,因此不能只看
|
||||
``PlatformFulfillmentTask.bind_task_id``。账号上的绑定状态才是最终事实。
|
||||
只在任务已经识别出待确认角色后同步,避免把账号历史绑定误当成当前订单结果。
|
||||
"""
|
||||
if scope != "elite":
|
||||
return 0
|
||||
account = db.get(Account, int(account_id))
|
||||
if account is None or account.role_bind_status != "bound":
|
||||
return 0
|
||||
task = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.join(AccountLease, AccountLease.id == PlatformFulfillmentTask.lease_id)
|
||||
.filter(
|
||||
PlatformFulfillmentTask.account_id == int(account_id),
|
||||
PlatformFulfillmentTask.scope == "elite",
|
||||
PlatformFulfillmentTask.binding_status.in_(("role_ready", "confirming")),
|
||||
PlatformFulfillmentTask.execution_status.notin_(
|
||||
("completed", "cancelled")
|
||||
),
|
||||
AccountLease.status == "active",
|
||||
)
|
||||
.order_by(
|
||||
PlatformFulfillmentTask.updated_at.desc(),
|
||||
PlatformFulfillmentTask.id.desc(),
|
||||
)
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if task is None:
|
||||
return 0
|
||||
task.binding_status = "bound"
|
||||
task.execution_status = "bound"
|
||||
task.issue_code = ""
|
||||
task.last_error = ""
|
||||
task.updated_at = _now()
|
||||
_append_event(
|
||||
db,
|
||||
task.id,
|
||||
"binding_synced_from_account",
|
||||
detail={
|
||||
"accountId": int(account.id),
|
||||
"accountName": account.nickname or account.username,
|
||||
"roleName": str(account.game_name or ""),
|
||||
"gameChannel": str(account.game_channel or ""),
|
||||
"roleChangeAvailableAt": (
|
||||
account.role_change_available_at.isoformat()
|
||||
if account.role_change_available_at
|
||||
else None
|
||||
),
|
||||
"sourceTaskId": source_task_id,
|
||||
},
|
||||
)
|
||||
_apply_task_lease_policy(db, task)
|
||||
_emit_order_site_binding_state(db, task.id)
|
||||
db.commit()
|
||||
return 1
|
||||
|
||||
|
||||
def requires_account_binding_sync(task_type: str) -> bool:
|
||||
return str(task_type or "") in BINDING_SYNC_TASK_TYPES
|
||||
|
||||
|
||||
def reconcile_binding_state_outbox(
|
||||
|
||||
@@ -185,7 +185,12 @@ def reset_task_binding(
|
||||
|
||||
|
||||
def refresh_exchange_eligibility(
|
||||
db: Session, *, task_id: int, current: User
|
||||
db: Session,
|
||||
*,
|
||||
task_id: int,
|
||||
current: User,
|
||||
automatic: bool = False,
|
||||
mark_failed_on_error: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
task = _load_task(db, task_id)
|
||||
if task.binding_status != "bound":
|
||||
@@ -231,20 +236,28 @@ def refresh_exchange_eligibility(
|
||||
detail={"error": str(exc)[:1000], "commodity_id": task.commodity_id},
|
||||
actor_id=current.id,
|
||||
)
|
||||
task.execution_status = "manual_required"
|
||||
task.exchange_status = "check_failed"
|
||||
task.issue_code = "eligibility_check_failed"
|
||||
task.last_error = str(exc)
|
||||
task.updated_at = _now()
|
||||
_append_event(
|
||||
db,
|
||||
task.id,
|
||||
"eligibility_check_failed",
|
||||
actor_type="user",
|
||||
actor_id=current.id,
|
||||
detail={"error": str(exc)},
|
||||
)
|
||||
_emit_order_site_binding_state(db, task.id)
|
||||
if mark_failed_on_error:
|
||||
task.execution_status = "manual_required"
|
||||
task.exchange_status = "check_failed"
|
||||
task.issue_code = "eligibility_check_failed"
|
||||
task.last_error = str(exc)
|
||||
task.updated_at = _now()
|
||||
_append_event(
|
||||
db,
|
||||
task.id,
|
||||
"eligibility_check_failed",
|
||||
actor_type="user",
|
||||
actor_id=current.id,
|
||||
detail={"error": str(exc)},
|
||||
)
|
||||
_emit_order_site_binding_state(db, task.id)
|
||||
else:
|
||||
_append_event(
|
||||
db,
|
||||
task.id,
|
||||
"eligibility_auto_refresh_failed",
|
||||
detail={"error": str(exc), "automatic": True},
|
||||
)
|
||||
db.commit()
|
||||
return get_task_detail(db, task.id)
|
||||
|
||||
@@ -366,11 +379,12 @@ def refresh_exchange_eligibility(
|
||||
db,
|
||||
task.id,
|
||||
"exchange_eligibility_checked",
|
||||
actor_type="user",
|
||||
actor_id=current.id,
|
||||
actor_type="system" if automatic else "user",
|
||||
actor_id=None if automatic else current.id,
|
||||
detail={
|
||||
"exchangeStatus": task.exchange_status,
|
||||
"limitedCount": len(limited_ids),
|
||||
"automatic": automatic,
|
||||
},
|
||||
)
|
||||
_emit_order_site_binding_state(db, task.id)
|
||||
@@ -378,6 +392,58 @@ def refresh_exchange_eligibility(
|
||||
return get_task_detail(db, task.id)
|
||||
|
||||
|
||||
def refresh_active_exchange_eligibility_for_account(
|
||||
db: Session,
|
||||
*,
|
||||
account_id: int,
|
||||
scope: str,
|
||||
actor_id: int | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""账号资产变化后,自动刷新当前活动履约任务的兑换投影。
|
||||
|
||||
自动刷新失败只记录时间线,不把已绑定任务打成人工;运营仍可手动重试。
|
||||
"""
|
||||
task = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.join(AccountLease, AccountLease.id == PlatformFulfillmentTask.lease_id)
|
||||
.filter(
|
||||
PlatformFulfillmentTask.account_id == int(account_id),
|
||||
PlatformFulfillmentTask.scope == str(scope or SCOPE_ELITE),
|
||||
PlatformFulfillmentTask.binding_status == "bound",
|
||||
PlatformFulfillmentTask.execution_status.notin_(
|
||||
("completed", "cancelled")
|
||||
),
|
||||
AccountLease.status == "active",
|
||||
)
|
||||
.order_by(
|
||||
PlatformFulfillmentTask.updated_at.desc(),
|
||||
PlatformFulfillmentTask.id.desc(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if task is None:
|
||||
return None
|
||||
actor = db.get(User, int(actor_id)) if actor_id is not None else None
|
||||
if actor is None and task.operator_id is not None:
|
||||
actor = db.get(User, int(task.operator_id))
|
||||
if actor is None:
|
||||
actor = (
|
||||
db.query(User)
|
||||
.filter(User.role == "super_admin", User.is_active.is_(True))
|
||||
.order_by(User.id.asc())
|
||||
.first()
|
||||
)
|
||||
if actor is None:
|
||||
return None
|
||||
return refresh_exchange_eligibility(
|
||||
db,
|
||||
task_id=int(task.id),
|
||||
current=actor,
|
||||
automatic=True,
|
||||
mark_failed_on_error=False,
|
||||
)
|
||||
|
||||
|
||||
def complete_manual_exchange(
|
||||
db: Session,
|
||||
*,
|
||||
|
||||
@@ -31,8 +31,10 @@ from .binding import ( # noqa: F401
|
||||
confirm_binding_sync,
|
||||
reconcile_binding_state_outbox,
|
||||
refresh_binding,
|
||||
requires_account_binding_sync,
|
||||
start_binding,
|
||||
start_binding_sync,
|
||||
sync_active_task_from_account_binding,
|
||||
sync_task_from_binding_runner,
|
||||
)
|
||||
from .binding_status import ( # noqa: F401
|
||||
@@ -68,6 +70,7 @@ from .lifecycle import (
|
||||
complete_manual_exchange,
|
||||
mark_manual_required,
|
||||
prepare_platform_task_for_collab_takeover,
|
||||
refresh_active_exchange_eligibility_for_account,
|
||||
refresh_exchange_eligibility,
|
||||
release_task_account,
|
||||
release_task_to_manual,
|
||||
@@ -155,15 +158,18 @@ __all__ = [
|
||||
"reconcile_binding_state_outbox",
|
||||
"record_douyu_operation_result",
|
||||
"record_douyu_operation_started",
|
||||
"refresh_active_exchange_eligibility_for_account",
|
||||
"refresh_binding",
|
||||
"refresh_exchange_eligibility",
|
||||
"release_task_account",
|
||||
"release_task_to_manual",
|
||||
"requires_account_binding_sync",
|
||||
"reset_task_binding",
|
||||
"restore_cancelled_task",
|
||||
"restore_mapping",
|
||||
"set_mapping_enabled",
|
||||
"start_binding",
|
||||
"sync_active_task_from_account_binding",
|
||||
"sync_order_item_ids",
|
||||
"sync_order_snapshot",
|
||||
"sync_pending_tasks",
|
||||
|
||||
@@ -362,6 +362,9 @@ def _task_out(
|
||||
)
|
||||
collab_order = resolved.collab_orders.get(int(task.id))
|
||||
bind_result = (bind_task.result or {}) if bind_task else {}
|
||||
account_binding_confirmed = bool(
|
||||
account is not None and account.role_bind_status == "bound"
|
||||
)
|
||||
effective_issue = _effective_binding_issue(task, bind_task, bind_result)
|
||||
effective_last_error = _effective_task_message(task, effective_issue)
|
||||
exchange_task_id = task.exchange_task_id
|
||||
@@ -377,7 +380,11 @@ def _task_out(
|
||||
.scalar()
|
||||
)
|
||||
# 外层只消费共享绑定规则,不再自己比较角色名或 bindAct。
|
||||
pending_role = pending_binding_role_from_result(bind_result)
|
||||
pending_role = (
|
||||
""
|
||||
if account_binding_confirmed or task.binding_status == "bound"
|
||||
else pending_binding_role_from_result(bind_result)
|
||||
)
|
||||
sale_mode = classification.normalize_sale_mode(task.sale_mode)
|
||||
availability = classification.availability_state(
|
||||
sale_mode=sale_mode,
|
||||
@@ -477,12 +484,19 @@ def _task_out(
|
||||
"status": bind_task.status,
|
||||
"message": bind_task.message,
|
||||
"qrUrl": str(bind_result.get("url") or "") if include_qr else "",
|
||||
"roleName": binding_role_from_result(bind_result),
|
||||
"roleName": (
|
||||
str(account.game_name or "")
|
||||
if account_binding_confirmed and account is not None
|
||||
else binding_role_from_result(bind_result)
|
||||
),
|
||||
"areaName": str(bind_result.get("area_name") or ""),
|
||||
"platName": str(bind_result.get("plat_name") or ""),
|
||||
"bindPhase": str(bind_result.get("bind_phase") or ""),
|
||||
"bindReadyForConfirm": bool(pending_role),
|
||||
"bindConfirmed": bool(bind_result.get("bind_confirmed")),
|
||||
"bindConfirmed": bool(
|
||||
account_binding_confirmed
|
||||
or bind_result.get("bind_confirmed")
|
||||
),
|
||||
}
|
||||
if bind_task
|
||||
else None
|
||||
@@ -620,7 +634,15 @@ def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
|
||||
else None
|
||||
)
|
||||
bind_result = (bind_task.result or {}) if bind_task else {}
|
||||
pending_role = pending_binding_role_from_result(bind_result)
|
||||
account = db.get(Account, int(task.account_id)) if task.account_id else None
|
||||
account_binding_confirmed = bool(
|
||||
account is not None and account.role_bind_status == "bound"
|
||||
)
|
||||
pending_role = (
|
||||
""
|
||||
if account_binding_confirmed or task.binding_status == "bound"
|
||||
else pending_binding_role_from_result(bind_result)
|
||||
)
|
||||
effective_issue = _effective_binding_issue(task, bind_task, bind_result)
|
||||
lease = (
|
||||
db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
|
||||
@@ -657,11 +679,18 @@ def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
|
||||
"qrUrl": str(bind_result.get("url") or ""),
|
||||
"qrGeneratedAt": str(bind_result.get("qr_generated_at") or ""),
|
||||
"qrExpiresAt": str(bind_result.get("qr_expires_at") or ""),
|
||||
"roleName": binding_role_from_result(bind_result),
|
||||
"roleName": (
|
||||
str(account.game_name or "")
|
||||
if account_binding_confirmed and account is not None
|
||||
else binding_role_from_result(bind_result)
|
||||
),
|
||||
"areaName": str(bind_result.get("area_name") or ""),
|
||||
"platName": str(bind_result.get("plat_name") or ""),
|
||||
"bindReadyForConfirm": (bool(pending_role) and not binding_failed),
|
||||
"bindConfirmed": bool(bind_result.get("bind_confirmed")) and binding_confirmed,
|
||||
"bindConfirmed": bool(
|
||||
binding_confirmed
|
||||
and (account_binding_confirmed or bind_result.get("bind_confirmed"))
|
||||
),
|
||||
"queueState": queue_state,
|
||||
"retryAfterMs": retry_after_ms,
|
||||
"queueLane": bind_task.queue_lane if bind_task else "",
|
||||
|
||||
@@ -30,6 +30,7 @@ export interface DouyuCollabOrder {
|
||||
id: number;
|
||||
order_no: string;
|
||||
shop: string;
|
||||
shop_original_name: string;
|
||||
owner_id: number | null;
|
||||
owner_name: string;
|
||||
source_type: string;
|
||||
@@ -179,6 +180,7 @@ export interface DouyuCollabOwner {
|
||||
export interface DouyuCollabShop {
|
||||
id: number;
|
||||
name: string;
|
||||
aliases: string[];
|
||||
sort_order: number;
|
||||
is_active: boolean;
|
||||
remark: string;
|
||||
@@ -348,11 +350,17 @@ export const douyuCollabApi = {
|
||||
owners: () => api.get<DouyuCollabOwner[], DouyuCollabOwner[]>('/douyu/external-orders/owners'),
|
||||
shops: () => api.get<string[], string[]>('/douyu/external-orders/shops'),
|
||||
shopRecords: () => api.get<DouyuCollabShop[], DouyuCollabShop[]>('/douyu/collab-shops'),
|
||||
createShop: (data: { name: string; remark?: string }) =>
|
||||
createShop: (data: { name: string; aliases?: string[]; remark?: string }) =>
|
||||
api.post<DouyuCollabShop, DouyuCollabShop>('/douyu/collab-shops', data),
|
||||
updateShop: (
|
||||
id: number,
|
||||
data: { name?: string; sort_order?: number; is_active?: boolean; remark?: string },
|
||||
data: {
|
||||
name?: string;
|
||||
aliases?: string[];
|
||||
sort_order?: number;
|
||||
is_active?: boolean;
|
||||
remark?: string;
|
||||
},
|
||||
) => api.put<DouyuCollabShop, DouyuCollabShop>(`/douyu/collab-shops/${id}`, data),
|
||||
deleteShop: (id: number) =>
|
||||
api.delete<{ success: boolean; name: string; id: number }, { success: boolean; name: string; id: number }>(
|
||||
|
||||
@@ -77,7 +77,12 @@ export default function DouyuCollabShopModal({
|
||||
|
||||
const patch = async (
|
||||
shop: DouyuCollabShop,
|
||||
payload: { sort_order?: number; is_active?: boolean; remark?: string },
|
||||
payload: {
|
||||
aliases?: string[];
|
||||
sort_order?: number;
|
||||
is_active?: boolean;
|
||||
remark?: string;
|
||||
},
|
||||
) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
@@ -150,6 +155,28 @@ export default function DouyuCollabShopModal({
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '完整名称 / 别名(手工映射)',
|
||||
dataIndex: 'aliases',
|
||||
width: 300,
|
||||
render: (value: string[] | undefined, row) => (
|
||||
<Input
|
||||
size="small"
|
||||
defaultValue={(value || []).join(',')}
|
||||
disabled={!canEdit || busy}
|
||||
placeholder="多个名称用逗号分隔"
|
||||
onBlur={(event) => {
|
||||
const aliases = event.target.value
|
||||
.split(/[,,\n]/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
if (aliases.join('\u0000') !== (value || []).join('\u0000')) {
|
||||
void patch(row, { aliases });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '排序',
|
||||
dataIndex: 'sort_order',
|
||||
@@ -225,12 +252,13 @@ export default function DouyuCollabShopModal({
|
||||
open={open}
|
||||
onCancel={onClose}
|
||||
footer={<Button onClick={onClose}>关闭</Button>}
|
||||
width={820}
|
||||
width={1080}
|
||||
destroyOnHidden
|
||||
>
|
||||
<Space direction="vertical" size={10} style={{ width: '100%' }}>
|
||||
<Text type="secondary">
|
||||
先在这里定义店铺,新建协作单时可以直接点选。停用只是不再出现在新建选择里,历史订单不受影响;
|
||||
完整名称/别名只按这里手工维护的映射归并平台同步店铺;筛选仍使用规范简称。
|
||||
重命名会自动同步已有订单,已有订单仍在使用的店铺不能删除。
|
||||
</Text>
|
||||
{canEdit && (
|
||||
|
||||
@@ -30,6 +30,8 @@ import {
|
||||
type TableProps,
|
||||
} from 'antd';
|
||||
import {
|
||||
ArrowDownOutlined,
|
||||
ArrowUpOutlined,
|
||||
CheckCircleOutlined,
|
||||
CopyOutlined,
|
||||
DeleteOutlined,
|
||||
@@ -44,6 +46,7 @@ import {
|
||||
RobotOutlined,
|
||||
SafetyCertificateOutlined,
|
||||
SearchOutlined,
|
||||
SettingOutlined,
|
||||
ShopOutlined,
|
||||
SyncOutlined,
|
||||
TagOutlined,
|
||||
@@ -94,6 +97,74 @@ function hasTextInputFocus(): boolean {
|
||||
/** 实时同步暂停开关按浏览器记住:刷新页面后仍保持暂停,直到手动恢复。 */
|
||||
const REALTIME_PAUSED_STORAGE_KEY = 'douyu.collab.realtime-paused';
|
||||
const REALTIME_WS_PATH = '/api/douyu/external-orders/ws';
|
||||
const COLUMN_LAYOUT_STORAGE_PREFIX = 'douyu.collab.columns';
|
||||
|
||||
const DEFAULT_COLUMN_LAYOUT = [
|
||||
{ key: 'sequence', visible: true },
|
||||
{ key: 'order_shop', visible: true },
|
||||
{ key: 'owner', visible: true },
|
||||
{ key: 'account', visible: true },
|
||||
{ key: 'bind_role', visible: true },
|
||||
{ key: 'home_images', visible: true },
|
||||
{ key: 'gift', visible: true },
|
||||
{ key: 'status', visible: true },
|
||||
{ key: 'balances', visible: true },
|
||||
{ key: 'last_query', visible: true },
|
||||
{ key: 'updated', visible: true },
|
||||
{ key: 'actions', visible: true },
|
||||
] as const;
|
||||
|
||||
const COLUMN_LABELS: Record<string, string> = {
|
||||
sequence: '序号',
|
||||
order_shop: '订单 / 店铺',
|
||||
owner: '负责人',
|
||||
account: '斗鱼账号',
|
||||
bind_role: '绑定角色',
|
||||
home_images: '主页截图',
|
||||
gift: '礼包 / 积分',
|
||||
status: '状态',
|
||||
balances: '鱼翅 / 积分',
|
||||
last_query: '最近查询',
|
||||
updated: '最后改动',
|
||||
actions: '操作',
|
||||
};
|
||||
|
||||
type ColumnPreference = { key: string; visible: boolean };
|
||||
|
||||
function normalizeColumnLayout(raw: unknown): ColumnPreference[] {
|
||||
const defaults = DEFAULT_COLUMN_LAYOUT.map((item) => ({ ...item }));
|
||||
if (!Array.isArray(raw)) return defaults;
|
||||
const known = new Set<string>(defaults.map((item) => item.key));
|
||||
const result: ColumnPreference[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const item of raw) {
|
||||
if (!item || typeof item !== 'object') continue;
|
||||
const row = item as { key?: unknown; visible?: unknown };
|
||||
const key = String(row.key || '');
|
||||
if (!known.has(key) || seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
result.push({
|
||||
key,
|
||||
visible: key === 'actions' ? true : row.visible !== false,
|
||||
});
|
||||
}
|
||||
for (const item of defaults) {
|
||||
if (!seen.has(item.key)) result.push(item);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function readColumnLayout(userId?: number): ColumnPreference[] {
|
||||
if (!userId) return normalizeColumnLayout(null);
|
||||
try {
|
||||
const raw = window.localStorage.getItem(
|
||||
`${COLUMN_LAYOUT_STORAGE_PREFIX}:${userId}`,
|
||||
);
|
||||
return normalizeColumnLayout(raw ? JSON.parse(raw) : null);
|
||||
} catch {
|
||||
return normalizeColumnLayout(null);
|
||||
}
|
||||
}
|
||||
|
||||
function readRealtimePaused(): boolean {
|
||||
try {
|
||||
@@ -445,6 +516,11 @@ export default function DouyuCollabPage() {
|
||||
canEdit && (user?.role === 'super_admin' || user?.role === 'operation');
|
||||
// 单行复制是一键带走凭据,和虎牙台账保持一致:只给超级管理员(后端再校验)
|
||||
const isAdmin = user?.role === 'super_admin';
|
||||
const [columnLayout, setColumnLayout] = useState<ColumnPreference[]>(
|
||||
() => readColumnLayout(user?.id),
|
||||
);
|
||||
const [columnSettingsOpen, setColumnSettingsOpen] = useState(false);
|
||||
const [columnDraft, setColumnDraft] = useState<ColumnPreference[]>([]);
|
||||
|
||||
const [orders, setOrders] = useState<DouyuCollabOrder[]>([]);
|
||||
const [summary, setSummary] = useState<DouyuCollabSummary>({
|
||||
@@ -508,6 +584,10 @@ export default function DouyuCollabPage() {
|
||||
const handledQueryOrderIdRef = useRef(0);
|
||||
const queryOrderId = Number(searchParams.get('orderId') || 0);
|
||||
|
||||
useEffect(() => {
|
||||
setColumnLayout(readColumnLayout(user?.id));
|
||||
}, [user?.id]);
|
||||
|
||||
const [statusTarget, setStatusTarget] = useState<DouyuCollabOrder | null>(null);
|
||||
const [batchStatusOpen, setBatchStatusOpen] = useState(false);
|
||||
const [statusValue, setStatusValue] = useState<DouyuCollabStatus>('to_recharge');
|
||||
@@ -1555,8 +1635,44 @@ export default function DouyuCollabPage() {
|
||||
})),
|
||||
];
|
||||
|
||||
const openColumnSettings = () => {
|
||||
setColumnDraft(columnLayout.map((item) => ({ ...item })));
|
||||
setColumnSettingsOpen(true);
|
||||
};
|
||||
|
||||
const moveColumn = (index: number, offset: number) => {
|
||||
setColumnDraft((current) => {
|
||||
const target = index + offset;
|
||||
if (target < 0 || target >= current.length) return current;
|
||||
const next = [...current];
|
||||
[next[index], next[target]] = [next[target], next[index]];
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const saveColumnSettings = () => {
|
||||
const normalized = normalizeColumnLayout(columnDraft);
|
||||
setColumnLayout(normalized);
|
||||
if (user?.id) {
|
||||
try {
|
||||
window.localStorage.setItem(
|
||||
`${COLUMN_LAYOUT_STORAGE_PREFIX}:${user.id}`,
|
||||
JSON.stringify(normalized),
|
||||
);
|
||||
} catch {
|
||||
// 隐私模式下仍保留本次页面会话的列设置。
|
||||
}
|
||||
}
|
||||
setColumnSettingsOpen(false);
|
||||
};
|
||||
|
||||
const resetColumnSettings = () => {
|
||||
setColumnDraft(normalizeColumnLayout(null));
|
||||
};
|
||||
|
||||
const columns: TableProps<DouyuCollabOrder>['columns'] = [
|
||||
{
|
||||
key: 'sequence',
|
||||
title: '序号',
|
||||
width: 72,
|
||||
fixed: 'left',
|
||||
@@ -1564,9 +1680,10 @@ export default function DouyuCollabPage() {
|
||||
render: (_, row) => <Text type="secondary">{row.id}</Text>,
|
||||
},
|
||||
{
|
||||
title: '订单编号',
|
||||
key: 'order_shop',
|
||||
title: '订单 / 店铺',
|
||||
dataIndex: 'order_no',
|
||||
width: 170,
|
||||
width: 260,
|
||||
fixed: 'left',
|
||||
render: (value: string, row) => (
|
||||
<Space direction="vertical" size={0}>
|
||||
@@ -1577,16 +1694,21 @@ export default function DouyuCollabPage() {
|
||||
<Tag color="cyan">履约同步 · #{row.source_task_id}</Tag>
|
||||
)}
|
||||
{row.status === 'void' && <Tag color="error">已作废:{row.void_reason || '-'}</Tag>}
|
||||
<Space size={4} wrap>
|
||||
<Tag color={row.shop ? 'blue' : 'default'}>
|
||||
{row.shop || '未填店铺'}
|
||||
</Tag>
|
||||
{row.shop_original_name && row.shop_original_name !== row.shop && (
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{row.shop_original_name}
|
||||
</Text>
|
||||
)}
|
||||
</Space>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '店铺',
|
||||
dataIndex: 'shop',
|
||||
width: 120,
|
||||
render: (value: string) => value || <Text type="secondary">未填</Text>,
|
||||
},
|
||||
{
|
||||
key: 'owner',
|
||||
title: '负责人',
|
||||
dataIndex: 'owner_id',
|
||||
width: 120,
|
||||
@@ -1617,6 +1739,7 @@ export default function DouyuCollabPage() {
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'account',
|
||||
title: '斗鱼账号',
|
||||
width: 210,
|
||||
render: (_, row) => (
|
||||
@@ -1666,6 +1789,7 @@ export default function DouyuCollabPage() {
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'bind_role',
|
||||
title: '绑定角色',
|
||||
width: 180,
|
||||
render: (_, row) => (
|
||||
@@ -1683,6 +1807,7 @@ export default function DouyuCollabPage() {
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'home_images',
|
||||
title: '主页截图',
|
||||
width: 110,
|
||||
align: 'center',
|
||||
@@ -1713,6 +1838,7 @@ export default function DouyuCollabPage() {
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'gift',
|
||||
title: '礼包 / 积分',
|
||||
width: 200,
|
||||
render: (_, row) => (
|
||||
@@ -1730,6 +1856,7 @@ export default function DouyuCollabPage() {
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 130,
|
||||
@@ -1741,6 +1868,7 @@ export default function DouyuCollabPage() {
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'balances',
|
||||
title: '鱼翅 / 积分',
|
||||
width: 170,
|
||||
render: (_, row) => {
|
||||
@@ -1758,6 +1886,7 @@ export default function DouyuCollabPage() {
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'last_query',
|
||||
title: '最近查询',
|
||||
width: 160,
|
||||
render: (_, row) =>
|
||||
@@ -1775,6 +1904,7 @@ export default function DouyuCollabPage() {
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'updated',
|
||||
title: '最后改动',
|
||||
width: 150,
|
||||
render: (_, row) => (
|
||||
@@ -1787,6 +1917,7 @@ export default function DouyuCollabPage() {
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'actions',
|
||||
title: '操作',
|
||||
width: 500,
|
||||
fixed: 'right',
|
||||
@@ -1891,6 +2022,14 @@ export default function DouyuCollabPage() {
|
||||
},
|
||||
];
|
||||
|
||||
const columnByKey = new Map(
|
||||
(columns || []).map((column) => [String(column.key || ''), column]),
|
||||
);
|
||||
const visibleColumns = columnLayout
|
||||
.filter((item) => item.visible)
|
||||
.map((item) => columnByKey.get(item.key))
|
||||
.filter((column): column is NonNullable<typeof column> => Boolean(column));
|
||||
|
||||
const goodsPool = lookup?.goods?.length ? lookup.goods : goods;
|
||||
const giftNameOptions = (() => {
|
||||
const options: Array<{ value: string; label: string; disabled: boolean }> = [];
|
||||
@@ -2133,6 +2272,9 @@ export default function DouyuCollabPage() {
|
||||
<Button icon={<ReloadOutlined />} onClick={() => void loadOrders()} loading={loading}>
|
||||
刷新
|
||||
</Button>
|
||||
<Button icon={<SettingOutlined />} onClick={openColumnSettings}>
|
||||
列设置
|
||||
</Button>
|
||||
{realtimePending && <Tag color="processing">有更新待同步</Tag>}
|
||||
<Text type="secondary">已选 {selectedCount} 单</Text>
|
||||
{canView && (
|
||||
@@ -2238,7 +2380,7 @@ export default function DouyuCollabPage() {
|
||||
size="small"
|
||||
tableLayout="fixed"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
columns={visibleColumns}
|
||||
dataSource={orders}
|
||||
scroll={{ x: 2190 }}
|
||||
rowSelection={{
|
||||
@@ -2262,6 +2404,64 @@ export default function DouyuCollabPage() {
|
||||
/>
|
||||
</Card>
|
||||
|
||||
<Modal
|
||||
title="表格列设置"
|
||||
open={columnSettingsOpen}
|
||||
onCancel={() => setColumnSettingsOpen(false)}
|
||||
onOk={saveColumnSettings}
|
||||
okText="保存"
|
||||
cancelText="取消"
|
||||
footer={(_, { OkBtn, CancelBtn }) => (
|
||||
<Space>
|
||||
<Button onClick={resetColumnSettings}>恢复默认</Button>
|
||||
<CancelBtn />
|
||||
<OkBtn />
|
||||
</Space>
|
||||
)}
|
||||
>
|
||||
<Space direction="vertical" size={8} style={{ width: '100%' }}>
|
||||
{columnDraft.map((item, index) => (
|
||||
<div
|
||||
key={item.key}
|
||||
style={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'minmax(0, 1fr) auto auto',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
padding: '4px 0',
|
||||
}}
|
||||
>
|
||||
<Checkbox
|
||||
checked={item.visible}
|
||||
disabled={item.key === 'actions'}
|
||||
onChange={(event) => {
|
||||
const visible = event.target.checked;
|
||||
setColumnDraft((current) => current.map((column) => (
|
||||
column.key === item.key ? { ...column, visible } : column
|
||||
)));
|
||||
}}
|
||||
>
|
||||
{COLUMN_LABELS[item.key] || item.key}
|
||||
</Checkbox>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<ArrowUpOutlined />}
|
||||
aria-label="上移"
|
||||
disabled={index === 0}
|
||||
onClick={() => moveColumn(index, -1)}
|
||||
/>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<ArrowDownOutlined />}
|
||||
aria-label="下移"
|
||||
disabled={index === columnDraft.length - 1}
|
||||
onClick={() => moveColumn(index, 1)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</Space>
|
||||
</Modal>
|
||||
|
||||
<DouyuCollabShopModal
|
||||
open={shopModalOpen}
|
||||
shops={shopRecords}
|
||||
|
||||
@@ -128,7 +128,9 @@ const EVENT_LABELS: Record<string, string> = {
|
||||
binding_failed: '游戏角色绑定失败',
|
||||
binding_reset: '重置角色资料和绑定记录',
|
||||
binding_stale_role_ignored: '忽略账号旧角色',
|
||||
binding_synced_from_account: '同步账号最新角色绑定',
|
||||
eligibility_check_failed: '兑换资格查询失败',
|
||||
eligibility_auto_refresh_failed: '自动刷新兑换资格失败',
|
||||
exchange_eligibility_checked: '刷新兑换资格',
|
||||
manual_exchange_completed: '人工兑换完成',
|
||||
marked_manual_required: '转人工处理',
|
||||
@@ -166,6 +168,7 @@ const ISSUE_LABELS: Record<string, string> = {
|
||||
};
|
||||
|
||||
const DOUYU_ACTION_LABELS: Record<string, string> = {
|
||||
query_game_name: '刷新角色绑定',
|
||||
query_elite_status: '查询精英宝典',
|
||||
create_elite_qr: '开通精英宝典',
|
||||
create_gold_qr: '充值鱼翅',
|
||||
@@ -241,7 +244,8 @@ function eventColor(value: string) {
|
||||
value.includes('completed') ||
|
||||
value.includes('allocated') ||
|
||||
value.includes('restored') ||
|
||||
value.includes('succeeded')
|
||||
value.includes('succeeded') ||
|
||||
value.includes('binding_synced')
|
||||
) {
|
||||
return 'green';
|
||||
}
|
||||
@@ -294,6 +298,9 @@ function eventDescription(event: { eventType: string; detail: Record<string, unk
|
||||
if (event.eventType === 'eligibility_check_failed') {
|
||||
return '实时查询兑换资格失败,可稍后重试';
|
||||
}
|
||||
if (event.eventType === 'eligibility_auto_refresh_failed') {
|
||||
return '账号变化后的自动刷新失败,任务状态保持不变,可手动刷新重试';
|
||||
}
|
||||
if (event.eventType === 'account_released') {
|
||||
return `释放原因:${String(detail.reason || '人工释放')}`;
|
||||
}
|
||||
@@ -331,6 +338,10 @@ function eventDescription(event: { eventType: string; detail: Record<string, unk
|
||||
if (event.eventType === 'binding_reset') {
|
||||
return `${String(detail.reason || '客服重置角色绑定')};客户需重新填写角色资料`;
|
||||
}
|
||||
if (event.eventType === 'binding_synced_from_account') {
|
||||
const channel = String(detail.gameChannel || '');
|
||||
return `账号已确认角色 ${String(detail.roleName || '-')}${channel ? `(${channel})` : ''}`;
|
||||
}
|
||||
if (event.eventType === 'task_created') return '订单已进入直播账号履约工作台';
|
||||
return '履约状态已更新';
|
||||
}
|
||||
@@ -1651,6 +1662,14 @@ export default function PlatformFulfillmentPage() {
|
||||
直接复用斗鱼精英宝典工作台任务,作用于当前履约账号;开通和充值会在任务窗口展示支付二维码。
|
||||
</Text>
|
||||
<Space wrap>
|
||||
<Button
|
||||
icon={<SyncOutlined />}
|
||||
disabled={!selected.account || !can('douyu:task')}
|
||||
loading={douyuActionLoading === 'query_game_name'}
|
||||
onClick={() => void runDouyuAccountAction('query_game_name')}
|
||||
>
|
||||
刷新角色绑定
|
||||
</Button>
|
||||
<Button
|
||||
icon={<ReloadOutlined />}
|
||||
disabled={!selected.account || !can('douyu:task')}
|
||||
|
||||
Reference in New Issue
Block a user