From dd48175b4a952b1eafce9287e3b53064e2cddc4d Mon Sep 17 00:00:00 2001 From: yml Date: Thu, 19 Nov 2026 16:03:17 +0800 Subject: [PATCH] =?UTF-8?q?fix(douyu):=20=E7=BB=9F=E4=B8=80=E5=A4=96?= =?UTF-8?q?=E9=83=A8=E5=8D=8F=E4=BD=9C=E8=B4=A6=E5=8F=B7=E7=A7=9F=E7=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_douyu_collab_orders.py | 166 ++++++- tests/test_migrations.py | 123 ++++- tests/test_platform_fulfillment.py | 66 ++- ...261119_0098_douyu_collab_account_leases.py | 243 ++++++++++ .../jobs/platform_fulfillment_lease_reaper.py | 47 +- web/backend/services/douyu_collab_service.py | 430 +++++++++++++++++- .../platform_fulfillment/account_selector.py | 91 +++- .../services/platform_fulfillment/service.py | 161 +++++-- 8 files changed, 1248 insertions(+), 79 deletions(-) create mode 100644 web/backend/migrations/versions/20261119_0098_douyu_collab_account_leases.py diff --git a/tests/test_douyu_collab_orders.py b/tests/test_douyu_collab_orders.py index 35479cd..a6b843d 100644 --- a/tests/test_douyu_collab_orders.py +++ b/tests/test_douyu_collab_orders.py @@ -3,7 +3,7 @@ import pytest from tests.support.db import get_test_engine, make_test_session -from web.backend.models import Account, AuditLog, User +from web.backend.models import Account, AccountEvent, AccountLease, AuditLog, User from web.backend.routers import douyu_collab as collab_api from web.backend.schemas import ( DouyuCollabAccountLookupOut, @@ -283,6 +283,167 @@ class TestDouyuCollabOrders: ) assert second.account_id == self.account.id assert collab.group_points_total(self.session, second) == 200 + lease = self.session.query(AccountLease).one() + assert lease.account_id == self.account.id + assert lease.purpose == collab.LEASE_PURPOSE_DOUYU_COLLAB + assert lease.batch_id == f"collab:{self.account.id}" + assert lease.status == "active" + assert ( + self.session.query(AccountEvent) + .filter(AccountEvent.event_type == "lease_acquired") + .count() + == 1 + ) + + def test_create_order_rejects_account_leased_by_platform(self): + self.session.add( + AccountLease( + account_id=self.account.id, + holder_user_id=self.admin.id, + scope="elite", + purpose="platform_fulfillment", + batch_id="pf:99", + status="active", + ) + ) + self.session.commit() + + with pytest.raises(collab.CollabError) as excinfo: + collab.create_order( + self.session, + self.admin, + order_no="DY-LEASE-CONFLICT", + shop="店铺A", + account_username="douyu-account-a", + gift_name="礼包A", + required_points=100, + home_images=["collab/home-conflict.png"], + client=FakeClient(), + ) + + assert excinfo.value.code == "account_lease_conflict" + assert ( + self.session.query(collab.DouyuExternalOrder) + .filter(collab.DouyuExternalOrder.order_no == "DY-LEASE-CONFLICT") + .first() + is None + ) + + def test_void_releases_only_after_last_active_order(self): + first = collab.create_order( + self.session, + self.admin, + order_no="DY-LEASE-VOID-1", + shop="店铺A", + account_username="douyu-account-a", + gift_name="礼包A", + required_points=100, + home_images=["collab/home-lease-void-1.png"], + client=FakeClient(), + ) + second = collab.create_order( + self.session, + self.admin, + order_no="DY-LEASE-VOID-2", + shop="店铺A", + account_username="douyu-account-a", + gift_name="礼包A", + required_points=100, + home_images=["collab/home-lease-void-2.png"], + client=FakeClient(), + ) + + collab.set_status( + self.session, + self.admin, + first, + status=collab.STATUS_VOID, + reason="第一单作废", + ) + lease = self.session.query(AccountLease).one() + assert lease.status == "active" + + collab.set_status( + self.session, + self.admin, + second, + status=collab.STATUS_VOID, + reason="第二单作废", + ) + self.session.refresh(lease) + assert lease.status == "released" + assert lease.release_reason == "douyu_collab_void" + + restored = collab.set_status( + self.session, + self.admin, + first, + status=collab.STATUS_INCOMPLETE, + reason="恢复第一单", + ) + restored_lease = ( + self.session.query(AccountLease) + .filter(AccountLease.status == "active") + .one() + ) + assert restored.status == collab.STATUS_INCOMPLETE + assert restored_lease.status == "active" + assert restored_lease.purpose == collab.LEASE_PURPOSE_DOUYU_COLLAB + + def test_set_account_conflict_keeps_original_lease(self): + order = collab.create_order( + self.session, + self.admin, + order_no="DY-LEASE-SWITCH", + shop="店铺A", + account_username="douyu-account-a", + gift_name="礼包A", + required_points=100, + home_images=["collab/home-lease-switch.png"], + client=FakeClient(), + ) + other = Account( + username="douyu-account-busy", + password="password", + email="busy@example.com", + email_password="mail-password", + cookie="acf_uid=200; acf_nickname=busy", + ) + self.session.add(other) + self.session.flush() + self.session.add( + AccountLease( + account_id=other.id, + holder_user_id=self.admin.id, + scope="elite", + purpose="platform_fulfillment", + batch_id="pf:100", + status="active", + ) + ) + self.session.commit() + + with pytest.raises(collab.CollabError) as excinfo: + collab.set_account( + self.session, + self.admin, + order, + other.username, + client=FakeClient(), + ) + + assert excinfo.value.code == "account_lease_conflict" + self.session.refresh(order) + assert order.account_id == self.account.id + original_lease = ( + self.session.query(AccountLease) + .filter( + AccountLease.account_id == self.account.id, + AccountLease.status == "active", + ) + .one() + ) + assert original_lease.purpose == collab.LEASE_PURPOSE_DOUYU_COLLAB def test_status_flow_and_exchange_record_marks_done(self): order = collab.create_order( @@ -319,6 +480,9 @@ class TestDouyuCollabOrders: assert result["verdict"] == collab.VERDICT_SUCCESS assert result["order"].status == collab.STATUS_DONE assert result["order"].done_at is not None + lease = self.session.query(AccountLease).one() + assert lease.status == "released" + assert lease.release_reason == "douyu_collab_done" def test_admin_can_restore_voided_order_to_another_status(self): order = collab.create_order( diff --git a/tests/test_migrations.py b/tests/test_migrations.py index 9f9b514..91f9ee4 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -40,7 +40,7 @@ TESTS_DIR = Path(__file__).resolve().parent PROJECT_ROOT = TESTS_DIR.parent VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions" -HEAD_REVISION = "20261119_0097" +HEAD_REVISION = "20261119_0098" # 迁移新增、但不声明在模型里的复合查询索引。 EXTRA_INDEXES = ( @@ -758,3 +758,124 @@ class TestMigrationSmoke: mig_engine.dispose() with admin_engine.begin() as conn: conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;")) + + def test_0098_backfills_collab_leases_without_stealing_active_leases(self): + creds = get_mysql_credentials() + mig_db = f"douyu_login_mig_{secrets.token_hex(4)}" + mig_url = ( + f"mysql+pymysql://{quote_plus(creds['user'])}:{quote_plus(creds['password'])}" + f"@{creds['host']}:{creds['port']}/{mig_db}?charset=utf8mb4" + ) + + admin_engine = get_test_engine() + with admin_engine.begin() as conn: + conn.execute( + text( + f"CREATE DATABASE `{mig_db}` " + "CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;" + ) + ) + + original_url = database_module.DATABASE_URL + mig_engine = create_engine(mig_url) + try: + database_module.DATABASE_URL = mig_url + cfg = _migration_config() + cfg.set_main_option("sqlalchemy.url", mig_url) + command.upgrade(cfg, "20261119_0097") + + with Session(mig_engine) as session: + owner = User( + username="migration-0098-owner", + password_hash="hash", + role="operation", + is_active=True, + ) + session.add(owner) + session.flush() + free_account = Account( + username="migration-0098-free", + password="p", + email="free@example.com", + email_password="ep", + ) + busy_account = Account( + username="migration-0098-busy", + password="p", + email="busy@example.com", + email_password="ep", + ) + session.add_all([free_account, busy_account]) + session.flush() + session.add_all( + [ + DouyuExternalOrder( + order_no="MIG-0098-FREE", + owner_id=owner.id, + account_id=free_account.id, + account_username=free_account.username, + status="to_recharge", + ), + DouyuExternalOrder( + order_no="MIG-0098-BUSY", + owner_id=owner.id, + account_id=busy_account.id, + account_username=busy_account.username, + status="incomplete", + ), + AccountLease( + account_id=busy_account.id, + holder_user_id=owner.id, + scope="elite", + purpose="platform_fulfillment", + batch_id="pf:0098", + status="active", + ), + ] + ) + session.commit() + free_account_id = free_account.id + busy_account_id = busy_account.id + + command.upgrade(cfg, "head") + + with Session(mig_engine) as session: + free_lease = ( + session.query(AccountLease) + .filter_by(account_id=free_account_id, status="active") + .one() + ) + busy_lease = ( + session.query(AccountLease) + .filter_by(account_id=busy_account_id, status="active") + .one() + ) + assert free_lease.purpose == "douyu_collab" + assert free_lease.batch_id == f"collab:{free_account_id}" + assert free_lease.release_reason == "migration_backfill" + assert busy_lease.purpose == "platform_fulfillment" + assert ( + session.query(AccountEvent) + .filter( + AccountEvent.account_id == free_account_id, + AccountEvent.event_type == "lease_acquired", + AccountEvent.source == "migration", + ) + .count() + == 1 + ) + assert ( + session.query(AccountEvent) + .filter( + AccountEvent.account_id == busy_account_id, + AccountEvent.event_type == "lease_conflict", + AccountEvent.source == "migration", + ) + .count() + == 1 + ) + 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}`;")) diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index 939ebff..1839a65 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -520,6 +520,8 @@ class TestFulfillmentCollabSync(_Base): .count() == 1 ) + lease = self.session.query(AccountLease).one() + assert lease.purpose == "douyu_collab" def test_manual_sync_does_not_clear_account_added_in_collab(self): task = self.task() @@ -1479,9 +1481,7 @@ class TestBindingAndCompletion(_Base): assert exc_info.value.status_code == 403 assert checker(current_user=admin) is admin - def test_restore_manual_cancel_requeues_task_and_restores_collab( - self, monkeypatch - ): + def test_restore_manual_cancel_requeues_task_and_restores_collab(self, monkeypatch): task = self.task() service.cancel_task( self.session, @@ -1711,6 +1711,36 @@ class TestBindingAndCompletion(_Base): assert event.detail_json["releasedAccountId"] == account_id assert event.detail_json["releasedLeaseId"] == lease_id + def test_release_to_manual_hands_lease_to_active_collab_order(self): + task = self._allocated() + lease_id = task.lease_id + order, _ = collab.sync_platform_fulfillment_order( + self.session, + self.admin, + task, + ) + assert order.status == collab.STATUS_INCOMPLETE + lease = self.session.query(AccountLease).filter_by(id=lease_id).one() + assert lease.purpose == "platform_fulfillment" + + detail = service.release_task_to_manual( + self.session, + task_id=task.id, + current=self.admin, + reason="以外部协作单的人工处理为准", + ) + + self.session.refresh(task) + self.session.refresh(lease) + assert detail["task"]["executionStatus"] == "manual_required" + assert task.account_id is None + assert task.lease_id is None + assert lease.status == "active" + assert lease.purpose == "douyu_collab" + assert lease.expires_at is None + assert lease.batch_id == f"collab:{lease.account_id}" + assert self.session.query(AccountLease).count() == 1 + def test_refresh_binding_maps_role_ready(self, monkeypatch): notified: list[int] = [] monkeypatch.setattr( @@ -2074,6 +2104,36 @@ class TestBindingAndCompletion(_Base): assert result["expired"] == 0 assert task.execution_status == "allocated" + def test_expired_platform_lease_hands_off_to_active_collab(self): + task = self._allocated() + lease = self.session.query(AccountLease).one() + collab.sync_platform_fulfillment_order( + self.session, + self.admin, + task, + ) + lease.expires_at = NOW - timedelta(minutes=1) + self.session.commit() + + job = AutomationJob(key=reaper.JOB_KEY, batch_size=100) + result = reaper.run_platform_fulfillment_lease_reaper( + self.session, + job, + now=NOW, + ) + + self.session.refresh(task) + self.session.refresh(lease) + assert result["expired"] == 0 + assert result["affected_tasks"] == 1 + assert task.execution_status == "manual_required" + assert task.account_id is None + assert task.lease_id is None + assert task.issue_code == "lease_expired_collab_handoff" + assert lease.status == "active" + assert lease.purpose == "douyu_collab" + assert lease.expires_at is None + def test_completion_rejects_limited_exchange(self): task = self._allocated() task.binding_status = "bound" diff --git a/web/backend/migrations/versions/20261119_0098_douyu_collab_account_leases.py b/web/backend/migrations/versions/20261119_0098_douyu_collab_account_leases.py new file mode 100644 index 0000000..5b7331e --- /dev/null +++ b/web/backend/migrations/versions/20261119_0098_douyu_collab_account_leases.py @@ -0,0 +1,243 @@ +"""把进行中的斗鱼外部协作单接入统一账号租约。 + +只给当前没有活动租约的账号补租约。已经被平台履约等业务占用的账号保持原状, +并写一条冲突事件供账号时间线追溯,避免迁移抢占正在执行的链路。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261119_0098" +down_revision: str | None = "20261119_0097" +branch_labels: str | None = None +depends_on: str | None = None + +ACTIVE_COLLAB_STATUSES = ( + "incomplete", + "to_recharge", + "recharged", + "scripted", + "points_error", + "failed", +) + + +def upgrade() -> None: + active_status_sql = ", ".join(f"'{item}'" for item in ACTIVE_COLLAB_STATUSES) + op.execute( + sa.text( + f""" + INSERT INTO account_leases ( + account_id, + holder_user_id, + scope, + purpose, + commodity_id, + batch_id, + status, + leased_at, + expires_at, + released_at, + release_reason, + created_at + ) + SELECT + candidates.account_id, + candidates.holder_user_id, + 'elite', + 'douyu_collab', + '', + CONCAT('collab:', candidates.account_id), + 'active', + UTC_TIMESTAMP(), + NULL, + NULL, + 'migration_backfill', + UTC_TIMESTAMP() + FROM ( + SELECT DISTINCT + o.account_id AS account_id, + COALESCE( + ( + SELECT o2.owner_id + FROM douyu_external_orders o2 + WHERE o2.account_id = o.account_id + AND o2.owner_id IS NOT NULL + AND o2.archived_at IS NULL + AND o2.status IN ({active_status_sql}) + ORDER BY o2.updated_at DESC, o2.id DESC + LIMIT 1 + ), + a.assigned_to, + ( + SELECT u.id + FROM users u + WHERE u.is_active = 1 + AND u.deleted_at IS NULL + ORDER BY + CASE u.role + WHEN 'super_admin' THEN 0 + WHEN 'operation' THEN 1 + ELSE 2 + END, + u.id ASC + LIMIT 1 + ) + ) AS holder_user_id + FROM douyu_external_orders o + JOIN accounts a ON a.id = o.account_id + WHERE o.account_id IS NOT NULL + AND o.archived_at IS NULL + AND o.status IN ({active_status_sql}) + ) AS candidates + WHERE candidates.holder_user_id IS NOT NULL + AND NOT EXISTS ( + SELECT 1 + FROM account_leases active_lease + WHERE active_lease.account_id = candidates.account_id + AND active_lease.status = 'active' + ) + """ + ) + ) + + op.execute( + sa.text( + """ + INSERT INTO account_events ( + account_id, + event_type, + category, + occurred_at, + title, + amount, + balance_after, + subject_type, + subject_key, + detail, + source, + actor_type, + actor_id, + source_ref, + created_at + ) + SELECT + lease.account_id, + 'lease_acquired', + 'ops', + UTC_TIMESTAMP(), + CONCAT('外部协作账号占用回填:账号 #', lease.account_id), + NULL, + NULL, + 'lease', + CONCAT('collab:', lease.account_id), + JSON_OBJECT( + 'lease_id', lease.id, + 'account_id', lease.account_id, + 'purpose', lease.purpose, + 'batch_id', lease.batch_id, + 'backfill', TRUE + ), + 'migration', + 'system', + NULL, + CONCAT('account_lease_backfill:', lease.id), + UTC_TIMESTAMP() + FROM account_leases lease + WHERE lease.status = 'active' + AND lease.purpose = 'douyu_collab' + AND lease.release_reason = 'migration_backfill' + """ + ) + ) + + op.execute( + sa.text( + f""" + INSERT INTO account_events ( + account_id, + event_type, + category, + occurred_at, + title, + amount, + balance_after, + subject_type, + subject_key, + detail, + source, + actor_type, + actor_id, + source_ref, + created_at + ) + SELECT DISTINCT + active_order.account_id, + 'lease_conflict', + 'ops', + UTC_TIMESTAMP(), + CONCAT( + '外部协作账号已被占用:', + active_order.account_id, + ' / ', + active_lease.purpose + ), + NULL, + NULL, + 'lease', + CONCAT('collab:', active_order.account_id), + JSON_OBJECT( + 'lease_id', active_lease.id, + 'account_id', active_order.account_id, + 'existing_purpose', active_lease.purpose, + 'existing_batch_id', active_lease.batch_id, + 'conflict', TRUE + ), + 'migration', + 'system', + NULL, + CONCAT( + 'account_lease_collab_conflict:', + active_order.account_id, + ':', + active_lease.id + ), + UTC_TIMESTAMP() + FROM douyu_external_orders active_order + JOIN account_leases active_lease + ON active_lease.account_id = active_order.account_id + AND active_lease.status = 'active' + WHERE active_order.account_id IS NOT NULL + AND active_order.archived_at IS NULL + AND active_order.status IN ({active_status_sql}) + AND active_lease.purpose <> 'douyu_collab' + """ + ) + ) + + +def downgrade() -> None: + op.execute( + sa.text( + """ + DELETE FROM account_events + WHERE source_ref LIKE 'account_lease_backfill:%' + OR source_ref LIKE 'account_lease_collab_conflict:%' + """ + ) + ) + op.execute( + sa.text( + """ + UPDATE account_leases + SET status = 'released', + released_at = UTC_TIMESTAMP(), + release_reason = 'migration_rollback' + WHERE status = 'active' + AND purpose = 'douyu_collab' + AND release_reason = 'migration_backfill' + """ + ) + ) diff --git a/web/backend/services/automation/jobs/platform_fulfillment_lease_reaper.py b/web/backend/services/automation/jobs/platform_fulfillment_lease_reaper.py index 34a3a8e..afac855 100644 --- a/web/backend/services/automation/jobs/platform_fulfillment_lease_reaper.py +++ b/web/backend/services/automation/jobs/platform_fulfillment_lease_reaper.py @@ -22,24 +22,62 @@ def run_platform_fulfillment_lease_reaper( now: datetime | None = None, ) -> dict[str, Any]: moment = now or datetime.now(UTC) - released_ids = { - lease_id - for (lease_id,) in db.query(AccountLease.id) + candidate_leases = ( + db.query(AccountLease) .filter( AccountLease.purpose == "platform_fulfillment", AccountLease.status == "active", AccountLease.expires_at.isnot(None), AccountLease.expires_at <= moment, ) + .order_by(AccountLease.id.asc()) .limit(max(1, int(job.batch_size or 500))) .all() - } + ) + released_ids = {int(lease.id) for lease in candidate_leases} + converted_tasks: dict[int, PlatformFulfillmentTask] = {} + if candidate_leases: + from ...douyu_collab_service import retain_lease_for_active_collab + + for lease in candidate_leases: + task = ( + db.query(PlatformFulfillmentTask) + .filter(PlatformFulfillmentTask.lease_id == lease.id) + .first() + ) + retained = retain_lease_for_active_collab( + db, + account_id=int(lease.account_id), + holder_user_id=int(task.operator_id or lease.holder_user_id) + if task is not None + else int(lease.holder_user_id), + lease=lease, + source_task_id=int(task.id) if task is not None else None, + reason="platform_lease_expired_collab_active", + commit=False, + ) + if retained is None: + continue + released_ids.discard(int(lease.id)) + if task is not None: + converted_tasks[int(task.id)] = task + expired = expire_platform_fulfillment_leases( db, now=moment, limit=max(1, int(job.batch_size or 500)), ) affected = 0 + for task in converted_tasks.values(): + if task.execution_status in {"completed", "cancelled"}: + continue + task.account_id = None + task.lease_id = None + task.execution_status = "manual_required" + task.issue_code = "lease_expired_collab_handoff" + task.last_error = "平台租约已到期,账号已转外部协作人工处理" + task.updated_at = moment + affected += 1 if released_ids: rows = ( db.query(PlatformFulfillmentTask) @@ -54,6 +92,7 @@ def run_platform_fulfillment_lease_reaper( task.last_error = "账号租约已过期,请重新分配账号" task.updated_at = moment affected += 1 + if released_ids or converted_tasks: db.commit() return { "scanned": expired, diff --git a/web/backend/services/douyu_collab_service.py b/web/backend/services/douyu_collab_service.py index b66af61..9f41c31 100644 --- a/web/backend/services/douyu_collab_service.py +++ b/web/backend/services/douyu_collab_service.py @@ -25,6 +25,7 @@ from core.douyu import DouyuActivityClient from ..models import ( Account, + AccountLease, AuditLog, DouyuCollabGift, DouyuCollabShop, @@ -38,7 +39,12 @@ from ..models import ( User, ) from .account_binding import binding_channel, binding_role_from_result -from .account_events_service import EVENT_COLLAB_SYNCED +from .account_events_service import ( + CATEGORY_OPS, + EVENT_COLLAB_SYNCED, + EVENT_LEASE_ACQUIRED, + emit, +) 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 @@ -59,6 +65,11 @@ from .douyu_goods_service import ( upsert_goods_snapshot, ) from .file_service import build_file_url +from .platform_fulfillment.account_selector import ( + acquire_account_lease, + active_lease_for_account, + release_lease, +) # --------------------------------------------------------------------------- # 状态机 @@ -72,6 +83,15 @@ STATUS_DONE = "done" STATUS_POINTS_ERROR = "points_error" STATUS_FAILED = "failed" STATUS_VOID = "void" +LEASE_PURPOSE_DOUYU_COLLAB = "douyu_collab" +COLLAB_LEASE_STATUSES: tuple[str, ...] = ( + STATUS_INCOMPLETE, + STATUS_TO_RECHARGE, + STATUS_RECHARGED, + STATUS_SCRIPTED, + STATUS_POINTS_ERROR, + STATUS_FAILED, +) ORDER_STATUSES: tuple[str, ...] = ( STATUS_INCOMPLETE, @@ -449,6 +469,308 @@ def _assert_mutable(order: DouyuExternalOrder) -> None: raise CollabError("已作废的订单不能再编辑", code="order_void") +def _order_occupies_account(order: DouyuExternalOrder) -> bool: + return ( + bool(order.account_id) + and order.archived_at is None + and order.status in COLLAB_LEASE_STATUSES + ) + + +def _active_collab_order( + db: Session, + account_id: int, + *, + exclude_order_id: int | None = None, +) -> DouyuExternalOrder | None: + query = db.query(DouyuExternalOrder).filter( + DouyuExternalOrder.account_id == int(account_id), + DouyuExternalOrder.status.in_(COLLAB_LEASE_STATUSES), + DouyuExternalOrder.archived_at.is_(None), + ) + if exclude_order_id is not None: + query = query.filter(DouyuExternalOrder.id != int(exclude_order_id)) + return query.order_by(DouyuExternalOrder.updated_at.desc()).first() + + +def _platform_lease_matches_source( + db: Session, lease: AccountLease, order: DouyuExternalOrder +) -> bool: + if ( + lease.purpose != "platform_fulfillment" + or order.source_type != SOURCE_TYPE_PLATFORM_FULFILLMENT + or not order.source_task_id + ): + return False + task = ( + db.query(PlatformFulfillmentTask) + .filter(PlatformFulfillmentTask.id == int(order.source_task_id)) + .first() + ) + return bool( + task is not None + and (task.lease_id == lease.id or lease.batch_id == f"pf:{int(task.id)}") + ) + + +def _audit_lease_action( + db: Session, + current: User, + *, + order: DouyuExternalOrder | None, + account_id: int, + action: str, + lease: AccountLease, + detail: Mapping[str, Any], +) -> None: + entry = record_audit( + db, + current, + action=action, + target=( + ( + f"douyu_external_order:{order.id}" + if order.id + else f"douyu_external_order_no:{order.order_no}" + ) + if order is not None + else f"account:{account_id}" + ), + detail=detail, + ) + entry.account_id = account_id + + +def _ensure_order_account_lease( + db: Session, + current: User, + order: DouyuExternalOrder, + *, + account_id: int | None = None, + force_active: bool = False, + commit: bool = False, +) -> AccountLease | None: + target_account_id = int(account_id or order.account_id or 0) + if not target_account_id: + return None + if not force_active and not _order_occupies_account(order): + return None + + lease = active_lease_for_account(db, target_account_id) + if lease is not None: + if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB: + return lease + if _platform_lease_matches_source(db, lease, order): + return lease + raise CollabError( + "该账号当前被平台履约占用,请先释放或转人工后再使用", + status_code=409, + code="account_lease_conflict", + ) + + lease = acquire_account_lease( + db, + account_id=target_account_id, + holder_user_id=int(current.id), + scope="elite", + purpose=LEASE_PURPOSE_DOUYU_COLLAB, + batch_id=f"collab:{target_account_id}", + commit=False, + ) + if lease is None: + raise CollabError( + "该账号刚被其他业务占用,请刷新后重试", + status_code=409, + code="account_lease_conflict", + ) + _audit_lease_action( + db, + current, + order=order, + account_id=target_account_id, + action="douyu:collab:lease_acquired", + lease=lease, + detail={ + "lease_id": lease.id, + "account_id": target_account_id, + "purpose": lease.purpose, + "batch_id": lease.batch_id, + }, + ) + if commit: + db.commit() + return lease + + +def _release_order_account_lease( + db: Session, + current: User, + order: DouyuExternalOrder, + *, + reason: str, + account_id: int | None = None, + commit: bool = False, +) -> bool: + target_account_id = int(account_id or order.account_id or 0) + if not target_account_id: + return False + if _active_collab_order(db, target_account_id, exclude_order_id=int(order.id)): + return False + lease = active_lease_for_account(db, target_account_id) + if lease is None or lease.purpose != LEASE_PURPOSE_DOUYU_COLLAB: + return False + released = release_lease(db, lease, reason=reason, commit=False) + if released: + _audit_lease_action( + db, + current, + order=order, + account_id=target_account_id, + action="douyu:collab:lease_released", + lease=lease, + detail={ + "lease_id": lease.id, + "account_id": target_account_id, + "reason": reason, + }, + ) + if commit: + db.commit() + return released + + +def _sync_order_lease( + db: Session, + current: User, + order: DouyuExternalOrder, + *, + reason: str, + force_active: bool = False, + commit: bool = False, +) -> AccountLease | None: + if force_active or _order_occupies_account(order): + return _ensure_order_account_lease( + db, + current, + order, + force_active=force_active, + commit=commit, + ) + _release_order_account_lease( + db, + current, + order, + reason=reason, + commit=commit, + ) + return None + + +def retain_lease_for_active_collab( + db: Session, + *, + account_id: int, + holder_user_id: int, + current: User | None = None, + lease: AccountLease | None = None, + source_task_id: int | None = None, + reason: str = "platform_release_to_collab", + commit: bool = False, +) -> AccountLease | None: + """平台释放账号时,把仍在活动的协作占用接续为统一协作租约。""" + active_lease = lease or active_lease_for_account(db, account_id) + if active_lease is not None and active_lease.status != "active": + return None + + query = db.query(DouyuExternalOrder).filter( + DouyuExternalOrder.account_id == int(account_id), + DouyuExternalOrder.status.in_(COLLAB_LEASE_STATUSES), + DouyuExternalOrder.archived_at.is_(None), + ) + if source_task_id: + preferred = ( + query.filter(DouyuExternalOrder.source_task_id == int(source_task_id)) + .order_by(DouyuExternalOrder.updated_at.desc()) + .first() + ) + order = ( + preferred or query.order_by(DouyuExternalOrder.updated_at.desc()).first() + ) + else: + order = query.order_by(DouyuExternalOrder.updated_at.desc()).first() + if order is None: + return None + + holder_id = int( + holder_user_id + or (order.owner_id if order.owner_id else 0) + or (active_lease.holder_user_id if active_lease else 0) + ) + if not holder_id: + return None + + if active_lease is None: + active_lease = acquire_account_lease( + db, + account_id=int(account_id), + holder_user_id=holder_id, + scope="elite", + purpose=LEASE_PURPOSE_DOUYU_COLLAB, + batch_id=f"collab:{int(account_id)}", + commit=False, + ) + if active_lease is None: + return None + elif active_lease.purpose != LEASE_PURPOSE_DOUYU_COLLAB: + previous_purpose = active_lease.purpose + active_lease.purpose = LEASE_PURPOSE_DOUYU_COLLAB + active_lease.batch_id = f"collab:{int(account_id)}"[:64] + active_lease.commodity_id = "" + active_lease.expires_at = None + active_lease.release_reason = "" + active_lease.holder_user_id = holder_id + emit( + db, + account_id=int(account_id), + event_type=EVENT_LEASE_ACQUIRED, + title=f"外部协作接管账号占用:{order.order_no}", + category=CATEGORY_OPS, + detail={ + "lease_id": active_lease.id, + "order_id": order.id, + "order_no": order.order_no, + "purpose": active_lease.purpose, + "previous_purpose": previous_purpose, + "reason": reason, + }, + source="lease", + subject_type="order", + subject_key=order.order_no, + actor_type="user" if current is not None else "system", + actor_id=int(current.id) if current is not None else None, + source_ref=f"account_lease_collab_takeover:{active_lease.id}", + ) + + if current is not None: + _audit_lease_action( + db, + current, + order=order, + account_id=int(account_id), + action="douyu:collab:lease_takeover", + lease=active_lease, + detail={ + "lease_id": active_lease.id, + "order_id": order.id, + "order_no": order.order_no, + "reason": reason, + }, + ) + if commit: + db.commit() + return active_lease + + def _resolve_gift( db: Session, *, gift_name: str, commodity_id: str, required_points: Any ) -> tuple[str, str, int | None]: @@ -649,6 +971,7 @@ def create_order( if order.shop: ensure_shops_registered(db, current, [order.shop]) + _ensure_order_account_lease(db, current, order, force_active=True) db.add(order) db.flush() record_audit( @@ -740,7 +1063,9 @@ def _apply_platform_fulfillment_binding( if task.bind_task_id else None ) - result = bind_task.result if bind_task and isinstance(bind_task.result, dict) else None + result = ( + bind_task.result if bind_task and isinstance(bind_task.result, dict) else None + ) role = binding_role_from_result(result) if not role: return @@ -875,6 +1200,12 @@ def sync_platform_fulfillment_order( _apply_platform_fulfillment_status(order, task, created=created) order.version = int(order.version or 0) + 1 db.flush() + _sync_order_lease( + db, + current, + order, + reason="douyu_collab_sync_terminal", + ) audit_detail = { "taskId": int(task.id), @@ -982,9 +1313,7 @@ def sync_platform_fulfillment_orders( } ) except Exception: # noqa: BLE001 - 批量边界需隔离单条未知故障 - logger.exception( - "同步直播履约任务 {} 到斗鱼外部协作失败", task_id - ) + logger.exception("同步直播履约任务 {} 到斗鱼外部协作失败", task_id) result["failed"] += 1 result["items"].append( { @@ -1013,6 +1342,7 @@ def update_order( ) -> dict[str, Any]: _assert_mutable(order) _assert_version(order, expected_version) + previous_account_id = int(order.account_id or 0) changes: dict[str, dict[str, Any]] = {} editable = { "order_no", @@ -1075,8 +1405,18 @@ def update_order( client=client, with_goods=True, ) + _ensure_order_account_lease( + db, + current, + order, + account_id=int(account.id), + force_active=order.status in COLLAB_LEASE_STATUSES, + ) apply_probe_snapshot(order, account, probe) - changes["account_id"] = {"old": None, "new": int(account.id)} + changes["account_id"] = { + "old": previous_account_id or None, + "new": int(account.id), + } changes["bind_game_role"] = {"old": "", "new": order.bind_game_role} if "home_images" in payload: images = normalize_images(payload.get("home_images")) @@ -1107,6 +1447,14 @@ def update_order( detail=changes, ) _maybe_advance_to_recharge(db, current, order) + if previous_account_id and previous_account_id != int(order.account_id or 0): + _release_order_account_lease( + db, + current, + order, + reason="douyu_collab_account_changed", + account_id=previous_account_id, + ) if commit: db.commit() db.refresh(order) @@ -1128,6 +1476,7 @@ def set_account( account = account_by_username(db, username) if account is None: raise CollabError("斗鱼账号不存在", code="account_not_found") + previous_account_id = int(order.account_id or 0) config = resolve_config(db) probe = _probe_with_client( account, @@ -1137,6 +1486,13 @@ def set_account( client=client, with_goods=True, ) + _ensure_order_account_lease( + db, + current, + order, + account_id=int(account.id), + force_active=order.status in COLLAB_LEASE_STATUSES, + ) apply_probe_snapshot(order, account, probe) order.updated_by = current.id order.version = int(order.version or 0) + 1 @@ -1153,6 +1509,14 @@ def set_account( }, ) _maybe_advance_to_recharge(db, current, order) + if previous_account_id and previous_account_id != int(order.account_id or 0): + _release_order_account_lease( + db, + current, + order, + reason="douyu_collab_account_changed", + account_id=previous_account_id, + ) if commit: db.commit() db.refresh(order) @@ -1249,6 +1613,8 @@ def _restore_void_status( target_index = STAGE_INDEX.get(target) if target_index is not None and target_index >= STAGE_INDEX[STATUS_TO_RECHARGE]: _assert_ready_for_recharge(order) + if target in COLLAB_LEASE_STATUSES: + _ensure_order_account_lease(db, current, order, force_active=True) old_void_reason = order.void_reason or "" # 取消作废等于重新进入状态机:先清空旧流程时间,再按目标状态补当前时间。 @@ -1275,6 +1641,12 @@ def _restore_void_status( "reason": _text(reason, max_length=256), }, ) + _sync_order_lease( + db, + current, + order, + reason="douyu_collab_void_restored", + ) if commit: db.commit() db.refresh(order) @@ -1324,6 +1696,12 @@ def set_status( target=_status_audit_target(order), detail={"from": old, "reason": order.void_reason}, ) + _sync_order_lease( + db, + current, + order, + reason="douyu_collab_void", + ) if commit: db.commit() db.refresh(order) @@ -1340,6 +1718,12 @@ def set_status( target=_status_audit_target(order), detail={"from": old, "to": target, "reason": _text(reason, max_length=256)}, ) + _sync_order_lease( + db, + current, + order, + reason="douyu_collab_failed", + ) if commit: db.commit() db.refresh(order) @@ -1356,6 +1740,12 @@ def set_status( target=_status_audit_target(order), detail={"from": old, "reason": _text(reason, max_length=256)}, ) + _sync_order_lease( + db, + current, + order, + reason="douyu_collab_points_error", + ) if commit: db.commit() db.refresh(order) @@ -1399,6 +1789,16 @@ def set_status( "reason": _text(reason, max_length=256), }, ) + _sync_order_lease( + db, + current, + order, + reason=( + "douyu_collab_done" + if target == STATUS_DONE + else "douyu_collab_status_changed" + ), + ) if commit: db.commit() db.refresh(order) @@ -2508,6 +2908,12 @@ def archive_orders( target=_status_audit_target(order), detail={"reason": order.archive_reason}, ) + _sync_order_lease( + db, + current, + order, + reason="douyu_collab_archived", + ) db.commit() return {"archived": archived} @@ -2536,6 +2942,12 @@ def unarchive_orders(db: Session, current: User, ids: list[int]) -> dict[str, An target=_status_audit_target(order), detail={}, ) + _sync_order_lease( + db, + current, + order, + reason="douyu_collab_unarchived", + ) db.commit() return {"unarchived": unarchived} @@ -2544,6 +2956,12 @@ def delete_order( db: Session, current: User, order: DouyuExternalOrder ) -> dict[str, Any]: order_no = order.order_no + _release_order_account_lease( + db, + current, + order, + reason="douyu_collab_deleted", + ) record_audit( db, current, diff --git a/web/backend/services/platform_fulfillment/account_selector.py b/web/backend/services/platform_fulfillment/account_selector.py index d01c76e..33096cb 100644 --- a/web/backend/services/platform_fulfillment/account_selector.py +++ b/web/backend/services/platform_fulfillment/account_selector.py @@ -290,14 +290,45 @@ def lease_account( now: datetime | None = None, ) -> AccountLease | None: """尝试领取一个账号;撞唯一索引时返回 None。""" - moment = _now(now) - lease = AccountLease( - account_id=candidate.account_id, + return acquire_account_lease( + db, + account_id=int(candidate.account_id), holder_user_id=holder_user_id, scope="elite", purpose="platform_fulfillment", commodity_id=commodity_id, batch_id=f"pf:{task_id}", + ttl_minutes=ttl_minutes, + now=now, + ) + + +def acquire_account_lease( + db: Session, + *, + account_id: int, + holder_user_id: int, + scope: str, + purpose: str, + commodity_id: str = "", + batch_id: str = "", + ttl_minutes: int | None = None, + now: datetime | None = None, + commit: bool = True, +) -> AccountLease | None: + """获取账号租约;调用方可在自己的事务内复用。 + + 唯一索引负责并发互斥。撞到已有活动租约时返回 ``None``,由调用方结合 + ``active_lease_for_account`` 决定是沿用合法占用的租约还是提示冲突。 + """ + moment = _now(now) + lease = AccountLease( + account_id=int(account_id), + holder_user_id=holder_user_id, + scope=str(scope or "elite")[:16], + purpose=str(purpose or "exchange")[:24], + commodity_id=str(commodity_id or "")[:64], + batch_id=str(batch_id or "")[:64], status="active", leased_at=moment, expires_at=( @@ -316,30 +347,54 @@ def lease_account( if lease in db: db.expunge(lease) return None + event_detail: dict[str, object] = { + "lease_id": lease.id, + "holder_user_id": holder_user_id, + "commodity_id": commodity_id, + "purpose": purpose, + "batch_id": batch_id, + } + if purpose == "platform_fulfillment" and batch_id.startswith("pf:"): + event_detail["task_id"] = int(batch_id.removeprefix("pf:")) emit( db, - account_id=int(candidate.account_id), + account_id=int(account_id), event_type=EVENT_LEASE_ACQUIRED, - title=f"履约占用:任务 #{task_id}", + title=( + f"履约占用:任务 #{batch_id.removeprefix('pf:')}" + if purpose == "platform_fulfillment" + else f"业务占用:{purpose}" + ), category=CATEGORY_OPS, - detail={ - "lease_id": lease.id, - "task_id": task_id, - "holder_user_id": holder_user_id, - "commodity_id": commodity_id, - "purpose": "platform_fulfillment", - }, + occurred_at=moment, + detail=event_detail, source="lease", - subject_type="task", - subject_key=str(task_id), + subject_type="task" if purpose == "platform_fulfillment" else "lease", + subject_key=batch_id, actor_type="user", actor_id=holder_user_id, source_ref=f"account_lease_acquired:{lease.id}", ) - db.commit() + if commit: + db.commit() return lease +def active_lease_for_account( + db: Session, account_id: int | None +) -> AccountLease | None: + if not account_id: + return None + return ( + db.query(AccountLease) + .filter( + AccountLease.account_id == int(account_id), + AccountLease.status == "active", + ) + .first() + ) + + def renew_lease( db: Session, lease: AccountLease, @@ -364,6 +419,7 @@ def release_lease( *, reason: str, now: datetime | None = None, + commit: bool = True, ) -> bool: if lease is None or lease.status != "active": return False @@ -387,7 +443,8 @@ def release_lease( actor_type="system", source_ref=f"account_lease_released:{lease.id}", ) - db.commit() + if commit: + db.commit() return True @@ -442,6 +499,8 @@ __all__ = [ "EXCHANGE_COOLDOWN_DAYS", "VALIDATION_LEASE_MINUTES", "AccountCandidate", + "acquire_account_lease", + "active_lease_for_account", "capability_candidate_accounts", "eligible_accounts", "expire_platform_fulfillment_leases", diff --git a/web/backend/services/platform_fulfillment/service.py b/web/backend/services/platform_fulfillment/service.py index fc24349..73f7407 100644 --- a/web/backend/services/platform_fulfillment/service.py +++ b/web/backend/services/platform_fulfillment/service.py @@ -82,6 +82,7 @@ def _matching_mode() -> str: mode = os.getenv("PLATFORM_FULFILLMENT_MATCH_MODE", "hybrid").strip().lower() return mode if mode in {"legacy", "hybrid", "capability"} else "hybrid" + _SYNC_LOCK = Lock() _AUTO_SYNC_LOCK = Lock() _AUTO_SYNC_LAST_ATTEMPT = float("-inf") @@ -150,7 +151,9 @@ def _upsert_order_snapshot( ) -> tuple[PlatformFulfillmentTask | None, bool, bool]: """应用一条订单项快照,返回 (task, created, ignored)。""" item_id = str( - _snapshot_value(snapshot, "sourceOrderItemId", "source_order_item_id", default="") + _snapshot_value( + snapshot, "sourceOrderItemId", "source_order_item_id", default="" + ) ).strip() if not item_id: return None, False, True @@ -177,11 +180,7 @@ def _upsert_order_snapshot( return None, False, True cutoff = _order_match_started_at(db) match_basis_at = paid_at or order_created_at - if ( - match_basis_at is not None - and cutoff is not None - and match_basis_at < cutoff - ): + if match_basis_at is not None and cutoff is not None and match_basis_at < cutoff: return None, False, True task = ( @@ -303,21 +302,11 @@ def _upsert_order_snapshot( default=task.source_fulfillment_id, ) ) - task.provider = str( - _snapshot_value(snapshot, "provider", default=task.provider) - ) - task.shop_id = str( - _snapshot_value(snapshot, "shopId", "shop_id", default="") - ) - task.shop_name = str( - _snapshot_value(snapshot, "shopName", "shop_name", default="") - ) - task.sku_code = str( - _snapshot_value(snapshot, "skuCode", "sku_code", default="") - ) - task.sku_name = str( - _snapshot_value(snapshot, "skuName", "sku_name", default="") - ) + task.provider = str(_snapshot_value(snapshot, "provider", default=task.provider)) + task.shop_id = str(_snapshot_value(snapshot, "shopId", "shop_id", default="")) + task.shop_name = str(_snapshot_value(snapshot, "shopName", "shop_name", default="")) + task.sku_code = str(_snapshot_value(snapshot, "skuCode", "sku_code", default="")) + task.sku_name = str(_snapshot_value(snapshot, "skuName", "sku_name", default="")) task.internal_sku_key = str( _snapshot_value( snapshot, @@ -453,7 +442,9 @@ def sync_order_item_ids( updated = 0 ignored = 0 task_ids: list[int] = [] - for item_id in dict.fromkeys(str(item or "").strip() for item in source_order_item_ids): + for item_id in dict.fromkeys( + str(item or "").strip() for item in source_order_item_ids + ): if not item_id: ignored += 1 continue @@ -461,7 +452,9 @@ def sync_order_item_ids( if snapshot is None: ignored += 1 continue - mapping = mapping_by_sku.get(str(snapshot.get("internal_sku_key") or "").strip()) + mapping = mapping_by_sku.get( + str(snapshot.get("internal_sku_key") or "").strip() + ) task, was_created, was_ignored = _upsert_order_snapshot( db, snapshot, @@ -765,6 +758,31 @@ def _load_task(db: Session, task_id: int) -> PlatformFulfillmentTask: return task +def _retain_lease_for_active_collab( + db: Session, + *, + task: PlatformFulfillmentTask, + lease: AccountLease | None, + current: User, + reason: str, +) -> AccountLease | None: + """平台释放账号前,把仍在活动的协作单占用接续到同一租约。""" + if lease is None or not task.account_id: + return None + from ..douyu_collab_service import retain_lease_for_active_collab + + return retain_lease_for_active_collab( + db, + account_id=int(task.account_id), + holder_user_id=int(current.id), + current=current, + lease=lease, + source_task_id=int(task.id), + reason=reason, + commit=False, + ) + + def _apply_mapping( task: PlatformFulfillmentTask, mapping: PlatformCommodityMapping | None, @@ -892,10 +910,10 @@ def _sync_pending_tasks( task.scope = SCOPE_ELITE task.source_snapshot_json = _jsonable(row) task.updated_at = _now() - if ( - task.account_id is None - and task.execution_status in {"pending_mapping", "ready"} - ): + if task.account_id is None and task.execution_status in { + "pending_mapping", + "ready", + }: _apply_mapping(task, mapping) if task.execution_status == "ready" and task.account_id is None: task.next_allocate_at = _now() @@ -1135,13 +1153,16 @@ def get_task_detail(db: Session, task_id: int) -> dict[str, Any]: actor_ids = { int(event.actor_id) for event in events - if event.actor_type == "user" - and str(event.actor_id or "").isdigit() + if event.actor_type == "user" and str(event.actor_id or "").isdigit() } - actors = { - int(user.id): user - for user in db.query(User).filter(User.id.in_(actor_ids)).all() - } if actor_ids else {} + actors = ( + { + int(user.id): user + for user in db.query(User).filter(User.id.in_(actor_ids)).all() + } + if actor_ids + else {} + ) return { "task": _task_out(db, task, include_qr=True), "events": [ @@ -1154,19 +1175,16 @@ def get_task_detail(db: Session, task_id: int) -> dict[str, Any]: actors[int(event.actor_id)].deleted_username or actors[int(event.actor_id)].username ) - if str(event.actor_id or "").isdigit() - and int(event.actor_id) in actors + if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors else "", "actorRole": actors[int(event.actor_id)].role - if str(event.actor_id or "").isdigit() - and int(event.actor_id) in actors + if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors else "", "actorRoleLabel": ROLE_LABELS.get( actors[int(event.actor_id)].role, actors[int(event.actor_id)].role, ) - if str(event.actor_id or "").isdigit() - and int(event.actor_id) in actors + if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors else "", "detail": event.detail_json or {}, "createdAt": event.created_at, @@ -1542,9 +1560,7 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any] availability=( AVAILABILITY_LIMITED if limited else AVAILABILITY_AVAILABLE ), - blocking_reason=( - "该账号已达此商品兑换上限" if limited else "" - ), + blocking_reason=("该账号已达此商品兑换上限" if limited else ""), raw_status="1" if limited else "0", observed_at=live_state.checked_at, source="live_check", @@ -1742,7 +1758,15 @@ def release_task_account( if task.lease_id else None ) - release_lease(db, lease, reason=reason) + retained = _retain_lease_for_active_collab( + db, + task=task, + lease=lease, + current=current, + reason="platform_released_to_collab", + ) + if retained is None: + release_lease(db, lease, reason=reason, commit=False) task.account_id = None task.lease_id = None task.bind_task_id = None @@ -2057,7 +2081,7 @@ def reconcile_binding_state_outbox( PlatformFulfillmentTask.id > normalized_after, PlatformFulfillmentTask.execution_status.notin_( ["completed", "cancelled"] - ) + ), ) .order_by(PlatformFulfillmentTask.id.asc()) .limit(batch_size) @@ -2297,7 +2321,20 @@ def complete_manual_exchange( task.last_error = "" task.issue_code = "" task.updated_at = _now() - release_lease(db, lease, reason="manual_exchange_completed") + retained = _retain_lease_for_active_collab( + db, + task=task, + lease=lease, + current=current, + reason="platform_completed_but_collab_active", + ) + if retained is None: + release_lease( + db, + lease, + reason="manual_exchange_completed", + commit=False, + ) _append_event( db, task.id, @@ -2378,7 +2415,20 @@ def cancel_task( linked_task.status = "stopped" linked_task.message = "履约任务已取消" linked_task.finished_at = _now() - release_lease(db, lease, reason="platform_fulfillment_cancelled") + retained = _retain_lease_for_active_collab( + db, + task=task, + lease=lease, + current=current, + reason="platform_cancelled_but_collab_active", + ) + if retained is None: + release_lease( + db, + lease, + reason="platform_fulfillment_cancelled", + commit=False, + ) task.account_id = None task.lease_id = None task.bind_task_id = None @@ -2455,7 +2505,9 @@ def restore_cancelled_task( or str(source.get("fulfillment_issue_code") or "") in {"user_refund", "platform_cancelled"} ): - raise HTTPException(status_code=409, detail="来源订单已退款、关闭或取消,不能恢复") + raise HTTPException( + status_code=409, detail="来源订单已退款、关闭或取消,不能恢复" + ) restore_reason = reason.strip() if len(restore_reason) < 2: @@ -2537,7 +2589,20 @@ def release_task_to_manual( if task.lease_id else None ) - release_lease(db, lease, reason="platform_fulfillment_manual") + retained = _retain_lease_for_active_collab( + db, + task=task, + lease=lease, + current=current, + reason="platform_release_to_manual", + ) + if retained is None: + release_lease( + db, + lease, + reason="platform_fulfillment_manual", + commit=False, + ) task.account_id = None task.lease_id = None task.bind_task_id = None