feat(fulfillment): 增加订单匹配起算时间

This commit is contained in:
yml
2026-11-18 12:32:04 +08:00
parent 79da819384
commit 0d57c615c9
14 changed files with 338 additions and 48 deletions
+28
View File
@@ -188,6 +188,34 @@ class TestDegradation:
assert src.list_pending_manual_fulfillments(internal_sku_keys=[]) == []
def test_pending_lookup_passes_paid_at_cutoff(self, monkeypatch):
monkeypatch.setenv("ORDER_SITE_DATABASE_URL", "postgresql://u:p@h:5432/db")
monkeypatch.setenv("ORDER_SITE_LOOKUP_ENABLED", "true")
cutoff = datetime(2026, 11, 18, 12, 0, tzinfo=UTC)
captured: dict[str, object] = {}
def _rows(*, limit, internal_sku_keys, paid_at_from):
captured.update(
{
"limit": limit,
"internal_sku_keys": internal_sku_keys,
"paid_at_from": paid_at_from,
}
)
return []
monkeypatch.setattr(src, "_fetch_pending_manual_fulfillments", _rows)
assert (
src.list_pending_manual_fulfillments(
limit=20,
internal_sku_keys=["兔兔白日梦头盔"],
paid_at_from=cutoff,
)
== []
)
assert captured["paid_at_from"] == cutoff
class TestCacheRoundTrip:
"""缓存读写:命中未过期快照就不查外部。"""
+1 -1
View File
@@ -35,7 +35,7 @@ TESTS_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = TESTS_DIR.parent
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
HEAD_REVISION = "20261117_0085"
HEAD_REVISION = "20261118_0087"
# 迁移新增、但不声明在模型里的复合查询索引。
EXTRA_INDEXES = (
+84 -1
View File
@@ -19,6 +19,7 @@ from web.backend.models import (
IntegrationOutbox,
PlatformCommodityMapping,
PlatformFulfillmentEvent,
PlatformFulfillmentSetting,
PlatformFulfillmentTask,
User,
)
@@ -46,6 +47,14 @@ class _Base:
self.session.add(self.admin)
self.session.commit()
self.admin_id = self.admin.id
self.session.add(
PlatformFulfillmentSetting(
id=1,
lease_duration_minutes=None,
order_match_started_at=NOW - timedelta(days=1),
)
)
self.session.commit()
self.refresh_patch = patch.object(
service,
"refresh_douyu_account_state",
@@ -168,11 +177,19 @@ class TestSyncAndMapping(_Base):
def test_sync_is_idempotent_and_applies_mapping(self, monkeypatch):
self.mapping()
cutoff = NOW - timedelta(days=1)
captured_keys: list[str] = []
captured_cutoff: list[datetime | None] = []
def _rows(*, limit: int, internal_sku_keys: list[str]):
def _rows(
*,
limit: int,
internal_sku_keys: list[str],
paid_at_from: datetime | None,
):
del limit
captured_keys.extend(internal_sku_keys)
captured_cutoff.append(paid_at_from)
return [
{
"source_order_id": "100",
@@ -205,6 +222,7 @@ class TestSyncAndMapping(_Base):
assert first["created"] == 1
assert second["created"] == 0
assert captured_keys == [INTERNAL_SKU, INTERNAL_SKU]
assert captured_cutoff == [cutoff, cutoff]
assert self.session.query(PlatformFulfillmentTask).count() == 1
task = self.session.query(PlatformFulfillmentTask).one()
assert task.execution_status == "ready"
@@ -248,6 +266,68 @@ class TestSyncAndMapping(_Base):
assert listed["pagination"]["total"] == 1
assert legacy.id != mapped.id
def test_list_hides_tasks_created_before_order_match_cutoff(self):
mapping = self.mapping()
task = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="104",
source_order_item_id="105",
source_fulfillment_id="205",
platform_order_id="ORDER-105",
sku_code=INTERNAL_SKU,
sku_name=INTERNAL_SKU,
internal_sku_key=INTERNAL_SKU,
quantity=1,
target_platform="douyu",
scope="elite",
commodity_mapping_id=mapping.id,
commodity_id=COMMODITY,
required_points=1280,
binding_status="not_started",
execution_status="ready",
exchange_status="not_started",
created_at=NOW - timedelta(hours=2),
updated_at=NOW - timedelta(hours=2),
)
self.session.add(task)
self.session.commit()
service.update_settings(
self.session,
lease_duration_minutes=None,
order_match_started_at=NOW - timedelta(hours=1),
current=self.admin,
)
listed = service.list_tasks(self.session)
assert listed["pagination"]["total"] == 0
def test_customer_session_ignores_task_before_order_match_cutoff(
self,
monkeypatch,
):
task = self.task()
service.update_settings(
self.session,
lease_duration_minutes=None,
order_match_started_at=task.created_at + timedelta(minutes=1),
current=self.admin,
)
monkeypatch.setattr(
service,
"sync_pending_tasks",
lambda *_args, **_kwargs: {"fetched": 0},
)
with pytest.raises(HTTPException) as exc_info:
service.ensure_customer_session(
self.session,
source_order_item_id=task.source_order_item_id,
platform_order_id=task.platform_order_id,
)
assert exc_info.value.status_code == 404
def test_upsert_mapping_advances_existing_task(self):
task = self.task(mapped=False)
self.session.add(
@@ -478,15 +558,18 @@ class TestAccountSelection(_Base):
finite = service.update_settings(
self.session,
lease_duration_minutes=90,
order_match_started_at=NOW - timedelta(days=1),
current=self.admin,
)
self.session.refresh(lease)
assert finite["leaseDurationMinutes"] == 90
assert finite["orderMatchStartedAt"] is not None
assert lease.expires_at is not None
unlimited = service.update_settings(
self.session,
lease_duration_minutes=None,
order_match_started_at=NOW - timedelta(days=1),
current=self.admin,
)
self.session.refresh(lease)
@@ -5,12 +5,23 @@ from __future__ import annotations
from datetime import UTC, datetime, timedelta
from unittest.mock import patch
from web.backend.models import PlatformFulfillmentTask, User
from web.backend.models import (
PlatformFulfillmentSetting,
PlatformFulfillmentTask,
User,
)
from web.backend.services.platform_fulfillment import auto_allocator
def test_auto_allocator_only_scans_ready_unassigned_tasks(db):
actor = User(username="auto-alloc-actor", password_hash="h", role="super_admin")
db.add(
PlatformFulfillmentSetting(
id=1,
lease_duration_minutes=None,
order_match_started_at=datetime.now(UTC) - timedelta(days=1),
)
)
ready = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="1",
@@ -35,7 +46,20 @@ def test_auto_allocator_only_scans_ready_unassigned_tasks(db):
exchange_status="not_started",
updated_at=datetime.now(UTC) - timedelta(minutes=2),
)
db.add_all([actor, ready, mapped_pending])
old_ready = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="3",
source_order_item_id="3",
platform_order_id="AUTO-OLD",
internal_sku_key="skin",
commodity_id="commodity-1",
execution_status="ready",
binding_status="not_started",
exchange_status="not_started",
created_at=datetime.now(UTC) - timedelta(days=2),
updated_at=datetime.now(UTC) - timedelta(days=2),
)
db.add_all([actor, ready, mapped_pending, old_ready])
db.commit()
calls: list[int] = []
@@ -45,8 +69,7 @@ def test_auto_allocator_only_scans_ready_unassigned_tasks(db):
auto_allocator.service,
"allocate_task",
side_effect=lambda _db, *, task_id, current: (
calls.append(task_id)
or {"task": {"account": {"id": 9}}}
calls.append(task_id) or {"task": {"account": {"id": 9}}}
),
),
):