fix(fulfillment): 修复历史账号绑定覆盖当前待确认角色
This commit is contained in:
+119
-1
@@ -31,6 +31,7 @@ from web.backend.models import (
|
||||
AuditLog,
|
||||
AutomationJob,
|
||||
DouyuExternalOrder,
|
||||
DouyuTask,
|
||||
HuyaExternalOrder,
|
||||
PlatformCommodityMapping,
|
||||
PlatformFulfillmentEvent,
|
||||
@@ -43,7 +44,7 @@ TESTS_DIR = Path(__file__).resolve().parent
|
||||
PROJECT_ROOT = TESTS_DIR.parent
|
||||
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
|
||||
|
||||
HEAD_REVISION = "20261123_0125"
|
||||
HEAD_REVISION = "20261123_0126"
|
||||
|
||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||
EXTRA_INDEXES = (
|
||||
@@ -464,6 +465,123 @@ class TestMigrationSmoke:
|
||||
with admin_engine.begin() as conn:
|
||||
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
|
||||
|
||||
def test_0126_repairs_false_confirmation_from_historical_account_binding(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_0125")
|
||||
with Session(mig_engine) as session:
|
||||
user = User(
|
||||
username="false-binding-user",
|
||||
password_hash="hash",
|
||||
role="super_admin",
|
||||
is_active=True,
|
||||
)
|
||||
account = Account(
|
||||
username="false-binding-account",
|
||||
password="password",
|
||||
email="false-binding@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",
|
||||
)
|
||||
bind_task = DouyuTask(
|
||||
batch_id="false-binding-qr",
|
||||
account_id=account.id,
|
||||
account_assigned_to=user.id,
|
||||
task_type="get_bind_qr",
|
||||
handbook_scope="elite",
|
||||
status="success",
|
||||
result={
|
||||
"role_name": "本次待确认角色",
|
||||
"game_channel": "手Q / 苹果(iOS)",
|
||||
"bind_ready_for_confirm": True,
|
||||
"bind_confirmed": False,
|
||||
"bind_phase": "role_ready",
|
||||
},
|
||||
created_by=user.id,
|
||||
)
|
||||
session.add_all([lease, bind_task])
|
||||
session.flush()
|
||||
task = PlatformFulfillmentTask(
|
||||
source_system="order_site",
|
||||
source_order_id="FALSE-BIND-ORDER",
|
||||
source_order_item_id="FALSE-BIND-ITEM",
|
||||
platform_order_id="FALSE-BIND-PLATFORM",
|
||||
internal_sku_key="误绑定修复测试",
|
||||
sku_name="误绑定修复测试",
|
||||
scope="elite",
|
||||
account_id=account.id,
|
||||
lease_id=lease.id,
|
||||
bind_task_id=bind_task.id,
|
||||
binding_status="bound",
|
||||
execution_status="bound",
|
||||
)
|
||||
session.add(task)
|
||||
session.flush()
|
||||
session.add(
|
||||
PlatformFulfillmentEvent(
|
||||
task_id=task.id,
|
||||
event_type="binding_synced_from_account",
|
||||
actor_type="system",
|
||||
actor_id="",
|
||||
detail_json={"backfilled": True},
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
task_id = int(task.id)
|
||||
|
||||
command.upgrade(cfg, "head")
|
||||
|
||||
with Session(mig_engine) as session:
|
||||
task = session.get(PlatformFulfillmentTask, task_id)
|
||||
repair = (
|
||||
session.query(PlatformFulfillmentEvent)
|
||||
.filter_by(
|
||||
task_id=task_id,
|
||||
event_type="binding_false_confirmation_reverted",
|
||||
)
|
||||
.one()
|
||||
)
|
||||
assert task.binding_status == "role_ready"
|
||||
assert task.execution_status == "role_ready"
|
||||
assert repair.detail_json["boundRoleName"] == "历史角色"
|
||||
assert repair.detail_json["pendingRoleName"] == "本次待确认角色"
|
||||
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)}"
|
||||
|
||||
@@ -1813,13 +1813,13 @@ class TestBindingAndCompletion(_Base):
|
||||
handbook_scope="elite",
|
||||
status="success",
|
||||
result={
|
||||
"role_name": "旧角色",
|
||||
"current_role_name": "旧角色",
|
||||
"baseline_role_name": "旧角色",
|
||||
"role_name": "新角色",
|
||||
"current_role_name": "新角色",
|
||||
"baseline_role_name": "历史角色",
|
||||
"baseline_is_bound_act": True,
|
||||
"before_bind_info": {
|
||||
"act_alias": "20260120QYOOB",
|
||||
"role_name": "旧角色",
|
||||
"role_name": "历史角色",
|
||||
"is_bound_act": True,
|
||||
"need_bind_act": True,
|
||||
},
|
||||
@@ -1838,7 +1838,7 @@ class TestBindingAndCompletion(_Base):
|
||||
task.execution_status = "role_ready"
|
||||
account = self.session.get(Account, task.account_id)
|
||||
account.role_bind_status = "bound"
|
||||
account.game_name = "新角色"
|
||||
account.game_name = "历史角色"
|
||||
account.game_channel = "微信 · 苹果(iOS)"
|
||||
confirm_task = DouyuTask(
|
||||
batch_id="confirm-from-elite-workbench",
|
||||
@@ -1860,8 +1860,11 @@ class TestBindingAndCompletion(_Base):
|
||||
|
||||
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
|
||||
assert pre_sync_detail["task"]["bindTask"]["bindReadyForConfirm"] is True
|
||||
|
||||
account.game_name = "新角色"
|
||||
account.role_bind_status = "bound"
|
||||
self.session.commit()
|
||||
synced = service.sync_task_from_binding_runner(
|
||||
self.session,
|
||||
douyu_task_id=confirm_task.id,
|
||||
@@ -1883,8 +1886,74 @@ class TestBindingAndCompletion(_Base):
|
||||
assert detail["task"]["bindTask"]["roleName"] == "新角色"
|
||||
assert detail["task"]["bindTask"]["bindReadyForConfirm"] is False
|
||||
assert detail["task"]["bindTask"]["bindConfirmed"] is True
|
||||
assert task.bind_task_id == confirm_task.id
|
||||
assert event.detail_json["roleName"] == "新角色"
|
||||
|
||||
def test_bind_qr_success_does_not_promote_existing_account_binding(self):
|
||||
task = self._allocated()
|
||||
account = self.session.get(Account, task.account_id)
|
||||
account.role_bind_status = "bound"
|
||||
account.game_name = "历史角色"
|
||||
account.game_channel = "微信 · 苹果(iOS)"
|
||||
bind_task = DouyuTask(
|
||||
batch_id="bind-pending-current-order",
|
||||
account_id=task.account_id,
|
||||
account_assigned_to=self.admin_id,
|
||||
task_type="get_bind_qr",
|
||||
handbook_scope="elite",
|
||||
status="success",
|
||||
result={
|
||||
"act_alias": "cjm",
|
||||
"role_name": "本次待确认角色",
|
||||
"area_name": "手Q",
|
||||
"plat_name": "苹果(iOS)",
|
||||
"baseline_role_name": "历史角色",
|
||||
"baseline_is_bound_act": True,
|
||||
"before_bind_info": {
|
||||
"act_alias": "20260120QYOOB",
|
||||
"role_name": "历史角色",
|
||||
"is_bound_act": True,
|
||||
"need_bind_act": True,
|
||||
},
|
||||
"need_bind_act": False,
|
||||
"is_bound_act": False,
|
||||
"bind_ready_for_confirm": True,
|
||||
"bind_confirmed": False,
|
||||
"bind_phase": "role_ready",
|
||||
},
|
||||
created_by=self.admin_id,
|
||||
)
|
||||
self.session.add(bind_task)
|
||||
self.session.flush()
|
||||
task.bind_task_id = bind_task.id
|
||||
task.binding_status = "role_ready"
|
||||
task.execution_status = "role_ready"
|
||||
self.session.commit()
|
||||
|
||||
synced = service.sync_task_from_binding_runner(
|
||||
self.session,
|
||||
douyu_task_id=bind_task.id,
|
||||
)
|
||||
self.session.refresh(task)
|
||||
detail = service.get_task_detail(self.session, task.id)
|
||||
|
||||
assert synced == 1
|
||||
assert task.bind_task_id == bind_task.id
|
||||
assert task.binding_status == "role_ready"
|
||||
assert task.execution_status == "role_ready"
|
||||
assert detail["task"]["bindTask"]["roleName"] == "本次待确认角色"
|
||||
assert detail["task"]["bindTask"]["bindReadyForConfirm"] is True
|
||||
assert detail["task"]["bindTask"]["bindConfirmed"] is False
|
||||
assert (
|
||||
self.session.query(PlatformFulfillmentEvent)
|
||||
.filter_by(
|
||||
task_id=task.id,
|
||||
event_type="binding_synced_from_account",
|
||||
)
|
||||
.count()
|
||||
== 0
|
||||
)
|
||||
|
||||
def test_customer_start_mapping_missing_is_idempotent(self, monkeypatch):
|
||||
task = self.task(mapped=False)
|
||||
task.issue_code = "mapping_missing"
|
||||
|
||||
@@ -501,6 +501,10 @@
|
||||
"20261123_0125_douyu_collab_shop_aliases.py": {
|
||||
"revision": "20261123_0125",
|
||||
"sha256": "ff11ab9c735043d95504c1d52ddfeb8db04068a8027e0e1253ec45330f227bad"
|
||||
},
|
||||
"20261123_0126_repair_false_binding_sync.py": {
|
||||
"revision": "20261123_0126",
|
||||
"sha256": "86c201d2298845f7f3eb3e733760fe46911638dc1ef046d4518c02172cfaba6f"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
"""repair fulfillment tasks promoted by historical account bindings.
|
||||
|
||||
Revision ID: 20261123_0126
|
||||
Revises: 20261123_0125
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261123_0126"
|
||||
down_revision: str | None = "20261123_0125"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
rows = bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
SELECT DISTINCT
|
||||
t.id AS task_id,
|
||||
a.id AS account_id,
|
||||
a.username,
|
||||
a.nickname,
|
||||
a.game_name AS bound_role_name,
|
||||
d.id AS bind_task_id,
|
||||
JSON_UNQUOTE(JSON_EXTRACT(d.result, '$.role_name')) AS pending_role_name,
|
||||
JSON_UNQUOTE(JSON_EXTRACT(d.result, '$.game_channel')) AS pending_channel
|
||||
FROM platform_fulfillment_tasks AS t
|
||||
JOIN accounts AS a ON a.id = t.account_id
|
||||
JOIN douyu_tasks AS d ON d.id = t.bind_task_id
|
||||
JOIN platform_fulfillment_events AS e
|
||||
ON e.task_id = t.id
|
||||
AND e.event_type = 'binding_synced_from_account'
|
||||
WHERE t.binding_status = 'bound'
|
||||
AND t.execution_status = 'bound'
|
||||
AND d.task_type IN ('get_bind_qr', 'query_game_name')
|
||||
AND JSON_EXTRACT(d.result, '$.bind_ready_for_confirm') = true
|
||||
AND COALESCE(JSON_EXTRACT(d.result, '$.bind_confirmed'), false) = false
|
||||
AND TRIM(COALESCE(a.game_name, '')) <> TRIM(
|
||||
COALESCE(
|
||||
JSON_UNQUOTE(JSON_EXTRACT(d.result, '$.role_name')),
|
||||
''
|
||||
)
|
||||
)
|
||||
"""
|
||||
)
|
||||
).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 = 'role_ready',
|
||||
execution_status = 'role_ready',
|
||||
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 ""),
|
||||
"bindTaskId": int(row["bind_task_id"]),
|
||||
"previousBindingStatus": "bound",
|
||||
"correctedBindingStatus": "role_ready",
|
||||
"boundRoleName": str(row["bound_role_name"] or ""),
|
||||
"pendingRoleName": str(row["pending_role_name"] or ""),
|
||||
"pendingChannel": str(row["pending_channel"] or ""),
|
||||
"reason": "historical_account_binding_not_current_order_confirmation",
|
||||
}
|
||||
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_false_confirmation_reverted',
|
||||
'system',
|
||||
'',
|
||||
:detail_json,
|
||||
:created_at
|
||||
)
|
||||
"""
|
||||
),
|
||||
{
|
||||
"task_id": task_id,
|
||||
"detail_json": json.dumps(detail, ensure_ascii=False),
|
||||
"created_at": now,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""数据修复不回退,避免再次用历史账号绑定覆盖当前待确认角色。"""
|
||||
@@ -57,6 +57,13 @@ BINDING_SYNC_TASK_TYPES = frozenset(
|
||||
"confirm_xpd_bind",
|
||||
}
|
||||
)
|
||||
ACCOUNT_CONFIRMATION_TASK_TYPES = frozenset(
|
||||
{
|
||||
"confirm_bind",
|
||||
"confirm_esports_bind",
|
||||
"confirm_xpd_bind",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def start_binding_sync(
|
||||
@@ -294,6 +301,15 @@ def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int:
|
||||
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)
|
||||
result = douyu_task.result or {}
|
||||
if (
|
||||
douyu_task.task_type not in ACCOUNT_CONFIRMATION_TASK_TYPES
|
||||
or result.get("bind_confirmed") is not True
|
||||
):
|
||||
# 查询/出码任务只能证明“账号历史绑定是什么”,不能证明本次订单已经确认。
|
||||
# 只有明确执行成功并回查到 bind_confirmed 的确认任务,才允许把账号权威
|
||||
# 绑定投影到履约任务。
|
||||
return len(task_ids)
|
||||
return len(task_ids) + sync_active_task_from_account_binding(
|
||||
db,
|
||||
account_id=int(douyu_task.account_id),
|
||||
@@ -317,6 +333,17 @@ def sync_active_task_from_account_binding(
|
||||
"""
|
||||
if scope != "elite":
|
||||
return 0
|
||||
source_task = (
|
||||
db.get(DouyuTask, int(source_task_id))
|
||||
if source_task_id is not None
|
||||
else None
|
||||
)
|
||||
if (
|
||||
source_task is None
|
||||
or source_task.task_type not in ACCOUNT_CONFIRMATION_TASK_TYPES
|
||||
or (source_task.result or {}).get("bind_confirmed") is not True
|
||||
):
|
||||
return 0
|
||||
account = db.get(Account, int(account_id))
|
||||
if account is None or account.role_bind_status != "bound":
|
||||
return 0
|
||||
@@ -341,6 +368,7 @@ def sync_active_task_from_account_binding(
|
||||
)
|
||||
if task is None:
|
||||
return 0
|
||||
task.bind_task_id = int(source_task.id)
|
||||
task.binding_status = "bound"
|
||||
task.execution_status = "bound"
|
||||
task.issue_code = ""
|
||||
|
||||
@@ -362,8 +362,11 @@ def _task_out(
|
||||
)
|
||||
collab_order = resolved.collab_orders.get(int(task.id))
|
||||
bind_result = (bind_task.result or {}) if bind_task else {}
|
||||
bind_result_confirmed = bool(bind_result.get("bind_confirmed"))
|
||||
account_binding_confirmed = bool(
|
||||
account is not None and account.role_bind_status == "bound"
|
||||
bind_result_confirmed
|
||||
and 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)
|
||||
@@ -635,8 +638,11 @@ def customer_binding_out(db: Session, task_id: int) -> dict[str, Any]:
|
||||
)
|
||||
bind_result = (bind_task.result or {}) if bind_task else {}
|
||||
account = db.get(Account, int(task.account_id)) if task.account_id else None
|
||||
bind_result_confirmed = bool(bind_result.get("bind_confirmed"))
|
||||
account_binding_confirmed = bool(
|
||||
account is not None and account.role_bind_status == "bound"
|
||||
bind_result_confirmed
|
||||
and account is not None
|
||||
and account.role_bind_status == "bound"
|
||||
)
|
||||
pending_role = (
|
||||
""
|
||||
|
||||
@@ -129,6 +129,7 @@ const EVENT_LABELS: Record<string, string> = {
|
||||
binding_reset: '重置角色资料和绑定记录',
|
||||
binding_stale_role_ignored: '忽略账号旧角色',
|
||||
binding_synced_from_account: '同步账号最新角色绑定',
|
||||
binding_false_confirmation_reverted: '纠正误判的账号历史绑定',
|
||||
eligibility_check_failed: '兑换资格查询失败',
|
||||
eligibility_auto_refresh_failed: '自动刷新兑换资格失败',
|
||||
exchange_eligibility_checked: '刷新兑换资格',
|
||||
|
||||
Reference in New Issue
Block a user