feat(fulfillment): 增加账号商品能力索引与生命周期事件

This commit is contained in:
yml
2026-11-18 19:30:59 +08:00
parent dc95d83b32
commit 667634a8df
35 changed files with 3076 additions and 82 deletions
@@ -0,0 +1,123 @@
"""履约需求驱动的账号商品能力刷新作业。"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from web.backend.models import (
Account,
AccountCommodityState,
AccountLease,
AutomationJob,
PlatformFulfillmentTask,
User,
)
from web.backend.services.automation.jobs import account_capability_refresh as job
NOW = datetime.now(UTC).replace(microsecond=0)
def _account(db, name: str) -> Account:
row = Account(
username=name,
password="p",
email=f"{name}@example.com",
email_password="ep",
cookie="acf_uid=1; acf_ccn=c",
ck_check_status="valid",
status="active",
auto_managed=True,
overview_queried_at=NOW - timedelta(days=1),
)
db.add(row)
db.flush()
return row
def _state(
db,
account: Account,
*,
commodity_id: str = "C",
valid_until: datetime | None = None,
) -> AccountCommodityState:
row = AccountCommodityState(
account_id=account.id,
platform="douyu",
scope="elite",
commodity_id=commodity_id,
availability="available",
observed_at=NOW - timedelta(hours=2),
valid_until=valid_until,
next_check_at=valid_until,
)
db.add(row)
return row
def test_selects_only_stale_demand_accounts(db):
user = User(
username="cap-refresh-admin",
password_hash="h",
role="super_admin",
is_active=True,
)
db.add(user)
db.flush()
db.add(
PlatformFulfillmentTask(
source_system="order_site",
source_order_id="1",
source_order_item_id="1",
internal_sku_key="skin",
commodity_id="C",
execution_status="ready",
binding_status="not_started",
exchange_status="not_started",
paid_at=NOW,
)
)
stale = _account(db, "cap-stale")
fresh = _account(db, "cap-fresh")
other = _account(db, "cap-other")
leased = _account(db, "cap-leased")
_state(db, stale, valid_until=NOW - timedelta(minutes=1))
_state(db, fresh, valid_until=NOW + timedelta(hours=1))
_state(db, other, commodity_id="OTHER", valid_until=NOW - timedelta(minutes=1))
_state(db, leased, valid_until=NOW - timedelta(minutes=1))
db.add(
AccountLease(
account_id=leased.id,
holder_user_id=user.id,
scope="elite",
purpose="platform_fulfillment",
status="active",
)
)
db.commit()
automation_job = AutomationJob(
key=job.JOB_KEY,
title="履约商品能力补充刷新",
interval_seconds=3600,
batch_size=10,
concurrency=3,
)
selected = job.build_select_query(db, automation_job, NOW).all()
assert [row.id for row in selected] == [stale.id]
def test_no_pending_task_means_no_refresh(db):
stale = _account(db, "cap-no-demand")
_state(db, stale, valid_until=NOW - timedelta(minutes=1))
db.commit()
automation_job = AutomationJob(
key=job.JOB_KEY,
title="履约商品能力补充刷新",
interval_seconds=3600,
batch_size=10,
concurrency=3,
)
assert job.build_select_query(db, automation_job, NOW).all() == []
+300
View File
@@ -0,0 +1,300 @@
"""账号商品能力索引与兑换历史投影。"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from web.backend.models import Account, AccountCommodityState, AccountEvent, User
from web.backend.routers.accounts import account_commodities
from web.backend.services import account_capability_service as service
NOW = datetime.now(UTC).replace(microsecond=0)
def _account(db, name: str = "cap-account") -> Account:
account = Account(
username=name,
password="p",
email=f"{name}@example.com",
email_password="ep",
cookie="acf_uid=1; acf_ccn=c",
ck_check_status="valid",
status="active",
auto_managed=True,
)
db.add(account)
db.commit()
return account
def test_classify_goods_item_keeps_unknown_when_status_missing():
available, reason, raw = service.classify_goods_item({"status": 0})
assert (available, reason, raw) == ("available", "", "0")
limited, reason, raw = service.classify_goods_item({"status": "1"})
assert (limited, reason, raw) == ("limited", "该账号已达此商品兑换上限", "1")
no_stock, reason, _ = service.classify_goods_item(
{"status": 0, "storeStatus": 0}
)
assert (no_stock, reason) == ("no_stock", "官方商城当前无库存")
unknown, reason, raw = service.classify_goods_item({})
assert unknown == "unknown"
assert "未返回" in reason
assert raw == ""
def test_time_limited_goods_use_schedule_before_account_limit():
limited = {
"status": "1",
"timeLimited": 1,
"startTime": str(int((NOW - timedelta(hours=1)).timestamp())),
"endTime": str(int((NOW + timedelta(hours=1)).timestamp())),
"specTimes": [
{
"startTime": str(int((NOW - timedelta(hours=1)).timestamp())),
"endTime": str(int((NOW + timedelta(hours=1)).timestamp())),
}
],
}
availability, reason, _ = service.classify_goods_item(limited, now=NOW)
assert availability == "limited"
assert "上限" in reason
future = {
"status": "1",
"timeLimited": 1,
"startTime": str(int((NOW + timedelta(hours=2)).timestamp())),
"endTime": str(int((NOW + timedelta(hours=3)).timestamp())),
}
availability, reason, _ = service.classify_goods_item(future, now=NOW)
assert availability == "not_open"
assert "未开始" in reason
expired = {
"status": "0",
"timeLimited": 1,
"startTime": str(int((NOW - timedelta(hours=3)).timestamp())),
"endTime": str(int((NOW - timedelta(hours=2)).timestamp())),
}
availability, reason, _ = service.classify_goods_item(expired, now=NOW)
assert availability == "expired"
assert "已结束" in reason
def test_sync_stores_time_window_and_next_boundary(db):
account = _account(db, "cap-window")
end_at = NOW + timedelta(minutes=5)
service.sync_account_goods_states(
db,
account,
[
{
"commodityId": "LIMITED",
"commodityName": "套装-兔兔白日梦",
"status": "1",
"timeLimited": 1,
"startTime": str(int((NOW - timedelta(days=1)).timestamp())),
"endTime": str(int(end_at.timestamp())),
"specTimes": [
{
"startTime": str(int((NOW - timedelta(days=1)).timestamp())),
"endTime": str(int(end_at.timestamp())),
}
],
}
],
observed_at=NOW,
)
db.commit()
state = (
db.query(AccountCommodityState)
.filter_by(account_id=account.id, commodity_id="LIMITED")
.one()
)
assert state.availability == "limited"
assert state.time_limited is True
assert state.available_until == end_at
assert state.next_check_at == end_at
assert state.schedule_json
def test_sync_account_goods_states_writes_capabilities_and_exchange_stats(db):
account = _account(db)
db.add(
AccountEvent(
account_id=account.id,
event_type="exchange",
category="business",
occurred_at=NOW - timedelta(days=10),
title="兑换 A",
source="official_sync",
subject_type="commodity",
subject_key="A",
)
)
db.commit()
changed = service.sync_account_goods_states(
db,
account,
[
{"commodityId": "A", "name": "商品 A", "status": "0"},
{"commodityId": "B", "name": "商品 B", "status": "1"},
{"commodityId": "C", "name": "商品 C", "status": "0", "storeStatus": 0},
{"commodityId": "D", "name": "商品 D"},
],
observed_at=NOW,
)
db.commit()
assert changed == 4
states = {
row.commodity_id: row
for row in db.query(AccountCommodityState).filter_by(account_id=account.id)
}
assert states["A"].availability == "available"
assert states["A"].exchange_count_365d == 1
assert states["A"].last_exchange_at == NOW - timedelta(days=10)
assert states["B"].availability == "limited"
assert states["C"].availability == "no_stock"
assert states["D"].availability == "unknown"
assert states["A"].valid_until == NOW + timedelta(
seconds=service.capability_ttl_seconds()
)
def test_next_sync_marks_missing_goods_not_offered(db):
account = _account(db, "cap-remove")
service.sync_account_goods_states(
db,
account,
[
{"commodityId": "A", "status": "0"},
{"commodityId": "B", "status": "0"},
],
observed_at=NOW,
)
db.commit()
service.sync_account_goods_states(
db,
account,
[{"commodityId": "A", "status": "0"}],
observed_at=NOW + timedelta(minutes=1),
)
db.commit()
removed = (
db.query(AccountCommodityState)
.filter_by(account_id=account.id, commodity_id="B")
.one()
)
assert removed.availability == "not_offered"
assert removed.valid_until is None
def test_mark_exchange_keeps_projection_in_sync(db):
account = _account(db, "cap-exchange")
service.sync_account_goods_states(
db,
account,
[{"commodityId": "A", "name": "商品 A", "status": "0"}],
observed_at=NOW,
)
db.commit()
occurred_at = NOW + timedelta(minutes=2)
db.add(
AccountEvent(
account_id=account.id,
event_type="exchange",
category="business",
occurred_at=occurred_at,
title="兑换 商品 A",
source="douyu_task",
subject_type="commodity",
subject_key="A",
)
)
db.flush()
service.mark_commodity_exchanged(
db,
account_id=account.id,
commodity_id="A",
occurred_at=occurred_at,
commodity_name="商品 A",
)
db.commit()
state = (
db.query(AccountCommodityState)
.filter_by(account_id=account.id, commodity_id="A")
.one()
)
assert state.availability == "limited"
assert state.exchange_count_365d == 1
assert state.last_exchange_at == occurred_at
assert state.valid_until is None
def test_invalidating_ck_removes_available_from_matching_pool(db):
account = _account(db, "cap-invalid")
service.sync_account_goods_states(
db,
account,
[{"commodityId": "A", "status": "0"}],
observed_at=NOW,
)
db.commit()
changed = service.invalidate_account_commodity_states(
db,
account_id=account.id,
reason="CK 已失效",
observed_at=NOW + timedelta(minutes=1),
)
db.commit()
assert changed == 1
state = db.query(AccountCommodityState).filter_by(account_id=account.id).one()
assert state.availability == "unknown"
assert state.valid_until is None
assert "CK" in state.blocking_reason
def test_account_commodities_api_returns_summary_and_freshness(db):
account = _account(db, "cap-api")
user = User(
username="cap-api-admin",
password_hash="h",
role="super_admin",
is_active=True,
)
db.add(user)
service.sync_account_goods_states(
db,
account,
[
{"commodityId": "A", "name": "商品 A", "status": "0"},
{"commodityId": "B", "name": "商品 B", "status": "1"},
],
observed_at=NOW,
)
db.commit()
result = account_commodities(
account.id,
scope="",
availability="",
limit=500,
db=db,
current=user,
)
assert result["summary"]["total"] == 2
assert result["summary"]["fresh_available"] == 1
assert {item["commodity_id"] for item in result["items"]} == {"A", "B"}
assert all(item["fresh"] for item in result["items"])
+9
View File
@@ -656,6 +656,15 @@ class TestLifecycleApi(_Base):
assert res["success"] and account.auto_managed is False
# 关掉自动化不等于停用:账号状态仍可用
assert account.status == life.STATUS_ACTIVE
event = (
self.session.query(AccountEvent)
.filter(
AccountEvent.account_id == account.id,
AccountEvent.event_type == "automation_changed",
)
.one()
)
assert event.detail["to"] is False
class TestStatusWriteFunnel:
+11
View File
@@ -485,6 +485,15 @@ class TestOverviewTaskTypeWiring:
.all()
)
assert len(created) == len(accs)
started_events = (
session.query(AccountEvent)
.filter(AccountEvent.event_type == "task_started")
.all()
)
assert len(started_events) == len(accs)
assert {event.account_id for event in started_events} == {
account.id for account in accs
}
finally:
session.close()
@@ -1113,6 +1122,8 @@ class TestOfficialExchangeBecomesAccountEvent:
assert event.occurred_at.year == 2026
assert event.occurred_at.month == 8 # 1788054985 → 2026-08-30 前后
assert event.amount == -1280
assert event.subject_type == "commodity"
assert event.subject_key == "C1"
assert event.detail["source"] == "official_sync"
assert event.source == "official_sync"
+55
View File
@@ -524,3 +524,58 @@ class TestExpireAtParsing:
from web.backend.services.douyu_runner_donate import _parse_expire_at
assert _parse_expire_at(value) is None, "认不出来就返回 None,不要猜一个时刻"
class TestAccountTaskActivity(_Base):
def test_task_start_and_result_are_written_to_account_timeline(self):
assert biz.record_douyu_task_started(
self.session,
self.account,
task_id=501,
task_type="query_account_overview",
task_label="一键查询账号信息",
scope="elite",
actor_id=self.user.id,
)
assert biz.record_douyu_task_result(
self.session,
self.account,
task_id=501,
task_type="query_account_overview",
task_label="一键查询账号信息",
scope="elite",
status="success",
message="查询完成",
)
self.session.commit()
started = self.events(svc.EVENT_TASK_STARTED)
succeeded = self.events(svc.EVENT_TASK_SUCCEEDED)
assert len(started) == 1
assert started[0].category == svc.CATEGORY_ACTIVITY
assert started[0].detail["task_id"] == 501
assert len(succeeded) == 1
assert succeeded[0].title == "一键查询账号信息:成功"
assert succeeded[0].detail["message"] == "查询完成"
def test_task_result_is_idempotent(self):
kwargs = {
"task_id": 502,
"task_type": "query_points",
"task_label": "一键查询积分",
"scope": "elite",
"status": "failed",
"message": "网络失败",
}
assert biz.record_douyu_task_result(
self.session,
self.account,
**kwargs,
)
assert not biz.record_douyu_task_result(
self.session,
self.account,
**kwargs,
)
self.session.commit()
assert len(self.events(svc.EVENT_TASK_FAILED)) == 1
+164 -1
View File
@@ -25,8 +25,12 @@ import web.backend.database as database_module
from tests.support.db import get_mysql_credentials, get_test_engine
from web.backend.database import Base
from web.backend.models import (
Account,
AccountEvent,
AccountLease,
AuditLog,
HuyaExternalOrder,
PlatformFulfillmentTask,
User,
WeiboAccount,
)
@@ -35,7 +39,7 @@ TESTS_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = TESTS_DIR.parent
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
HEAD_REVISION = "20261118_0089"
HEAD_REVISION = "20261118_0093"
# 迁移新增、但不声明在模型里的复合查询索引。
EXTRA_INDEXES = (
@@ -521,3 +525,162 @@ class TestMigrationSmoke:
mig_engine.dispose()
with admin_engine.begin() as conn:
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
def test_0090_restores_allocated_tasks_with_active_leases(self):
creds = get_mysql_credentials()
mig_db = f"douyu_login_mig_{secrets.token_hex(4)}"
mig_url = (
f"mysql+pymysql://{quote_plus(creds['user'])}:"
f"{quote_plus(creds['password'])}@{creds['host']}:{creds['port']}/"
f"{mig_db}?charset=utf8mb4"
)
admin_engine = get_test_engine()
with admin_engine.begin() as conn:
conn.execute(
text(
f"CREATE DATABASE `{mig_db}` "
"CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;"
)
)
original_url = database_module.DATABASE_URL
mig_engine = create_engine(mig_url)
try:
database_module.DATABASE_URL = mig_url
cfg = _migration_config()
cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261118_0089")
with Session(mig_engine) as session:
user = User(
username="migration-pf-actor",
password_hash="hash",
role="super_admin",
is_active=True,
)
account = Account(
username="migration-pf-account",
password="p",
email="migration-pf@example.com",
email_password="ep",
)
session.add_all([user, account])
session.commit()
lease = AccountLease(
account_id=account.id,
holder_user_id=user.id,
scope="elite",
purpose="platform_fulfillment",
status="active",
)
session.add(lease)
session.commit()
broken = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="MIG-0090",
source_order_item_id="MIG-0090-1",
account_id=account.id,
lease_id=lease.id,
execution_status="ready",
binding_status="not_started",
exchange_status="points_short",
issue_code="",
last_error="",
)
unassigned = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="MIG-0090",
source_order_item_id="MIG-0090-2",
execution_status="ready",
binding_status="not_started",
exchange_status="not_started",
issue_code="no_eligible_account",
last_error="当前没有可用账号",
)
session.add_all([broken, unassigned])
session.commit()
broken_id = broken.id
unassigned_id = unassigned.id
command.upgrade(cfg, "20261118_0090")
with Session(mig_engine) as session:
repaired = session.get(PlatformFulfillmentTask, broken_id)
untouched = session.get(PlatformFulfillmentTask, unassigned_id)
assert repaired is not None
assert repaired.execution_status == "allocated"
assert repaired.issue_code == "points_short"
assert repaired.last_error == "账号积分不足,可充值后继续"
assert repaired.next_allocate_at is None
assert untouched is not None
assert untouched.execution_status == "ready"
assert untouched.issue_code == "no_eligible_account"
finally:
database_module.DATABASE_URL = original_url
mig_engine.dispose()
with admin_engine.begin() as conn:
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
def test_0092_backfills_official_exchange_subject_key(self):
creds = get_mysql_credentials()
mig_db = f"douyu_login_mig_{secrets.token_hex(4)}"
mig_url = (
f"mysql+pymysql://{quote_plus(creds['user'])}:"
f"{quote_plus(creds['password'])}@{creds['host']}:{creds['port']}/"
f"{mig_db}?charset=utf8mb4"
)
admin_engine = get_test_engine()
with admin_engine.begin() as conn:
conn.execute(
text(
f"CREATE DATABASE `{mig_db}` "
"CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;"
)
)
original_url = database_module.DATABASE_URL
mig_engine = create_engine(mig_url)
try:
database_module.DATABASE_URL = mig_url
cfg = _migration_config()
cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261118_0091")
with Session(mig_engine) as session:
account = Account(
username="migration-exchange-account",
password="p",
email="migration-exchange@example.com",
email_password="ep",
)
session.add(account)
session.commit()
event = AccountEvent(
account_id=account.id,
event_type="exchange",
category="business",
occurred_at=datetime.now(UTC),
title="兑换测试商品",
detail={"commodity_id": "MIG-COMMODITY-0092"},
source="official_sync",
subject_type="goods",
subject_key="",
)
session.add(event)
session.commit()
event_id = event.id
command.upgrade(cfg, "20261118_0092")
with Session(mig_engine) as session:
repaired = session.get(AccountEvent, event_id)
assert repaired is not None
assert repaired.subject_type == "commodity"
assert repaired.subject_key == "MIG-COMMODITY-0092"
finally:
database_module.DATABASE_URL = original_url
mig_engine.dispose()
with admin_engine.begin() as conn:
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
+138
View File
@@ -12,6 +12,8 @@ from fastapi import HTTPException
from tests.support.db import get_test_engine, make_test_session
from web.backend.models import (
Account,
AccountCommodityState,
AccountEvent,
AccountLease,
AutomationJob,
DouyuGoodsSnapshot,
@@ -453,6 +455,45 @@ class TestSnapshotSync(_Base):
outbox = self.session.query(IntegrationOutbox).one()
assert outbox.payload_json["items"][0]["stateVersion"] == 1
def test_duplicate_snapshot_keeps_allocated_task_state(self):
self.mapping()
account = self.account("snapshot-allocated")
service.sync_order_snapshot(self.session, {"data": self.snapshot()})
task = self.session.query(PlatformFulfillmentTask).one()
service.allocate_task(
self.session,
task_id=task.id,
current=self.admin,
)
service.sync_order_snapshot(self.session, {"data": self.snapshot()})
self.session.refresh(task)
assert task.execution_status == "allocated"
assert task.account_id == account.id
assert task.lease_id is not None
assert task.next_allocate_at is None
assert task.exchange_status == "eligible"
assert task.issue_code == ""
def test_duplicate_snapshot_preserves_allocation_retry(self):
self.mapping()
service.sync_order_snapshot(self.session, {"data": self.snapshot()})
task = self.session.query(PlatformFulfillmentTask).one()
retry_at = NOW + timedelta(seconds=45)
task.issue_code = "no_eligible_account"
task.last_error = "当前没有可用账号"
task.next_allocate_at = retry_at
self.session.commit()
service.sync_order_snapshot(self.session, {"data": self.snapshot()})
self.session.refresh(task)
assert task.execution_status == "ready"
assert task.issue_code == "no_eligible_account"
assert task.last_error == "当前没有可用账号"
assert task.next_allocate_at == retry_at
def test_legacy_event_only_reads_the_specified_order_item(self, monkeypatch):
self.mapping()
requested: list[str] = []
@@ -496,6 +537,85 @@ class TestSnapshotSync(_Base):
class TestAccountSelection(_Base):
def test_capability_match_checks_only_selected_candidate(self, monkeypatch):
account = self.account("capability-fast")
task = self.task()
self.session.add(
AccountCommodityState(
account_id=account.id,
platform="douyu",
scope="elite",
commodity_id=COMMODITY,
commodity_name=INTERNAL_SKU,
availability="available",
observed_at=NOW,
valid_until=NOW + timedelta(minutes=15),
source="overview",
)
)
self.session.commit()
monkeypatch.setenv("PLATFORM_FULFILLMENT_MATCH_MODE", "capability")
detail = service.allocate_task(
self.session,
task_id=task.id,
current=self.admin,
)
assert detail["task"]["account"]["id"] == account.id
assert detail["task"]["executionStatus"] == "allocated"
self.refresh_mock.assert_called_once()
def test_hybrid_falls_back_to_live_scan_when_capability_candidate_fails(
self,
monkeypatch,
):
capability_account = self.account("capability-stale")
live_account = self.account("live-fallback")
task = self.task()
self.session.add(
AccountCommodityState(
account_id=capability_account.id,
platform="douyu",
scope="elite",
commodity_id=COMMODITY,
availability="available",
observed_at=NOW,
valid_until=NOW + timedelta(minutes=15),
source="overview",
)
)
self.session.commit()
def live_state(_db, account, **_kwargs):
return DouyuLiveAccountState(
account_id=account.id,
account_name=account.username,
checked_at=NOW,
ck_verdict="valid",
ck_message="有效",
elite_opened=True,
points=2000,
limited_ids=(
frozenset({COMMODITY})
if account.id == capability_account.id
else frozenset()
),
role_change_available_at=None,
)
self.refresh_mock.side_effect = live_state
monkeypatch.setenv("PLATFORM_FULFILLMENT_MATCH_MODE", "hybrid")
detail = service.allocate_task(
self.session,
task_id=task.id,
current=self.admin,
)
assert detail["task"]["account"]["id"] == live_account.id
assert self.refresh_mock.call_count == 2
def test_allocation_refreshes_live_state_instead_of_cached_filters(self):
account = Account(
username="live-refresh-account",
@@ -678,6 +798,15 @@ class TestAccountSelection(_Base):
assert lease.purpose == "platform_fulfillment"
assert lease.status == "active"
assert lease.expires_at is None
acquired = (
self.session.query(AccountEvent)
.filter(
AccountEvent.account_id == account.id,
AccountEvent.event_type == "lease_acquired",
)
.one()
)
assert acquired.detail["task_id"] == task.id
released = service.release_task_account(
self.session,
@@ -687,6 +816,15 @@ class TestAccountSelection(_Base):
assert released["task"]["executionStatus"] == "ready"
self.session.refresh(lease)
assert lease.status == "released"
released_event = (
self.session.query(AccountEvent)
.filter(
AccountEvent.account_id == account.id,
AccountEvent.event_type == "lease_released",
)
.one()
)
assert released_event.detail["lease_id"] == lease.id
def test_lease_settings_support_unlimited_and_finite_duration(self):
self.account("settings-account")
@@ -124,3 +124,60 @@ def test_auto_allocator_schedules_retry_only_after_failed_allocation(db):
assert result == {"checked": 1, "allocated": 0, "failed": 1}
assert task.next_allocate_at is not None
assert task.next_allocate_at >= moment + timedelta(seconds=10)
def test_auto_allocator_prioritizes_oldest_paid_task_after_due_check(db):
actor = User(username="auto-fair-actor", password_hash="h", role="super_admin")
moment = datetime.now(UTC)
db.add(
PlatformFulfillmentSetting(
id=1,
lease_duration_minutes=None,
order_match_started_at=moment - timedelta(days=1),
)
)
older = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="20",
source_order_item_id="20",
platform_order_id="AUTO-OLDER",
internal_sku_key="skin",
commodity_id="commodity-1",
execution_status="ready",
binding_status="not_started",
exchange_status="not_started",
paid_at=moment - timedelta(minutes=10),
next_allocate_at=moment,
updated_at=moment,
)
newer = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="21",
source_order_item_id="21",
platform_order_id="AUTO-NEWER",
internal_sku_key="skin",
commodity_id="commodity-1",
execution_status="ready",
binding_status="not_started",
exchange_status="not_started",
paid_at=moment - timedelta(minutes=1),
next_allocate_at=moment,
updated_at=moment,
)
db.add_all([actor, older, newer])
db.commit()
calls: list[int] = []
with (
patch.object(auto_allocator.service, "_integration_actor", return_value=actor),
patch.object(
auto_allocator.service,
"allocate_task",
side_effect=lambda _db, *, task_id, current: (
calls.append(task_id) or {"task": {"account": {"id": 9}}}
),
),
):
auto_allocator.run_auto_allocation_once(db, limit=1, now=moment)
assert calls == [older.id]