diff --git a/tests/test_douyu_collab_orders.py b/tests/test_douyu_collab_orders.py index 6ac4192..e2a496a 100644 --- a/tests/test_douyu_collab_orders.py +++ b/tests/test_douyu_collab_orders.py @@ -477,9 +477,7 @@ class TestDouyuCollabOrders: include_rebindable=False, limit=5, ) - assert [item["account_id"] for item in unbound_only["candidates"]] == [ - empty.id - ] + assert [item["account_id"] for item in unbound_only["candidates"]] == [empty.id] def test_create_strict_order_uses_internal_account_and_advances(self): order = collab.create_order( @@ -2699,11 +2697,15 @@ class TestDouyuCollabOrders: ) wrong_role_record = { - **exchange_record(name="冥河战士大礼包", commodity_id="20260120QYOOB_bag413"), + **exchange_record( + name="冥河战士大礼包", commodity_id="20260120QYOOB_bag413" + ), "showName": "其他角色(安卓(android)-微信)", } matched_record = { - **exchange_record(name="冥河战士大礼包", commodity_id="20260120QYOOB_bag413"), + **exchange_record( + name="冥河战士大礼包", commodity_id="20260120QYOOB_bag413" + ), "showName": "角色A(苹果(iOS)-微信)", "score": "8000", } @@ -2733,3 +2735,85 @@ class TestDouyuCollabOrders: ) assert result["verdict"] == collab.VERDICT_SUCCESS assert result["order"].status == collab.STATUS_DONE + + +def test_collab_takeover_blocked_when_shared_lease_has_other_active_platform_task(): + engine = get_test_engine() + session = make_test_session(engine) + try: + admin = User( + username="collab-shared-admin", password_hash="h", role="super_admin" + ) + acc = Account( + username="collab-shared-acc", + password="p", + email="collab-shared@example.com", + email_password="ep", + status="active", + ck_check_status="valid", + cookie="PHPSESSID=x", + elite_opened=True, + points=5000, + gold_balance=1000, + ) + session.add_all([admin, acc]) + session.flush() + lease = AccountLease( + account_id=acc.id, + holder_user_id=admin.id, + scope="elite", + purpose="platform_fulfillment", + batch_id="pf:1", + status="active", + ) + session.add(lease) + session.flush() + t1 = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="cs-1", + source_order_item_id="cs-1", + platform_order_id="CS-1", + internal_sku_key="sku-1", + commodity_id="cid-1", + account_id=acc.id, + lease_id=lease.id, + execution_status="bound", + binding_status="bound", + exchange_status="eligible", + ) + t2 = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="cs-2", + source_order_item_id="cs-2", + platform_order_id="CS-2", + internal_sku_key="sku-2", + commodity_id="cid-2", + account_id=acc.id, + lease_id=lease.id, + execution_status="bound", + binding_status="bound", + exchange_status="eligible", + ) + session.add_all([t1, t2]) + session.flush() + lease.batch_id = f"pf:{t1.id}" + session.commit() + + with pytest.raises(collab.CollabError) as excinfo: + collab.create_order( + session, + admin, + order_no="DY-SHARED-BLOCKED", + shop="店铺A", + account_username="collab-shared-acc", + gift_name="礼包A", + required_points=100, + home_images=["collab/home-shared.png"], + takeover_platform_lease=True, + client=FakeClient(), + ) + assert excinfo.value.code == "account_lease_conflict" + assert lease.status == "active" + assert lease.purpose == "platform_fulfillment" + finally: + session.close() diff --git a/tests/test_migrations.py b/tests/test_migrations.py index 0b17432..da6f30d 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -45,7 +45,7 @@ TESTS_DIR = Path(__file__).resolve().parent PROJECT_ROOT = TESTS_DIR.parent VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions" -HEAD_REVISION = "20261125_0135" +HEAD_REVISION = "20261128_0136" # 迁移新增、但不声明在模型里的复合查询索引。 EXTRA_INDEXES = ( @@ -108,6 +108,9 @@ _LATER_ORM_COLUMNS = { "store_status": "INTEGER NULL", "open_status": "INTEGER NULL", }, + "platform_fulfillment_settings": { + "allocation_policy_json": "JSON NULL", + }, } @@ -302,10 +305,10 @@ class TestMigrationSmoke: "(user_id, username, action, target, detail, success, created_at) " "VALUES " "(NULL, 'migration-test', 'douyu:collab:status', :target, " - "'{\"from\":\"scripted\",\"to\":\"done\"}', 1, " + '\'{"from":"scripted","to":"done"}\', 1, ' "'2026-11-02 10:00:00'), " "(NULL, 'migration-test', 'douyu:collab:status', :target, " - "'{\"from\":\"done\",\"to\":\"to_recharge\"}', 1, " + '\'{"from":"done","to":"to_recharge"}\', 1, ' "'2026-11-03 10:00:00')" ), {"target": f"douyu_external_order:{rolled_back_id}"}, @@ -320,10 +323,7 @@ class TestMigrationSmoke: "FROM douyu_external_orders ORDER BY id" ) ).mappings() - succeeded = { - row["order_no"]: row["succeeded_at"] - for row in rows - } + succeeded = {row["order_no"]: row["succeeded_at"] for row in rows} assert succeeded["DY-MIG-DONE"] is not None assert succeeded["DY-MIG-ROLLED-BACK"] is not None assert succeeded["DY-MIG-ACTIVE"] is None @@ -804,24 +804,32 @@ class TestMigrationSmoke: command.upgrade(cfg, "head") with mig_engine.begin() as conn: - shops = conn.execute( - text( - """ + shops = ( + conn.execute( + text( + """ SELECT name, aliases FROM douyu_collab_shops ORDER BY id """ + ) ) - ).mappings().all() - order = conn.execute( - text( - """ + .mappings() + .all() + ) + order = ( + conn.execute( + text( + """ SELECT shop, shop_original_name FROM douyu_external_orders WHERE order_no = 'DY-SHOP-MIGRATION' """ + ) ) - ).mappings().one() + .mappings() + .one() + ) assert [shop["name"] for shop in shops] == ["向日葵"] aliases = ( json.loads(shops[0]["aliases"]) @@ -862,9 +870,7 @@ class TestMigrationSmoke: command.upgrade(cfg, "20261121_0104") before = { row["name"] - for row in inspect(mig_engine).get_columns( - "platform_fulfillment_tasks" - ) + for row in inspect(mig_engine).get_columns("platform_fulfillment_tasks") } assert "exchange_result_image_key" not in before assert "exchange_result_image_saved_at" not in before @@ -872,9 +878,7 @@ class TestMigrationSmoke: command.upgrade(cfg, "head") after = { row["name"] - for row in inspect(mig_engine).get_columns( - "platform_fulfillment_tasks" - ) + for row in inspect(mig_engine).get_columns("platform_fulfillment_tasks") } assert "exchange_result_image_key" in after assert "exchange_result_image_saved_at" in after @@ -882,9 +886,7 @@ class TestMigrationSmoke: command.downgrade(cfg, "20261121_0104") downgraded = { row["name"] - for row in inspect(mig_engine).get_columns( - "platform_fulfillment_tasks" - ) + for row in inspect(mig_engine).get_columns("platform_fulfillment_tasks") } assert "exchange_result_image_key" not in downgraded assert "exchange_result_image_saved_at" not in downgraded @@ -1031,23 +1033,25 @@ class TestMigrationSmoke: command.upgrade(cfg, "head") with mig_engine.connect() as conn: columns = { - item["name"] - for item in inspect(conn).get_columns("douyu_tasks") + item["name"] for item in inspect(conn).get_columns("douyu_tasks") } indexes = { - item["name"] - for item in inspect(conn).get_indexes("douyu_tasks") + item["name"] for item in inspect(conn).get_indexes("douyu_tasks") } - rows = conn.execute( - text( - """ + rows = ( + conn.execute( + text( + """ SELECT status, message, active_binding_key FROM douyu_tasks WHERE batch_id = 'repair-0107-batch' ORDER BY id """ + ) ) - ).mappings().all() + .mappings() + .all() + ) assert "active_binding_key" in columns assert "uq_douyu_tasks_active_binding" in indexes assert [row["status"] for row in rows] == ["stopped", "running"] diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index a23c697..d738724 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -69,6 +69,7 @@ class _Base: ) ) self.session.commit() + def teardown_method(self): views.invalidate_task_list_count_cache() self.session.close() @@ -1251,8 +1252,12 @@ class TestSnapshotSync(_Base): task = self.session.query(PlatformFulfillmentTask).one() assert task.flow_version == 1 - assert service.list_tasks(self.session, flow_version=2)["pagination"]["total"] == 0 - assert service.list_tasks(self.session, flow_version=1)["pagination"]["total"] == 1 + assert ( + service.list_tasks(self.session, flow_version=2)["pagination"]["total"] == 0 + ) + assert ( + service.list_tasks(self.session, flow_version=1)["pagination"]["total"] == 1 + ) def test_legacy_task_is_frozen_against_snapshot_transitions(self): task = self.task() @@ -1261,7 +1266,11 @@ class TestSnapshotSync(_Base): service.sync_order_snapshot( self.session, - {"data": self.snapshot(orderStatus="refunded", douyuFulfillmentEnabled=False)}, + { + "data": self.snapshot( + orderStatus="refunded", douyuFulfillmentEnabled=False + ) + }, ) self.session.refresh(task) @@ -1412,8 +1421,7 @@ class TestAccountSelection(_Base): assert query is not None selected = { - str(description["name"]) - for description in query.column_descriptions + str(description["name"]) for description in query.column_descriptions } assert { "account_id", @@ -2895,9 +2903,7 @@ class TestBindingAndCompletion(_Base): enqueue_execution=False, ) qr_task = ( - self.session.query(DouyuTask) - .filter(DouyuTask.batch_id == qr_batch) - .one() + self.session.query(DouyuTask).filter(DouyuTask.batch_id == qr_batch).one() ) assert qr_count == 1 assert qr_task.platform_task_id == task.id @@ -3129,9 +3135,7 @@ class TestBindingAndCompletion(_Base): assert event.detail_json["roleLockLeasePurpose"] == "douyu_collab" assert event.detail_json["sourceTaskId"] == qr_task.id assert ( - self.session.query(DouyuTask) - .filter_by(task_type="confirm_bind") - .count() + self.session.query(DouyuTask).filter_by(task_type="confirm_bind").count() == 0 ) @@ -3199,9 +3203,7 @@ class TestBindingAndCompletion(_Base): task.execution_status = "role_ready" self.session.commit() confirm_count = ( - self.session.query(DouyuTask) - .filter_by(task_type="confirm_bind") - .count() + self.session.query(DouyuTask).filter_by(task_type="confirm_bind").count() ) detail = service.confirm_binding_sync( @@ -3212,9 +3214,7 @@ class TestBindingAndCompletion(_Base): self.session.refresh(task) assert ( - self.session.query(DouyuTask) - .filter_by(task_type="confirm_bind") - .count() + self.session.query(DouyuTask).filter_by(task_type="confirm_bind").count() == confirm_count ) assert detail["task"]["bindingStatus"] == "failed" @@ -3657,9 +3657,7 @@ class TestBindingAndCompletion(_Base): ) assert _binding_failure_issue(task, result) == "role_changed" - assert "扫码角色已失效" in _binding_failure_raw_message( - "role_changed", result - ) + assert "扫码角色已失效" in _binding_failure_raw_message("role_changed", result) def test_customer_profile_requires_home_image(self): task = self._allocated() @@ -3733,7 +3731,10 @@ class TestBindingAndCompletion(_Base): # 客户页 readiness 与确认接口必须读同一层事实: # 平台任务还在 qr_pending 时不能显示“可确认”。 - assert views.customer_binding_out(self.session, task.id)["bindReadyForConfirm"] is False + assert ( + views.customer_binding_out(self.session, task.id)["bindReadyForConfirm"] + is False + ) service.refresh_binding(self.session, task_id=task.id) @@ -3745,13 +3746,14 @@ class TestBindingAndCompletion(_Base): assert evidence["targetRole"] == "" assert evidence["confirmable"] is False assert evidence["scannedRole"] == "" - assert views.customer_binding_out(self.session, task.id)["bindReadyForConfirm"] is False + assert ( + views.customer_binding_out(self.session, task.id)["bindReadyForConfirm"] + is False + ) assert evidence["legacyLatest"]["roleName"] == "cjm新角色" assert evidence["actionCurrent"]["roleName"] == "旧角色" assert ( - self.session.query(DouyuTask) - .filter_by(task_type="confirm_bind") - .count() + self.session.query(DouyuTask).filter_by(task_type="confirm_bind").count() == 0 ) @@ -3836,9 +3838,7 @@ class TestBindingAndCompletion(_Base): assert event.detail_json["roleName"] == "同对角色" assert event.detail_json["reason"] == "same_account_same_role" assert ( - self.session.query(DouyuTask) - .filter_by(task_type="confirm_bind") - .count() + self.session.query(DouyuTask).filter_by(task_type="confirm_bind").count() == 0 ) @@ -4006,13 +4006,17 @@ class TestBindingAndCompletion(_Base): ), ) - payload = asyncio.run(service.customer_start_binding(self.session, task_id=task.id)) + payload = asyncio.run( + service.customer_start_binding(self.session, task_id=task.id) + ) assert payload["accepted"] is True assert payload["queueState"] == "allocation_queued" assert calls == [[task.id]] - def test_customer_start_creates_one_binding_task_and_links_platform(self, monkeypatch): + def test_customer_start_creates_one_binding_task_and_links_platform( + self, monkeypatch + ): task = self._allocated() self.complete_customer_profile(task) monkeypatch.setattr( @@ -4021,8 +4025,12 @@ class TestBindingAndCompletion(_Base): lambda _db, **_kwargs: None, ) - first = asyncio.run(service.customer_start_binding(self.session, task_id=task.id)) - second = asyncio.run(service.customer_start_binding(self.session, task_id=task.id)) + first = asyncio.run( + service.customer_start_binding(self.session, task_id=task.id) + ) + second = asyncio.run( + service.customer_start_binding(self.session, task_id=task.id) + ) assert first["accepted"] is True assert second["accepted"] is False @@ -4068,9 +4076,7 @@ class TestBindingAndCompletion(_Base): task = self._allocated() with pytest.raises(HTTPException) as exc_info: - asyncio.run( - service.customer_start_binding(self.session, task_id=task.id) - ) + asyncio.run(service.customer_start_binding(self.session, task_id=task.id)) assert exc_info.value.status_code == 409 assert "游戏主页截图" in str(exc_info.value.detail) @@ -4874,8 +4880,7 @@ class TestBindingAndCompletion(_Base): task.execution_status = "manual_required" task.issue_code = "account_role_cooldown" task.last_error = ( - "斗鱼账号当前绑定角色(测试角色)未到可换绑时间," - "请更换斗鱼账号或稍后重试" + "斗鱼账号当前绑定角色(测试角色)未到可换绑时间,请更换斗鱼账号或稍后重试" ) self.session.add_all( [ @@ -5132,9 +5137,7 @@ class TestBindingAndCompletion(_Base): assert detail["task"]["exchangeStatus"] == "points_short" assert detail["task"]["account"]["id"] == account.id - def test_presale_refresh_after_binding_shows_waiting_release( - self, monkeypatch - ): + def test_presale_refresh_after_binding_shows_waiting_release(self, monkeypatch): task = self._allocated() task.binding_status = "bound" task.execution_status = "bound" @@ -6185,7 +6188,9 @@ class TestBindingAndCompletion(_Base): assert "妎朊" in task.last_error assert "妎䏓" in task.last_error - def test_verify_task_binding_records_success_and_reverts_mismatch(self, monkeypatch): + def test_verify_task_binding_records_success_and_reverts_mismatch( + self, monkeypatch + ): """确认绑定后复核斗鱼:一致时记复核通过;斗鱼未绑定或角色不一致时回退转人工。""" from web.backend.services.platform_fulfillment import binding as pf_binding @@ -6532,3 +6537,374 @@ class TestBindingAndCompletion(_Base): assert evt.detail_json["operatorUsername"] == "pf-op" assert evt.detail_json["accountRole"] == "客户目标角色" assert evt.detail_json["goodsName"] == "套装-花椰椰" + + +TRIO_BAG412 = "20260120QYOOB_bag412" +TRIO_BAG413 = "20260120QYOOB_bag413" +TRIO_BAG414 = "20260120QYOOB_bag414" + + +class TestAllocationPolicyAndSameRoleReuse(_Base): + def _add_commodity_state( + self, + account: Account, + commodity_id: str, + *, + eligibility: str = "eligible", + availability: str = "available", + ) -> None: + self.session.add( + AccountCommodityState( + account_id=account.id, + platform="douyu", + scope="elite", + commodity_id=commodity_id, + commodity_name=commodity_id, + account_eligibility=eligibility, + offer_state="active", + stock_state="in_stock", + availability=availability, + observed_at=NOW, + valid_until=NOW + timedelta(hours=6), + source="test_fixture", + ) + ) + + def _create_commodity_task( + self, + *, + commodity_id: str, + order_suffix: str, + role_name: str = "", + required_points: int = 8000, + ) -> PlatformFulfillmentTask: + mapping = ( + self.session.query(PlatformCommodityMapping) + .filter_by(commodity_id=commodity_id) + .first() + ) + if mapping is None: + mapping = PlatformCommodityMapping( + target_platform="douyu", + internal_sku_key=f"sku-{commodity_id}", + commodity_id=commodity_id, + goods_name=f"商品-{commodity_id}", + required_points=required_points, + scope="elite", + enabled=True, + created_by=self.admin_id, + created_at=NOW, + updated_at=NOW, + ) + self.session.add(mapping) + self.session.flush() + task = PlatformFulfillmentTask( + source_system="order_site", + source_order_id=f"ord-{order_suffix}", + source_order_item_id=f"item-{order_suffix}", + source_fulfillment_id=f"ff-{order_suffix}", + platform_order_id=f"ORDER-{order_suffix}", + provider="91kaquan", + shop_id="shop-1", + shop_name="测试店", + sku_code=mapping.internal_sku_key, + sku_name=mapping.goods_name, + internal_sku_key=mapping.internal_sku_key, + quantity=1, + order_amount_fen=9900, + target_platform="douyu", + scope="elite", + commodity_mapping_id=mapping.id, + commodity_id=commodity_id, + required_points=required_points, + customer_role_name=role_name, + customer_platform="wechat" if role_name else "", + customer_system="android" if role_name else "", + binding_status="not_started", + execution_status="ready", + exchange_status="not_started", + source_snapshot_json={"order_no": f"ORDER-{order_suffix}"}, + paid_at=NOW, + created_at=NOW, + updated_at=NOW, + ) + self.session.add(task) + self.session.commit() + return task + + def test_trio_bundle_requires_all_three_and_ordinary_preserves_bundle_pool(self): + # 只有部分资格(缺 bag414) + partial = self.account("partial-trio", points=8000, capability=False) + self._add_commodity_state(partial, TRIO_BAG412, eligibility="eligible") + self._add_commodity_state(partial, TRIO_BAG413, eligibility="eligible") + self._add_commodity_state(partial, TRIO_BAG414, eligibility="limited") + + # 仅普通商品有资格(无三皮肤全资格) + ordinary_only = self.account("ordinary-only", points=8000, capability=False) + self._add_commodity_state(ordinary_only, COMMODITY, eligibility="eligible") + + # 具备三皮肤全资格 + 普通商品资格 + full_trio = self.account("full-trio", points=8000, capability=False) + self._add_commodity_state(full_trio, TRIO_BAG412, eligibility="eligible") + self._add_commodity_state(full_trio, TRIO_BAG413, eligibility="eligible") + self._add_commodity_state(full_trio, TRIO_BAG414, eligibility="eligible") + self._add_commodity_state(full_trio, COMMODITY, eligibility="eligible") + self.session.commit() + + # 普通单应避开 full-trio,把全资格账号池留给三皮肤联合订单 + ordinary_task = self._create_commodity_task( + commodity_id=COMMODITY, + order_suffix="ord-1", + required_points=1280, + ) + ordinary_detail = service.allocate_task( + self.session, + task_id=ordinary_task.id, + current=self.admin, + ) + assert ordinary_detail["task"]["account"]["id"] == ordinary_only.id + + # 购买三皮肤之一必须匹配三者全部可兑的账号 + trio_task = self._create_commodity_task( + commodity_id=TRIO_BAG412, + order_suffix="trio-1", + role_name="联合玩家", + ) + trio_detail = service.allocate_task( + self.session, + task_id=trio_task.id, + current=self.admin, + ) + assert trio_detail["task"]["account"]["id"] == full_trio.id + + # 当全资格账号均已被占用,只剩 partial-trio 时,必须阻止误选并标明联合缺口 + second_trio = self._create_commodity_task( + commodity_id=TRIO_BAG413, + order_suffix="trio-2", + role_name="另一个玩家", + ) + failed = service.allocate_task( + self.session, + task_id=second_trio.id, + current=self.admin, + ) + assert failed["task"]["account"] is None + assert failed["task"]["issueCode"] == "bundle_co_eligibility_missing" + + def test_bundle_prefer_all_and_settings_policy_persistence(self): + saved = service.update_settings( + self.session, + lease_duration_minutes=None, + order_match_started_at=NOW - timedelta(days=1), + allocation_policy={ + "sameRoleReuseEnabled": True, + "preserveBundlePool": False, + "priorityOrder": [ + "bundle_match", + "same_role_reuse", + "resource_ready", + "points_asc", + "ck_freshness", + "preserve_bundle_pool", + ], + "bundleRules": [ + { + "id": "soft-duo", + "name": "两件套优先全部可兑", + "enabled": True, + "mode": "prefer_all", + "commodityIds": [TRIO_BAG412, TRIO_BAG413], + } + ], + }, + current=self.admin, + ) + assert saved["allocationPolicy"]["preserveBundlePool"] is False + assert saved["allocationPolicy"]["priorityOrder"][0] == "bundle_match" + assert saved["allocationPolicy"]["bundleRules"][0]["mode"] == "prefer_all" + + fetched = service.get_settings(self.session) + assert fetched["allocationPolicy"]["bundleRules"][0]["commodityIds"] == [ + TRIO_BAG412, + TRIO_BAG413, + ] + + partial = self.account("prefer-partial", points=8000, capability=False) + self._add_commodity_state(partial, TRIO_BAG412, eligibility="eligible") + full = self.account("prefer-full", points=9000, capability=False) + self._add_commodity_state(full, TRIO_BAG412, eligibility="eligible") + self._add_commodity_state(full, TRIO_BAG413, eligibility="eligible") + self.session.commit() + + # Full 可用时 prefer_all 优先 full + t1 = self._create_commodity_task( + commodity_id=TRIO_BAG412, + order_suffix="pref-1", + role_name="玩家A", + ) + d1 = service.allocate_task(self.session, task_id=t1.id, current=self.admin) + assert d1["task"]["account"]["id"] == full.id + + # Full 已被占用后,prefer_all 允许降级命中 partial + t2 = self._create_commodity_task( + commodity_id=TRIO_BAG412, + order_suffix="pref-2", + role_name="玩家B", + ) + d2 = service.allocate_task(self.session, task_id=t2.id, current=self.admin) + assert d2["task"]["account"]["id"] == partial.id + + def test_same_role_multi_skin_shares_account_lease_and_propagates_bound(self): + trio_acc = self.account("shared-trio-acc", points=24000, capability=False) + for cid in (TRIO_BAG412, TRIO_BAG413, TRIO_BAG414): + self._add_commodity_state(trio_acc, cid, eligibility="eligible") + backup_acc = self.account("backup-trio-acc", points=24000, capability=False) + for cid in (TRIO_BAG412, TRIO_BAG413, TRIO_BAG414): + self._add_commodity_state(backup_acc, cid, eligibility="eligible") + self.session.commit() + + task1 = self._create_commodity_task( + commodity_id=TRIO_BAG412, + order_suffix="same-1", + role_name="同角色三连下单", + ) + task2 = self._create_commodity_task( + commodity_id=TRIO_BAG413, + order_suffix="same-2", + role_name="同角色三连下单", + ) + task3 = self._create_commodity_task( + commodity_id=TRIO_BAG414, + order_suffix="same-3", + role_name="同角色三连下单", + ) + + d1 = service.allocate_task(self.session, task_id=task1.id, current=self.admin) + d2 = service.allocate_task(self.session, task_id=task2.id, current=self.admin) + d3 = service.allocate_task(self.session, task_id=task3.id, current=self.admin) + + acc_id = d1["task"]["account"]["id"] + assert d2["task"]["account"]["id"] == acc_id + assert d3["task"]["account"]["id"] == acc_id + assert self.session.query(AccountLease).count() == 1 + assert sorted(d3["task"].get("sharedLeaseTaskIds") or []) == sorted( + [task1.id, task2.id] + ) + d1_latest = service.get_task_detail(self.session, task1.id) + assert sorted(d1_latest["task"].get("sharedLeaseTaskIds") or []) == sorted( + [task2.id, task3.id] + ) + + # 首单完成绑定确认 -> 同角色共享任务自动传播为 bound + confirm_task = DouyuTask( + batch_id="shared-confirm-1", + account_id=acc_id, + account_assigned_to=self.admin_id, + task_type="confirm_bind", + handbook_scope="elite", + status="success", + platform_task_id=task1.id, + result={ + "role_name": "同角色三连下单", + "area_name": "微信", + "plat_name": "安卓", + "is_bound_act": True, + "bind_confirmed": True, + "bind_phase": "confirmed", + }, + created_by=self.admin_id, + ) + self.session.add(confirm_task) + self.session.flush() + task1.bind_task_id = confirm_task.id + task1.binding_status = "role_ready" + task1.execution_status = "role_ready" + self.session.commit() + + synced = service.sync_task_from_binding_runner( + self.session, + douyu_task_id=confirm_task.id, + ) + assert synced >= 1 + for sibling in (task1, task2, task3): + self.session.refresh(sibling) + assert sibling.binding_status == "bound" + assert sibling.execution_status == "bound" + + # 取消 task2 仅摘除 task2 自己,共享租约必须仍为 active + service.cancel_task( + self.session, + task_id=task2.id, + current=self.admin, + reason="退单其中一个皮肤", + ) + lease = self.session.query(AccountLease).one() + assert lease.status == "active" + self.session.refresh(task2) + assert task2.lease_id is None + + # 同角色若再下一单完全相同的 commodity_id(bag412),不能复用同一账号 + dup_task = self._create_commodity_task( + commodity_id=TRIO_BAG412, + order_suffix="same-dup", + role_name="同角色三连下单", + ) + d_dup = service.allocate_task( + self.session, + task_id=dup_task.id, + current=self.admin, + ) + assert d_dup["task"]["account"]["id"] != acc_id + + def test_lease_reaper_cleans_null_task_orphan_and_preserves_shared_lease(self): + acc1 = self.account("reap-acc-1", points=2000) + acc2 = self.account("reap-acc-2", points=2000) + task1 = self._create_commodity_task( + commodity_id=COMMODITY, + order_suffix="reap-1", + required_points=1280, + ) + task2 = self._create_commodity_task( + commodity_id=COMMODITY, + order_suffix="reap-2", + required_points=1280, + ) + + # 孤儿租约:原 task1 的 account_id/lease_id 已为 NULL(回归 NULL != id 漏网 bug) + orphan_lease = AccountLease( + account_id=acc1.id, + holder_user_id=self.admin_id, + scope="elite", + purpose="platform_fulfillment", + batch_id=f"pf:{task1.id}", + status="active", + ) + # 共享租约:batch_id 仍指着已置空的 task1,但 task2 正在持有它 + shared_lease = AccountLease( + account_id=acc2.id, + holder_user_id=self.admin_id, + scope="elite", + purpose="platform_fulfillment", + batch_id=f"pf:{task1.id}", + status="active", + ) + self.session.add_all([orphan_lease, shared_lease]) + self.session.flush() + + task2.account_id = acc2.id + task2.lease_id = shared_lease.id + task2.execution_status = "allocated" + self.session.commit() + + job = AutomationJob(key=reaper.JOB_KEY, batch_size=100) + result = reaper.run_platform_fulfillment_lease_reaper( + self.session, + job, + now=NOW + timedelta(minutes=5), + ) + + self.session.refresh(orphan_lease) + self.session.refresh(shared_lease) + assert result["orphan_released"] == 1 + assert orphan_lease.status == "released" + assert shared_lease.status == "active" diff --git a/tests/test_platform_fulfillment_auto_allocator.py b/tests/test_platform_fulfillment_auto_allocator.py index 0145aff..b2f50ed 100644 --- a/tests/test_platform_fulfillment_auto_allocator.py +++ b/tests/test_platform_fulfillment_auto_allocator.py @@ -360,9 +360,7 @@ def test_schedule_retry_preserves_longer_capability_retry(db): def test_auto_allocator_ignores_legacy_tasks(db): - actor = User( - username="auto-legacy-actor", password_hash="h", role="super_admin" - ) + actor = User(username="auto-legacy-actor", password_hash="h", role="super_admin") db.add_all( [ actor, @@ -398,3 +396,98 @@ def test_auto_allocator_ignores_legacy_tasks(db): result = auto_allocator.run_auto_allocation_once(db, limit=10) assert result == {"checked": 0, "allocated": 0, "failed": 0} + + +def test_start_allocated_bindings_skips_shared_lease_sibling_when_active_bind_exists( + db, +): + actor = User(username="auto-shared-actor", password_hash="h", role="super_admin") + moment = datetime.now(UTC).replace(microsecond=0) + db.add_all( + [ + actor, + PlatformFulfillmentSetting( + id=1, + lease_duration_minutes=None, + order_match_started_at=moment - timedelta(days=1), + ), + ] + ) + db.flush() + + from web.backend.models import Account, AccountLease + + acc = Account( + username="shared-bind-acc", + password="p", + email="shared-bind@example.com", + email_password="ep", + status="active", + ck_check_status="valid", + cookie="PHPSESSID=x", + elite_opened=True, + points=8000, + ) + db.add(acc) + db.flush() + lease = AccountLease( + account_id=acc.id, + holder_user_id=actor.id, + scope="elite", + purpose="platform_fulfillment", + batch_id="pf:shared-1", + status="active", + ) + db.add(lease) + db.flush() + + first = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="shared-1", + source_order_item_id="shared-1", + platform_order_id="SHARED-1", + internal_sku_key="skin-1", + commodity_id="cid-1", + account_id=acc.id, + lease_id=lease.id, + execution_status="waiting_bind", + binding_status="qr_pending", + exchange_status="not_started", + paid_at=moment, + updated_at=moment, + ) + sibling = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="shared-2", + source_order_item_id="shared-2", + platform_order_id="SHARED-2", + internal_sku_key="skin-2", + commodity_id="cid-2", + account_id=acc.id, + lease_id=lease.id, + execution_status="allocated", + binding_status="not_started", + exchange_status="not_started", + paid_at=moment, + updated_at=moment, + ) + db.add_all([first, sibling]) + db.commit() + + called_ids: list[int] = [] + + async def _fake_start_binding(_db, *, task_id: int, current): + called_ids.append(task_id) + + with ( + patch.object(auto_allocator.service, "_integration_actor", return_value=actor), + patch.object( + auto_allocator.service, + "start_binding", + side_effect=_fake_start_binding, + ), + ): + result = auto_allocator.start_allocated_bindings_once(db, limit=10) + + assert called_ids == [] + assert result == 0 diff --git a/web/backend/migrations/migration_manifest.json b/web/backend/migrations/migration_manifest.json index c67f79c..8584c69 100644 --- a/web/backend/migrations/migration_manifest.json +++ b/web/backend/migrations/migration_manifest.json @@ -541,6 +541,10 @@ "20261125_0135_protected_login_quota_limits.py": { "revision": "20261125_0135", "sha256": "8bc4b6a5e9952087e6a18f038f1cb4a054bf25feed311677c94ffcbd1b5711f2" + }, + "20261128_0136_fulfillment_allocation_policy.py": { + "revision": "20261128_0136", + "sha256": "d92e34a71c7b39a018636b41f21230d73013e6d6361d1a3f231cf0091c827d7e" } } } diff --git a/web/backend/migrations/versions/20261128_0136_fulfillment_allocation_policy.py b/web/backend/migrations/versions/20261128_0136_fulfillment_allocation_policy.py new file mode 100644 index 0000000..456993b --- /dev/null +++ b/web/backend/migrations/versions/20261128_0136_fulfillment_allocation_policy.py @@ -0,0 +1,40 @@ +"""为履约设置新增选号优先级与全资格捆绑策略 JSON 列。""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261128_0136" +down_revision: str | None = "20261125_0135" +branch_labels: str | None = None +depends_on: str | None = None + +TABLE = "platform_fulfillment_settings" +COLUMN = "allocation_policy_json" + + +def _column_exists(name: str) -> bool: + conn = op.get_bind() + count = conn.execute( + sa.text( + "SELECT COUNT(*) FROM information_schema.columns " + "WHERE table_schema = DATABASE() AND table_name = :table " + "AND column_name = :name" + ), + {"table": TABLE, "name": name}, + ).scalar() + return bool(count) + + +def upgrade() -> None: + if not _column_exists(COLUMN): + op.add_column( + TABLE, + sa.Column(COLUMN, sa.JSON(), nullable=True), + ) + + +def downgrade() -> None: + if _column_exists(COLUMN): + op.drop_column(TABLE, COLUMN) diff --git a/web/backend/models.py b/web/backend/models.py index 1afb0de..b48a5e8 100644 --- a/web/backend/models.py +++ b/web/backend/models.py @@ -180,18 +180,14 @@ class Account(Base): ) # 最近一次精英 bind_ok 的业务发生时间,以及本地“一个账号 7 天只能绑一个角色” # 的锁到期时间。分配只看 role_change_available_at(官方时间与本地锁取大)。 - last_bind_ok_at: Mapped[datetime | None] = mapped_column( - UTCDateTime, nullable=True - ) + last_bind_ok_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) role_bind_lock_until: Mapped[datetime | None] = mapped_column( UTCDateTime, nullable=True ) role_change_checked_at: Mapped[datetime | None] = mapped_column( UTCDateTime, nullable=True ) - role_change_source: Mapped[str | None] = mapped_column( - String(16), nullable=True - ) + role_change_source: Mapped[str | None] = mapped_column(String(16), nullable=True) # 精英宝典当前有效开通状态(getUserInfo 的 manualType + expireTime)。 # manualType 只表示开过;写入时还要按 expireTime 判断是否已过期。 # 光看积分区分不了「开通后积分花完」和「从未开通」,必须单独落库。 @@ -433,9 +429,7 @@ class DouyuTask(Base): String(32), nullable=False, default="", server_default="" ) next_run_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) - run_deadline_at: Mapped[datetime | None] = mapped_column( - UTCDateTime, nullable=True - ) + run_deadline_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) last_run_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) attempt_count: Mapped[int] = mapped_column( Integer, nullable=False, default=0, server_default="0" @@ -818,9 +812,7 @@ class DouyuRoleApiLog(Base): need_bind_role: Mapped[bool] = mapped_column( Boolean, nullable=False, default=False, server_default="0" ) - change_role_wait_time: Mapped[int | None] = mapped_column( - BigInteger, nullable=True - ) + change_role_wait_time: Mapped[int | None] = mapped_column(BigInteger, nullable=True) can_change_time: Mapped[int | None] = mapped_column(BigInteger, nullable=True) request_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) response_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) @@ -999,9 +991,7 @@ class DouyuExternalOrder(Base): source_platform_order_id: Mapped[str] = mapped_column( String(128), nullable=False, default="", server_default="" ) - last_synced_at: Mapped[datetime | None] = mapped_column( - UTCDateTime, nullable=True - ) + last_synced_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) # ---- 内部斗鱼账号(CK 不落本表)---- account_id: Mapped[int | None] = mapped_column( @@ -2099,22 +2089,12 @@ class AccountCommodityState(Base): time_limited: Mapped[bool] = mapped_column( Boolean, nullable=False, default=False, server_default="0" ) - available_from: Mapped[datetime | None] = mapped_column( - UTCDateTime, nullable=True - ) - available_until: Mapped[datetime | None] = mapped_column( - UTCDateTime, nullable=True - ) + available_from: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) + available_until: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) schedule_json: Mapped[list | None] = mapped_column(JSON, nullable=True) - observed_at: Mapped[datetime | None] = mapped_column( - UTCDateTime, nullable=True - ) - valid_until: Mapped[datetime | None] = mapped_column( - UTCDateTime, nullable=True - ) - next_check_at: Mapped[datetime | None] = mapped_column( - UTCDateTime, nullable=True - ) + observed_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) + valid_until: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) + next_check_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) last_exchange_at: Mapped[datetime | None] = mapped_column( UTCDateTime, nullable=True ) @@ -2321,6 +2301,11 @@ class PlatformFulfillmentSetting(Base): UTCDateTime, nullable=True, ) + # 选号优先级与全资格捆绑策略配置(JSON);NULL 时回退代码内置默认策略。 + allocation_policy_json: Mapped[dict | None] = mapped_column( + JSON, + nullable=True, + ) updated_by: Mapped[int | None] = mapped_column( ForeignKey("users.id", ondelete="SET NULL"), nullable=True, @@ -2341,7 +2326,10 @@ class PlatformCommodityMapping(Base): ) internal_sku_key: Mapped[str] = mapped_column(String(255), nullable=False) campaign_key: Mapped[str] = mapped_column( - String(128), nullable=False, default="douyu-current", server_default="douyu-current" + String(128), + nullable=False, + default="douyu-current", + server_default="douyu-current", ) campaign_name: Mapped[str] = mapped_column( String(255), nullable=False, default="", server_default="" @@ -2619,16 +2607,10 @@ class AccountSyncState(Base): String(16), nullable=False, default="douyu", server_default="douyu" ) domain: Mapped[str] = mapped_column(String(32), nullable=False) - last_attempt_at: Mapped[datetime | None] = mapped_column( - UTCDateTime, nullable=True - ) - last_success_at: Mapped[datetime | None] = mapped_column( - UTCDateTime, nullable=True - ) + last_attempt_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) + last_success_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) valid_until: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) - next_retry_at: Mapped[datetime | None] = mapped_column( - UTCDateTime, nullable=True - ) + next_retry_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) status: Mapped[str] = mapped_column( String(16), nullable=False, default="never", server_default="never" ) @@ -2701,9 +2683,7 @@ class AccountSyncRun(Base): task_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True) started_at: Mapped[datetime] = mapped_column(UTCDateTime, nullable=False) finished_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) - status: Mapped[str] = mapped_column( - String(16), nullable=False, default="running" - ) + status: Mapped[str] = mapped_column(String(16), nullable=False, default="running") source: Mapped[str] = mapped_column( String(32), nullable=False, default="", server_default="" ) @@ -2961,9 +2941,7 @@ class AccountSupplySnapshot(Base): UTCDateTime, default=_utcnow, onupdate=_utcnow ) - __table_args__ = ( - Index("ix_account_supply_snapshot_checked", "checked_at"), - ) + __table_args__ = (Index("ix_account_supply_snapshot_checked", "checked_at"),) class LoginAttempt(Base): diff --git a/web/backend/routers/platform_fulfillment.py b/web/backend/routers/platform_fulfillment.py index 2280165..e6d9c21 100644 --- a/web/backend/routers/platform_fulfillment.py +++ b/web/backend/routers/platform_fulfillment.py @@ -43,6 +43,11 @@ def update_settings( db: Session = Depends(get_db), current: User = Depends(require_permission("platform_fulfillment:admin")), ) -> dict[str, Any]: + raw_policy = ( + req.allocation_policy.model_dump(by_alias=True) + if hasattr(req.allocation_policy, "model_dump") + else req.allocation_policy + ) result = service.update_settings( db, lease_duration_minutes=req.lease_duration_minutes, @@ -50,13 +55,10 @@ def update_settings( manual_completed_release_delay_minutes=( req.manual_completed_release_delay_minutes ), - presale_waiting_release_ttl_minutes=( - req.presale_waiting_release_ttl_minutes - ), - manual_required_lease_ttl_minutes=( - req.manual_required_lease_ttl_minutes - ), + presale_waiting_release_ttl_minutes=(req.presale_waiting_release_ttl_minutes), + manual_required_lease_ttl_minutes=(req.manual_required_lease_ttl_minutes), order_match_started_at=req.order_match_started_at, + allocation_policy=raw_policy, current=current, ) record_audit( @@ -67,11 +69,13 @@ def update_settings( detail=result, ) db.commit() + from ..services.platform_fulfillment.auto_allocator import wake_auto_allocator from ..services.platform_fulfillment.views import ( invalidate_task_list_count_cache, ) invalidate_task_list_count_cache() + wake_auto_allocator() return result @@ -390,10 +394,9 @@ def allocate_task( db.commit() from ..services.platform_fulfillment.auto_allocator import queue_task_allocation - result["allocationQueued"] = ( - result.get("task", {}).get("executionStatus") == "ready" - and queue_task_allocation(task_id) - ) + result["allocationQueued"] = result.get("task", {}).get( + "executionStatus" + ) == "ready" and queue_task_allocation(task_id) return result diff --git a/web/backend/schemas.py b/web/backend/schemas.py index 521bb21..7434b8f 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -1785,6 +1785,43 @@ class PlatformFulfillmentCustomerProfileUpdate(BaseModel): reopen_binding: bool = True +class PlatformFulfillmentBundleRule(BaseModel): + id: str = Field(default="", max_length=64) + name: str = Field(default="", max_length=128) + enabled: bool = True + mode: str = Field(default="require_all", pattern="^(require_all|prefer_all)$") + commodity_ids: list[str] = Field( + default_factory=list, + alias="commodityIds", + max_length=30, + ) + + model_config = {"populate_by_name": True} + + +class PlatformFulfillmentAllocationPolicy(BaseModel): + same_role_reuse_enabled: bool = Field( + default=True, + alias="sameRoleReuseEnabled", + ) + preserve_bundle_pool: bool = Field( + default=True, + alias="preserveBundlePool", + ) + priority_order: list[str] = Field( + default_factory=list, + alias="priorityOrder", + max_length=16, + ) + bundle_rules: list[PlatformFulfillmentBundleRule] = Field( + default_factory=list, + alias="bundleRules", + max_length=20, + ) + + model_config = {"populate_by_name": True} + + class PlatformFulfillmentSettingsUpdate(BaseModel): lease_duration_minutes: int | None = Field(..., ge=1, le=525600) completed_release_delay_minutes: int | None = Field( @@ -1808,6 +1845,11 @@ class PlatformFulfillmentSettingsUpdate(BaseModel): le=525600, ) order_match_started_at: datetime | None = None + allocation_policy: PlatformFulfillmentAllocationPolicy | dict[str, Any] | None = ( + Field(default=None, alias="allocationPolicy") + ) + + model_config = {"populate_by_name": True} class PlatformFulfillmentCustomerSessionRequest(BaseModel): diff --git a/web/backend/services/account_query_filters.py b/web/backend/services/account_query_filters.py index f9356f5..2dcefb5 100644 --- a/web/backend/services/account_query_filters.py +++ b/web/backend/services/account_query_filters.py @@ -309,6 +309,7 @@ def fresh_eligible_state_filter( now: datetime, *, allow_before_open: bool = False, + state_model=AccountCommodityState, ): allowed_offer_states = ( (OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE) @@ -316,11 +317,10 @@ def fresh_eligible_state_filter( else (OFFER_STATE_ACTIVE,) ) return and_( - AccountCommodityState.account_eligibility - == ACCOUNT_ELIGIBILITY_ELIGIBLE, - AccountCommodityState.offer_state.in_(allowed_offer_states), - AccountCommodityState.valid_until.isnot(None), - AccountCommodityState.valid_until > now, + state_model.account_eligibility == ACCOUNT_ELIGIBILITY_ELIGIBLE, + state_model.offer_state.in_(allowed_offer_states), + state_model.valid_until.isnot(None), + state_model.valid_until > now, ) 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 529497b..9956467 100644 --- a/web/backend/services/automation/jobs/platform_fulfillment_lease_reaper.py +++ b/web/backend/services/automation/jobs/platform_fulfillment_lease_reaper.py @@ -5,7 +5,7 @@ from __future__ import annotations from datetime import UTC, datetime, timedelta from typing import Any -from sqlalchemy import Integer, cast, func, or_ +from sqlalchemy import select from sqlalchemy.orm import Session from ....models import Account, AccountLease, AutomationJob, PlatformFulfillmentTask @@ -123,28 +123,24 @@ def run_platform_fulfillment_lease_reaper( if task is not None: converted_tasks[int(task.id)] = task - # 分配并发/重试可能留下「batch_id 指向 task,但 task 实际用另一个账号/租约」 - # 的孤儿 active 租约。它不会自然过期(expires_at 常为 NULL),会永久占住账号, - # 并让预售单接管时报“任务与租约不一致”。这里按 task 的真实归属回收。 - # 注意:不能在过滤孤儿前先 limit active 租约。生产有 3,900+ 条 active - # pf 租约,先取前 500 条会被合法租约占满,后面的孤儿永远轮不到。 - # 这里直接用 SQL 关联出「task 不存在 / task 账号或租约不一致」。 - task_id_expr = cast(func.substring(AccountLease.batch_id, 4), Integer) + # 分配并发/重试或任务清空可能留下「batch_id 指向 pf:task,但没有任何未取消任务 + # 真正持有该租约」的孤儿 active 租约。使用 EXISTS(~has_holder) 避免 SQL `NULL != id` + # 为 UNKNOWN 漏掉被清空 account_id/lease_id 的孤儿租约,同时也兼容同角色共享租约。 + has_holder = ( + select(PlatformFulfillmentTask.id) + .where( + PlatformFulfillmentTask.lease_id == AccountLease.id, + PlatformFulfillmentTask.account_id == AccountLease.account_id, + ) + .exists() + ) orphan_leases = ( db.query(AccountLease) - .outerjoin( - PlatformFulfillmentTask, - PlatformFulfillmentTask.id == task_id_expr, - ) .filter( AccountLease.purpose == "platform_fulfillment", AccountLease.status == "active", AccountLease.batch_id.like("pf:%"), - or_( - PlatformFulfillmentTask.id.is_(None), - PlatformFulfillmentTask.account_id != AccountLease.account_id, - PlatformFulfillmentTask.lease_id != AccountLease.id, - ), + ~has_holder, ) .order_by(AccountLease.id.asc()) .limit(max(1, int(job.batch_size or 500))) diff --git a/web/backend/services/douyu_collab_leases.py b/web/backend/services/douyu_collab_leases.py index eba053d..7dfd1c1 100644 --- a/web/backend/services/douyu_collab_leases.py +++ b/web/backend/services/douyu_collab_leases.py @@ -87,10 +87,7 @@ def _collab_order_expected_role( explicit = str(incoming_role or order.bind_game_role or "").strip() if explicit: return explicit - if ( - order.source_type == SOURCE_TYPE_PLATFORM_FULFILLMENT - and order.source_task_id - ): + if order.source_type == SOURCE_TYPE_PLATFORM_FULFILLMENT and order.source_task_id: task = db.get(PlatformFulfillmentTask, int(order.source_task_id)) if task is not None and task.customer_role_name: return str(task.customer_role_name or "").strip() @@ -235,6 +232,34 @@ def _takeover_platform_lease_for_collab( status_code=409, code="account_lease_conflict", ) + all_lease_tasks = ( + db.query(PlatformFulfillmentTask) + .filter( + PlatformFulfillmentTask.lease_id == int(lease.id), + PlatformFulfillmentTask.execution_status != "cancelled", + ) + .with_for_update() + .all() + ) + active_siblings = [ + item + for item in all_lease_tasks + if int(item.id) != int(platform_task.id) + and item.execution_status not in {"completed", "cancelled"} + ] + if active_siblings: + sibling_ids = ", ".join(f"#{item.id}" for item in active_siblings) + raise CollabError( + f"该账号同时被同角色其他进行中履约任务({sibling_ids})共享占用,暂不能直接接管", + status_code=409, + code="account_lease_conflict", + ) + for item in all_lease_tasks: + if ( + int(item.id) != int(platform_task.id) + and item.execution_status == "completed" + ): + item.lease_id = None blocking = ( db.query(DouyuTask) .filter( diff --git a/web/backend/services/douyu_collab_service.py b/web/backend/services/douyu_collab_service.py index bd6b513..2eca307 100644 --- a/web/backend/services/douyu_collab_service.py +++ b/web/backend/services/douyu_collab_service.py @@ -481,9 +481,7 @@ def recommend_accounts( name, cid, points = _resolve_gift( db, gift_name=gift_name if gift_name is not None else order.gift_name, - commodity_id=( - commodity_id if commodity_id is not None else order.commodity_id - ), + commodity_id=(commodity_id if commodity_id is not None else order.commodity_id), required_points=( required_points if required_points is not None else order.required_points ), @@ -499,12 +497,31 @@ def recommend_accounts( now = _now() candidates_by_id: dict[int, Account | CapabilityAccount] = {} if cid: + from .platform_fulfillment.policy import ( + bundle_requirements_for_commodity, + normalize_allocation_policy, + protected_bundle_commodities, + ) + from .platform_fulfillment.runtime import ( + get_settings as get_fulfillment_settings, + ) + + policy = normalize_allocation_policy( + get_fulfillment_settings(db).get("allocationPolicy") + ) + required_co, preferred_co = bundle_requirements_for_commodity(policy, cid) + protected_co = protected_bundle_commodities(policy, cid) for account in capability_candidate_accounts( db, limit=effective_scan_limit, required_points=required, commodity_id=cid, scope="elite", + allow_before_open=bool(required_co or preferred_co), + required_co_commodities=required_co, + preferred_co_commodities=preferred_co, + protected_bundle_commodities=protected_co, + priority_order=policy.get("priorityOrder") or (), ): candidates_by_id[int(account.id)] = account if not candidates_by_id: @@ -572,7 +589,9 @@ def recommend_accounts( continue elite_opened = account.elite_opened is True live_points = _to_int(account.points) - ready = bool(elite_opened and live_points is not None and live_points >= required) + ready = bool( + elite_opened and live_points is not None and live_points >= required + ) reasons = [ "未绑定角色,可直接绑定" if match_type == "empty" @@ -588,9 +607,7 @@ def recommend_accounts( # 后续“使用此账号”按内部 username 反查,不能用展示昵称。 "account_username": str(account.username or ""), "account_uid": str(account.uid or ""), - "account_nickname": str( - account.nickname or account.username or "" - ), + "account_nickname": str(account.nickname or account.username or ""), "ck_status": CK_VALID, "role_status": role_status, "bind_game_role": str(account.game_name or ""), @@ -1248,15 +1265,16 @@ def _collab_order_role_mismatch_reason( expected = _text(order.bind_game_role) if not expected: return None - acc = account or account_by_id(db, order.account_id) or account_by_username( - db, order.account_username + acc = ( + account + or account_by_id(db, order.account_id) + or account_by_username(db, order.account_username) ) if acc is not None: current_role = _text(acc.game_name) if current_role and not role_names_match(expected, current_role): return ( - f"账号当前绑定角色({current_role})" - f"与订单目标角色({expected})不一致" + f"账号当前绑定角色({current_role})与订单目标角色({expected})不一致" ) if str(acc.role_bind_status or "") == "unbound": return f"账号当前未绑定任何游戏角色,与订单目标角色({expected})不一致" @@ -1290,10 +1308,7 @@ def _collab_order_role_mismatch_reason( or record.get("bindRoleName") ) if record_role and not role_names_match(expected, record_role): - return ( - f"兑换记录角色({record_role})" - f"与订单目标角色({expected})不一致" - ) + return f"兑换记录角色({record_role})与订单目标角色({expected})不一致" return None @@ -1623,9 +1638,7 @@ def _exchange_record_time(record: Mapping[str, Any]) -> datetime | None: def _extract_record_role(record: Mapping[str, Any]) -> str: explicit = _text( - record.get("roleName") - or record.get("role_name") - or record.get("bindRoleName") + record.get("roleName") or record.get("role_name") or record.get("bindRoleName") ) if explicit: return explicit @@ -1647,9 +1660,7 @@ def _evaluate_exchange_record( expected_cid = _text(order.commodity_id) expected_name = _normalize_exchange_name(order.gift_name) record_cid = _text( - record.get("commodityId") - or record.get("commodity_id") - or record.get("goodsId") + record.get("commodityId") or record.get("commodity_id") or record.get("goodsId") ) record_name = _normalize_exchange_name( record.get("commodityName") @@ -1747,9 +1758,7 @@ def list_order_exchange_records( if refresh: try: - raw_records = _load_exchange_records_for_orders( - db, [order], client=client - ) + raw_records = _load_exchange_records_for_orders(db, [order], client=client) synced_at = _now() except Exception as exc: # noqa: BLE001 error_text = str(exc) @@ -1781,7 +1790,9 @@ def list_order_exchange_records( if sync_row is not None and isinstance(sync_row.raw_payload_json, Mapping): elite_rows = sync_row.raw_payload_json.get("elite") if isinstance(elite_rows, list): - raw_records = [dict(item) for item in elite_rows if isinstance(item, Mapping)] + raw_records = [ + dict(item) for item in elite_rows if isinstance(item, Mapping) + ] if synced_at is None: synced_at = sync_row.updated_at if not raw_records: @@ -2209,32 +2220,6 @@ def query_activity_batch( return results - - - - - - - - - - - - - - - - - - - - - - - - - - def archive_orders( db: Session, current: User, diff --git a/web/backend/services/platform_fulfillment/account_selector.py b/web/backend/services/platform_fulfillment/account_selector.py index 91c4757..e7c570b 100644 --- a/web/backend/services/platform_fulfillment/account_selector.py +++ b/web/backend/services/platform_fulfillment/account_selector.py @@ -8,10 +8,11 @@ from __future__ import annotations from dataclasses import dataclass from datetime import UTC, datetime, timedelta +from typing import Any -from sqlalchemy import and_, case, or_, select +from sqlalchemy import and_, case, literal, or_, select from sqlalchemy.exc import IntegrityError -from sqlalchemy.orm import Session +from sqlalchemy.orm import Session, aliased from ...models import ( Account, @@ -39,6 +40,14 @@ from ..account_query_filters import ( ) from ..account_sync_runner import WORK_STOREHOME_SYNC from ..account_work_queue import active_account_work_exists +from .policy import ( + PRIORITY_KEY_BUNDLE_MATCH, + PRIORITY_KEY_CK_FRESHNESS, + PRIORITY_KEY_POINTS_ASC, + PRIORITY_KEY_PRESERVE_BUNDLE_POOL, + PRIORITY_KEY_RESOURCE_READY, + normalize_priority_order, +) VALIDATION_LEASE_MINUTES = 5 BINDING_LEASE_MINUTES = 120 @@ -84,6 +93,8 @@ class CapabilityAccount: role_bind_status: str ck_check_status: str game_name: str + ck_checked_at: datetime | None = None + status: str = "" @dataclass(frozen=True) @@ -96,6 +107,8 @@ class CapabilityState: available_from: datetime | None valid_until: datetime | None blocking_reason: str + bundle_missing_count: int = 0 + is_protected_bundle: bool = False def _now(now: datetime | None = None) -> datetime: @@ -252,15 +265,57 @@ def live_candidate_accounts( case((Account.role_bind_status == "unbound", 0), else_=1), ) rows.extend( - tier_query.order_by(*order_by) - .limit(effective_limit - len(rows)) - .all() + tier_query.order_by(*order_by).limit(effective_limit - len(rows)).all() ) if len(rows) >= effective_limit: break return rows +def _co_commodity_eligible_exists( + commodity_id: str, + *, + scope: str, + moment: datetime, + since: datetime, +): + """协同商品资格子查询:只要账号本身具备可兑资格(含未开放预售)且近 365 天未兑过。""" + co_state = aliased(AccountCommodityState) + return ( + select(co_state.id) + .where( + co_state.account_id == Account.id, + co_state.platform == "douyu", + co_state.scope == scope, + co_state.commodity_id == commodity_id, + fresh_eligible_state_filter( + moment, + allow_before_open=True, + state_model=co_state, + ), + or_( + co_state.last_exchange_at.is_(None), + co_state.last_exchange_at < since, + ), + ) + .correlate(Account) + .exists() + ) + + +def _clean_commodity_group( + values: tuple[str, ...] | list[str] | None, + *, + exclude: str = "", +) -> tuple[str, ...]: + seen: list[str] = [] + for raw in values or (): + text = str(raw or "").strip() + if text and text != exclude and text not in seen: + seen.append(text) + return tuple(seen) + + def _capability_candidate_query( db: Session, *, @@ -270,6 +325,10 @@ def _capability_candidate_query( limit: int = 20, now: datetime | None = None, allow_before_open: bool = False, + required_co_commodities: tuple[str, ...] | list[str] = (), + preferred_co_commodities: tuple[str, ...] | list[str] = (), + protected_bundle_commodities: tuple[str, ...] | list[str] = (), + priority_order: tuple[str, ...] | list[str] = (), ): commodity = commodity_id.strip() if not commodity: @@ -280,6 +339,123 @@ def _capability_candidate_query( moment, allow_before_open=allow_before_open, ) + required_co = _clean_commodity_group(required_co_commodities, exclude=commodity) + preferred_co = _clean_commodity_group( + preferred_co_commodities, + exclude=commodity, + ) + preferred_co = tuple(cid for cid in preferred_co if cid not in required_co) + protected_co = _clean_commodity_group(protected_bundle_commodities) + + filters = [ + AccountCommodityState.platform == "douyu", + AccountCommodityState.scope == scope, + AccountCommodityState.commodity_id == commodity, + eligibility_filter, + or_( + AccountCommodityState.last_exchange_at.is_(None), + AccountCommodityState.last_exchange_at < since, + ), + cookie_present_filter(), + valid_ck_filter(), + automatable_account_filter(), + role_change_ready_filter(moment), + assigned_to_pool_filter(), + ~active_lease_exists(), + ~active_collab_order_exists(), + ] + for co_cid in required_co: + filters.append( + _co_commodity_eligible_exists( + co_cid, + scope=scope, + moment=moment, + since=since, + ) + ) + + if preferred_co: + missing_terms = [ + case( + ( + _co_commodity_eligible_exists( + co_cid, + scope=scope, + moment=moment, + since=since, + ), + 0, + ), + else_=1, + ) + for co_cid in preferred_co + ] + missing_count_expr = missing_terms[0] + for term in missing_terms[1:]: + missing_count_expr = missing_count_expr + term + else: + missing_count_expr = literal(0) + + if protected_co: + all_protected_expr = and_( + *[ + _co_commodity_eligible_exists( + co_cid, + scope=scope, + moment=moment, + since=since, + ) + for co_cid in protected_co + ] + ) + protected_flag_expr = case((all_protected_expr, 1), else_=0) + else: + protected_flag_expr = literal(0) + + order_clauses: list[Any] = [ + case( + (AccountCommodityState.offer_state == OFFER_STATE_ACTIVE, 0), + else_=1, + ) + ] + for key in normalize_priority_order(priority_order): + if key == PRIORITY_KEY_BUNDLE_MATCH and preferred_co: + order_clauses.append(missing_count_expr.asc()) + elif key == PRIORITY_KEY_PRESERVE_BUNDLE_POOL and protected_co: + order_clauses.append(protected_flag_expr.asc()) + elif key == PRIORITY_KEY_RESOURCE_READY: + order_clauses.extend( + [ + case((Account.elite_opened.is_(True), 0), else_=1), + case( + (Account.points >= max(0, int(required_points)), 0), + else_=1, + ), + ] + ) + elif key == PRIORITY_KEY_POINTS_ASC: + order_clauses.extend( + [ + Account.points.is_(None).asc(), + Account.points.asc(), + ] + ) + elif key == PRIORITY_KEY_CK_FRESHNESS: + order_clauses.extend( + [ + case((Account.ck_check_status == "valid", 0), else_=1), + case((Account.status == "active", 0), else_=1), + Account.ck_checked_at.is_(None).asc(), + Account.ck_checked_at.desc(), + ] + ) + order_clauses.extend( + [ + AccountCommodityState.observed_at.desc(), + Account.id.asc(), + ] + ) + return ( db.query( Account.id.label("account_id"), @@ -289,55 +465,24 @@ def _capability_candidate_query( Account.points.label("account_points"), Account.gold_balance.label("account_gold_balance"), Account.points_expire_at.label("account_points_expire_at"), - Account.role_change_available_at.label( - "account_role_change_available_at" - ), + Account.role_change_available_at.label("account_role_change_available_at"), Account.elite_opened.label("account_elite_opened"), Account.role_bind_status.label("account_role_bind_status"), Account.ck_check_status.label("account_ck_check_status"), + Account.ck_checked_at.label("account_ck_checked_at"), + Account.status.label("account_status"), Account.game_name.label("account_game_name"), AccountCommodityState.offer_state.label("state_offer_state"), AccountCommodityState.observed_at.label("state_observed_at"), + missing_count_expr.label("bundle_missing_count"), + protected_flag_expr.label("is_protected_bundle"), ) .join( AccountCommodityState, AccountCommodityState.account_id == Account.id, ) - .filter( - AccountCommodityState.platform == "douyu", - AccountCommodityState.scope == scope, - AccountCommodityState.commodity_id == commodity, - eligibility_filter, - or_( - AccountCommodityState.last_exchange_at.is_(None), - AccountCommodityState.last_exchange_at < since, - ), - cookie_present_filter(), - valid_ck_filter(), - automatable_account_filter(), - role_change_ready_filter(moment), - assigned_to_pool_filter(), - ~active_lease_exists(), - ~active_collab_order_exists(), - ) - .order_by( - case( - (AccountCommodityState.offer_state == OFFER_STATE_ACTIVE, 0), - else_=1, - ), - case((Account.ck_check_status == "valid", 0), else_=1), - case((Account.status == "active", 0), else_=1), - Account.ck_checked_at.is_(None).asc(), - Account.ck_checked_at.desc(), - case((Account.elite_opened.is_(True), 0), else_=1), - case( - (Account.points >= max(0, int(required_points)), 0), - else_=1, - ), - Account.points.asc(), - AccountCommodityState.observed_at.desc(), - Account.id.asc(), - ) + .filter(*filters) + .order_by(*order_clauses) .limit(max(1, min(int(limit), 100))) ) @@ -351,6 +496,10 @@ def capability_candidate_rows( limit: int = 20, now: datetime | None = None, allow_before_open: bool = False, + required_co_commodities: tuple[str, ...] | list[str] = (), + preferred_co_commodities: tuple[str, ...] | list[str] = (), + protected_bundle_commodities: tuple[str, ...] | list[str] = (), + priority_order: tuple[str, ...] | list[str] = (), ) -> list[CapabilityCandidate]: """读取账号与能力快照;只访问本地数据库,不触发官网请求。""" query = _capability_candidate_query( @@ -361,6 +510,10 @@ def capability_candidate_rows( limit=limit, now=now, allow_before_open=allow_before_open, + required_co_commodities=required_co_commodities, + preferred_co_commodities=preferred_co_commodities, + protected_bundle_commodities=protected_bundle_commodities, + priority_order=priority_order, ) if query is None: return [] @@ -400,9 +553,19 @@ def capability_candidate_rows( candidates: list[CapabilityCandidate] = [] for row in rows: account_id = int(row.account_id) - state = states.get(account_id) - if state is None: + base_state = states.get(account_id) + if base_state is None: continue + state = CapabilityState( + account_eligibility=base_state.account_eligibility, + offer_state=base_state.offer_state, + observed_at=base_state.observed_at, + available_from=base_state.available_from, + valid_until=base_state.valid_until, + blocking_reason=base_state.blocking_reason, + bundle_missing_count=int(getattr(row, "bundle_missing_count", 0) or 0), + is_protected_bundle=bool(getattr(row, "is_protected_bundle", 0)), + ) candidates.append( CapabilityCandidate( account=CapabilityAccount( @@ -413,13 +576,13 @@ def capability_candidate_rows( points=row.account_points, gold_balance=row.account_gold_balance, points_expire_at=row.account_points_expire_at, - role_change_available_at=( - row.account_role_change_available_at - ), + role_change_available_at=(row.account_role_change_available_at), elite_opened=row.account_elite_opened, role_bind_status=str(row.account_role_bind_status or ""), ck_check_status=str(row.account_ck_check_status or ""), game_name=str(row.account_game_name or ""), + ck_checked_at=getattr(row, "account_ck_checked_at", None), + status=str(getattr(row, "account_status", "") or ""), ), state=state, ) @@ -436,6 +599,10 @@ def capability_candidate_accounts( limit: int = 20, now: datetime | None = None, allow_before_open: bool = False, + required_co_commodities: tuple[str, ...] | list[str] = (), + preferred_co_commodities: tuple[str, ...] | list[str] = (), + protected_bundle_commodities: tuple[str, ...] | list[str] = (), + priority_order: tuple[str, ...] | list[str] = (), ) -> list[CapabilityAccount]: """从新鲜的商品能力索引读取候选账号,不产生外部请求。""" return [ @@ -448,6 +615,10 @@ def capability_candidate_accounts( limit=limit, now=now, allow_before_open=allow_before_open, + required_co_commodities=required_co_commodities, + preferred_co_commodities=preferred_co_commodities, + protected_bundle_commodities=protected_bundle_commodities, + priority_order=priority_order, ) ] diff --git a/web/backend/services/platform_fulfillment/allocation.py b/web/backend/services/platform_fulfillment/allocation.py index 7fce829..13adff2 100644 --- a/web/backend/services/platform_fulfillment/allocation.py +++ b/web/backend/services/platform_fulfillment/allocation.py @@ -7,7 +7,7 @@ from datetime import datetime, timedelta from typing import Any from fastapi import HTTPException -from sqlalchemy import func, select +from sqlalchemy import case, func, or_, select from sqlalchemy.orm import Session from ...models import ( @@ -26,6 +26,7 @@ from ..account_capability_service import ( OFFER_STATE_BEFORE, allocation_availability, ) +from ..account_lifecycle import MANUAL_STATES from ..account_query_filters import ( active_collab_order_exists, active_lease_exists, @@ -40,9 +41,14 @@ from ..account_work_queue import ( active_account_work_count, enqueue_account_work, ) +from ..binding_ownership import ( + active_collab_order_for_account, + role_names_match, +) from ..douyu_account_state import DouyuLiveAccountState from . import classification from .account_selector import ( + EXCHANGE_COOLDOWN_DAYS, AccountCandidate, CapabilityCandidate, capability_candidate_rows, @@ -52,6 +58,7 @@ from .account_selector import ( ) from .common import ( DEFAULT_CAPABILITY_CANDIDATE_LIMIT, + FLOW_VERSION_CLEAN, LOCAL_CACHE_MISS_RETRY_SECONDS, LOCAL_LEASE_CONFLICT_RETRY_SECONDS, LOCAL_STOCK_RETRY_SECONDS, @@ -62,11 +69,24 @@ from .common import ( _now, ) from .outbox import _emit_order_site_binding_state +from .policy import ( + PRIORITY_KEY_BUNDLE_MATCH, + PRIORITY_KEY_CK_FRESHNESS, + PRIORITY_KEY_POINTS_ASC, + PRIORITY_KEY_PRESERVE_BUNDLE_POOL, + PRIORITY_KEY_RESOURCE_READY, + bundle_requirements_for_commodity, + normalize_allocation_policy, + normalize_priority_order, + protected_bundle_commodities, +) from .repository import _load_task, _load_task_for_update +from .role_lock import find_account_lock, find_role_lock from .runtime import ( _append_event, _apply_task_lease_policy, _lease_duration_minutes, + get_settings, ) from .views import get_task_detail @@ -323,6 +343,432 @@ def _seed_capability_refresh( return len(accounts) +def _candidate_sort_key( + candidate: CapabilityCandidate, + cached_state: DouyuLiveAccountState, + *, + required_points: int, + priority_order: list[str] | tuple[str, ...], +) -> tuple[Any, ...]: + """保持与 SQL 查询一致的多维度优先级排序,避免 Python 二次排序打乱保护顺序。""" + account = candidate.account + state = candidate.state + parts: list[Any] = [0 if state.offer_state == OFFER_STATE_ACTIVE else 1] + for key in normalize_priority_order(priority_order): + if key == PRIORITY_KEY_BUNDLE_MATCH: + parts.append(int(state.bundle_missing_count or 0)) + elif key == PRIORITY_KEY_PRESERVE_BUNDLE_POOL: + parts.append(1 if state.is_protected_bundle else 0) + elif key == PRIORITY_KEY_RESOURCE_READY: + parts.append(cached_state.readiness_rank(required_points=required_points)) + elif key == PRIORITY_KEY_POINTS_ASC: + parts.append(1 if cached_state.points is None else 0) + parts.append(int(cached_state.points or 0)) + elif key == PRIORITY_KEY_CK_FRESHNESS: + checked_at = account.ck_checked_at + parts.append(0 if account.ck_check_status == "valid" else 1) + parts.append(0 if account.status == "active" else 1) + parts.append(1 if checked_at is None else 0) + parts.append(-(checked_at.timestamp()) if checked_at is not None else 0.0) + parts.append(int(account.id)) + return tuple(parts) + + +def _apply_allocated_account_state( + db: Session, + *, + task: PlatformFulfillmentTask, + account_id: int, + account_name: str, + lease: AccountLease, + cached_state: DouyuLiveAccountState, + required_points: int, + is_presale: bool, + current: User, + moment: datetime, + allocation_strategy: str, + observed_at: datetime | None = None, + valid_until: datetime | None = None, + extra_event_detail: dict[str, Any] | None = None, + already_bound_role: str = "", +) -> dict[str, Any]: + stale_leases = ( + db.query(AccountLease) + .filter( + AccountLease.status == "active", + AccountLease.batch_id == f"pf:{int(task.id)}", + AccountLease.id != int(lease.id), + ) + .with_for_update() + .all() + ) + for stale in stale_leases: + release_lease( + db, + stale, + reason="allocation_replaced", + commit=False, + ) + task.account_id = int(account_id) + task.lease_id = int(lease.id) + task.operator_id = current.id + task.execution_status = "bound" if already_bound_role else "allocated" + task.next_allocate_at = None + task.binding_status = "bound" if already_bound_role else "not_started" + soft_reasons = cached_state.soft_requirement_reasons( + required_points=required_points + ) + gate_status, gate_issue, gate_message = _exchange_gate( + cached_state, + task.commodity_id, + allow_not_open=is_presale, + ) + if gate_status: + task.exchange_status = gate_status + task.issue_code = gate_issue + task.last_error = gate_message + elif cached_state.elite_opened is not True: + task.exchange_status = "not_opened" + task.issue_code = "elite_not_opened" + task.last_error = "账号尚未开通精英宝典,可开通后继续" + elif cached_state.points is None or cached_state.points < required_points: + task.exchange_status = "points_short" + task.issue_code = "points_short" + task.last_error = "账号积分不足,可充值后继续" + else: + task.exchange_status = "eligible" + task.issue_code = "" + task.last_error = "" + task.updated_at = moment + _apply_task_lease_policy(db, task, lease=lease) + detail: dict[str, Any] = { + "accountId": int(account_id), + "accountName": account_name, + "points": cached_state.points, + "eliteOpened": cached_state.elite_opened, + "softReasons": soft_reasons, + "exchangeStatus": task.exchange_status, + "allocationStrategy": allocation_strategy, + "capabilityObservedAt": _jsonable(observed_at), + "capabilityValidUntil": _jsonable(valid_until), + } + if extra_event_detail: + detail.update(extra_event_detail) + _append_event( + db, + task.id, + "account_allocated", + actor_type="user", + actor_id=current.id, + detail=detail, + ) + if already_bound_role: + _append_event( + db, + task.id, + "binding_reused_same_role_account", + detail={ + "roleName": already_bound_role[:128], + "accountId": int(account_id), + "accountName": account_name, + "reason": "same_role_existing_account", + }, + ) + _emit_order_site_binding_state(db, task.id) + db.commit() + return get_task_detail(db, task.id) + + +def _account_meets_commodity_eligibility( + db: Session, + *, + account_id: int, + commodity_id: str, + scope: str, + moment: datetime, + allow_before_open: bool, +) -> AccountCommodityState | None: + since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS) + allowed_offers = ( + (OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE) + if allow_before_open + else (OFFER_STATE_ACTIVE,) + ) + return ( + db.query(AccountCommodityState) + .filter( + AccountCommodityState.account_id == int(account_id), + AccountCommodityState.platform == TARGET_PLATFORM, + AccountCommodityState.scope == scope, + AccountCommodityState.commodity_id == commodity_id, + AccountCommodityState.account_eligibility == "eligible", + AccountCommodityState.offer_state.in_(allowed_offers), + AccountCommodityState.valid_until.isnot(None), + AccountCommodityState.valid_until > moment, + or_( + AccountCommodityState.last_exchange_at.is_(None), + AccountCommodityState.last_exchange_at < since, + ), + ) + .first() + ) + + +def _try_reuse_same_role_account( + db: Session, + *, + task: PlatformFulfillmentTask, + current: User, + policy: dict[str, Any], + required_co: tuple[str, ...], + moment: datetime, +) -> dict[str, Any] | None: + """同客户角色多单时,优先复用已分配/已绑定的同一斗鱼账号,避免撞 7 天角色锁。""" + if not policy.get("sameRoleReuseEnabled", True): + return None + role = str(task.customer_role_name or "").strip() + if not role: + return None + + scope = task.scope or SCOPE_ELITE + is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale" + required_points = int(task.required_points or 0) + since_365 = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS) + + sibling_rows = ( + db.query(PlatformFulfillmentTask) + .filter( + PlatformFulfillmentTask.flow_version == FLOW_VERSION_CLEAN, + PlatformFulfillmentTask.id != int(task.id), + PlatformFulfillmentTask.account_id.isnot(None), + PlatformFulfillmentTask.execution_status != "cancelled", + func.lower(func.trim(PlatformFulfillmentTask.customer_role_name)) + == role.casefold(), + ) + .order_by( + case((PlatformFulfillmentTask.lease_id.isnot(None), 0), else_=1), + case((PlatformFulfillmentTask.binding_status == "bound", 0), else_=1), + PlatformFulfillmentTask.updated_at.desc(), + PlatformFulfillmentTask.id.desc(), + ) + .limit(10) + .all() + ) + candidate_account_ids: list[int] = [] + for row in sibling_rows: + if row.account_id and int(row.account_id) not in candidate_account_ids: + candidate_account_ids.append(int(row.account_id)) + role_lock = find_role_lock(db, role, current_account_id=None, now=moment) + if role_lock is not None and int(role_lock.account_id) not in candidate_account_ids: + candidate_account_ids.append(int(role_lock.account_id)) + if not candidate_account_ids: + return None + + for candidate_account_id in candidate_account_ids: + account = db.get(Account, int(candidate_account_id)) + if account is None: + continue + if ( + not bool(account.auto_managed) + or str(account.status or "") in MANUAL_STATES + or not str(account.cookie or "").strip() + or str(account.ck_check_status or "") != "valid" + or account.assigned_to is not None + ): + continue + account_role = str(account.game_name or "").strip() + if str(account.role_bind_status or "") == "bound" and ( + not account_role or not role_names_match(account_role, role) + ): + continue + if find_account_lock(db, account.id, role, now=moment) is not None: + continue + + # 同一斗鱼号不能用来兑换两次完全相同的商品。 + duplicate_commodity = ( + db.query(PlatformFulfillmentTask.id) + .filter( + PlatformFulfillmentTask.account_id == int(account.id), + PlatformFulfillmentTask.id != int(task.id), + PlatformFulfillmentTask.execution_status != "cancelled", + PlatformFulfillmentTask.commodity_id == task.commodity_id, + ) + .first() + ) + if duplicate_commodity is not None: + continue + + primary_state = _account_meets_commodity_eligibility( + db, + account_id=int(account.id), + commodity_id=task.commodity_id, + scope=scope, + moment=moment, + allow_before_open=is_presale, + ) + if primary_state is None: + continue + co_missing = any( + _account_meets_commodity_eligibility( + db, + account_id=int(account.id), + commodity_id=co_cid, + scope=scope, + moment=moment, + allow_before_open=True, + ) + is None + for co_cid in required_co + ) + if co_missing: + continue + + recent_exchange = ( + db.query(AccountEvent.id) + .filter( + AccountEvent.account_id == int(account.id), + AccountEvent.event_type == "exchange", + AccountEvent.subject_key.in_([task.commodity_id, *required_co]), + AccountEvent.occurred_at >= since_365, + ) + .first() + ) + if recent_exchange is not None: + continue + + active_collab = active_collab_order_for_account(db, int(account.id)) + if active_collab is not None: + collab_role = str(active_collab.bind_game_role or "").strip() + if not collab_role and active_collab.source_task_id: + source_task = db.get( + PlatformFulfillmentTask, int(active_collab.source_task_id) + ) + if source_task is not None: + collab_role = str(source_task.customer_role_name or "").strip() + if not collab_role or not role_names_match(collab_role, role): + continue + + active_lease = ( + db.query(AccountLease) + .filter( + AccountLease.account_id == int(account.id), + AccountLease.status == "active", + ) + .with_for_update() + .first() + ) + reused_existing_lease = False + sibling_ids: list[int] = [] + sibling_bound = False + if active_lease is not None: + if active_lease.purpose != "platform_fulfillment": + continue + holders = ( + db.query(PlatformFulfillmentTask) + .filter( + PlatformFulfillmentTask.lease_id == int(active_lease.id), + PlatformFulfillmentTask.execution_status != "cancelled", + ) + .all() + ) + if not holders: + continue + if any( + not str(holder.customer_role_name or "").strip() + or not role_names_match(holder.customer_role_name, role) + or holder.commodity_id == task.commodity_id + for holder in holders + ): + continue + lease = active_lease + reused_existing_lease = True + sibling_ids = [int(holder.id) for holder in holders] + sibling_bound = any(holder.binding_status == "bound" for holder in holders) + else: + if active_collab is not None: + continue + candidate_model = AccountCandidate( + account_id=int(account.id), + username=str(account.username or ""), + nickname=str(account.nickname or ""), + points=int(account.points or 0), + gold_balance=account.gold_balance, + points_expire_at=account.points_expire_at, + role_change_available_at=account.role_change_available_at, + ) + lease = lease_account( + db, + candidate=candidate_model, + holder_user_id=current.id, + task_id=task.id, + commodity_id=task.commodity_id, + ttl_minutes=_lease_duration_minutes(db), + commit=False, + ) + if lease is None: + continue + + already_bound_role = "" + if ( + str(account.role_bind_status or "") == "bound" + and account_role + and role_names_match(account_role, role) + and ( + sibling_bound + or ( + role_lock is not None + and int(role_lock.account_id) == int(account.id) + ) + ) + ): + already_bound_role = account_role + + account_name = account.nickname or account.username or f"#{account.id}" + availability = allocation_availability( + primary_state.account_eligibility, + primary_state.offer_state, + ) + cached_state = DouyuLiveAccountState( + account_id=int(account.id), + account_name=account_name, + checked_at=primary_state.observed_at or moment, + ck_verdict="valid", + ck_message="同角色复用关联账号 CK 有效", + elite_opened=account.elite_opened, + points=account.points, + limited_ids=frozenset(), + role_change_available_at=account.role_change_available_at, + commodity_availability={task.commodity_id: availability}, + commodity_blocking_reasons=( + {task.commodity_id: str(primary_state.blocking_reason or "")} + if primary_state.blocking_reason + else {} + ), + ) + return _apply_allocated_account_state( + db, + task=task, + account_id=int(account.id), + account_name=account_name, + lease=lease, + cached_state=cached_state, + required_points=required_points, + is_presale=is_presale, + current=current, + moment=moment, + allocation_strategy="same_role_reuse", + observed_at=primary_state.observed_at, + valid_until=primary_state.valid_until, + extra_event_detail={ + "sharedLease": reused_existing_lease, + "siblingTaskIds": sibling_ids, + "reusedRoleName": role, + }, + already_bound_role=already_bound_role, + ) + return None + + def _allocate_task_from_capability( db: Session, *, @@ -336,14 +782,31 @@ def _allocate_task_from_capability( task = _load_task_for_update(db, int(task.id)) if task.account_id and task.lease_id: current_lease = ( - db.query(AccountLease) - .filter(AccountLease.id == int(task.lease_id)) - .first() + db.query(AccountLease).filter(AccountLease.id == int(task.lease_id)).first() ) if current_lease is not None and current_lease.status == "active": return get_task_detail(db, task.id) moment = _now() required_points = int(task.required_points or 0) + policy = normalize_allocation_policy(get_settings(db).get("allocationPolicy")) + required_co, preferred_co = bundle_requirements_for_commodity( + policy, + task.commodity_id, + ) + protected_co = protected_bundle_commodities(policy, task.commodity_id) + priority_order = policy.get("priorityOrder") or () + + reused = _try_reuse_same_role_account( + db, + task=task, + current=current, + policy=policy, + required_co=required_co, + moment=moment, + ) + if reused is not None: + return reused + try: candidate_limit = int( os.getenv( @@ -363,11 +826,16 @@ def _allocate_task_from_capability( scope=task.scope or SCOPE_ELITE, now=moment, allow_before_open=is_presale, + required_co_commodities=required_co, + preferred_co_commodities=preferred_co, + protected_bundle_commodities=protected_co, + priority_order=priority_order, ) recent_exchange_ids: set[int] = set() if capability_candidates: candidate_ids = [int(item.account.id) for item in capability_candidates] since = moment - timedelta(days=365) + commodity_check_ids = list(dict.fromkeys([task.commodity_id, *required_co])) recent_exchange_ids = { int(account_id) for (account_id,) in ( @@ -375,7 +843,7 @@ def _allocate_task_from_capability( .filter( AccountEvent.account_id.in_(candidate_ids), AccountEvent.event_type == "exchange", - AccountEvent.subject_key == task.commodity_id, + AccountEvent.subject_key.in_(commodity_check_ids), AccountEvent.occurred_at >= since, ) .distinct() @@ -393,7 +861,7 @@ def _allocate_task_from_capability( "accountId": account_id, "accountName": candidate.account.nickname or candidate.account.username, - "reasons": ["365 天内已有该商品兑换事件"], + "reasons": ["365 天内已有该商品或捆绑商品兑换事件"], "source": "capability", } ) @@ -409,10 +877,11 @@ def _allocate_task_from_capability( ) qualified.sort( - key=lambda item: ( - item[1].readiness_rank(required_points=required_points), - int(item[1].points or 0), - int(item[0].account.id), + key=lambda item: _candidate_sort_key( + item[0], + item[1], + required_points=required_points, + priority_order=priority_order, ) ) selected: CapabilityCandidate | None = None @@ -466,6 +935,13 @@ def _allocate_task_from_capability( availability_counts=availability_counts, lease_conflict=bool(qualified), ) + if ( + required_co + and not capability_candidates + and retry_reason == "lease_conflict" + ): + retry_reason = "bundle_co_eligibility_missing" + retry_at = moment + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS) refresh_queued = ( _seed_capability_refresh(db, task=task, now=moment) if retry_reason @@ -473,6 +949,7 @@ def _allocate_task_from_capability( "capability_cache_miss", "account_role_cooldown", "account_pool_busy", + "bundle_co_eligibility_missing", } else 0 ) @@ -482,6 +959,11 @@ def _allocate_task_from_capability( elif retry_reason == "capability_cache_miss": task.issue_code = "capability_cache_miss" task.last_error = "暂无该商品的新鲜账号兑换资格,等待后台刷新" + elif retry_reason == "bundle_co_eligibility_missing": + task.issue_code = "bundle_co_eligibility_missing" + task.last_error = ( + "已有单个商品可兑账号,但缺少同时具备捆绑商品全部兑换资格的可用账号" + ) elif retry_reason == "lease_conflict": task.issue_code = "account_lease_conflict" task.last_error = "已找到候选账号,但刚被其他任务占用" @@ -512,6 +994,8 @@ def _allocate_task_from_capability( "matchingMode": "capability", "strategy": "local_capability", "capabilityCandidates": len(capability_candidates), + "requiredCoCommodities": list(required_co), + "preferredCoCommodities": list(preferred_co), "availabilityCounts": availability_counts, "retryAt": _jsonable(retry_at), "retryReason": retry_reason, @@ -524,76 +1008,26 @@ def _allocate_task_from_capability( return get_task_detail(db, task.id) selected_account = selected.account - stale_leases = ( - db.query(AccountLease) - .filter( - AccountLease.status == "active", - AccountLease.batch_id == f"pf:{int(task.id)}", - AccountLease.id != int(lease.id), - ) - .with_for_update() - .all() - ) - for stale in stale_leases: - release_lease( - db, - stale, - reason="allocation_replaced", - commit=False, - ) - task.account_id = selected_account.id - task.lease_id = lease.id - task.operator_id = current.id - task.execution_status = "allocated" - task.next_allocate_at = None - task.binding_status = "not_started" - soft_reasons = selected_state.soft_requirement_reasons( - required_points=required_points - ) - gate_status, gate_issue, gate_message = _exchange_gate( - selected_state, - task.commodity_id, - allow_not_open=is_presale, - ) - if gate_status: - task.exchange_status = gate_status - task.issue_code = gate_issue - task.last_error = gate_message - elif selected_state.elite_opened is not True: - task.exchange_status = "not_opened" - task.issue_code = "elite_not_opened" - task.last_error = "账号尚未开通精英宝典,可开通后继续" - elif selected_state.points is None or selected_state.points < required_points: - task.exchange_status = "points_short" - task.issue_code = "points_short" - task.last_error = "账号积分不足,可充值后继续" - else: - task.exchange_status = "eligible" - task.issue_code = "" - task.last_error = "" - task.updated_at = moment - _apply_task_lease_policy(db, task, lease=lease) - _append_event( + return _apply_allocated_account_state( db, - task.id, - "account_allocated", - actor_type="user", - actor_id=current.id, - detail={ - "accountId": selected_account.id, - "accountName": selected_state.account_name, - "points": selected_state.points, - "eliteOpened": selected_state.elite_opened, - "softReasons": soft_reasons, - "exchangeStatus": task.exchange_status, - "allocationStrategy": "local_capability", - "capabilityObservedAt": _jsonable(selected.state.observed_at), - "capabilityValidUntil": _jsonable(selected.state.valid_until), + task=task, + account_id=int(selected_account.id), + account_name=selected_state.account_name, + lease=lease, + cached_state=selected_state, + required_points=required_points, + is_presale=is_presale, + current=current, + moment=moment, + allocation_strategy="local_capability", + observed_at=selected.state.observed_at, + valid_until=selected.state.valid_until, + extra_event_detail={ + "requiredCoCommodities": list(required_co), + "preferredCoCommodities": list(preferred_co), + "bundleMissingCount": int(selected.state.bundle_missing_count or 0), }, ) - _emit_order_site_binding_state(db, task.id) - db.commit() - return get_task_detail(db, task.id) def prepare_manual_allocation( diff --git a/web/backend/services/platform_fulfillment/auto_allocator.py b/web/backend/services/platform_fulfillment/auto_allocator.py index 461bbc7..16e11eb 100644 --- a/web/backend/services/platform_fulfillment/auto_allocator.py +++ b/web/backend/services/platform_fulfillment/auto_allocator.py @@ -300,6 +300,28 @@ def start_allocated_bindings_once( for task in rows: if not _has_game_home_profile(task): continue + # 若共享同一租约的兄弟任务已在出码/扫码/确认中,等待兄弟绑定完成后自动同步,避免重复发码。 + if task.lease_id: + in_flight_sibling = ( + db.query(PlatformFulfillmentTask.id) + .filter( + PlatformFulfillmentTask.lease_id == int(task.lease_id), + PlatformFulfillmentTask.id != int(task.id), + PlatformFulfillmentTask.execution_status != "cancelled", + PlatformFulfillmentTask.binding_status.in_( + ( + "preparing", + "qr_pending", + "waiting_bind", + "role_ready", + "confirming", + ) + ), + ) + .first() + ) + if in_flight_sibling is not None: + continue try: service.start_binding_sync( db, diff --git a/web/backend/services/platform_fulfillment/binding.py b/web/backend/services/platform_fulfillment/binding.py index f4ddcbb..16e9994 100644 --- a/web/backend/services/platform_fulfillment/binding.py +++ b/web/backend/services/platform_fulfillment/binding.py @@ -3,6 +3,7 @@ from __future__ import annotations import uuid +from datetime import timedelta from typing import Any from fastapi import HTTPException @@ -13,6 +14,7 @@ from starlette.concurrency import run_in_threadpool from ...models import ( Account, + AccountEvent, AccountLease, DouyuTask, PlatformFulfillmentEvent, @@ -115,6 +117,126 @@ BINDING_EVIDENCE_TASK_TYPES = frozenset({"get_bind_qr", "confirm_bind"}) assert BINDING_EVIDENCE_TASK_TYPES <= BINDING_TASK_TYPES +def _can_reuse_existing_account_binding( + db: Session, + *, + task: PlatformFulfillmentTask, + account: Account | None, +) -> str: + """共享账号若已绑定到本单填写的同一客户角色(且有同租约/7天绑定依据),直接复用绑定。""" + customer_role = str(task.customer_role_name or "").strip() + if not customer_role or account is None or not task.lease_id: + return "" + if str(account.role_bind_status or "") != "bound": + return "" + account_role = str(account.game_name or "").strip() + if not account_role or not role_names_match(account_role, customer_role): + return "" + sibling_bound = ( + db.query(PlatformFulfillmentTask.id) + .filter( + PlatformFulfillmentTask.lease_id == int(task.lease_id), + PlatformFulfillmentTask.account_id == int(account.id), + PlatformFulfillmentTask.id != int(task.id), + PlatformFulfillmentTask.execution_status != "cancelled", + PlatformFulfillmentTask.binding_status == "bound", + ) + .first() + ) + if sibling_bound is not None: + return account_role + since = _now() - timedelta(days=7) + recent_bind = ( + db.query(AccountEvent.id) + .filter( + AccountEvent.account_id == int(account.id), + AccountEvent.event_type == "bind_ok", + AccountEvent.subject_type == "elite_role", + AccountEvent.subject_key == account_role, + AccountEvent.occurred_at >= since, + ) + .first() + ) + return account_role if recent_bind is not None else "" + + +def _mark_same_role_reused_bound( + db: Session, + *, + task: PlatformFulfillmentTask, + account: Account, + role_name: str, + lease: AccountLease | None = None, + source_task_id: int | None = None, +) -> None: + resolved_lease = lease or _lease_for_task(db, task) + task.binding_status = "bound" + task.execution_status = "bound" + task.issue_code = "" + task.last_error = "" + task.updated_at = _now() + detail: dict[str, Any] = { + "roleName": role_name[:128], + "accountId": int(account.id), + "accountName": account.nickname or account.username or "", + "reason": "same_role_existing_account", + } + if source_task_id is not None: + detail["sourcePlatformTaskId"] = int(source_task_id) + _append_event( + db, + task.id, + "binding_reused_same_role_account", + detail=detail, + ) + _apply_task_lease_policy(db, task, lease=resolved_lease) + _emit_order_site_binding_state(db, task.id) + + +def _propagate_same_role_binding_to_siblings( + db: Session, + *, + bound_task: PlatformFulfillmentTask, + account: Account | None, + role_name: str, +) -> int: + """同租约主单绑定成功后,把同角色共享账号的其它在途履约单同步置为 bound。""" + if ( + not bound_task.lease_id + or not bound_task.account_id + or account is None + or not role_name + ): + return 0 + siblings = ( + db.query(PlatformFulfillmentTask) + .filter( + PlatformFulfillmentTask.lease_id == int(bound_task.lease_id), + PlatformFulfillmentTask.account_id == int(bound_task.account_id), + PlatformFulfillmentTask.id != int(bound_task.id), + PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")), + PlatformFulfillmentTask.binding_status.in_( + ACTIVE_BINDING_STATUSES | {"confirming"} + ), + PlatformFulfillmentTask.customer_role_name != "", + ) + .all() + ) + updated = 0 + for sibling in siblings: + if not role_names_match(sibling.customer_role_name, role_name): + continue + _mark_same_role_reused_bound( + db, + task=sibling, + account=account, + role_name=role_name, + source_task_id=int(bound_task.id), + ) + updated += 1 + return updated + + def start_binding_sync( db: Session, *, @@ -128,9 +250,30 @@ def start_binding_sync( lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() if lease is None or lease.status != "active": raise HTTPException(status_code=409, detail="账号租约已失效,请重新分配") + account = db.query(Account).filter(Account.id == task.account_id).first() + reused_role = _can_reuse_existing_account_binding( + db, + task=task, + account=account, + ) + if reused_role and account is not None: + if task.binding_status != "bound": + task.operator_id = current.id + _mark_same_role_reused_bound( + db, + task=task, + account=account, + role_name=reused_role, + lease=lease, + ) + db.commit() + return get_task_detail(db, task.id) if task.bind_task_id: existing = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() - if existing is not None and existing.platform_task_id not in (None, int(task.id)): + if existing is not None and existing.platform_task_id not in ( + None, + int(task.id), + ): # 当前指针指向了别的订单的任务:当作没有绑定任务,重新出码。 existing = None if existing: @@ -344,11 +487,7 @@ def _order_target_role( 优先取当前绑定任务;当前任务已经是确认任务时,从订单自己更新的绑码任务里回看。 只用带订单归属的任务,不看账号历史。 """ - current = ( - db.get(DouyuTask, int(task.bind_task_id)) - if task.bind_task_id - else None - ) + current = db.get(DouyuTask, int(task.bind_task_id)) if task.bind_task_id else None role = _pending_role_of(current) if role: return role @@ -446,9 +585,7 @@ def _sync_confirmed_observation( db, task, observation, - reason="target_mismatch" - if target_role - else "missing_target", + reason="target_mismatch" if target_role else "missing_target", confirmed_role=confirmed_role, target_role=target_role, ) @@ -490,6 +627,12 @@ def _sync_confirmed_observation( ) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) + _propagate_same_role_binding_to_siblings( + db, + bound_task=task, + account=account, + role_name=confirmed_role, + ) changed += 1 return changed @@ -793,8 +936,10 @@ def _same_pair_reuse_role( if not isinstance(result, dict) or account is None: return "" # 发码预检/轮询未变化阶段绝不复用账号历史角色,必须等扫码完成或观测到扫码变化。 - if task_status and task_status != "success" and not bool( - result.get("bind_poll_legacy_observed_change") + if ( + task_status + and task_status != "success" + and not bool(result.get("bind_poll_legacy_observed_change")) ): return "" if str(account.role_bind_status or "") != "bound": @@ -814,19 +959,15 @@ def _same_pair_reuse_role( else [] ) candidates = [ - raw - for raw in (result.get("bind_candidates") or []) - if isinstance(raw, dict) + raw for raw in (result.get("bind_candidates") or []) if isinstance(raw, dict) ] action_candidates = [ raw for raw in candidates - if str(raw.get("act_alias") or raw.get("alias") or "").strip() - in action_aliases + if str(raw.get("act_alias") or raw.get("alias") or "").strip() in action_aliases ] if any( - str(raw.get("role_name") or "").strip() - and not bool(raw.get("is_bound_act")) + str(raw.get("role_name") or "").strip() and not bool(raw.get("is_bound_act")) for raw in action_candidates ): # 动作 alias 上已有新的 pending:客户扫了新角色,交给正常确认。 @@ -860,10 +1001,9 @@ def _same_pair_reuse_role( for raw in action_candidates ) return current if action_bound else "" - if ( - (not action_aliases or selected_alias not in action_aliases) - and str(result.get("current_role_name") or "").strip() == current - ): + if (not action_aliases or selected_alias not in action_aliases) and str( + result.get("current_role_name") or "" + ).strip() == current: return current return "" @@ -891,9 +1031,7 @@ def _mark_reused_pair( "roleName": role_name[:128], "accountId": task.account_id, "accountName": ( - (account.nickname or account.username) - if account is not None - else "" + (account.nickname or account.username) if account is not None else "" ), "sourceTaskId": int(source.id), "sourceTaskType": str(source.task_type or ""), @@ -902,6 +1040,12 @@ def _mark_reused_pair( ) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) + _propagate_same_role_binding_to_siblings( + db, + bound_task=task, + account=account, + role_name=role_name, + ) return True @@ -1022,7 +1166,11 @@ def _apply_binding_task( else "" ) expected_name = str( - (last_mismatch.get("expected_role_name") if isinstance(last_mismatch, dict) else "") + ( + last_mismatch.get("expected_role_name") + if isinstance(last_mismatch, dict) + else "" + ) or task.customer_role_name or "" ).strip() @@ -1076,7 +1224,9 @@ def _apply_binding_task( target_role = _order_target_role( db, task, - before_task_id=int(source.id) if source.task_type == "confirm_bind" else None, + before_task_id=int(source.id) + if source.task_type == "confirm_bind" + else None, ) expected_role = customer_role or explicit_expected or target_role if is_current: @@ -1146,9 +1296,7 @@ def _apply_binding_task( task, source, reason=( - reason - if reason != "missing_target" - else "untrusted_confirmation" + reason if reason != "missing_target" else "untrusted_confirmation" ), confirmed_role=confirmed_role, target_role=expected_role, @@ -1180,6 +1328,12 @@ def _apply_binding_task( ) _apply_task_lease_policy(db, task, lease=lease) _emit_order_site_binding_state(db, task.id) + _propagate_same_role_binding_to_siblings( + db, + bound_task=task, + account=account, + role_name=confirmed_role, + ) return True if binding.status == BINDING_VIEW_PENDING: @@ -1374,9 +1528,7 @@ def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int: if douyu_task.platform_task_id: task = ( db.query(PlatformFulfillmentTask) - .filter( - PlatformFulfillmentTask.id == int(douyu_task.platform_task_id) - ) + .filter(PlatformFulfillmentTask.id == int(douyu_task.platform_task_id)) .with_for_update() .first() ) @@ -1408,9 +1560,7 @@ def sync_task_from_binding_runner(db: Session, *, douyu_task_id: int) -> int: .filter( PlatformFulfillmentTask.account_id == int(douyu_task.account_id), PlatformFulfillmentTask.scope == "elite", - PlatformFulfillmentTask.binding_status.in_( - ACTIVE_BINDING_STATUSES - ), + PlatformFulfillmentTask.binding_status.in_(ACTIVE_BINDING_STATUSES), PlatformFulfillmentTask.execution_status.notin_( ("completed", "cancelled", "manual_required") ), @@ -1460,9 +1610,7 @@ def _revert_false_same_pair_reuse( PlatformFulfillmentTask.account_id.isnot(None), PlatformFulfillmentTask.bind_task_id.isnot(None), PlatformFulfillmentTask.binding_status == "bound", - PlatformFulfillmentTask.execution_status.notin_( - ("completed", "cancelled") - ), + PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")), PlatformFulfillmentTask.exchange_status.notin_( ("succeeded", "locked", "submitting") ), @@ -1491,9 +1639,7 @@ def _revert_false_same_pair_reuse( ) if reuse_event is None: continue - reused_role = str( - (reuse_event.detail_json or {}).get("roleName") or "" - ).strip() + reused_role = str((reuse_event.detail_json or {}).get("roleName") or "").strip() customer_role = str(task.customer_role_name or "").strip() if not customer_role or ( reused_role and role_names_match(reused_role, customer_role) @@ -1547,9 +1693,7 @@ def reconcile_binding_observations( PlatformFulfillmentTask.binding_status.in_( tuple(ACTIVE_BINDING_STATUSES) + ("confirming", "failed") ), - PlatformFulfillmentTask.execution_status.notin_( - ("completed", "cancelled") - ), + PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")), ) .order_by( # role_ready 订单最可能已有新观测可自愈;先处理它们,避免 @@ -1581,9 +1725,7 @@ def reconcile_binding_observations( reconciled += 1 continue current = ( - db.get(DouyuTask, int(task.bind_task_id)) - if task.bind_task_id - else None + db.get(DouyuTask, int(task.bind_task_id)) if task.bind_task_id else None ) if ( current is not None @@ -1644,10 +1786,7 @@ def _latest_pending_binding_task( db: Session, task: PlatformFulfillmentTask, ) -> DouyuTask | None: - if ( - not task.account_id - or task.binding_status not in ACTIVE_BINDING_STATUSES - ): + if not task.account_id or task.binding_status not in ACTIVE_BINDING_STATUSES: return None lease = _lease_for_task(db, task) if not lease_is_active(lease): @@ -1685,11 +1824,7 @@ def _attach_pending_binding_task( task: PlatformFulfillmentTask, bind_task: DouyuTask, ) -> bool: - account = ( - db.get(Account, int(task.account_id)) - if task.account_id - else None - ) + account = db.get(Account, int(task.account_id)) if task.account_id else None lease = _lease_for_task(db, task) binding = resolve_douyu_binding(bind_task, account=account) if ( @@ -1758,9 +1893,7 @@ def sync_active_task_from_account_binding( if scope != "elite": return 0 source_task = ( - db.get(DouyuTask, int(source_task_id)) - if source_task_id is not None - else None + db.get(DouyuTask, int(source_task_id)) if source_task_id is not None else None ) if ( source_task is None @@ -1779,9 +1912,7 @@ def sync_active_task_from_account_binding( PlatformFulfillmentTask.account_id == int(account_id), PlatformFulfillmentTask.scope == "elite", PlatformFulfillmentTask.binding_status == "role_ready", - PlatformFulfillmentTask.execution_status.notin_( - ("completed", "cancelled") - ), + PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")), AccountLease.status == "active", AccountLease.purpose == "platform_fulfillment", ) @@ -1836,9 +1967,7 @@ def sync_active_task_from_account_binding( detail={ "accountId": int(account_id), "accountName": ( - account.nickname or account.username - if account is not None - else "" + account.nickname or account.username if account is not None else "" ), "roleName": binding.confirmed_role_name, "gameChannel": ( @@ -1860,6 +1989,7 @@ def sync_active_task_from_account_binding( db.commit() return 1 + def requires_account_binding_sync(task_type: str) -> bool: return str(task_type or "") in BINDING_SYNC_TASK_TYPES @@ -1944,7 +2074,10 @@ def confirm_binding_sync(db: Session, *, task_id: int, current: User) -> dict[st db.commit() return get_task_detail(db, task.id) expected_role_name = str( - task.customer_role_name or target_role_name or current_bind_result.get("role_name") or "" + task.customer_role_name + or target_role_name + or current_bind_result.get("role_name") + or "" ).strip() baseline_role_name = str(current_bind_result.get("current_role_name") or "").strip() batch_id = f"pfconfirm-{task.id}-{uuid.uuid4().hex[:8]}" @@ -2096,7 +2229,10 @@ def verify_task_binding_sync( actor_type = "system" if automatic or current is None else "user" actor_id = None if automatic or current is None else int(current.id) if role_status in {ROLE_ERROR, ROLE_UNKNOWN}: - err_text = ";".join(str(x) for x in (role.get("errors") or []) if x) or "斗鱼接口查询异常" + err_text = ( + ";".join(str(x) for x in (role.get("errors") or []) if x) + or "斗鱼接口查询异常" + ) _append_event( db, task.id, @@ -2144,9 +2280,7 @@ def verify_task_binding_sync( else "" ) actual_alias = str( - (action_bound or {}).get("act_alias") - or role.get("source_alias") - or "" + (action_bound or {}).get("act_alias") or role.get("source_alias") or "" ).strip() actual_channel = str(role.get("game_channel") or "").strip() expected_role = str( @@ -2184,7 +2318,9 @@ def verify_task_binding_sync( ) issue_code = "role_changed" else: - pending_role = str(role.get("pending_role_name") or role.get("role_name") or "").strip() + pending_role = str( + role.get("pending_role_name") or role.get("role_name") or "" + ).strip() mismatch_msg = ( f"斗鱼复核未通过:角色「{pending_role}」仍处于待确认,尚未绑定生效" if pending_role diff --git a/web/backend/services/platform_fulfillment/lifecycle.py b/web/backend/services/platform_fulfillment/lifecycle.py index 79c6277..2785506 100644 --- a/web/backend/services/platform_fulfillment/lifecycle.py +++ b/web/backend/services/platform_fulfillment/lifecycle.py @@ -5,6 +5,7 @@ from __future__ import annotations from typing import Any from fastapi import HTTPException +from sqlalchemy import case from sqlalchemy.orm import Session from ...models import ( @@ -66,6 +67,52 @@ from .runtime import ( from .views import get_task_detail +def _release_or_detach_shared_lease( + db: Session, + *, + task: PlatformFulfillmentTask, + lease: AccountLease | None, + current: User, + collab_reason: str, + release_reason: str, +) -> None: + """释放/取消前先检查是否有同租约共享账号的未取消履约任务。""" + if lease is None or lease.status != "active": + return + remaining_holders = ( + db.query(PlatformFulfillmentTask) + .filter( + PlatformFulfillmentTask.lease_id == int(lease.id), + PlatformFulfillmentTask.id != int(task.id), + PlatformFulfillmentTask.execution_status != "cancelled", + ) + .order_by( + case( + (PlatformFulfillmentTask.execution_status != "completed", 0), + else_=1, + ), + PlatformFulfillmentTask.id.asc(), + ) + .all() + ) + if remaining_holders: + next_holder = remaining_holders[0] + if lease.batch_id == f"pf:{int(task.id)}": + lease.batch_id = f"pf:{int(next_holder.id)}"[:64] + task.lease_id = None + _apply_task_lease_policy(db, next_holder, lease=lease) + return + retained = _retain_lease_for_active_collab( + db, + task=task, + lease=lease, + current=current, + reason=collab_reason, + ) + if retained is None: + release_lease(db, lease, reason=release_reason, commit=False) + + def release_task_account( db: Session, *, @@ -79,15 +126,14 @@ def release_task_account( if task.lease_id else None ) - retained = _retain_lease_for_active_collab( + _release_or_detach_shared_lease( db, task=task, lease=lease, current=current, - reason="platform_released_to_collab", + collab_reason="platform_released_to_collab", + release_reason=reason, ) - 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 @@ -426,9 +472,7 @@ def refresh_active_exchange_eligibility_for_account( PlatformFulfillmentTask.account_id == int(account_id), PlatformFulfillmentTask.scope == str(scope or SCOPE_ELITE), PlatformFulfillmentTask.binding_status == "bound", - PlatformFulfillmentTask.execution_status.notin_( - ("completed", "cancelled") - ), + PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")), AccountLease.status == "active", ) .order_by( @@ -583,20 +627,14 @@ def cancel_task( linked_task.status = "stopped" linked_task.message = "履约任务已取消" linked_task.finished_at = _now() - retained = _retain_lease_for_active_collab( + _release_or_detach_shared_lease( db, task=task, lease=lease, current=current, - reason="platform_cancelled_but_collab_active", + collab_reason="platform_cancelled_but_collab_active", + release_reason="platform_fulfillment_cancelled", ) - 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 @@ -799,20 +837,14 @@ def release_task_to_manual( if task.lease_id else None ) - retained = _retain_lease_for_active_collab( + _release_or_detach_shared_lease( db, task=task, lease=lease, current=current, - reason="platform_release_to_manual", + collab_reason="platform_release_to_manual", + release_reason="platform_fulfillment_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 diff --git a/web/backend/services/platform_fulfillment/policy.py b/web/backend/services/platform_fulfillment/policy.py new file mode 100644 index 0000000..ae6341b --- /dev/null +++ b/web/backend/services/platform_fulfillment/policy.py @@ -0,0 +1,211 @@ +"""直播账号履约的选号优先级与全资格捆绑规则配置。""" + +from __future__ import annotations + +from copy import deepcopy +from typing import Any + +PRIORITY_KEY_SAME_ROLE_REUSE = "same_role_reuse" +PRIORITY_KEY_BUNDLE_MATCH = "bundle_match" +PRIORITY_KEY_PRESERVE_BUNDLE_POOL = "preserve_bundle_pool" +PRIORITY_KEY_RESOURCE_READY = "resource_ready" +PRIORITY_KEY_POINTS_ASC = "points_asc" +PRIORITY_KEY_CK_FRESHNESS = "ck_freshness" + +DEFAULT_PRIORITY_ORDER: tuple[str, ...] = ( + PRIORITY_KEY_SAME_ROLE_REUSE, + PRIORITY_KEY_BUNDLE_MATCH, + PRIORITY_KEY_PRESERVE_BUNDLE_POOL, + PRIORITY_KEY_RESOURCE_READY, + PRIORITY_KEY_POINTS_ASC, + PRIORITY_KEY_CK_FRESHNESS, +) +ALLOWED_PRIORITY_KEYS = frozenset(DEFAULT_PRIORITY_ORDER) + +BUNDLE_MODE_REQUIRE_ALL = "require_all" +BUNDLE_MODE_PREFER_ALL = "prefer_all" +ALLOWED_BUNDLE_MODES = frozenset({BUNDLE_MODE_REQUIRE_ALL, BUNDLE_MODE_PREFER_ALL}) + +DEFAULT_BUNDLE_RULE: dict[str, Any] = { + "id": "presale_trio_2026_11", + "name": "怪诞乔克/冥河/雪国三皮肤全资格捆绑(临时)", + "enabled": True, + "mode": BUNDLE_MODE_REQUIRE_ALL, + "commodityIds": [ + "20260120QYOOB_bag412", # 怪诞乔克服装礼包 + "20260120QYOOB_bag413", # 冥河战士大礼包 + "20260120QYOOB_bag414", # 雪国幻梦服装礼包 + ], +} + + +def default_allocation_policy() -> dict[str, Any]: + """默认选号策略:启用同角色复用、保护全资格池,以及三皮肤临时硬捆绑。""" + return { + "sameRoleReuseEnabled": True, + "preserveBundlePool": True, + "priorityOrder": list(DEFAULT_PRIORITY_ORDER), + "bundleRules": [deepcopy(DEFAULT_BUNDLE_RULE)], + } + + +def _clean_commodity_ids(raw_values: Any) -> list[str]: + if not isinstance(raw_values, (list, tuple)): + return [] + seen: list[str] = [] + for item in raw_values: + text = str(item or "").strip() + if text and text not in seen: + seen.append(text[:64]) + return seen + + +def normalize_priority_order(raw_order: Any) -> list[str]: + order: list[str] = [] + if isinstance(raw_order, (list, tuple)): + for item in raw_order: + key = str(item or "").strip() + if key in ALLOWED_PRIORITY_KEYS and key not in order: + order.append(key) + for key in DEFAULT_PRIORITY_ORDER: + if key not in order: + order.append(key) + return order + + +def normalize_bundle_rules(raw_rules: Any) -> list[dict[str, Any]]: + if not isinstance(raw_rules, (list, tuple)): + return [deepcopy(DEFAULT_BUNDLE_RULE)] + rules: list[dict[str, Any]] = [] + used_ids: set[str] = set() + for idx, raw in enumerate(raw_rules): + if not isinstance(raw, dict): + continue + commodity_ids = _clean_commodity_ids( + raw.get("commodityIds") or raw.get("commodity_ids") + ) + if len(commodity_ids) < 2: + continue + rule_id = str(raw.get("id") or f"bundle_{idx + 1}").strip()[:64] + if not rule_id or rule_id in used_ids: + rule_id = f"bundle_{idx + 1}" + used_ids.add(rule_id) + mode = str(raw.get("mode") or BUNDLE_MODE_REQUIRE_ALL).strip() + if mode not in ALLOWED_BUNDLE_MODES: + mode = BUNDLE_MODE_REQUIRE_ALL + name = str(raw.get("name") or f"联合资格规则 {len(rules) + 1}").strip()[:128] + rules.append( + { + "id": rule_id, + "name": name, + "enabled": bool(raw.get("enabled", True)), + "mode": mode, + "commodityIds": commodity_ids, + } + ) + return rules + + +def normalize_allocation_policy(raw: Any) -> dict[str, Any]: + """把库内 JSON 或接口入参归一化为稳定结构;None 时返回默认策略。""" + if not isinstance(raw, dict): + return default_allocation_policy() + same_role = raw.get("sameRoleReuseEnabled") + if same_role is None: + same_role = raw.get("same_role_reuse_enabled", True) + preserve_pool = raw.get("preserveBundlePool") + if preserve_pool is None: + preserve_pool = raw.get("preserve_bundle_pool", True) + raw_order = raw.get("priorityOrder") + if raw_order is None: + raw_order = raw.get("priority_order") + raw_rules = raw.get("bundleRules") + if raw_rules is None: + raw_rules = raw.get("bundle_rules") + return { + "sameRoleReuseEnabled": bool(same_role), + "preserveBundlePool": bool(preserve_pool), + "priorityOrder": normalize_priority_order(raw_order), + "bundleRules": normalize_bundle_rules(raw_rules), + } + + +def matching_bundle_rules( + policy: dict[str, Any] | None, + commodity_id: str, +) -> list[dict[str, Any]]: + cid = str(commodity_id or "").strip() + if not cid: + return [] + normalized = normalize_allocation_policy(policy) + return [ + rule + for rule in normalized["bundleRules"] + if rule.get("enabled") and cid in (rule.get("commodityIds") or []) + ] + + +def bundle_requirements_for_commodity( + policy: dict[str, Any] | None, + commodity_id: str, +) -> tuple[tuple[str, ...], tuple[str, ...]]: + """返回命中商品的 (必须同时可兑商品, 优先同时可兑商品),不含自身。""" + cid = str(commodity_id or "").strip() + if not cid: + return (), () + required: list[str] = [] + preferred: list[str] = [] + for rule in matching_bundle_rules(policy, cid): + mode = str(rule.get("mode") or BUNDLE_MODE_REQUIRE_ALL) + for peer in rule.get("commodityIds") or []: + if peer == cid: + continue + if mode == BUNDLE_MODE_REQUIRE_ALL: + if peer not in required: + required.append(peer) + elif peer not in required and peer not in preferred: + preferred.append(peer) + preferred = [peer for peer in preferred if peer not in required] + return tuple(required), tuple(preferred) + + +def protected_bundle_commodities( + policy: dict[str, Any] | None, + commodity_id: str, +) -> tuple[str, ...]: + """普通单反向保护:非捆绑单尽量避开同时具备这些全套资格的账号。""" + cid = str(commodity_id or "").strip() + normalized = normalize_allocation_policy(policy) + if not normalized.get("preserveBundlePool"): + return () + if matching_bundle_rules(normalized, cid): + return () + protected: list[str] = [] + for rule in normalized["bundleRules"]: + if not rule.get("enabled"): + continue + for item in rule.get("commodityIds") or []: + if item not in protected: + protected.append(item) + return tuple(protected) + + +__all__ = [ + "ALLOWED_BUNDLE_MODES", + "ALLOWED_PRIORITY_KEYS", + "BUNDLE_MODE_PREFER_ALL", + "BUNDLE_MODE_REQUIRE_ALL", + "DEFAULT_BUNDLE_RULE", + "DEFAULT_PRIORITY_ORDER", + "PRIORITY_KEY_BUNDLE_MATCH", + "PRIORITY_KEY_CK_FRESHNESS", + "PRIORITY_KEY_POINTS_ASC", + "PRIORITY_KEY_PRESERVE_BUNDLE_POOL", + "PRIORITY_KEY_RESOURCE_READY", + "PRIORITY_KEY_SAME_ROLE_REUSE", + "bundle_requirements_for_commodity", + "default_allocation_policy", + "matching_bundle_rules", + "normalize_allocation_policy", + "protected_bundle_commodities", +] diff --git a/web/backend/services/platform_fulfillment/runtime.py b/web/backend/services/platform_fulfillment/runtime.py index f3bf48c..77c4e23 100644 --- a/web/backend/services/platform_fulfillment/runtime.py +++ b/web/backend/services/platform_fulfillment/runtime.py @@ -33,6 +33,22 @@ from .common import ( _now, binding_failed_lease_ttl_minutes, ) +from .policy import normalize_allocation_policy + + +def _settings_out(row: PlatformFulfillmentSetting) -> dict[str, Any]: + return { + "leaseDurationMinutes": row.lease_duration_minutes, + "completedReleaseDelayMinutes": row.completed_release_delay_minutes, + "manualCompletedReleaseDelayMinutes": ( + row.manual_completed_release_delay_minutes + ), + "presaleWaitingReleaseTtlMinutes": (row.presale_waiting_release_ttl_minutes), + "manualRequiredLeaseTtlMinutes": (row.manual_required_lease_ttl_minutes), + "orderMatchStartedAt": _jsonable(row.order_match_started_at), + "allocationPolicy": normalize_allocation_policy(row.allocation_policy_json), + "updatedAt": _jsonable(row.updated_at), + } def get_settings(db: Session) -> dict[str, Any]: @@ -55,17 +71,7 @@ def get_settings(db: Session) -> dict[str, Any]: db.add(row) db.commit() db.refresh(row) - return { - "leaseDurationMinutes": row.lease_duration_minutes, - "completedReleaseDelayMinutes": row.completed_release_delay_minutes, - "manualCompletedReleaseDelayMinutes": ( - row.manual_completed_release_delay_minutes - ), - "presaleWaitingReleaseTtlMinutes": (row.presale_waiting_release_ttl_minutes), - "manualRequiredLeaseTtlMinutes": (row.manual_required_lease_ttl_minutes), - "orderMatchStartedAt": _jsonable(row.order_match_started_at), - "updatedAt": _jsonable(row.updated_at), - } + return _settings_out(row) def _lease_policy_for_task( @@ -141,7 +147,28 @@ def _apply_task_lease_policy( ): return active_lease - if str(task.execution_status or "") in {"completed", "cancelled"}: + holders = ( + db.query(PlatformFulfillmentTask) + .filter( + PlatformFulfillmentTask.lease_id == int(active_lease.id), + PlatformFulfillmentTask.execution_status != "cancelled", + ) + .all() + ) + if task.execution_status != "cancelled" and all( + int(holder.id) != int(task.id) for holder in holders + ): + holders.append(task) + has_other_active_pf = any( + int(holder.id) != int(task.id) + and str(holder.execution_status or "") not in {"completed", "cancelled"} + for holder in holders + ) + + if ( + str(task.execution_status or "") in {"completed", "cancelled"} + and not has_other_active_pf + ): # 终态释放前先检查活动预售单。若账号仍被预售单使用,租约转换为 # douyu_collab 并保持无限,不能被平台 TTL 抢走。 from ..douyu_collab_service import retain_lease_for_active_collab @@ -158,7 +185,33 @@ def _apply_task_lease_policy( if retained is not None: return retained - policy, minutes = _lease_policy_for_task(task, settings or get_settings(db)) + resolved_settings = settings or get_settings(db) + if holders: + holder_policies = [ + _lease_policy_for_task(holder, resolved_settings) for holder in holders + ] + if any(holder_minutes is None for _, holder_minutes in holder_policies): + policy = next( + ( + holder_policy + for holder_policy, holder_minutes in holder_policies + if holder_minutes is None + ), + "active", + ) + minutes = None + else: + best_policy, best_minutes = max( + ( + (holder_policy, max(0, int(holder_minutes or 0))) + for holder_policy, holder_minutes in holder_policies + ), + key=lambda item: item[1], + ) + policy = best_policy + minutes = best_minutes + else: + policy, minutes = _lease_policy_for_task(task, resolved_settings) if minutes is not None: minutes = max(0, int(minutes)) old_expiry = active_lease.expires_at @@ -181,7 +234,7 @@ def _apply_task_lease_policy( }, ) - if minutes == 0: + if minutes == 0 and not any(int(holder.id) != int(task.id) for holder in holders): release_lease( db, active_lease, @@ -202,6 +255,7 @@ def update_settings( presale_waiting_release_ttl_minutes: int | None = None, manual_required_lease_ttl_minutes: int | None = None, order_match_started_at: datetime | None = None, + allocation_policy: dict[str, Any] | None = None, current: User, ) -> dict[str, Any]: row = ( @@ -223,6 +277,8 @@ def update_settings( row.manual_completed_release_delay_minutes = manual_completed_release_delay_minutes row.presale_waiting_release_ttl_minutes = presale_waiting_release_ttl_minutes row.manual_required_lease_ttl_minutes = manual_required_lease_ttl_minutes + if allocation_policy is not None: + row.allocation_policy_json = normalize_allocation_policy(allocation_policy) row.updated_by = current.id row.updated_at = now settings = { @@ -258,17 +314,7 @@ def update_settings( now=now, ) db.commit() - return { - "leaseDurationMinutes": row.lease_duration_minutes, - "completedReleaseDelayMinutes": row.completed_release_delay_minutes, - "manualCompletedReleaseDelayMinutes": ( - row.manual_completed_release_delay_minutes - ), - "presaleWaitingReleaseTtlMinutes": (row.presale_waiting_release_ttl_minutes), - "manualRequiredLeaseTtlMinutes": (row.manual_required_lease_ttl_minutes), - "orderMatchStartedAt": _jsonable(row.order_match_started_at), - "updatedAt": _jsonable(row.updated_at), - } + return _settings_out(row) def _lease_duration_minutes(db: Session) -> int | None: diff --git a/web/backend/services/platform_fulfillment/views.py b/web/backend/services/platform_fulfillment/views.py index 2f0b51e..bc5f8fc 100644 --- a/web/backend/services/platform_fulfillment/views.py +++ b/web/backend/services/platform_fulfillment/views.py @@ -65,6 +65,7 @@ class _TaskOutputContext: leases: dict[int, AccountLease] bind_tasks: dict[int, DouyuTask] collab_orders: dict[int, DouyuExternalOrder] + shared_lease_tasks: dict[int, list[int]] def invalidate_task_list_count_cache() -> None: @@ -124,15 +125,9 @@ def _load_task_output_context( tasks: list[PlatformFulfillmentTask], ) -> _TaskOutputContext: mapping_ids = { - int(task.commodity_mapping_id) - for task in tasks - if task.commodity_mapping_id - } - commodity_ids = { - str(task.commodity_id) - for task in tasks - if task.commodity_id + int(task.commodity_mapping_id) for task in tasks if task.commodity_mapping_id } + commodity_ids = {str(task.commodity_id) for task in tasks if task.commodity_id} account_ids = {int(task.account_id) for task in tasks if task.account_id} lease_ids = {int(task.lease_id) for task in tasks if task.lease_id} bind_task_ids = {int(task.bind_task_id) for task in tasks if task.bind_task_id} @@ -178,9 +173,7 @@ def _load_task_output_context( bind_tasks = ( { int(row.id): row - for row in db.query(DouyuTask) - .filter(DouyuTask.id.in_(bind_task_ids)) - .all() + for row in db.query(DouyuTask).filter(DouyuTask.id.in_(bind_task_ids)).all() } if bind_task_ids else {} @@ -195,6 +188,22 @@ def _load_task_output_context( ): if row.source_task_id is not None: collab_orders.setdefault(int(row.source_task_id), row) + shared_lease_tasks: dict[int, list[int]] = {} + if lease_ids: + for row_id, row_lease_id in ( + db.query( + PlatformFulfillmentTask.id, + PlatformFulfillmentTask.lease_id, + ) + .filter( + PlatformFulfillmentTask.lease_id.in_(lease_ids), + PlatformFulfillmentTask.execution_status != "cancelled", + ) + .order_by(PlatformFulfillmentTask.id.asc()) + .all() + ): + if row_lease_id is not None: + shared_lease_tasks.setdefault(int(row_lease_id), []).append(int(row_id)) return _TaskOutputContext( mappings=mappings, goods=goods, @@ -202,6 +211,7 @@ def _load_task_output_context( leases=leases, bind_tasks=bind_tasks, collab_orders=collab_orders, + shared_lease_tasks=shared_lease_tasks, ) @@ -355,25 +365,17 @@ def _task_out( if task.commodity_mapping_id else None ) - goods = ( - resolved.goods.get(str(task.commodity_id)) - if task.commodity_id - else None - ) + goods = resolved.goods.get(str(task.commodity_id)) if task.commodity_id else None goods_name = ( str(getattr(mapping, "goods_name", "") or "") or str(getattr(goods, "name", "") or "") or task.sku_name or task.internal_sku_key ) - account = ( - resolved.accounts.get(int(task.account_id)) if task.account_id else None - ) + account = resolved.accounts.get(int(task.account_id)) if task.account_id else None lease = resolved.leases.get(int(task.lease_id)) if task.lease_id else None bind_task = ( - resolved.bind_tasks.get(int(task.bind_task_id)) - if task.bind_task_id - else None + resolved.bind_tasks.get(int(task.bind_task_id)) if task.bind_task_id else None ) collab_order = resolved.collab_orders.get(int(task.id)) bind_result = (bind_task.result or {}) if bind_task else {} @@ -489,6 +491,15 @@ def _task_out( if lease else None ), + "sharedLeaseTaskIds": ( + [ + tid + for tid in resolved.shared_lease_tasks.get(int(task.lease_id), []) + if tid != int(task.id) + ] + if task.lease_id + else [] + ), "bindTask": ( { "id": bind_task.id, @@ -501,12 +512,12 @@ def _task_out( "platName": binding.effective_plat_name, "bindPhase": binding.bind_phase, # 客户页的“可确认”必须与确认接口读的同一层事实一致: - # 绑定任务 pending 且平台任务已经进入 role_ready,才显示确认按钮。 - # 否则会出现客户页让确认、确认接口报“没有待确认角色”的错位。 - "bindReadyForConfirm": ( - binding.status == BINDING_VIEW_PENDING - and str(task.binding_status or "") == "role_ready" - ), + # 绑定任务 pending 且平台任务已经进入 role_ready,才显示确认按钮。 + # 否则会出现客户页让确认、确认接口报“没有待确认角色”的错位。 + "bindReadyForConfirm": ( + binding.status == BINDING_VIEW_PENDING + and str(task.binding_status or "") == "role_ready" + ), "bindConfirmed": binding.bind_confirmed, } if bind_task @@ -736,7 +747,9 @@ def _customer_profile_out( or "" ) if customer_channel and account_channel: - channel_matched = all(part in account_channel for part in customer_channel.split()) + channel_matched = all( + part in account_channel for part in customer_channel.split() + ) if role and not platform_role: message = "客户已填角色,平台还未识别绑定角色" elif role_matched is True and channel_matched is not False: diff --git a/web/frontend/src/api/platformFulfillment.ts b/web/frontend/src/api/platformFulfillment.ts index 9eb7fb9..eace26c 100644 --- a/web/frontend/src/api/platformFulfillment.ts +++ b/web/frontend/src/api/platformFulfillment.ts @@ -1,5 +1,6 @@ import api from './client'; import type { + PlatformFulfillmentAllocationPolicy, PlatformFulfillmentAllocationResult, PlatformFulfillmentDetail, PlatformFulfillmentCollabSyncResult, @@ -34,6 +35,7 @@ export const platformFulfillmentApi = { presaleWaitingReleaseTtlMinutes: number | null; manualRequiredLeaseTtlMinutes: number | null; orderMatchStartedAt: string | null; + allocationPolicy?: PlatformFulfillmentAllocationPolicy; }) => api.put( '/platform-fulfillment/settings', @@ -47,6 +49,7 @@ export const platformFulfillmentApi = { manual_required_lease_ttl_minutes: data.manualRequiredLeaseTtlMinutes, order_match_started_at: data.orderMatchStartedAt, + allocation_policy: data.allocationPolicy, }, ), listTasks: (params: { diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index 9d12a78..67cc58c 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -2559,6 +2559,21 @@ export interface PlatformFulfillmentAccount { roleChangeAvailableAt: string | null; } +export interface PlatformFulfillmentBundleRule { + id: string; + name: string; + enabled: boolean; + mode: 'require_all' | 'prefer_all'; + commodityIds: string[]; +} + +export interface PlatformFulfillmentAllocationPolicy { + sameRoleReuseEnabled: boolean; + preserveBundlePool: boolean; + priorityOrder: string[]; + bundleRules: PlatformFulfillmentBundleRule[]; +} + export interface PlatformFulfillmentSettings { leaseDurationMinutes: number | null; completedReleaseDelayMinutes: number | null; @@ -2566,6 +2581,7 @@ export interface PlatformFulfillmentSettings { presaleWaitingReleaseTtlMinutes: number | null; manualRequiredLeaseTtlMinutes: number | null; orderMatchStartedAt: string | null; + allocationPolicy?: PlatformFulfillmentAllocationPolicy; updatedAt: string | null; } @@ -2707,6 +2723,7 @@ export interface PlatformFulfillmentTask { } | null; account: PlatformFulfillmentAccount | null; lease: { id: number; status: string; expiresAt: string | null } | null; + sharedLeaseTaskIds?: number[]; bindTask: PlatformFulfillmentBindTask | null; bindingEvidence: PlatformFulfillmentBindingEvidence | null; customerProfile: PlatformFulfillmentCustomerProfile | null; diff --git a/web/frontend/src/pages/PlatformFulfillmentPage.tsx b/web/frontend/src/pages/PlatformFulfillmentPage.tsx index 2d2e87b..395f7e2 100644 --- a/web/frontend/src/pages/PlatformFulfillmentPage.tsx +++ b/web/frontend/src/pages/PlatformFulfillmentPage.tsx @@ -3,10 +3,10 @@ import { useNavigate } from 'react-router-dom'; import dayjs from 'dayjs'; import type { Dayjs } from 'dayjs'; import { Alert, Button, Card, Col, DatePicker, Descriptions, Drawer, Empty, Image, Input, InputNumber, Modal, QRCode, Row, Segmented, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd'; -import { CheckCircleOutlined, CopyOutlined, CreditCardOutlined, DownloadOutlined, GiftOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, ShoppingOutlined, SyncOutlined, UndoOutlined, UserSwitchOutlined } from '@ant-design/icons'; +import { ArrowDownOutlined, ArrowUpOutlined, CheckCircleOutlined, CopyOutlined, CreditCardOutlined, DeleteOutlined, DownloadOutlined, GiftOutlined, LinkOutlined, PlusOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, ShoppingOutlined, SyncOutlined, UndoOutlined, UserSwitchOutlined } from '@ant-design/icons'; import type { ColumnsType } from 'antd/es/table'; import { douyuApi, platformFulfillmentApi } from '../api/modules'; -import type { DouyuGoodsItem, DouyuTaskItem, PlatformFulfillmentBindingLog, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentSettings, PlatformFulfillmentTask } from '../api/modules'; +import type { DouyuGoodsItem, DouyuTaskItem, PlatformFulfillmentBindingLog, PlatformFulfillmentBundleRule, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentSettings, PlatformFulfillmentTask } from '../api/modules'; import ExchangeResultImage from '../components/ExchangeResultImage'; import { copyImageToClipboard, fetchExchangeImageBlob, getExchangeImage, isExchangeTask } from '../utils/exchangeImage'; import { TASK_STATUS_COLORS, TASK_STATUS_LABELS, taskQrUrl } from './douyu-tasks/config'; @@ -171,6 +171,7 @@ const EVENT_LABELS: Record = { binding_confirmed: '履约绑定已确认', binding_manually_confirmed: '人工确认绑定', binding_reused_existing_pair: '复用同账号同角色', + binding_reused_same_role_account: '同角色共享账号自动同步绑定', binding_sync_rejected: '忽略不匹配的绑定证据', binding_scanned_role_mismatch: '扫码角色与下单资料不一致', binding_verified: '斗鱼绑定复核通过', @@ -196,6 +197,7 @@ const EVENT_LABELS: Record = { const ISSUE_LABELS: Record = { mapping_missing: '商品映射缺失', no_eligible_account: '没有可分配账号', + bundle_co_eligibility_missing: '没有同时可兑联合皮肤的账号', capability_cache_miss: '账号商品能力待补货', account_lease_conflict: '候选账号正被其他任务占用', account_pool_busy: '资格账号暂时全部占用', @@ -228,6 +230,36 @@ const DOUYU_ACTION_LABELS: Record = { exchange_goods: '兑换订单皮肤', }; +const DEFAULT_PRIORITY_ORDER = [ + 'same_role_reuse', + 'bundle_match', + 'preserve_bundle_pool', + 'resource_ready', + 'points_asc', + 'ck_freshness', +]; + +const PRIORITY_LABELS: Record = { + same_role_reuse: { label: '同客户角色复用', desc: '同角色多单优先分配给已绑定的同一个斗鱼账号' }, + bundle_match: { label: '联合全资格匹配', desc: '命中捆绑商品时优先全量可兑账号' }, + preserve_bundle_pool: { label: '保留捆绑账号池', desc: '普通单尽量避开具备全捆绑资格的账号' }, + resource_ready: { label: '资源就绪度', desc: '优先已开通精英宝典且积分充足的账号' }, + points_asc: { label: '积分升序', desc: '尽量优先消耗积分贴近需求的账号' }, + ck_freshness: { label: 'CK 新鲜度', desc: '优先最近刚校验通过 CK 的账号' }, +}; + +const DEFAULT_BUNDLE_RULE: PlatformFulfillmentBundleRule = { + id: 'presale_trio_2026_11', + name: '怪诞乔克/冥河/雪国三皮肤全资格捆绑(临时)', + enabled: true, + mode: 'require_all', + commodityIds: [ + '20260120QYOOB_bag412', + '20260120QYOOB_bag413', + '20260120QYOOB_bag414', + ], +}; + function statusLabel(value: string) { return STATUS_OPTIONS.find((item) => item.value === value)?.label || value; } @@ -342,7 +374,8 @@ function eventDescription(event: { eventType: string; detail: Record(null); const [manualRequiredLeaseTtl, setManualRequiredLeaseTtl] = useState(null); const [orderMatchStartedAt, setOrderMatchStartedAt] = useState(null); + const [sameRoleReuseEnabled, setSameRoleReuseEnabled] = useState(true); + const [preserveBundlePool, setPreserveBundlePool] = useState(true); + const [priorityOrder, setPriorityOrder] = useState(DEFAULT_PRIORITY_ORDER); + const [bundleRules, setBundleRules] = useState([DEFAULT_BUNDLE_RULE]); const [savingSettings, setSavingSettings] = useState(false); const [douyuActionLoading, setDouyuActionLoading] = useState(''); const [douyuActionType, setDouyuActionType] = useState(''); @@ -1330,9 +1370,95 @@ export default function PlatformFulfillmentPage() { setManualRequiredLeaseTtl( settings?.manualRequiredLeaseTtlMinutes ?? null, ); + const policy = settings?.allocationPolicy; + setSameRoleReuseEnabled(policy?.sameRoleReuseEnabled ?? true); + setPreserveBundlePool(policy?.preserveBundlePool ?? true); + setPriorityOrder( + policy?.priorityOrder?.length ? [...policy.priorityOrder] : [...DEFAULT_PRIORITY_ORDER], + ); + setBundleRules( + policy?.bundleRules + ? policy.bundleRules.map((rule) => ({ + ...rule, + commodityIds: [...rule.commodityIds], + })) + : [{ ...DEFAULT_BUNDLE_RULE, commodityIds: [...DEFAULT_BUNDLE_RULE.commodityIds] }], + ); setSettingsOpen(true); + if (!goods.length || !mappings.length) { + void Promise.all([ + goods.length ? Promise.resolve(goods) : douyuApi.listLiveGoods().catch(() => []), + mappings.length + ? Promise.resolve(mappings) + : platformFulfillmentApi.listMappings({ include_archived: false }).catch(() => []), + ]).then(([goodsRows, mappingRows]) => { + if (goodsRows.length && !goods.length) setGoods(goodsRows); + if (mappingRows.length && !mappings.length) setMappings(mappingRows); + }); + } }; + const movePriorityItem = (index: number, direction: -1 | 1) => { + const nextIndex = index + direction; + if (nextIndex < 0 || nextIndex >= priorityOrder.length) return; + setPriorityOrder((prev) => { + const next = [...prev]; + const [item] = next.splice(index, 1); + next.splice(nextIndex, 0, item); + return next; + }); + }; + + const addBundleRule = () => { + const nextIndex = bundleRules.length + 1; + setBundleRules((prev) => [ + ...prev, + { + id: `bundle_rule_${Date.now()}_${nextIndex}`, + name: `联合选号规则 ${nextIndex}`, + enabled: true, + mode: 'require_all', + commodityIds: [], + }, + ]); + }; + + const updateBundleRule = ( + index: number, + patch: Partial, + ) => { + setBundleRules((prev) => + prev.map((item, idx) => (idx === index ? { ...item, ...patch } : item)), + ); + }; + + const removeBundleRule = (index: number) => { + setBundleRules((prev) => prev.filter((_, idx) => idx !== index)); + }; + + const bundleCommodityOptions = (() => { + const map = new Map(); + for (const item of goods) { + const id = String(item.commodity_id || '').trim(); + if (!id) continue; + map.set(id, `${item.name || id}(${id})`); + } + for (const row of mappings) { + const id = String(row.commodityId || '').trim(); + if (!id || map.has(id)) continue; + map.set(id, `${row.goodsName || row.internalSkuKey || id}(${id})`); + } + for (const rule of bundleRules) { + for (const rawId of rule.commodityIds) { + const id = String(rawId || '').trim(); + if (id && !map.has(id)) { + map.set(id, id); + } + } + } + return Array.from(map.entries()).map(([value, label]) => ({ value, label })); + })(); + const saveLeaseSettings = async () => { const minutes = leaseDurationMode === 'unlimited' @@ -1357,6 +1483,16 @@ export default function PlatformFulfillmentPage() { presaleWaitingReleaseTtlMinutes: presaleWaitingReleaseTtl, manualRequiredLeaseTtlMinutes: manualRequiredLeaseTtl, orderMatchStartedAt: orderMatchStartedAt.toISOString(), + allocationPolicy: { + sameRoleReuseEnabled, + preserveBundlePool, + priorityOrder, + bundleRules: bundleRules.map((rule) => ({ + ...rule, + name: rule.name.trim() || rule.id, + commodityIds: rule.commodityIds.map((id) => id.trim()).filter(Boolean), + })), + }, }); setSettings(result); setSettingsOpen(false); @@ -1442,6 +1578,9 @@ export default function PlatformFulfillmentPage() { 租约 {task.lease ? '占用中' : '未占用'} · {task.lease ? leaseExpiresLabel(task.lease.expiresAt) : '-'} + {task.sharedLeaseTaskIds?.length ? ( + 同角色共享 #{task.sharedLeaseTaskIds.join(', #')} + ) : null} ) : ( 未分配 @@ -2156,7 +2295,12 @@ export default function PlatformFulfillmentPage() { {formatTime(selected.account.roleChangeAvailableAt) || '无冷却'} - {selected.lease ? leaseExpiresLabel(selected.lease.expiresAt) : '-'} + + {selected.lease ? leaseExpiresLabel(selected.lease.expiresAt) : '-'} + {selected.sharedLeaseTaskIds?.length ? ( + 同角色共享 #{selected.sharedLeaseTaskIds.join(', #')} + ) : null} + ) : ( @@ -2729,7 +2873,8 @@ export default function PlatformFulfillmentPage() { void saveLeaseSettings()} @@ -2840,6 +2985,155 @@ export default function PlatformFulfillmentPage() { message="按任务状态应用租约策略" description="保存后会按每个任务当前状态重新计算租约,不会把所有预售、人工和进行中任务统一套用同一个 TTL。" /> + + + + + + + 同客户角色多单复用同一斗鱼号 + + + + + + 普通单避开三皮肤全资格账号池 + + + + +
+ 选号优先级顺序(自上而下依次生效) + + {priorityOrder.map((key, idx) => { + const meta = PRIORITY_LABELS[key] || { label: key, desc: '' }; + return ( +
+
+ {idx + 1}. {meta.label} + {meta.desc ? ( + + {meta.desc} + + ) : null} +
+ +
+ ); + })} +
+
+ +
+
+ 商品全资格捆绑规则 + +
+ {bundleRules.length === 0 ? ( + 暂无捆绑规则,所有商品按单品资格自由选号。 + ) : ( + + {bundleRules.map((rule, idx) => ( + + updateBundleRule(idx, { enabled: checked })} + /> + updateBundleRule(idx, { name: e.target.value })} + placeholder="规则名称" + style={{ width: 260 }} + /> + + } + extra={ + + + updateBundleRule(idx, { + commodityIds: values.map((v) => String(v).trim()).filter(Boolean), + }) + } + options={bundleCommodityOptions} + /> + + ))} + + )} +
+
+