From f23ef42e676abc51a2e06d3b13c865fdd2f9b07d Mon Sep 17 00:00:00 2001 From: yml Date: Sat, 28 Nov 2026 16:17:04 +0800 Subject: [PATCH] =?UTF-8?q?fix(fulfillment):=20=E6=94=AF=E6=8C=81=E5=85=88?= =?UTF-8?q?=E5=88=86=E9=85=8D=E5=90=8E=E8=A1=A5=E8=A7=92=E8=89=B2=E6=88=96?= =?UTF-8?q?=E6=92=9E=E9=94=81=E6=97=B6=E7=9A=84=E5=90=8C=E8=A7=92=E8=89=B2?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E5=90=88=E5=B9=B6=E6=94=B9=E6=8C=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_platform_fulfillment.py | 212 ++++++++++ .../platform_fulfillment/allocation.py | 400 ++++++++++++++---- .../services/platform_fulfillment/binding.py | 74 +++- .../services/platform_fulfillment/customer.py | 43 +- .../platform_fulfillment/order_sync.py | 31 +- 5 files changed, 667 insertions(+), 93 deletions(-) diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index 5ee9e59..c6f0711 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -6929,3 +6929,215 @@ class TestAllocationPolicyAndSameRoleReuse(_Base): self.session.commit() detail = service.get_task_detail(self.session, task.id) assert detail["task"]["manualReason"] == issue + + def test_late_customer_profile_merges_preallocated_sibling_and_releases_old_lease( + self, + ): + acc1 = self.account("late-merge-1", points=24000, capability=False) + acc2 = self.account("late-merge-2", points=24000, capability=False) + for acc in (acc1, acc2): + for cid in (TRIO_BAG412, TRIO_BAG413, TRIO_BAG414): + self._add_commodity_state(acc, cid, eligibility="eligible") + self.session.commit() + + # 先连下两单且当时均未填客户角色名,auto_allocator 分别预分配不同账号 + t1 = self._create_commodity_task( + commodity_id=TRIO_BAG413, + order_suffix="late-1", + role_name="", + ) + t2 = self._create_commodity_task( + commodity_id=TRIO_BAG414, + order_suffix="late-2", + role_name="", + ) + d1 = service.allocate_task(self.session, task_id=t1.id, current=self.admin) + d2 = service.allocate_task(self.session, task_id=t2.id, current=self.admin) + assert d1["task"]["account"]["id"] != d2["task"]["account"]["id"] + old_t2_lease_id = d2["task"]["lease"]["id"] + + # 买家随后补交同一角色名:第二单自动释放空号并合并共享第一单的账号与租约 + service.save_customer_profile( + self.session, + task_id=t1.id, + customer_role_name="迟填多单老板", + platform="wechat", + system="android", + home_images=[{"url": "https://example.com/late-1.png"}], + ) + service.save_customer_profile( + self.session, + task_id=t2.id, + customer_role_name="迟填多单老板", + platform="wechat", + system="android", + home_images=[{"url": "https://example.com/late-2.png"}], + ) + + self.session.refresh(t1) + self.session.refresh(t2) + old_lease = self.session.get(AccountLease, old_t2_lease_id) + assert t2.account_id == t1.account_id + assert t2.lease_id == t1.lease_id + assert old_lease.status == "released" + + def test_sibling_bound_and_role_lock_redirect_merges_preallocated_orders_to_bound( + self, + ): + acc1 = self.account("merge-bound-1", points=24000, capability=False) + acc2 = self.account("merge-bound-2", points=24000, capability=False) + acc3 = self.account("merge-bound-3", points=24000, capability=False) + for acc in (acc1, acc2, acc3): + for cid in (TRIO_BAG412, TRIO_BAG413, TRIO_BAG414): + self._add_commodity_state(acc, cid, eligibility="eligible") + self.session.commit() + + t1 = self._create_commodity_task( + commodity_id=TRIO_BAG413, + order_suffix="merge-1", + role_name="小李腰不准", + ) + t2 = self._create_commodity_task( + commodity_id=TRIO_BAG414, + order_suffix="merge-2", + role_name="", + ) + t3 = self._create_commodity_task( + commodity_id=TRIO_BAG412, + order_suffix="merge-3", + role_name="", + ) + # 确保三单初始各拿不同账号,且 t2 已填好角色但尚未完成扫码(qr_pending) + d1 = service.allocate_task(self.session, task_id=t1.id, current=self.admin) + d2 = service.allocate_task(self.session, task_id=t2.id, current=self.admin) + d3 = service.allocate_task(self.session, task_id=t3.id, current=self.admin) + assert ( + len( + { + d1["task"]["account"]["id"], + d2["task"]["account"]["id"], + d3["task"]["account"]["id"], + } + ) + == 3 + ) + + t2_old_qr = DouyuTask( + batch_id="t2-old-qr", + account_id=d2["task"]["account"]["id"], + account_assigned_to=self.admin_id, + task_type="get_bind_qr", + handbook_scope="elite", + status="running", + platform_task_id=t2.id, + result={"url": "https://example.test/old-qr", "bind_phase": "qr_pending"}, + created_by=self.admin_id, + ) + self.session.add(t2_old_qr) + self.session.flush() + t2.customer_role_name = "小李腰不准" + t2.bind_task_id = t2_old_qr.id + t2.binding_status = "qr_pending" + t2.execution_status = "waiting_bind" + self.session.commit() + + # 场景 A:主单 t1 确认绑定 -> 跨账号的未绑定兄弟单 t2 自动停旧码、释放旧租约并合并为 bound + confirm_t1 = DouyuTask( + batch_id="t1-confirm", + account_id=d1["task"]["account"]["id"], + account_assigned_to=self.admin_id, + task_type="confirm_bind", + handbook_scope="elite", + status="success", + platform_task_id=t1.id, + result={ + "role_name": "小李腰不准", + "area_name": "微信", + "plat_name": "安卓", + "is_bound_act": True, + "bind_confirmed": True, + "bind_phase": "confirmed", + }, + created_by=self.admin_id, + ) + self.session.add(confirm_t1) + self.session.flush() + t1.bind_task_id = confirm_t1.id + t1.binding_status = "role_ready" + t1.execution_status = "role_ready" + self.session.commit() + + service.sync_task_from_binding_runner(self.session, douyu_task_id=confirm_t1.id) + self.session.refresh(t1) + self.session.refresh(t2) + self.session.refresh(t2_old_qr) + assert t2.account_id == t1.account_id + assert t2.lease_id == t1.lease_id + assert t2.binding_status == "bound" + assert t2.execution_status == "bound" + assert t2_old_qr.status == "stopped" + + # 场景 B:t3 连客户资料角色都没预先匹配,直接扫码扫出「小李腰不准」撞 7 天锁 -> + # 不应转 manual_required,而是直接改挂合并到 acc1 并标 bound + acc1_row = self.session.get(Account, t1.account_id) + acc1_row.role_bind_status = "bound" + acc1_row.game_name = "小李腰不准" + self.session.add( + AccountEvent( + account_id=acc1_row.id, + event_type="bind_ok", + category="account", + title="绑定成功", + subject_type="elite_role", + subject_key="小李腰不准", + source="test", + actor_type="system", + occurred_at=NOW, + ) + ) + t3_old_acc = d3["task"]["account"]["id"] + t3_old_lease_id = d3["task"]["lease"]["id"] + t3_qr = DouyuTask( + batch_id="t3-scan-locked-role", + account_id=t3_old_acc, + account_assigned_to=self.admin_id, + task_type="get_bind_qr", + handbook_scope="elite", + status="success", + platform_task_id=t3.id, + result={ + "act_alias": "20260120QYOOB", + "role_name": "小李腰不准", + "current_role_name": "小李腰不准", + "baseline_role_name": "旧角色", + "before_bind_info": { + "act_alias": "20260120QYOOB", + "role_name": "旧角色", + "is_bound_act": True, + "need_bind_act": True, + }, + "area_name": "微信", + "plat_name": "安卓", + "is_bound_act": False, + "bind_ready_for_confirm": True, + "bind_confirmed": False, + "bind_phase": "role_ready", + }, + created_by=self.admin_id, + ) + self.session.add(t3_qr) + self.session.flush() + t3.bind_task_id = t3_qr.id + t3.binding_status = "qr_pending" + t3.execution_status = "waiting_bind" + self.session.commit() + + service.sync_task_from_binding_runner(self.session, douyu_task_id=t3_qr.id) + self.session.refresh(t3) + t3_old_lease = self.session.get(AccountLease, t3_old_lease_id) + assert t3.account_id == t1.account_id + assert t3.lease_id == t1.lease_id + assert t3.binding_status == "bound" + assert t3.execution_status == "bound" + assert t3.issue_code != "customer_role_bound_elsewhere" + assert t3_old_lease.status == "released" diff --git a/web/backend/services/platform_fulfillment/allocation.py b/web/backend/services/platform_fulfillment/allocation.py index 13adff2..f99f504 100644 --- a/web/backend/services/platform_fulfillment/allocation.py +++ b/web/backend/services/platform_fulfillment/allocation.py @@ -15,6 +15,7 @@ from ...models import ( AccountCommodityState, AccountEvent, AccountLease, + DouyuTask, PlatformFulfillmentTask, User, ) @@ -391,6 +392,7 @@ def _apply_allocated_account_state( valid_until: datetime | None = None, extra_event_detail: dict[str, Any] | None = None, already_bound_role: str = "", + commit: bool = True, ) -> dict[str, Any]: stale_leases = ( db.query(AccountLease) @@ -475,6 +477,8 @@ def _apply_allocated_account_state( }, ) _emit_order_site_binding_state(db, task.id) + if not commit: + return {} db.commit() return get_task_detail(db, task.id) @@ -514,26 +518,23 @@ def _account_meets_commodity_eligibility( ) -def _try_reuse_same_role_account( +def _find_reusable_same_role_target( db: Session, *, task: PlatformFulfillmentTask, - current: User, + role: str, policy: dict[str, Any], required_co: tuple[str, ...], moment: datetime, + preferred_account_ids: tuple[int, ...] = (), ) -> dict[str, Any] | None: - """同客户角色多单时,优先复用已分配/已绑定的同一斗鱼账号,避免撞 7 天角色锁。""" - if not policy.get("sameRoleReuseEnabled", True): - return None - role = str(task.customer_role_name or "").strip() - if not role: + """查找可与当前订单同客户角色合并/复用的目标斗鱼账号(不改动当前订单)。""" + if not policy.get("sameRoleReuseEnabled", True) or not role: return None scope = task.scope or SCOPE_ELITE - is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale" - required_points = int(task.required_points or 0) since_365 = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS) + is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale" sibling_rows = ( db.query(PlatformFulfillmentTask) @@ -555,6 +556,9 @@ def _try_reuse_same_role_account( .all() ) candidate_account_ids: list[int] = [] + for preferred_id in preferred_account_ids: + if preferred_id and int(preferred_id) not in candidate_account_ids: + candidate_account_ids.append(int(preferred_id)) for row in sibling_rows: if row.account_id and int(row.account_id) not in candidate_account_ids: candidate_account_ids.append(int(row.account_id)) @@ -564,7 +568,10 @@ def _try_reuse_same_role_account( if not candidate_account_ids: return None + current_account_id = int(task.account_id) if task.account_id else 0 for candidate_account_id in candidate_account_ids: + if current_account_id and int(candidate_account_id) == current_account_id: + continue account = db.get(Account, int(candidate_account_id)) if account is None: continue @@ -660,6 +667,8 @@ def _try_reuse_same_role_account( reused_existing_lease = False sibling_ids: list[int] = [] sibling_bound = False + has_active_qr_sibling = False + earliest_sibling_id: int | None = None if active_lease is not None: if active_lease.purpose != "platform_fulfillment": continue @@ -680,93 +689,330 @@ def _try_reuse_same_role_account( for holder in holders ): continue - lease = active_lease reused_existing_lease = True sibling_ids = [int(holder.id) for holder in holders] sibling_bound = any(holder.binding_status == "bound" for holder in holders) + has_active_qr_sibling = any( + holder.binding_status + in { + "preparing", + "qr_pending", + "waiting_bind", + "role_ready", + "confirming", + } + for holder in holders + ) + earliest_sibling_id = min(sibling_ids) + elif active_collab is not None: + continue else: - if active_collab is not None: - continue - candidate_model = AccountCandidate( - account_id=int(account.id), - username=str(account.username or ""), - nickname=str(account.nickname or ""), - points=int(account.points or 0), - gold_balance=account.gold_balance, - points_expire_at=account.points_expire_at, - role_change_available_at=account.role_change_available_at, - ) - lease = lease_account( - db, - candidate=candidate_model, - holder_user_id=current.id, - task_id=task.id, - commodity_id=task.commodity_id, - ttl_minutes=_lease_duration_minutes(db), - commit=False, - ) - if lease is None: - continue + acc_siblings = [ + row + for row in sibling_rows + if int(row.account_id or 0) == int(account.id) + ] + if acc_siblings: + sibling_bound = any( + row.binding_status == "bound" for row in acc_siblings + ) + earliest_sibling_id = min(int(row.id) for row in acc_siblings) + role_lock_matches = bool( + role_lock is not None and int(role_lock.account_id) == int(account.id) + ) already_bound_role = "" - if ( + if sibling_bound: + already_bound_role = account_role or role + elif ( str(account.role_bind_status or "") == "bound" and account_role and role_names_match(account_role, role) - and ( - sibling_bound - or ( - role_lock is not None - and int(role_lock.account_id) == int(account.id) - ) - ) + and role_lock_matches ): already_bound_role = account_role - account_name = account.nickname or account.username or f"#{account.id}" - availability = allocation_availability( - primary_state.account_eligibility, - primary_state.offer_state, - ) - cached_state = DouyuLiveAccountState( + return { + "account": account, + "primary_state": primary_state, + "active_lease": active_lease, + "reused_existing_lease": reused_existing_lease, + "sibling_ids": sibling_ids, + "sibling_bound": sibling_bound, + "has_active_qr_sibling": has_active_qr_sibling, + "earliest_sibling_id": earliest_sibling_id, + "role_lock_matches": role_lock_matches, + "already_bound_role": already_bound_role, + } + return None + + +def _attach_task_to_same_role_target( + db: Session, + *, + task: PlatformFulfillmentTask, + target: dict[str, Any], + role: str, + current: User, + moment: datetime, + extra_event_detail: dict[str, Any] | None = None, + commit: bool = True, +) -> dict[str, Any] | None: + account: Account = target["account"] + primary_state: AccountCommodityState = target["primary_state"] + lease: AccountLease | None = target["active_lease"] + reused_existing_lease: bool = bool(target["reused_existing_lease"]) + sibling_ids: list[int] = list(target["sibling_ids"]) + already_bound_role: str = str(target["already_bound_role"] or "") + + if lease is None: + candidate_model = AccountCandidate( account_id=int(account.id), - account_name=account_name, - checked_at=primary_state.observed_at or moment, - ck_verdict="valid", - ck_message="同角色复用关联账号 CK 有效", - elite_opened=account.elite_opened, - points=account.points, - limited_ids=frozenset(), + username=str(account.username or ""), + nickname=str(account.nickname or ""), + points=int(account.points or 0), + gold_balance=account.gold_balance, + points_expire_at=account.points_expire_at, role_change_available_at=account.role_change_available_at, - commodity_availability={task.commodity_id: availability}, - commodity_blocking_reasons=( - {task.commodity_id: str(primary_state.blocking_reason or "")} - if primary_state.blocking_reason - else {} - ), ) - return _apply_allocated_account_state( + lease = lease_account( + db, + candidate=candidate_model, + holder_user_id=current.id, + task_id=task.id, + commodity_id=task.commodity_id, + ttl_minutes=_lease_duration_minutes(db), + commit=False, + ) + if lease is None: + return None + + account_name = account.nickname or account.username or f"#{account.id}" + availability = allocation_availability( + primary_state.account_eligibility, + primary_state.offer_state, + ) + cached_state = DouyuLiveAccountState( + account_id=int(account.id), + account_name=account_name, + checked_at=primary_state.observed_at or moment, + ck_verdict="valid", + ck_message="同角色复用关联账号 CK 有效", + elite_opened=account.elite_opened, + points=account.points, + limited_ids=frozenset(), + role_change_available_at=account.role_change_available_at, + commodity_availability={task.commodity_id: availability}, + commodity_blocking_reasons=( + {task.commodity_id: str(primary_state.blocking_reason or "")} + if primary_state.blocking_reason + else {} + ), + ) + merged_detail = { + "sharedLease": reused_existing_lease, + "siblingTaskIds": sibling_ids, + "reusedRoleName": role, + } + if extra_event_detail: + merged_detail.update(extra_event_detail) + return _apply_allocated_account_state( + db, + task=task, + account_id=int(account.id), + account_name=account_name, + lease=lease, + cached_state=cached_state, + required_points=int(task.required_points or 0), + is_presale=classification.normalize_sale_mode(task.sale_mode) == "presale", + current=current, + moment=moment, + allocation_strategy="same_role_reuse", + observed_at=primary_state.observed_at, + valid_until=primary_state.valid_until, + extra_event_detail=merged_detail, + already_bound_role=already_bound_role, + commit=commit, + ) + + +def _try_reuse_same_role_account( + db: Session, + *, + task: PlatformFulfillmentTask, + current: User, + policy: dict[str, Any], + required_co: tuple[str, ...], + moment: datetime, +) -> dict[str, Any] | None: + """同客户角色多单时,优先复用已分配/已绑定的同一斗鱼账号,避免撞 7 天角色锁。""" + role = str(task.customer_role_name or "").strip() + target = _find_reusable_same_role_target( + db, + task=task, + role=role, + policy=policy, + required_co=required_co, + moment=moment, + ) + if target is None: + return None + return _attach_task_to_same_role_target( + db, + task=task, + target=target, + role=role, + current=current, + moment=moment, + commit=True, + ) + + +def try_reallocate_task_to_same_role( + db: Session, + *, + task: PlatformFulfillmentTask, + current: User, + role_name: str = "", + trigger: str = "role_sync", + preferred_account_id: int | None = None, + allow_pending_role_ready: bool = False, + commit: bool = False, + now: datetime | None = None, +) -> bool: + """晚提交角色资料或发现同角色已绑他号时,把尚未绑定完成的任务合并到同角色账号。""" + if ( + task.flow_version != FLOW_VERSION_CLEAN + or task.execution_status in {"completed", "cancelled"} + or not task.commodity_id + ): + return False + allowed_binding_statuses = { + "not_started", + "preparing", + "qr_pending", + "waiting_bind", + } + if allow_pending_role_ready: + allowed_binding_statuses.add("role_ready") + if str(task.binding_status or "") not in allowed_binding_statuses: + return False + + role = str(role_name or task.customer_role_name or "").strip() + if not role: + return False + task_role = str(task.customer_role_name or "").strip() + if task_role and not role_names_match(task_role, role): + return False + + moment = now or _now() + policy = normalize_allocation_policy(get_settings(db).get("allocationPolicy")) + required_co, _preferred_co = bundle_requirements_for_commodity( + task.commodity_id, policy + ) + preferred_ids = (int(preferred_account_id),) if preferred_account_id else () + target = _find_reusable_same_role_target( + db, + task=task, + role=role, + policy=policy, + required_co=required_co, + moment=moment, + preferred_account_ids=preferred_ids, + ) + if target is None: + return False + + if task.account_id is not None: + target_is_bound = bool( + target["already_bound_role"] + or target["sibling_bound"] + or target["role_lock_matches"] + ) + if not target_is_bound: + if str(task.binding_status or "") != "not_started": + return False + earliest_sibling_id = target["earliest_sibling_id"] + if not target["has_active_qr_sibling"] and ( + earliest_sibling_id is None or int(earliest_sibling_id) >= int(task.id) + ): + return False + + from .lifecycle import _release_or_detach_shared_lease + + old_account_id = int(task.account_id) + old_lease = ( + db.query(AccountLease).filter(AccountLease.id == int(task.lease_id)).first() + if task.lease_id + else None + ) + _release_or_detach_shared_lease( db, task=task, - account_id=int(account.id), - account_name=account_name, - lease=lease, - cached_state=cached_state, - required_points=required_points, - is_presale=is_presale, + lease=old_lease, current=current, - moment=moment, - allocation_strategy="same_role_reuse", - observed_at=primary_state.observed_at, - valid_until=primary_state.valid_until, - extra_event_detail={ - "sharedLease": reused_existing_lease, - "siblingTaskIds": sibling_ids, - "reusedRoleName": role, - }, - already_bound_role=already_bound_role, + collab_reason=f"same_role_merge:{trigger}", + release_reason=f"same_role_merge:{trigger}", ) - return None + if task.bind_task_id: + old_bind = db.get(DouyuTask, int(task.bind_task_id)) + if old_bind is not None and old_bind.status in { + "planned", + "pending", + "running", + }: + shared_bind = ( + db.query(PlatformFulfillmentTask.id) + .filter( + PlatformFulfillmentTask.bind_task_id == int(old_bind.id), + PlatformFulfillmentTask.id != int(task.id), + PlatformFulfillmentTask.execution_status != "cancelled", + ) + .first() + ) + if shared_bind is None: + old_bind.status = "stopped" + old_bind.message = "同角色已改用原绑定账号,终止旧绑码任务" + old_bind.finished_at = moment + old_bind.queue_lane = "" + old_bind.next_run_at = None + task.account_id = None + task.lease_id = None + task.bind_task_id = None + task.execution_status = "ready" + task.binding_status = "not_started" + task.exchange_status = "not_started" + task.issue_code = "" + task.last_error = "" + _append_event( + db, + task.id, + "account_released", + actor_type="system", + detail={ + "reason": f"same_role_merge:{trigger}", + "previousAccountId": old_account_id, + "targetAccountId": int(target["account"].id), + }, + ) + extra_detail = { + "mergedFromAccountId": old_account_id, + "mergeTrigger": trigger, + } + else: + extra_detail = {"mergeTrigger": trigger} + + attached = _attach_task_to_same_role_target( + db, + task=task, + target=target, + role=role, + current=current, + moment=moment, + extra_event_detail=extra_detail, + commit=commit, + ) + return attached is not None def _allocate_task_from_capability( diff --git a/web/backend/services/platform_fulfillment/binding.py b/web/backend/services/platform_fulfillment/binding.py index 16e9994..adcad35 100644 --- a/web/backend/services/platform_fulfillment/binding.py +++ b/web/backend/services/platform_fulfillment/binding.py @@ -7,7 +7,7 @@ from datetime import timedelta from typing import Any from fastapi import HTTPException -from sqlalchemy import case +from sqlalchemy import case, func from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from starlette.concurrency import run_in_threadpool @@ -63,6 +63,7 @@ from .common import FLOW_VERSION_CLEAN, SCOPE_ELITE, _has_game_home_profile, _no from .outbox import _emit_order_site_binding_state from .repository import ( _binding_qr_expired, + _integration_actor, _load_task, _load_task_for_update, ) @@ -234,6 +235,41 @@ def _propagate_same_role_binding_to_siblings( source_task_id=int(bound_task.id), ) updated += 1 + + # 同角色如果有多单但之前因未填角色名被预分配到了不同账号, + # 主单确认绑定后把未完成绑定的兄弟单自动释放旧空号并改挂到主账号。 + cross_account_siblings = ( + db.query(PlatformFulfillmentTask) + .filter( + PlatformFulfillmentTask.flow_version == FLOW_VERSION_CLEAN, + PlatformFulfillmentTask.id != int(bound_task.id), + PlatformFulfillmentTask.account_id.isnot(None), + PlatformFulfillmentTask.account_id != int(bound_task.account_id), + PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")), + PlatformFulfillmentTask.binding_status.in_(ACTIVE_BINDING_STATUSES), + PlatformFulfillmentTask.customer_role_name != "", + func.lower(func.trim(PlatformFulfillmentTask.customer_role_name)) + == role_name.casefold(), + ) + .order_by(PlatformFulfillmentTask.id.asc()) + .with_for_update(skip_locked=True) + .all() + ) + if cross_account_siblings: + from .allocation import try_reallocate_task_to_same_role + + actor = _integration_actor(db) + for sibling in cross_account_siblings: + if try_reallocate_task_to_same_role( + db, + task=sibling, + current=actor, + role_name=role_name, + preferred_account_id=int(bound_task.account_id), + trigger="sibling_bound", + commit=False, + ): + updated += 1 return updated @@ -268,6 +304,27 @@ def start_binding_sync( ) db.commit() return get_task_detail(db, task.id) + if task.customer_role_name and task.binding_status != "bound": + from .allocation import try_reallocate_task_to_same_role + + if try_reallocate_task_to_same_role( + db, + task=task, + current=current, + role_name=task.customer_role_name, + trigger="start_binding", + commit=True, + ): + if task.binding_status == "bound": + return get_task_detail(db, task.id) + lease = ( + db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() + if task.lease_id + else None + ) + if lease is None or lease.status != "active": + return get_task_detail(db, task.id) + account = db.query(Account).filter(Account.id == task.account_id).first() if task.bind_task_id: existing = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() if existing is not None and existing.platform_task_id not in ( @@ -875,7 +932,7 @@ def _block_on_role_lock( role_name: str, source: DouyuTask | None = None, ) -> bool: - """角色已绑在别的账号上时,把订单转人工;返回是否拦截。""" + """角色已绑在别的账号上时,优先尝试同角色合并改挂,否则把订单转人工。""" if str(task.issue_code or "") == ROLE_LOCK_ISSUE: return False lock = find_role_lock( @@ -885,6 +942,19 @@ def _block_on_role_lock( ) if lock is None: return False + from .allocation import try_reallocate_task_to_same_role + + if try_reallocate_task_to_same_role( + db, + task=task, + current=_integration_actor(db), + role_name=role_name, + preferred_account_id=int(lock.account_id), + allow_pending_role_ready=True, + trigger="role_lock_redirect", + commit=False, + ): + return True return _mark_role_locked(db, task, source, lock) diff --git a/web/backend/services/platform_fulfillment/customer.py b/web/backend/services/platform_fulfillment/customer.py index 077131e..52e5431 100644 --- a/web/backend/services/platform_fulfillment/customer.py +++ b/web/backend/services/platform_fulfillment/customer.py @@ -90,8 +90,12 @@ def save_customer_profile( images.append( { "url": url[:2048], - "thumbnailUrl": str(item.get("thumbnail_url") or item.get("thumbnailUrl") or url)[:2048], - "objectKey": str(item.get("object_key") or item.get("objectKey") or "")[:512], + "thumbnailUrl": str( + item.get("thumbnail_url") or item.get("thumbnailUrl") or url + )[:2048], + "objectKey": str(item.get("object_key") or item.get("objectKey") or "")[ + :512 + ], } ) if not images: @@ -115,6 +119,17 @@ def save_customer_profile( "homeImageCount": len(images), }, ) + if task.account_id and task.customer_role_name: + from .allocation import try_reallocate_task_to_same_role + + try_reallocate_task_to_same_role( + db, + task=task, + current=_integration_actor(db), + role_name=task.customer_role_name, + trigger="customer_profile_saved", + commit=False, + ) if commit: db.commit() return customer_binding_out(db, task.id) @@ -135,10 +150,11 @@ async def customer_start_binding( raise HTTPException(status_code=409, detail="请先提交游戏角色和游戏主页截图") if not task.account_id or not task.lease_id: - if ( - task.execution_status == "manual_required" - and task.issue_code in {"binding_failed", "lease_expired", "role_changed"} - ): + if task.execution_status == "manual_required" and task.issue_code in { + "binding_failed", + "lease_expired", + "role_changed", + }: from .allocation import prepare_manual_allocation prepare_manual_allocation( @@ -218,7 +234,9 @@ def update_customer_profile_by_operator( if task.execution_status in {"completed", "cancelled"}: raise HTTPException(status_code=409, detail="订单已结束,不能修改客户资料") if task.binding_status == "bound": - raise HTTPException(status_code=409, detail="角色已绑定确认,不能直接修改客户资料") + raise HTTPException( + status_code=409, detail="角色已绑定确认,不能直接修改客户资料" + ) if task.binding_status == "confirming": raise HTTPException(status_code=409, detail="正在确认绑定中,请稍后再试") @@ -293,6 +311,17 @@ def update_customer_profile_by_operator( }, ) _emit_order_site_binding_state(db, task.id) + if task.execution_status != "manual_required" and task.binding_status != "bound": + from .allocation import try_reallocate_task_to_same_role + + try_reallocate_task_to_same_role( + db, + task=task, + current=current, + role_name=new_role, + trigger="operator_profile_updated", + commit=False, + ) db.commit() if reopened and task.execution_status == "ready": from .auto_allocator import wake_auto_allocator diff --git a/web/backend/services/platform_fulfillment/order_sync.py b/web/backend/services/platform_fulfillment/order_sync.py index f209b52..d58adea 100644 --- a/web/backend/services/platform_fulfillment/order_sync.py +++ b/web/backend/services/platform_fulfillment/order_sync.py @@ -60,16 +60,13 @@ def _apply_customer_profile( if not keys.intersection(snapshot): return task.customer_role_name = str( - _snapshot_value(snapshot, "customerRoleName", "customer_role_name") - or "" + _snapshot_value(snapshot, "customerRoleName", "customer_role_name") or "" )[:128] task.customer_platform = str( - _snapshot_value(snapshot, "customerPlatform", "customer_platform") - or "" + _snapshot_value(snapshot, "customerPlatform", "customer_platform") or "" )[:16] task.customer_system = str( - _snapshot_value(snapshot, "customerSystem", "customer_system") - or "" + _snapshot_value(snapshot, "customerSystem", "customer_system") or "" )[:16] raw_images = _snapshot_value( snapshot, @@ -83,7 +80,9 @@ def _apply_customer_profile( if isinstance(item, str): url = item.strip() if url: - images.append({"url": url[:2048], "thumbnailUrl": url[:2048], "objectKey": ""}) + images.append( + {"url": url[:2048], "thumbnailUrl": url[:2048], "objectKey": ""} + ) continue if not isinstance(item, dict): continue @@ -114,6 +113,24 @@ def _apply_customer_profile( from .binding import sync_customer_role_to_bind_task sync_customer_role_to_bind_task(db, task) + if ( + db is not None + and task.id is not None + and task.account_id is not None + and task.customer_role_name + and task.binding_status != "bound" + ): + from .allocation import try_reallocate_task_to_same_role + from .repository import _integration_actor + + try_reallocate_task_to_same_role( + db, + task=task, + current=_integration_actor(db), + role_name=task.customer_role_name, + trigger="order_snapshot_sync", + commit=False, + ) def _upsert_order_snapshot(