From cc78208048b6c60d067860dceffbc8cc2dbd7390 Mon Sep 17 00:00:00 2001 From: yml Date: Mon, 30 Nov 2026 14:28:00 +0800 Subject: [PATCH] =?UTF-8?q?feat(douyu):=20=E6=94=AF=E6=8C=81=E6=96=97?= =?UTF-8?q?=E9=B1=BC=E9=A2=84=E5=94=AE=E5=BD=92=E6=A1=A3=E8=B4=A6=E5=8F=B7?= =?UTF-8?q?=E5=AE=89=E5=85=A8=E9=87=8A=E6=94=BE=E5=9B=9E=E5=8F=B7=E5=BA=93?= =?UTF-8?q?=E5=B9=B6=E4=BF=AE=E5=A4=8D=E5=AE=8C=E6=88=90=E5=BD=92=E6=A1=A3?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E8=A7=A3=E7=A7=9F=20(v0.4.25)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- pyproject.toml | 2 +- tests/test_douyu_collab_orders.py | 613 +++++++++++++ uv.lock | 2 +- web/backend/routers/douyu_collab.py | 66 ++ web/backend/schemas.py | 61 ++ web/backend/services/douyu_collab_leases.py | 855 +++++++++++++++++- web/backend/services/douyu_collab_service.py | 4 + web/frontend/src/api/douyuCollab.ts | 71 ++ web/frontend/src/pages/DouyuCollabPage.tsx | 259 +++++- .../src/pages/DouyuCollabPageConfig.ts | 1 + 11 files changed, 1927 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index bf7253f..a115ad7 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 直播账号运营后台 -斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.24)。 +斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.25)。 ## 能做什么 diff --git a/pyproject.toml b/pyproject.toml index 8d56210..4481da4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "live-hub-py" -version = "0.4.24" +version = "0.4.25" description = "直播账号运营 Web 后台" readme = "README.md" requires-python = ">=3.12,<3.13" diff --git a/tests/test_douyu_collab_orders.py b/tests/test_douyu_collab_orders.py index e2a496a..1b91d7d 100644 --- a/tests/test_douyu_collab_orders.py +++ b/tests/test_douyu_collab_orders.py @@ -2817,3 +2817,616 @@ def test_collab_takeover_blocked_when_shared_lease_has_other_active_platform_tas assert lease.purpose == "platform_fulfillment" finally: session.close() + + +def test_done_and_archive_auto_close_bound_platform_task_and_release_lease(): + engine = get_test_engine() + session = make_test_session(engine) + try: + admin = User( + username="collab-auto-close-admin", password_hash="h", role="super_admin" + ) + acc_done = Account( + username="collab-close-done", + password="p", + email="close-done@example.com", + email_password="ep", + status="active", + ck_check_status="valid", + cookie="PHPSESSID=1", + elite_opened=True, + points=5000, + ) + acc_legacy = Account( + username="collab-close-legacy", + password="p", + email="close-legacy@example.com", + email_password="ep", + status="active", + ck_check_status="valid", + cookie="PHPSESSID=2", + elite_opened=True, + points=5000, + ) + acc_shared = Account( + username="collab-close-shared", + password="p", + email="close-shared@example.com", + email_password="ep", + status="active", + ck_check_status="valid", + cookie="PHPSESSID=3", + elite_opened=True, + points=5000, + ) + session.add_all([admin, acc_done, acc_legacy, acc_shared]) + session.flush() + + # Case 1: 预售单从 scripted -> done 时,自动完结 bound 履约单并释放租约 + lease_done = AccountLease( + account_id=acc_done.id, + holder_user_id=admin.id, + scope="elite", + purpose="platform_fulfillment", + batch_id="pf:pending-1", + status="active", + expires_at=None, + ) + # Case 2: 历史已是 done 的单点击批量归档时,兜底完结 bound 履约单并释放租约 + lease_legacy = AccountLease( + account_id=acc_legacy.id, + holder_user_id=admin.id, + scope="elite", + purpose="platform_fulfillment", + batch_id="pf:pending-2", + status="active", + expires_at=None, + ) + # Case 3: 同一租约被两个履约单共享时,只完结当前单并保留租约给兄弟履约单 + lease_shared = AccountLease( + account_id=acc_shared.id, + holder_user_id=admin.id, + scope="elite", + purpose="platform_fulfillment", + batch_id="pf:pending-3", + status="active", + expires_at=None, + ) + session.add_all([lease_done, lease_legacy, lease_shared]) + session.flush() + + pf_done = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="auto-close-1", + source_order_item_id="auto-close-1", + platform_order_id="AUTO-CLOSE-1", + internal_sku_key="sku-1", + commodity_id="cid-1", + customer_role_name="角色1", + account_id=acc_done.id, + lease_id=lease_done.id, + execution_status="bound", + binding_status="bound", + exchange_status="eligible", + ) + pf_legacy = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="auto-close-2", + source_order_item_id="auto-close-2", + platform_order_id="AUTO-CLOSE-2", + internal_sku_key="sku-2", + commodity_id="cid-2", + customer_role_name="角色2", + account_id=acc_legacy.id, + lease_id=lease_legacy.id, + execution_status="bound", + binding_status="bound", + exchange_status="eligible", + ) + pf_shared_1 = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="auto-close-3a", + source_order_item_id="auto-close-3a", + platform_order_id="AUTO-CLOSE-3A", + internal_sku_key="sku-3a", + commodity_id="cid-3a", + customer_role_name="角色3", + account_id=acc_shared.id, + lease_id=lease_shared.id, + execution_status="bound", + binding_status="bound", + exchange_status="eligible", + ) + pf_shared_2 = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="auto-close-3b", + source_order_item_id="auto-close-3b", + platform_order_id="AUTO-CLOSE-3B", + internal_sku_key="sku-3b", + commodity_id="cid-3b", + customer_role_name="角色3", + account_id=acc_shared.id, + lease_id=lease_shared.id, + execution_status="bound", + binding_status="bound", + exchange_status="eligible", + ) + session.add_all([pf_done, pf_legacy, pf_shared_1, pf_shared_2]) + session.flush() + + lease_done.batch_id = f"pf:{pf_done.id}" + lease_legacy.batch_id = f"pf:{pf_legacy.id}" + lease_shared.batch_id = f"pf:{pf_shared_1.id}" + + order_done = collab.DouyuExternalOrder( + order_no="DY-CLOSE-DONE", + source_type=collab.SOURCE_TYPE_PLATFORM_FULFILLMENT, + source_task_id=pf_done.id, + account_id=acc_done.id, + account_username=acc_done.username, + bind_game_role="角色1", + gift_name="礼包A", + commodity_id="cid-1", + required_points=100, + home_images=["collab/c1.png"], + status=collab.STATUS_SCRIPTED, + owner_id=admin.id, + created_by=admin.id, + ) + order_legacy = collab.DouyuExternalOrder( + order_no="DY-CLOSE-LEGACY", + source_type=collab.SOURCE_TYPE_PLATFORM_FULFILLMENT, + source_task_id=pf_legacy.id, + account_id=acc_legacy.id, + account_username=acc_legacy.username, + bind_game_role="角色2", + gift_name="礼包B", + commodity_id="cid-2", + required_points=100, + home_images=["collab/c2.png"], + status=collab.STATUS_DONE, + owner_id=admin.id, + created_by=admin.id, + ) + order_shared = collab.DouyuExternalOrder( + order_no="DY-CLOSE-SHARED", + source_type=collab.SOURCE_TYPE_PLATFORM_FULFILLMENT, + source_task_id=pf_shared_1.id, + account_id=acc_shared.id, + account_username=acc_shared.username, + bind_game_role="角色3", + gift_name="礼包C", + commodity_id="cid-3a", + required_points=100, + home_images=["collab/c3.png"], + status=collab.STATUS_SCRIPTED, + owner_id=admin.id, + created_by=admin.id, + ) + session.add_all([order_done, order_legacy, order_shared]) + session.commit() + + collab.set_status( + session, + admin, + order_done, + status=collab.STATUS_DONE, + reason="确认抢购成功", + ) + session.refresh(pf_done) + session.refresh(lease_done) + assert pf_done.execution_status == "completed" + assert pf_done.exchange_status == "manual_done" + assert pf_done.lease_id is None + assert lease_done.status == "released" + assert lease_done.release_reason == "douyu_collab_done" + + archive_res = collab.archive_orders( + session, admin, [order_legacy.id], reason="归档" + ) + assert archive_res["archived"] == 1 + session.refresh(pf_legacy) + session.refresh(lease_legacy) + assert pf_legacy.execution_status == "completed" + assert pf_legacy.lease_id is None + assert lease_legacy.status == "released" + assert lease_legacy.release_reason == "douyu_collab_archived" + + collab.set_status( + session, + admin, + order_shared, + status=collab.STATUS_DONE, + reason="同号一单先成功", + ) + session.refresh(pf_shared_1) + session.refresh(pf_shared_2) + session.refresh(lease_shared) + assert pf_shared_1.execution_status == "completed" + assert pf_shared_1.lease_id is None + assert pf_shared_2.execution_status == "bound" + assert pf_shared_2.lease_id == lease_shared.id + assert lease_shared.status == "active" + assert lease_shared.batch_id == f"pf:{pf_shared_2.id}" + finally: + session.close() + + +def test_archived_account_pool_release_preview_and_execute_with_guards(): + engine = get_test_engine() + session = make_test_session(engine) + try: + now = datetime.now(UTC) + admin = User( + username="pool-release-admin", password_hash="h", role="super_admin" + ) + support = User( + username="pool-release-support", password_hash="h", role="support" + ) + session.add_all([admin, support]) + session.flush() + + cooldown_past = now - timedelta(days=1) + cooldown_future = now + timedelta(days=3) + + acc_bound = Account( + username="arch-acc-bound", + password="p", + email="ab1@example.com", + email_password="ep", + status="active", + ck_check_status="valid", + cookie="PHPSESSID=a1", + assigned_to=support.id, + role_change_available_at=cooldown_past, + ) + acc_manual = Account( + username="arch-acc-manual", + password="p", + email="ab2@example.com", + email_password="ep", + status="active", + ck_check_status="valid", + cookie="PHPSESSID=a2", + assigned_to=support.id, + role_change_available_at=cooldown_future, + ) + acc_assigned_only = Account( + username="arch-acc-assigned", + password="p", + email="ab3@example.com", + email_password="ep", + status="active", + ck_check_status="valid", + cookie="PHPSESSID=a3", + assigned_to=support.id, + role_change_available_at=cooldown_past, + ) + acc_active_collab = Account( + username="arch-acc-collab-busy", + password="p", + email="ab4@example.com", + email_password="ep", + status="active", + ck_check_status="valid", + cookie="PHPSESSID=a4", + assigned_to=support.id, + role_change_available_at=cooldown_past, + ) + acc_active_pf = Account( + username="arch-acc-pf-busy", + password="p", + email="ab5@example.com", + email_password="ep", + status="active", + ck_check_status="valid", + cookie="PHPSESSID=a5", + assigned_to=support.id, + role_change_available_at=cooldown_past, + ) + session.add_all( + [acc_bound, acc_manual, acc_assigned_only, acc_active_collab, acc_active_pf] + ) + session.flush() + + # 保留历史兑换事件:回池不能删除历史兑换记录 + exchange_evt = AccountEvent( + account_id=acc_bound.id, + event_type="exchange", + title="历史皮肤兑换", + category="business", + subject_type="commodity", + subject_key="cid-history-skin", + occurred_at=now - timedelta(days=10), + ) + session.add(exchange_evt) + + lease_bound = AccountLease( + account_id=acc_bound.id, + holder_user_id=admin.id, + scope="elite", + purpose="platform_fulfillment", + batch_id="pf:b", + status="active", + ) + lease_manual = AccountLease( + account_id=acc_manual.id, + holder_user_id=admin.id, + scope="elite", + purpose="platform_fulfillment", + batch_id="pf:m", + status="active", + ) + lease_collab_busy = AccountLease( + account_id=acc_active_collab.id, + holder_user_id=admin.id, + scope="elite", + purpose="douyu_collab", + batch_id=f"collab:{acc_active_collab.id}", + status="active", + ) + lease_pf_busy = AccountLease( + account_id=acc_active_pf.id, + holder_user_id=admin.id, + scope="elite", + purpose="platform_fulfillment", + batch_id="pf:busy", + status="active", + ) + session.add_all([lease_bound, lease_manual, lease_collab_busy, lease_pf_busy]) + session.flush() + + pf_bound = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="pr-1", + source_order_item_id="pr-1", + platform_order_id="PR-1", + internal_sku_key="sku-pr1", + commodity_id="cid-pr1", + account_id=acc_bound.id, + lease_id=lease_bound.id, + execution_status="bound", + binding_status="bound", + exchange_status="eligible", + ) + pf_manual = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="pr-2", + source_order_item_id="pr-2", + platform_order_id="PR-2", + internal_sku_key="sku-pr2", + commodity_id="cid-pr2", + account_id=acc_manual.id, + lease_id=lease_manual.id, + execution_status="manual_required", + binding_status="failed", + exchange_status="not_started", + issue_code="manual_required", + ) + pf_busy = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="pr-5", + source_order_item_id="pr-5", + platform_order_id="PR-5", + internal_sku_key="sku-pr5", + commodity_id="cid-pr5", + account_id=acc_active_pf.id, + lease_id=lease_pf_busy.id, + execution_status="waiting_bind", + binding_status="qr_pending", + exchange_status="not_started", + ) + session.add_all([pf_bound, pf_manual, pf_busy]) + session.flush() + + lease_bound.batch_id = f"pf:{pf_bound.id}" + lease_manual.batch_id = f"pf:{pf_manual.id}" + lease_pf_busy.batch_id = f"pf:{pf_busy.id}" + + archived_orders = [ + collab.DouyuExternalOrder( + order_no="DY-ARCH-1", + source_type=collab.SOURCE_TYPE_PLATFORM_FULFILLMENT, + source_task_id=pf_bound.id, + account_id=acc_bound.id, + account_username=acc_bound.username, + gift_name="礼包1", + home_images=["collab/arch-1.png"], + status=collab.STATUS_DONE, + archived_at=now - timedelta(days=5), + archived_by=admin.id, + owner_id=admin.id, + created_by=admin.id, + ), + collab.DouyuExternalOrder( + order_no="DY-ARCH-2", + source_type=collab.SOURCE_TYPE_PLATFORM_FULFILLMENT, + source_task_id=pf_manual.id, + account_id=acc_manual.id, + account_username=acc_manual.username, + gift_name="礼包2", + home_images=["collab/arch-2.png"], + status=collab.STATUS_DONE, + archived_at=now - timedelta(days=5), + archived_by=admin.id, + owner_id=admin.id, + created_by=admin.id, + ), + collab.DouyuExternalOrder( + order_no="DY-ARCH-3", + account_id=acc_assigned_only.id, + account_username=acc_assigned_only.username, + gift_name="礼包3", + home_images=["collab/arch-3.png"], + status=collab.STATUS_DONE, + archived_at=now - timedelta(days=5), + archived_by=admin.id, + owner_id=admin.id, + created_by=admin.id, + ), + collab.DouyuExternalOrder( + order_no="DY-ARCH-4", + account_id=acc_active_collab.id, + account_username=acc_active_collab.username, + gift_name="礼包4", + home_images=["collab/arch-4.png"], + status=collab.STATUS_DONE, + archived_at=now - timedelta(days=5), + archived_by=admin.id, + owner_id=admin.id, + created_by=admin.id, + ), + collab.DouyuExternalOrder( + order_no="DY-ARCH-5", + account_id=acc_active_pf.id, + account_username=acc_active_pf.username, + gift_name="礼包5", + home_images=["collab/arch-5.png"], + status=collab.STATUS_DONE, + archived_at=now - timedelta(days=5), + archived_by=admin.id, + owner_id=admin.id, + created_by=admin.id, + ), + ] + # Acc 4 还有一个未归档活跃预售单,必须跳过 + unarchived_active = collab.DouyuExternalOrder( + order_no="DY-UNARCH-ACTIVE-4", + account_id=acc_active_collab.id, + account_username=acc_active_collab.username, + gift_name="礼包4-新", + home_images=["collab/unarch-4.png"], + status=collab.STATUS_ROLE_ERROR, + archived_at=None, + owner_id=admin.id, + created_by=admin.id, + ) + session.add_all([*archived_orders, unarchived_active]) + session.commit() + + # 1) 默认预览:不包含 manual_required,但包含清空 assigned_to + preview_default = collab.preview_archived_account_release( + session, + all_archived=True, + include_manual_required=False, + clear_assigned_to=True, + ) + assert preview_default["matched_orders"] == 5 + assert preview_default["total_accounts"] == 5 + assert preview_default["releasable_total"] == 2 # acc_bound + acc_assigned_only + assert preview_default["release_lease_total"] == 1 + assert preview_default["release_platform_bound_count"] == 1 + assert preview_default["clear_assigned_count"] == 2 + assert preview_default["skipped_active_collab"] == 1 + assert preview_default["skipped_active_platform"] == 1 + assert preview_default["skipped_manual_required"] == 1 + assert preview_default["cooldown_ready_count"] == 2 + + # 2) 包含 manual_required 后再执行释放 + result = collab.execute_archived_account_release( + session, + admin, + all_archived=True, + include_manual_required=True, + clear_assigned_to=True, + reason="测试活动结束回池", + ) + assert ( + result["processed_accounts"] == 3 + ) # acc_bound + acc_manual + acc_assigned_only + assert result["released_leases"] == 2 + assert result["closed_platform_tasks"] == 1 + assert result["cancelled_manual_tasks"] == 1 + assert result["cleared_assigned_accounts"] == 3 + assert result["skipped_active_collab"] == 1 + assert result["skipped_active_platform"] == 1 + assert result["cooldown_ready_count"] == 2 + assert result["cooldown_waiting_count"] == 1 + + # 核查数据库状态:历史记录与冷却完整保留,限制解除 + session.refresh(acc_bound) + session.refresh(acc_manual) + session.refresh(acc_assigned_only) + session.refresh(acc_active_collab) + session.refresh(acc_active_pf) + session.refresh(lease_bound) + session.refresh(lease_manual) + session.refresh(lease_collab_busy) + session.refresh(lease_pf_busy) + session.refresh(pf_bound) + session.refresh(pf_manual) + session.refresh(pf_busy) + + assert acc_bound.assigned_to is None + assert acc_manual.assigned_to is None + assert acc_assigned_only.assigned_to is None + # 被保护的账号不得动 + assert acc_active_collab.assigned_to == support.id + assert acc_active_pf.assigned_to == support.id + assert lease_collab_busy.status == "active" + assert lease_pf_busy.status == "active" + assert pf_busy.execution_status == "waiting_bind" + + # 释放后冷却期仍保留 + assert acc_bound.role_change_available_at is not None + assert acc_manual.role_change_available_at is not None + assert lease_bound.status == "released" + assert lease_bound.release_reason == "archived_collab_pool_release" + assert lease_manual.status == "released" + assert pf_bound.execution_status == "completed" + assert pf_manual.execution_status == "cancelled" + assert pf_manual.account_id is None + + # 归档预售单与历史兑换事件一行都没删 + assert ( + session.query(collab.DouyuExternalOrder) + .filter(collab.DouyuExternalOrder.archived_at.isnot(None)) + .count() + == 5 + ) + assert session.get(AccountEvent, exchange_evt.id) is not None + assert ( + session.query(AuditLog) + .filter_by(action="douyu:collab:archived_pool_release") + .count() + == 1 + ) + finally: + session.close() + + +def test_archived_account_release_route_requires_manage_permission(): + engine = get_test_engine() + session = make_test_session(engine) + try: + support = User(username="arch-route-support", password_hash="h", role="support") + operation = User(username="arch-route-op", password_hash="h", role="operation") + session.add_all([support, operation]) + session.commit() + + from fastapi import HTTPException + + from web.backend.deps import require_permission + from web.backend.schemas import DouyuCollabArchivedAccountReleaseRequest + + guard = require_permission("douyu:collab:manage") + with pytest.raises(HTTPException) as excinfo: + guard(support) + assert excinfo.value.status_code == 403 + + allowed = guard(operation) + assert allowed.id == operation.id + + req = DouyuCollabArchivedAccountReleaseRequest(all_archived=True) + preview = collab_api.preview_archived_external_order_account_release( + req, session, operation + ) + assert preview["matched_orders"] == 0 + assert preview["releasable_total"] == 0 + + result = collab_api.release_archived_external_order_accounts( + req, session, operation + ) + assert result["processed_accounts"] == 0 + finally: + session.close() diff --git a/uv.lock b/uv.lock index 97cc1ed..f60fd52 100644 --- a/uv.lock +++ b/uv.lock @@ -381,7 +381,7 @@ wheels = [ [[package]] name = "live-hub-py" -version = "0.4.24" +version = "0.4.25" source = { editable = "." } dependencies = [ { name = "alembic" }, diff --git a/web/backend/routers/douyu_collab.py b/web/backend/routers/douyu_collab.py index 8b147f5..0b4474b 100644 --- a/web/backend/routers/douyu_collab.py +++ b/web/backend/routers/douyu_collab.py @@ -32,6 +32,9 @@ from ..schemas import ( DouyuCollabAccountRecommendRequest, DouyuCollabAccountRequest, DouyuCollabAccountUnlinkRequest, + DouyuCollabArchivedAccountReleaseOut, + DouyuCollabArchivedAccountReleasePreviewOut, + DouyuCollabArchivedAccountReleaseRequest, DouyuCollabArchiveRequest, DouyuCollabCkExportOut, DouyuCollabCkExportRequest, @@ -698,6 +701,69 @@ def unarchive_external_orders( return result +@router.post( + "/external-orders/archived-account-release/preview", + response_model=DouyuCollabArchivedAccountReleasePreviewOut, +) +def preview_archived_external_order_account_release( + req: DouyuCollabArchivedAccountReleaseRequest, + db: Session = Depends(get_db), + _current: User = Depends(require_permission("douyu:collab:manage")), +): + try: + return collab.preview_archived_account_release( + db, + order_ids=req.order_ids, + all_archived=req.all_archived, + status=req.status, + shop=req.shop, + owner_id=req.owner_id, + gift_name=req.gift_name, + keyword=req.keyword, + ck_status=req.ck_status, + include_void=req.include_void, + include_manual_required=req.include_manual_required, + clear_assigned_to=req.clear_assigned_to, + ) + except collab.CollabError as exc: + raise _http_error(exc) from exc + + +@router.post( + "/external-orders/archived-account-release", + response_model=DouyuCollabArchivedAccountReleaseOut, +) +def release_archived_external_order_accounts( + req: DouyuCollabArchivedAccountReleaseRequest, + db: Session = Depends(get_db), + current: User = Depends(require_permission("douyu:collab:manage")), +): + try: + result = collab.execute_archived_account_release( + db, + current, + order_ids=req.order_ids, + all_archived=req.all_archived, + status=req.status, + shop=req.shop, + owner_id=req.owner_id, + gift_name=req.gift_name, + keyword=req.keyword, + ck_status=req.ck_status, + include_void=req.include_void, + include_manual_required=req.include_manual_required, + clear_assigned_to=req.clear_assigned_to, + reason=req.reason, + ) + except collab.CollabError as exc: + raise _http_error(exc) from exc + if result.get("processed_accounts"): + _publish_change( + current, scope="orders", action="order.archived_account_release" + ) + return result + + @router.get( "/external-orders/{order_id}/timeline", response_model=list[DouyuCollabTimelineOut], diff --git a/web/backend/schemas.py b/web/backend/schemas.py index 611c5ee..ae763ab 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -2946,6 +2946,67 @@ class DouyuCollabArchiveRequest(BaseModel): reason: str = Field("", max_length=256) +class DouyuCollabArchivedAccountReleaseRequest(BaseModel): + order_ids: list[int] = Field(default_factory=list) + all_archived: bool = False + status: str = "" + shop: str = "" + owner_id: int | None = None + gift_name: str = "" + keyword: str = "" + ck_status: str = "" + include_void: bool = False + include_manual_required: bool = False + clear_assigned_to: bool = True + reason: str = Field("", max_length=256) + + +class DouyuCollabArchivedAccountReleasePreviewOut(BaseModel): + matched_orders: int = 0 + total_accounts: int = 0 + releasable_total: int = 0 + release_lease_total: int = 0 + release_collab_count: int = 0 + release_platform_bound_count: int = 0 + release_platform_manual_count: int = 0 + clear_assigned_count: int = 0 + already_free_count: int = 0 + skipped_total: int = 0 + skipped_active_collab: int = 0 + skipped_active_platform: int = 0 + skipped_running_task: int = 0 + skipped_manual_required: int = 0 + cooldown_ready_count: int = 0 + cooldown_waiting_count: int = 0 + invalid_ck_count: int = 0 + include_manual_required: bool = False + clear_assigned_to: bool = True + + +class DouyuCollabArchivedAccountReleaseOut(BaseModel): + matched_orders: int = 0 + total_accounts: int = 0 + processed_accounts: int = 0 + released_leases: int = 0 + release_collab_count: int = 0 + release_platform_bound_count: int = 0 + release_platform_manual_count: int = 0 + closed_platform_tasks: int = 0 + cancelled_manual_tasks: int = 0 + cleared_assigned_accounts: int = 0 + already_free_count: int = 0 + skipped_total: int = 0 + skipped_active_collab: int = 0 + skipped_active_platform: int = 0 + skipped_running_task: int = 0 + skipped_manual_required: int = 0 + cooldown_ready_count: int = 0 + cooldown_waiting_count: int = 0 + invalid_ck_count: int = 0 + include_manual_required: bool = False + clear_assigned_to: bool = True + + class DouyuCollabCkExportRequest(BaseModel): """勾选多行,导出关联内部账号的 CK 明文(一次最多 50 条)。""" diff --git a/web/backend/services/douyu_collab_leases.py b/web/backend/services/douyu_collab_leases.py index 7dfd1c1..dafceeb 100644 --- a/web/backend/services/douyu_collab_leases.py +++ b/web/backend/services/douyu_collab_leases.py @@ -2,9 +2,11 @@ from __future__ import annotations -from collections.abc import Mapping +from collections.abc import Mapping, Sequence +from datetime import UTC, datetime from typing import Any +from sqlalchemy import func from sqlalchemy.orm import Session from ..models import ( @@ -18,9 +20,11 @@ from ..models import ( from ..permissions import user_has_permission from .account_events_service import ( CATEGORY_OPS, + EVENT_ASSIGNED, EVENT_LEASE_ACQUIRED, emit, ) +from .account_sync_service import lock_account_row from .audit_service import record_audit from .binding_ownership import role_names_match from .douyu_collab_common import ( @@ -28,10 +32,13 @@ from .douyu_collab_common import ( LEASE_PURPOSE_DOUYU_COLLAB, PLATFORM_TAKEOVER_BLOCKING_TASK_TYPES, SOURCE_TYPE_PLATFORM_FULFILLMENT, + STATUS_DONE, STATUS_FAILED, STATUS_POINTS_ERROR, STATUS_ROLE_ERROR, CollabError, + _now, + _text, ) from .platform_fulfillment.account_selector import ( acquire_account_lease, @@ -442,6 +449,241 @@ def _ensure_order_account_lease( return lease +_DOUYU_TASK_INFLIGHT_STATUSES = ("planned", "pending", "running") +_PF_SAFE_TERMINABLE_STATUSES = frozenset({"bound", "completed", "cancelled"}) +_PF_MANUAL_STATUSES = frozenset({"manual_required"}) +_ARCHIVED_POOL_RELEASE_REASON = "archived_collab_pool_release" +_ARCHIVED_RELEASE_CHUNK_SIZE = 100 + + +def _complete_platform_task_from_collab( + db: Session, + current: User, + *, + task: PlatformFulfillmentTask, + now: datetime, + reason: str, + order: DouyuExternalOrder | None = None, +) -> None: + """预售台账完成/归档/回池时,联动收口处于 bound 的来源履约任务。""" + from .platform_fulfillment.outbox import _emit_order_site_binding_state + from .platform_fulfillment.runtime import _append_event + + task.execution_status = "completed" + if str(task.exchange_status or "") not in {"auto_done", "manual_done"}: + task.exchange_status = "manual_done" + if task.completed_at is None: + task.completed_at = now + task.issue_code = "" + task.last_error = "" + task.operator_id = int(current.id) + task.updated_at = now + task.lease_id = None + _append_event( + db, + int(task.id), + "collab_order_completed", + actor_type="user", + actor_id=int(current.id), + detail={ + "orderId": int(order.id) if order is not None and order.id else None, + "orderNo": str(order.order_no or "") if order is not None else "", + "reason": reason, + }, + ) + _emit_order_site_binding_state(db, int(task.id)) + + +def _cancel_manual_platform_task_from_archived_release( + db: Session, + current: User, + *, + task: PlatformFulfillmentTask, + now: datetime, + reason: str, +) -> None: + """归档账号批量回池时,收口滞留的 manual_required 履约任务。""" + from .douyu_batch_launcher import stop_douyu_batches + from .platform_fulfillment.outbox import _emit_order_site_binding_state + from .platform_fulfillment.runtime import _append_event + + previous_execution_status = task.execution_status + previous_binding_status = task.binding_status + previous_exchange_status = task.exchange_status + previous_account_id = task.account_id + previous_lease_id = task.lease_id + linked_ids = [ + int(value) + for value in (task.bind_task_id, task.exchange_task_id) + if value is not None + ] + linked_tasks = ( + db.query(DouyuTask).filter(DouyuTask.id.in_(linked_ids)).all() + if linked_ids + else [] + ) + stopped_batches = stop_douyu_batches( + [str(linked_task.batch_id or "") for linked_task in linked_tasks] + ) + for linked_task in linked_tasks: + if linked_task.status in _DOUYU_TASK_INFLIGHT_STATUSES: + linked_task.status = "stopped" + linked_task.message = reason[:512] + linked_task.finished_at = now + task.account_id = None + task.lease_id = None + task.bind_task_id = None + task.exchange_task_id = None + task.binding_status = "not_started" + task.execution_status = "cancelled" + task.exchange_status = "not_started" + task.issue_code = "" + task.operator_id = int(current.id) + task.last_error = reason[:2000] + task.updated_at = now + _append_event( + db, + int(task.id), + "task_cancelled", + actor_type="user", + actor_id=int(current.id), + detail={ + "reason": task.last_error, + "previousExecutionStatus": previous_execution_status, + "previousBindingStatus": previous_binding_status, + "previousExchangeStatus": previous_exchange_status, + "releasedAccountId": previous_account_id, + "releasedLeaseId": previous_lease_id, + "stoppedBatches": stopped_batches, + "source": _ARCHIVED_POOL_RELEASE_REASON, + }, + ) + _emit_order_site_binding_state(db, int(task.id)) + + +def _locked_platform_holders_for_lease( + db: Session, + lease: AccountLease, +) -> list[PlatformFulfillmentTask]: + holders = ( + db.query(PlatformFulfillmentTask) + .filter( + PlatformFulfillmentTask.lease_id == int(lease.id), + PlatformFulfillmentTask.execution_status != "cancelled", + ) + .order_by(PlatformFulfillmentTask.id.asc()) + .with_for_update() + .all() + ) + holder_ids = {int(item.id) for item in holders} + if lease.batch_id.startswith("pf:"): + try: + batch_task_id = int(lease.batch_id.removeprefix("pf:")) + except ValueError: + batch_task_id = 0 + if batch_task_id and batch_task_id not in holder_ids: + fallback = ( + db.query(PlatformFulfillmentTask) + .filter(PlatformFulfillmentTask.id == batch_task_id) + .with_for_update() + .first() + ) + if ( + fallback is not None + and fallback.execution_status != "cancelled" + and ( + fallback.lease_id == int(lease.id) + or fallback.account_id == int(lease.account_id) + ) + ): + holders.append(fallback) + return holders + + +def _try_release_platform_lease_from_collab( + db: Session, + current: User, + order: DouyuExternalOrder, + lease: AccountLease, + *, + reason: str, +) -> bool: + """当预售单完成/归档时,若来源履约任务仅停在 bound 或已 completed,联动收口并释放租约。""" + from .platform_fulfillment.runtime import _apply_task_lease_policy + + now = _now() + holders = _locked_platform_holders_for_lease(db, lease) + holder_by_id = {int(item.id): item for item in holders} + + source_task: PlatformFulfillmentTask | None = None + if order.source_type == SOURCE_TYPE_PLATFORM_FULFILLMENT and order.source_task_id: + source_id = int(order.source_task_id) + source_task = holder_by_id.get(source_id) + if source_task is None: + candidate = ( + db.query(PlatformFulfillmentTask) + .filter(PlatformFulfillmentTask.id == source_id) + .with_for_update() + .first() + ) + if candidate is not None and ( + candidate.lease_id == int(lease.id) + or lease.batch_id == f"pf:{source_id}" + ): + source_task = candidate + if candidate.execution_status != "cancelled": + holder_by_id[source_id] = candidate + holders.append(candidate) + + all_holder_ids = list(holder_by_id.keys()) + if all_holder_ids: + running_douyu_task = ( + db.query(DouyuTask.id) + .filter( + DouyuTask.platform_task_id.in_(all_holder_ids), + DouyuTask.status.in_(_DOUYU_TASK_INFLIGHT_STATUSES), + ) + .first() + ) + if running_douyu_task is not None: + return False + + source_is_bound = bool( + source_task is not None and source_task.execution_status == "bound" + ) + other_active_holders = [ + item + for item in holders + if (not source_is_bound or int(item.id) != int(source_task.id)) # type: ignore[union-attr] + and str(item.execution_status or "") not in {"completed", "cancelled"} + ] + if source_is_bound and source_task is not None: + _complete_platform_task_from_collab( + db, + current, + task=source_task, + now=now, + reason=reason, + order=order, + ) + if other_active_holders: + next_holder = min( + other_active_holders, + key=lambda item: int(item.id), + ) + if lease.batch_id == f"pf:{int(source_task.id)}": + lease.batch_id = f"pf:{int(next_holder.id)}"[:64] + _apply_task_lease_policy(db, next_holder, lease=lease, now=now) + return False + elif not holders or other_active_holders: + return False + + for item in holders: + if item.execution_status == "completed" and item.lease_id == int(lease.id): + item.lease_id = None + return release_lease(db, lease, reason=reason, now=now, commit=False) + + def _release_order_account_lease( db: Session, current: User, @@ -449,6 +691,7 @@ def _release_order_account_lease( *, reason: str, account_id: int | None = None, + allow_close_platform_bound: bool = False, commit: bool = False, ) -> bool: target_account_id = int(account_id or order.account_id or 0) @@ -456,10 +699,22 @@ def _release_order_account_lease( 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: + lock_account_row(db, target_account_id) + lease = _lock_active_lease_for_account(db, target_account_id) + if lease is None: + return False + if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB: + released = release_lease(db, lease, reason=reason, commit=False) + elif lease.purpose == "platform_fulfillment" and allow_close_platform_bound: + released = _try_release_platform_lease_from_collab( + db, + current, + order, + lease, + reason=reason, + ) + else: return False - released = release_lease(db, lease, reason=reason, commit=False) if released: _audit_lease_action( db, @@ -488,6 +743,7 @@ def _sync_order_lease( force_active: bool = False, reuse_active_lease: bool = False, incoming_role: str = "", + allow_close_platform_bound: bool = False, commit: bool = False, ) -> AccountLease | None: if force_active or _order_occupies_account(order): @@ -525,11 +781,15 @@ def _sync_order_lease( incoming_role=incoming_role, commit=commit, ) + should_close_pf = allow_close_platform_bound or ( + order.status == STATUS_DONE or order.archived_at is not None + ) _release_order_account_lease( db, current, order, reason=reason, + allow_close_platform_bound=should_close_pf, commit=commit, ) return None @@ -638,3 +898,590 @@ def retain_lease_for_active_collab( if commit: db.commit() return active_lease + + +def _as_utc(value: datetime | None) -> datetime | None: + if value is None: + return None + return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC) + + +def _chunked(values: Sequence[int], size: int) -> list[list[int]]: + return [list(values[idx : idx + size]) for idx in range(0, len(values), size)] + + +def _parse_pf_batch_task_id(batch_id: str | None) -> int: + text = str(batch_id or "") + if not text.startswith("pf:"): + return 0 + try: + return int(text.removeprefix("pf:")) + except ValueError: + return 0 + + +def _resolve_archived_target_scope( + db: Session, + *, + order_ids: Sequence[int] = (), + all_archived: bool = False, + status: str = "", + shop: str = "", + owner_id: int | None = None, + gift_name: str = "", + keyword: str = "", + ck_status: str = "", + include_void: bool = False, +) -> tuple[int, list[int]]: + from .douyu_collab_query import _apply_order_filters, _base_order_query + + if all_archived: + query = _apply_order_filters( + db, + _base_order_query(db), + include_void=include_void, + archive_scope="archived", + status=status, + shop=shop, + owner_id=owner_id, + gift_name=gift_name, + keyword=keyword, + ck_status=ck_status, + ).filter(DouyuExternalOrder.archived_at.isnot(None)) + else: + clean_ids = [int(item) for item in order_ids if int(item) > 0] + if not clean_ids: + raise CollabError( + "请先勾选已归档订单,或选择释放当前筛选下全部归档账号", + code="order_ids_required", + ) + query = db.query(DouyuExternalOrder).filter( + DouyuExternalOrder.id.in_(clean_ids), + DouyuExternalOrder.archived_at.isnot(None), + ) + + matched_orders = ( + query.order_by(None).with_entities(func.count(DouyuExternalOrder.id)).scalar() + or 0 + ) + account_rows = ( + query.order_by(None) + .filter(DouyuExternalOrder.account_id.isnot(None)) + .with_entities(DouyuExternalOrder.account_id) + .distinct() + .all() + ) + account_ids = sorted({int(row[0]) for row in account_rows if row[0]}) + return int(matched_orders), account_ids + + +def _analyze_archived_accounts_plan( + db: Session, + account_ids: Sequence[int], + *, + include_manual_required: bool, + clear_assigned_to: bool, + now: datetime, +) -> dict[str, Any]: + counts: dict[str, int] = { + "total_accounts": 0, + "releasable_total": 0, + "release_lease_total": 0, + "release_collab_count": 0, + "release_platform_bound_count": 0, + "release_platform_manual_count": 0, + "clear_assigned_count": 0, + "already_free_count": 0, + "skipped_total": 0, + "skipped_active_collab": 0, + "skipped_active_platform": 0, + "skipped_running_task": 0, + "skipped_manual_required": 0, + "cooldown_ready_count": 0, + "cooldown_waiting_count": 0, + "invalid_ck_count": 0, + } + actionable_account_ids: list[int] = [] + if not account_ids: + return {**counts, "actionable_account_ids": actionable_account_ids} + + now_utc = _as_utc(now) or now + accounts_by_id: dict[int, Account] = {} + active_collab_ids: set[int] = set() + running_task_account_ids: set[int] = set() + active_leases_by_account: dict[int, AccountLease] = {} + + for chunk in _chunked(list(account_ids), 1000): + for acc in db.query(Account).filter(Account.id.in_(chunk)).all(): + accounts_by_id[int(acc.id)] = acc + for (aid,) in ( + db.query(DouyuExternalOrder.account_id) + .filter( + DouyuExternalOrder.account_id.in_(chunk), + DouyuExternalOrder.archived_at.is_(None), + DouyuExternalOrder.status.in_(COLLAB_LEASE_STATUSES), + ) + .distinct() + .all() + ): + if aid: + active_collab_ids.add(int(aid)) + for (aid,) in ( + db.query(DouyuTask.account_id) + .filter( + DouyuTask.account_id.in_(chunk), + DouyuTask.status.in_(_DOUYU_TASK_INFLIGHT_STATUSES), + ) + .distinct() + .all() + ): + if aid: + running_task_account_ids.add(int(aid)) + for lease in ( + db.query(AccountLease) + .filter( + AccountLease.account_id.in_(chunk), + AccountLease.status == "active", + ) + .all() + ): + active_leases_by_account[int(lease.account_id)] = lease + + lease_ids = [int(lease.id) for lease in active_leases_by_account.values()] + batch_task_ids = { + parsed + for lease in active_leases_by_account.values() + if lease.purpose == "platform_fulfillment" + and (parsed := _parse_pf_batch_task_id(lease.batch_id)) > 0 + } + holders_by_lease: dict[int, list[PlatformFulfillmentTask]] = {} + pf_tasks_by_id: dict[int, PlatformFulfillmentTask] = {} + if lease_ids: + for chunk in _chunked(lease_ids, 1000): + for task in ( + db.query(PlatformFulfillmentTask) + .filter( + PlatformFulfillmentTask.lease_id.in_(chunk), + PlatformFulfillmentTask.execution_status != "cancelled", + ) + .all() + ): + pf_tasks_by_id[int(task.id)] = task + if task.lease_id: + holders_by_lease.setdefault(int(task.lease_id), []).append(task) + missing_batch_ids = sorted(batch_task_ids - set(pf_tasks_by_id.keys())) + if missing_batch_ids: + for chunk in _chunked(missing_batch_ids, 1000): + for task in ( + db.query(PlatformFulfillmentTask) + .filter( + PlatformFulfillmentTask.id.in_(chunk), + PlatformFulfillmentTask.execution_status != "cancelled", + ) + .all() + ): + pf_tasks_by_id[int(task.id)] = task + + running_pf_task_ids: set[int] = set() + if pf_tasks_by_id: + for chunk in _chunked(list(pf_tasks_by_id.keys()), 1000): + for (pt_id,) in ( + db.query(DouyuTask.platform_task_id) + .filter( + DouyuTask.platform_task_id.in_(chunk), + DouyuTask.status.in_(_DOUYU_TASK_INFLIGHT_STATUSES), + ) + .distinct() + .all() + ): + if pt_id: + running_pf_task_ids.add(int(pt_id)) + + for account_id in account_ids: + account = accounts_by_id.get(int(account_id)) + if account is None: + continue + counts["total_accounts"] += 1 + if int(account_id) in active_collab_ids: + counts["skipped_active_collab"] += 1 + counts["skipped_total"] += 1 + continue + if int(account_id) in running_task_account_ids: + counts["skipped_running_task"] += 1 + counts["skipped_total"] += 1 + continue + + lease = active_leases_by_account.get(int(account_id)) + lease_action = "none" + if lease is not None: + if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB: + lease_action = "release_collab" + elif lease.purpose == "platform_fulfillment": + holders = list(holders_by_lease.get(int(lease.id), ())) + batch_tid = _parse_pf_batch_task_id(lease.batch_id) + if batch_tid and all(int(t.id) != batch_tid for t in holders): + fallback = pf_tasks_by_id.get(batch_tid) + if fallback is not None and ( + fallback.lease_id == int(lease.id) + or fallback.account_id == int(account_id) + ): + holders.append(fallback) + if any(int(t.id) in running_pf_task_ids for t in holders): + counts["skipped_running_task"] += 1 + counts["skipped_total"] += 1 + continue + statuses = {str(t.execution_status or "") for t in holders} + non_terminable = ( + statuses - _PF_SAFE_TERMINABLE_STATUSES - _PF_MANUAL_STATUSES + ) + if non_terminable: + counts["skipped_active_platform"] += 1 + counts["skipped_total"] += 1 + continue + if statuses & _PF_MANUAL_STATUSES: + if include_manual_required: + lease_action = "release_platform_manual" + else: + counts["skipped_manual_required"] += 1 + counts["skipped_total"] += 1 + continue + else: + lease_action = "release_platform_bound" + else: + counts["skipped_active_platform"] += 1 + counts["skipped_total"] += 1 + continue + + needs_clear_assigned = bool( + clear_assigned_to and account.assigned_to is not None + ) + if lease_action == "none" and not needs_clear_assigned: + counts["already_free_count"] += 1 + continue + + actionable_account_ids.append(int(account_id)) + counts["releasable_total"] += 1 + if lease_action != "none": + counts["release_lease_total"] += 1 + counts[f"{lease_action}_count"] += 1 + if needs_clear_assigned: + counts["clear_assigned_count"] += 1 + + if account.status == "active" and account.ck_check_status == "valid": + cooldown_at = _as_utc(account.role_change_available_at) + if cooldown_at is None or cooldown_at <= now_utc: + counts["cooldown_ready_count"] += 1 + else: + counts["cooldown_waiting_count"] += 1 + else: + counts["invalid_ck_count"] += 1 + + return {**counts, "actionable_account_ids": actionable_account_ids} + + +def preview_archived_account_release( + db: Session, + *, + order_ids: Sequence[int] = (), + all_archived: bool = False, + status: str = "", + shop: str = "", + owner_id: int | None = None, + gift_name: str = "", + keyword: str = "", + ck_status: str = "", + include_void: bool = False, + include_manual_required: bool = False, + clear_assigned_to: bool = True, +) -> dict[str, Any]: + now = _now() + matched_orders, account_ids = _resolve_archived_target_scope( + db, + order_ids=order_ids, + all_archived=all_archived, + status=status, + shop=shop, + owner_id=owner_id, + gift_name=gift_name, + keyword=keyword, + ck_status=ck_status, + include_void=include_void, + ) + plan = _analyze_archived_accounts_plan( + db, + account_ids, + include_manual_required=include_manual_required, + clear_assigned_to=clear_assigned_to, + now=now, + ) + plan.pop("actionable_account_ids", None) + return { + "matched_orders": matched_orders, + "include_manual_required": bool(include_manual_required), + "clear_assigned_to": bool(clear_assigned_to), + **plan, + } + + +def execute_archived_account_release( + db: Session, + current: User, + *, + order_ids: Sequence[int] = (), + all_archived: bool = False, + status: str = "", + shop: str = "", + owner_id: int | None = None, + gift_name: str = "", + keyword: str = "", + ck_status: str = "", + include_void: bool = False, + include_manual_required: bool = False, + clear_assigned_to: bool = True, + reason: str = "", +) -> dict[str, Any]: + now = _now() + now_utc = _as_utc(now) or now + current_id = int(current.id) + clean_reason = _text(reason, max_length=256) or "活动结束,归档账号批量释放回号池" + matched_orders, account_ids = _resolve_archived_target_scope( + db, + order_ids=order_ids, + all_archived=all_archived, + status=status, + shop=shop, + owner_id=owner_id, + gift_name=gift_name, + keyword=keyword, + ck_status=ck_status, + include_void=include_void, + ) + plan = _analyze_archived_accounts_plan( + db, + account_ids, + include_manual_required=include_manual_required, + clear_assigned_to=clear_assigned_to, + now=now, + ) + actionable_ids: list[int] = list(plan.get("actionable_account_ids") or []) + + released_leases = 0 + release_collab_count = 0 + release_platform_bound_count = 0 + release_platform_manual_count = 0 + closed_platform_tasks = 0 + cancelled_manual_tasks = 0 + cleared_assigned_accounts = 0 + processed_accounts = 0 + cooldown_ready_count = 0 + cooldown_waiting_count = 0 + invalid_ck_count = 0 + + skipped_active_collab = int(plan["skipped_active_collab"]) + skipped_active_platform = int(plan["skipped_active_platform"]) + skipped_running_task = int(plan["skipped_running_task"]) + skipped_manual_required = int(plan["skipped_manual_required"]) + already_free_count = int(plan["already_free_count"]) + + for chunk in _chunked(actionable_ids, _ARCHIVED_RELEASE_CHUNK_SIZE): + actor = db.get(User, current_id) or current + chunk_now = _now() + for account_id in chunk: + lock_account_row(db, account_id) + account = db.get(Account, int(account_id)) + if account is None: + continue + if _active_collab_order(db, account_id) is not None: + skipped_active_collab += 1 + continue + running_account_task = ( + db.query(DouyuTask.id) + .filter( + DouyuTask.account_id == int(account_id), + DouyuTask.status.in_(_DOUYU_TASK_INFLIGHT_STATUSES), + ) + .first() + ) + if running_account_task is not None: + skipped_running_task += 1 + continue + + lease = _lock_active_lease_for_account(db, account_id) + released_here = False + if lease is not None: + if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB: + if release_lease( + db, + lease, + reason=_ARCHIVED_POOL_RELEASE_REASON, + now=chunk_now, + commit=False, + ): + released_here = True + released_leases += 1 + release_collab_count += 1 + elif lease.purpose == "platform_fulfillment": + holders = _locked_platform_holders_for_lease(db, lease) + holder_ids = [int(item.id) for item in holders] + if holder_ids: + running_pf = ( + db.query(DouyuTask.id) + .filter( + DouyuTask.platform_task_id.in_(holder_ids), + DouyuTask.status.in_(_DOUYU_TASK_INFLIGHT_STATUSES), + ) + .first() + ) + if running_pf is not None: + skipped_running_task += 1 + continue + statuses = {str(item.execution_status or "") for item in holders} + non_terminable = ( + statuses - _PF_SAFE_TERMINABLE_STATUSES - _PF_MANUAL_STATUSES + ) + if non_terminable: + skipped_active_platform += 1 + continue + has_manual = bool(statuses & _PF_MANUAL_STATUSES) + if has_manual and not include_manual_required: + skipped_manual_required += 1 + continue + for holder in holders: + if holder.execution_status == "bound": + _complete_platform_task_from_collab( + db, + actor, + task=holder, + now=chunk_now, + reason=clean_reason, + ) + closed_platform_tasks += 1 + elif ( + holder.execution_status == "manual_required" + and include_manual_required + ): + _cancel_manual_platform_task_from_archived_release( + db, + actor, + task=holder, + now=chunk_now, + reason=clean_reason, + ) + cancelled_manual_tasks += 1 + elif ( + holder.execution_status == "completed" + and holder.lease_id == int(lease.id) + ): + holder.lease_id = None + if release_lease( + db, + lease, + reason=_ARCHIVED_POOL_RELEASE_REASON, + now=chunk_now, + commit=False, + ): + released_here = True + released_leases += 1 + if has_manual: + release_platform_manual_count += 1 + else: + release_platform_bound_count += 1 + else: + skipped_active_platform += 1 + continue + + cleared_here = False + if clear_assigned_to and account.assigned_to is not None: + previous_assigned = int(account.assigned_to) + account.assigned_to = None + db.query(DouyuTask).filter( + DouyuTask.account_id == int(account.id) + ).update( + {DouyuTask.account_assigned_to: None}, + synchronize_session=False, + ) + emit( + db, + account_id=int(account.id), + event_type=EVENT_ASSIGNED, + title="归档账号释放回公共号池", + category=CATEGORY_OPS, + detail={ + "previous_assigned_to": previous_assigned, + "assigned_to": None, + "reason": clean_reason, + }, + source="lease", + actor_type="user", + actor_id=current_id, + ) + cleared_here = True + cleared_assigned_accounts += 1 + + if released_here or cleared_here: + processed_accounts += 1 + if account.status == "active" and account.ck_check_status == "valid": + cooldown_at = _as_utc(account.role_change_available_at) + if cooldown_at is None or cooldown_at <= now_utc: + cooldown_ready_count += 1 + else: + cooldown_waiting_count += 1 + else: + invalid_ck_count += 1 + else: + already_free_count += 1 + db.commit() + + actor = db.get(User, current_id) or current + skipped_total = ( + skipped_active_collab + + skipped_active_platform + + skipped_running_task + + skipped_manual_required + ) + record_audit( + db, + actor, + action="douyu:collab:archived_pool_release", + target="douyu_collab:archived_pool_release", + detail={ + "matched_orders": matched_orders, + "total_accounts": int(plan["total_accounts"]), + "processed_accounts": processed_accounts, + "released_leases": released_leases, + "release_collab_count": release_collab_count, + "release_platform_bound_count": release_platform_bound_count, + "release_platform_manual_count": release_platform_manual_count, + "closed_platform_tasks": closed_platform_tasks, + "cancelled_manual_tasks": cancelled_manual_tasks, + "cleared_assigned_accounts": cleared_assigned_accounts, + "skipped_total": skipped_total, + "include_manual_required": bool(include_manual_required), + "clear_assigned_to": bool(clear_assigned_to), + "reason": clean_reason, + }, + ) + db.commit() + return { + "matched_orders": matched_orders, + "total_accounts": int(plan["total_accounts"]), + "processed_accounts": processed_accounts, + "released_leases": released_leases, + "release_collab_count": release_collab_count, + "release_platform_bound_count": release_platform_bound_count, + "release_platform_manual_count": release_platform_manual_count, + "closed_platform_tasks": closed_platform_tasks, + "cancelled_manual_tasks": cancelled_manual_tasks, + "cleared_assigned_accounts": cleared_assigned_accounts, + "already_free_count": already_free_count, + "skipped_total": skipped_total, + "skipped_active_collab": skipped_active_collab, + "skipped_active_platform": skipped_active_platform, + "skipped_running_task": skipped_running_task, + "skipped_manual_required": skipped_manual_required, + "cooldown_ready_count": cooldown_ready_count, + "cooldown_waiting_count": cooldown_waiting_count, + "invalid_ck_count": invalid_ck_count, + "include_manual_required": bool(include_manual_required), + "clear_assigned_to": bool(clear_assigned_to), + } diff --git a/web/backend/services/douyu_collab_service.py b/web/backend/services/douyu_collab_service.py index 869298f..729b805 100644 --- a/web/backend/services/douyu_collab_service.py +++ b/web/backend/services/douyu_collab_service.py @@ -156,6 +156,8 @@ from .douyu_collab_leases import ( _ensure_order_account_lease, _release_order_account_lease, _sync_order_lease, + execute_archived_account_release, + preview_archived_account_release, retain_lease_for_active_collab, ) from .douyu_collab_query import ( @@ -1647,6 +1649,7 @@ def set_status( current, order, reuse_active_lease=True, + allow_close_platform_bound=(target == STATUS_DONE), reason=( "douyu_collab_done" if target == STATUS_DONE @@ -2349,6 +2352,7 @@ def archive_orders( current, order, reason="douyu_collab_archived", + allow_close_platform_bound=True, ) db.commit() return {"archived": archived} diff --git a/web/frontend/src/api/douyuCollab.ts b/web/frontend/src/api/douyuCollab.ts index 817c415..12a22f2 100644 --- a/web/frontend/src/api/douyuCollab.ts +++ b/web/frontend/src/api/douyuCollab.ts @@ -356,6 +356,67 @@ export interface DouyuCollabBatchQueryItem { message?: string; } +export interface DouyuCollabArchivedAccountReleaseRequest { + order_ids?: number[]; + all_archived?: boolean; + status?: string; + shop?: string; + owner_id?: number; + gift_name?: string; + keyword?: string; + ck_status?: string; + include_void?: boolean; + include_manual_required?: boolean; + clear_assigned_to?: boolean; + reason?: string; +} + +export interface DouyuCollabArchivedAccountReleasePreview { + matched_orders: number; + total_accounts: number; + releasable_total: number; + release_lease_total: number; + release_collab_count: number; + release_platform_bound_count: number; + release_platform_manual_count: number; + clear_assigned_count: number; + already_free_count: number; + skipped_total: number; + skipped_active_collab: number; + skipped_active_platform: number; + skipped_running_task: number; + skipped_manual_required: number; + cooldown_ready_count: number; + cooldown_waiting_count: number; + invalid_ck_count: number; + include_manual_required: boolean; + clear_assigned_to: boolean; +} + +export interface DouyuCollabArchivedAccountReleaseResult { + matched_orders: number; + total_accounts: number; + processed_accounts: number; + released_leases: number; + release_collab_count: number; + release_platform_bound_count: number; + release_platform_manual_count: number; + closed_platform_tasks: number; + cancelled_manual_tasks: number; + cleared_assigned_accounts: number; + already_free_count: number; + skipped_total: number; + skipped_active_collab: number; + skipped_active_platform: number; + skipped_running_task: number; + skipped_manual_required: number; + cooldown_ready_count: number; + cooldown_waiting_count: number; + invalid_ck_count: number; + include_manual_required: boolean; + clear_assigned_to: boolean; +} + export const douyuCollabApi = { listOrders: (params: { page?: number; @@ -547,6 +608,16 @@ export const douyuCollabApi = { api.post<{ archived: number }, { archived: number }>('/douyu/external-orders/archive', { ids, reason }), unarchive: (ids: number[]) => api.post<{ unarchived: number }, { unarchived: number }>('/douyu/external-orders/unarchive', ids), + previewArchivedAccountRelease: (data: DouyuCollabArchivedAccountReleaseRequest) => + api.post( + '/douyu/external-orders/archived-account-release/preview', + data, + ), + releaseArchivedAccounts: (data: DouyuCollabArchivedAccountReleaseRequest) => + api.post( + '/douyu/external-orders/archived-account-release', + data, + ), timeline: (id: number) => api.get(`/douyu/external-orders/${id}/timeline`), metrics: (id: number) => diff --git a/web/frontend/src/pages/DouyuCollabPage.tsx b/web/frontend/src/pages/DouyuCollabPage.tsx index 0575629..17adcbc 100644 --- a/web/frontend/src/pages/DouyuCollabPage.tsx +++ b/web/frontend/src/pages/DouyuCollabPage.tsx @@ -17,6 +17,7 @@ import { Input, InputNumber, Modal, + Radio, Row, Select, Space, @@ -64,6 +65,7 @@ import type { DouyuCollabAccountCandidate, DouyuCollabAccountLookup, DouyuCollabAccountRecommendation, + DouyuCollabArchivedAccountReleasePreview, DouyuCollabCkExportResult, DouyuCollabExchangeRecord, DouyuCollabExchangeRecordsResponse, @@ -224,6 +226,17 @@ export default function DouyuCollabPage() { const [usernameExport, setUsernameExport] = useState(null); + const [archivedReleaseOpen, setArchivedReleaseOpen] = useState(false); + const [archivedReleaseScope, setArchivedReleaseScope] = useState<'selected' | 'all_archived'>('all_archived'); + const [archivedReleaseIncludeManual, setArchivedReleaseIncludeManual] = useState(false); + const [archivedReleaseClearAssigned, setArchivedReleaseClearAssigned] = useState(true); + const [archivedReleaseReason, setArchivedReleaseReason] = useState(''); + const [archivedReleasePreview, setArchivedReleasePreview] = + useState(null); + const [archivedReleaseLoading, setArchivedReleaseLoading] = useState(false); + const [archivedReleaseSubmitting, setArchivedReleaseSubmitting] = useState(false); + const archivedReleaseSeq = useRef(0); + // 切换标签/筛选后旧勾选可能已不在当前结果里,批量操作前必须清空,避免误改其他状态的单。 const resetFilterState = useCallback(() => { setPage(1); @@ -317,7 +330,8 @@ export default function DouyuCollabPage() { ckExportOpen || usernameExportOpen || unlinkOpen || - recommendOpen, + recommendOpen || + archivedReleaseOpen, ); // 暂停后连 WebSocket 也不建:既不自动重拉,也不做断线兜底轮询。 const realtimeSyncEnabled = canView && !realtimePaused; @@ -1230,6 +1244,107 @@ export default function DouyuCollabPage() { } }; + const buildArchivedReleasePayload = useCallback( + ( + scopeMode: 'selected' | 'all_archived', + includeManual: boolean, + clearAssigned: boolean, + reasonText = '', + ) => ({ + order_ids: scopeMode === 'selected' ? selectedIds : [], + all_archived: scopeMode === 'all_archived', + status: statusFilter || undefined, + shop: shopFilter || undefined, + owner_id: ownerFilter, + gift_name: giftFilter || undefined, + keyword: keyword.trim() || undefined, + ck_status: ckFilter || undefined, + include_void: includeVoid, + include_manual_required: includeManual, + clear_assigned_to: clearAssigned, + reason: reasonText.trim() || undefined, + }), + [ + selectedIds, + statusFilter, + shopFilter, + ownerFilter, + giftFilter, + keyword, + ckFilter, + includeVoid, + ], + ); + + const loadArchivedReleasePreview = useCallback( + async ( + scopeMode: 'selected' | 'all_archived', + includeManual: boolean, + clearAssigned: boolean, + ) => { + const seq = ++archivedReleaseSeq.current; + setArchivedReleaseLoading(true); + try { + const preview = await douyuCollabApi.previewArchivedAccountRelease( + buildArchivedReleasePayload(scopeMode, includeManual, clearAssigned), + ); + if (seq !== archivedReleaseSeq.current) return; + setArchivedReleasePreview(preview); + } catch (error) { + if (seq === archivedReleaseSeq.current) { + message.error(getErrorMessage(error)); + } + } finally { + if (seq === archivedReleaseSeq.current) { + setArchivedReleaseLoading(false); + } + } + }, + [buildArchivedReleasePayload], + ); + + const openArchivedReleaseModal = () => { + const defaultScope: 'selected' | 'all_archived' = + selectedIds.length > 0 ? 'selected' : 'all_archived'; + setArchivedReleaseScope(defaultScope); + setArchivedReleaseIncludeManual(false); + setArchivedReleaseClearAssigned(true); + setArchivedReleaseReason(''); + setArchivedReleasePreview(null); + setArchivedReleaseOpen(true); + void loadArchivedReleasePreview(defaultScope, false, true); + }; + + const closeArchivedReleaseModal = () => { + archivedReleaseSeq.current += 1; + setArchivedReleaseOpen(false); + setArchivedReleasePreview(null); + }; + + const submitArchivedRelease = async () => { + setArchivedReleaseSubmitting(true); + try { + const result = await douyuCollabApi.releaseArchivedAccounts( + buildArchivedReleasePayload( + archivedReleaseScope, + archivedReleaseIncludeManual, + archivedReleaseClearAssigned, + archivedReleaseReason, + ), + ); + closeArchivedReleaseModal(); + message.success( + `已释放 ${result.processed_accounts} 个归档账号回公共号库(解除租约 ${result.released_leases} 个,清空专属归属 ${result.cleared_assigned_accounts} 个;其中 ${result.cooldown_ready_count} 个已过换绑冷却可立即可用)`, + ); + setSelectedRowKeys([]); + refreshAll(); + } catch (error) { + message.error(getErrorMessage(error)); + } finally { + setArchivedReleaseSubmitting(false); + } + }; + const batchArchive = () => { if (!canArchiveSelected) { message.warning('只有勾选的抢购成功订单才能批量归档'); @@ -1237,7 +1352,7 @@ export default function DouyuCollabPage() { } modal.confirm({ title: `归档选中的 ${selectedIds.length} 单?`, - content: '归档后这些订单在「查看归档」里只读展示,需要继续操作时可取消归档。', + content: '归档后这些订单在「查看归档」里只读保留历史记录;若账号没有其他活跃单据,会自动收口来源履约单并释放租约(换绑冷却时间不变),需要继续操作时也可取消归档。', onOk: async () => { try { const result = await douyuCollabApi.archive(selectedIds, ''); @@ -2055,6 +2170,18 @@ export default function DouyuCollabPage() { 批量取消归档{selectedCount > 0 ? `(${selectedCount})` : ''} )} + {canManage && archiveScope === 'archived' && ( + + + + )} {canEdit && (