feat(fulfillment): 支持选号优先级、三皮肤联合资格捆绑与同角色共享租约
This commit is contained in:
@@ -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()
|
||||
|
||||
+36
-32
@@ -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"]
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user