fix(fulfillment): mark confirmed role observations as bound

This commit is contained in:
yml
2026-11-23 23:05:18 +08:00
parent 23c4b93e9c
commit 58d782643b
7 changed files with 180 additions and 35 deletions
+5 -6
View File
@@ -26,7 +26,6 @@ from web.backend.services.account_binding import (
)
from web.backend.services.douyu_binding import (
BINDING_RECONCILE_CONFIRMED,
BINDING_RECONCILE_STALE_PENDING,
BINDING_VIEW_CONFIRMED,
BINDING_VIEW_FAILED,
BINDING_VIEW_NONE,
@@ -563,7 +562,7 @@ def test_newer_observation_reconciles_pending_role_by_identity():
assert fulfillment_view.effective_role_name == "续梦乖"
def test_newer_observation_invalidates_different_pending_role():
def test_newer_observation_confirms_bound_role_replacing_pending_role():
account = _binding_account()
account.game_name = "续梦乖"
pending = resolve_douyu_binding(
@@ -607,17 +606,17 @@ def test_newer_observation_invalidates_different_pending_role():
fulfillment_view = resolve_fulfillment_binding(
observation_task,
account=account,
binding_status="waiting_bind",
binding_status="bound",
)
assert reconciliation.action == BINDING_RECONCILE_STALE_PENDING
assert reconciliation.action == BINDING_RECONCILE_CONFIRMED
assert reconciliation.pending_role_name == "布丁贩卖机"
assert reconciliation.observed_role_name == "续梦乖"
assert fulfillment_view.status == BINDING_VIEW_NONE
assert fulfillment_view.status == BINDING_VIEW_CONFIRMED
assert fulfillment_view.pending_role_name == ""
assert fulfillment_view.effective_role_name == "续梦乖"
assert fulfillment_view.bind_ready_for_confirm is False
assert fulfillment_view.bind_confirmed is False
assert fulfillment_view.bind_confirmed is True
def test_confirmed_new_role_replaces_account_current_role():
+36
View File
@@ -84,6 +84,42 @@ def test_http_response_keeps_application_cache_control():
assert headers[b"x-content-type-options"] == b"nosniff"
def test_html_response_gets_no_store_cache_control():
async def app(scope, receive, send):
assert scope["type"] == "http"
await send(
{
"type": "http.response.start",
"status": 200,
"headers": [],
}
)
await send({"type": "http.response.body", "body": b"html"})
messages: list[dict] = []
async def send(message):
messages.append(message)
async def receive():
return {"type": "http.request", "body": b"", "more_body": False}
scope = {
"type": "http",
"method": "GET",
"path": "/platform-fulfillment",
"headers": [],
"scheme": "http",
"server": ("testserver", 80),
"client": ("testclient", 123),
"query_string": b"",
}
asyncio.run(SecurityHeadersMiddleware(app)(scope, receive, send))
headers = dict(messages[0]["headers"])
assert headers[b"cache-control"] == b"no-store, max-age=0"
def test_asset_response_gets_immutable_cache_control():
message = _run_http("/assets/index-abc123.js")
headers = dict(message["headers"])
+59 -5
View File
@@ -2076,12 +2076,13 @@ class TestBindingAndCompletion(_Base):
assert event.detail_json["previousBindTaskId"] == old_bind_task.id
assert event.detail_json["bindTaskId"] == latest_bind_task.id
def test_newer_observation_invalidates_different_pending_role(self):
def test_newer_observation_confirms_different_pending_role(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "续梦乖"
account.game_channel = "手Q · 安卓(android)"
account.role_bind_status = "bound"
account.role_change_available_at = NOW + timedelta(days=6)
pending_task = DouyuTask(
batch_id="pending-old-role",
account_id=task.account_id,
@@ -2143,17 +2144,18 @@ class TestBindingAndCompletion(_Base):
self.session.query(PlatformFulfillmentEvent)
.filter_by(
task_id=task.id,
event_type="binding_pending_observation_superseded",
event_type="binding_observation_confirmed",
)
.one()
)
assert synced == 1
assert task.bind_task_id == observation.id
assert task.binding_status == "waiting_bind"
assert task.execution_status == "waiting_bind"
assert task.binding_status == "bound"
assert task.execution_status == "bound"
assert detail["task"]["bindTask"]["roleName"] == "续梦乖"
assert detail["task"]["bindTask"]["bindReadyForConfirm"] is False
assert detail["task"]["bindTask"]["bindConfirmed"] is False
assert detail["task"]["bindTask"]["bindConfirmed"] is True
assert detail["task"]["account"]["roleChangeAvailableAt"] is not None
assert event.detail_json["pendingRoleName"] == "布丁贩卖机"
assert event.detail_json["observedRoleName"] == "续梦乖"
@@ -2228,6 +2230,58 @@ class TestBindingAndCompletion(_Base):
assert detail["task"]["bindTask"]["bindReadyForConfirm"] is False
assert detail["task"]["bindTask"]["bindConfirmed"] is True
def test_startup_promotes_waiting_task_with_confirmed_observation(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.game_name = "续梦乖"
account.game_channel = "手Q · 安卓(android)"
account.role_bind_status = "bound"
account.role_change_available_at = NOW + timedelta(days=6)
observation = DouyuTask(
batch_id="observe-already-bound",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="query_game_name",
handbook_scope="elite",
status="success",
platform_task_id=task.id,
result={
"role_name": "续梦乖",
"area_name": "手Q",
"plat_name": "安卓(android)",
"is_bound_act": True,
"bind_confirmed": True,
"bind_phase": "confirmed",
},
created_by=self.admin_id,
)
self.session.add(observation)
self.session.flush()
task.bind_task_id = observation.id
task.binding_status = "waiting_bind"
task.execution_status = "waiting_bind"
self.session.commit()
reconciled = service.reconcile_binding_observations(self.session)
self.session.refresh(task)
detail = service.get_task_detail(self.session, task.id)
event = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(
task_id=task.id,
event_type="binding_observation_confirmed",
)
.one()
)
assert reconciled == 1
assert task.binding_status == "bound"
assert task.execution_status == "bound"
assert detail["task"]["bindTask"]["roleName"] == "续梦乖"
assert detail["task"]["bindTask"]["bindConfirmed"] is True
assert detail["task"]["account"]["roleChangeAvailableAt"] is not None
assert event.detail_json["observedRoleName"] == "续梦乖"
def test_refresh_binding_attaches_latest_pending_account_workbench_role(self):
task = self._allocated()
old_bind_task = DouyuTask(
+4
View File
@@ -134,6 +134,10 @@ class SecurityHeadersMiddleware:
for key, value in message.get("headers", [])
if key not in replaced_headers
]
if not is_asset and not any(
key == b"cache-control" for key, _value in headers
):
headers.append((b"cache-control", b"no-store, max-age=0"))
headers.extend(
[
(b"x-content-type-options", b"nosniff"),
+1 -10
View File
@@ -37,7 +37,6 @@ BINDING_OBSERVATION_TASK_TYPES = frozenset(
BINDING_RECONCILE_NONE = "none"
BINDING_RECONCILE_CONFIRMED = "confirmed"
BINDING_RECONCILE_STALE_PENDING = "stale_pending"
@dataclass(frozen=True)
@@ -249,16 +248,8 @@ def reconcile_douyu_binding(
pending_role_name=current.pending_role_name,
observed_role_name=observation.confirmed_role_name,
)
same_role = (
current.pending_role_name.casefold()
== observation.confirmed_role_name.casefold()
)
return DouyuBindingReconciliation(
action=(
BINDING_RECONCILE_CONFIRMED
if same_role
else BINDING_RECONCILE_STALE_PENDING
),
action=BINDING_RECONCILE_CONFIRMED,
pending_role_name=current.pending_role_name,
observed_role_name=observation.confirmed_role_name,
)
@@ -21,7 +21,6 @@ from ..business_events import record_douyu_task_started
from ..douyu_binding import (
BINDING_OBSERVATION_TASK_TYPES,
BINDING_RECONCILE_CONFIRMED,
BINDING_RECONCILE_STALE_PENDING,
BINDING_VIEW_CONFIRMED,
BINDING_VIEW_PENDING,
DouyuBindingReconciliation,
@@ -442,24 +441,16 @@ def _apply_binding_observation(
account=resolved_account,
)
reconciliation = reconcile_douyu_binding(current, observation)
if reconciliation.action not in {
BINDING_RECONCILE_CONFIRMED,
BINDING_RECONCILE_STALE_PENDING,
}:
if reconciliation.action != BINDING_RECONCILE_CONFIRMED:
return None
previous_bind_task_id = task.bind_task_id
task.bind_task_id = int(observation_task.id)
task.issue_code = ""
task.last_error = ""
task.updated_at = _now()
if reconciliation.action == BINDING_RECONCILE_CONFIRMED:
task.binding_status = "bound"
task.execution_status = "bound"
event_type = "binding_observation_confirmed"
else:
task.binding_status = "waiting_bind"
task.execution_status = "waiting_bind"
event_type = "binding_pending_observation_superseded"
task.binding_status = "bound"
task.execution_status = "bound"
event_type = "binding_observation_confirmed"
_append_event(
db,
task.id,
@@ -507,6 +498,47 @@ def _sync_binding_observation(
return 1
def _promote_bound_observation(
db: Session,
task: PlatformFulfillmentTask,
observation_task: DouyuTask,
*,
account: Account | None = None,
) -> bool:
if observation_task.task_type not in BINDING_OBSERVATION_TASK_TYPES:
return False
binding = resolve_douyu_binding(
observation_task,
account=account
or (
db.get(Account, int(task.account_id))
if task.account_id
else None
),
)
if binding.status != BINDING_VIEW_CONFIRMED:
return False
task.binding_status = "bound"
task.execution_status = "bound"
task.issue_code = ""
task.last_error = ""
task.updated_at = _now()
_append_event(
db,
task.id,
"binding_observation_confirmed",
detail={
"bindTaskId": int(observation_task.id),
"previousBindTaskId": task.bind_task_id,
"observedRoleName": binding.confirmed_role_name,
"sourceTaskType": observation_task.task_type,
},
)
_apply_task_lease_policy(db, task)
_emit_order_site_binding_state(db, task.id)
return True
def reconcile_binding_observations(
db: Session,
*,
@@ -517,7 +549,9 @@ def reconcile_binding_observations(
db.query(PlatformFulfillmentTask)
.filter(
PlatformFulfillmentTask.scope == "elite",
PlatformFulfillmentTask.binding_status == "role_ready",
PlatformFulfillmentTask.binding_status.in_(
("role_ready", "waiting_bind")
),
PlatformFulfillmentTask.execution_status.notin_(
("completed", "cancelled", "manual_required")
),
@@ -529,6 +563,18 @@ def reconcile_binding_observations(
)
reconciled = 0
for task in tasks:
current_task = (
db.get(DouyuTask, int(task.bind_task_id))
if task.bind_task_id
else None
)
if current_task is not None and _promote_bound_observation(
db,
task,
current_task,
):
reconciled += 1
continue
observation_task = _binding_observation_task(db, task)
if observation_task is None:
continue
@@ -347,6 +347,16 @@ function eventDescription(event: { eventType: string; detail: Record<string, unk
const channel = String(detail.gameChannel || '');
return `账号已确认角色 ${String(detail.roleName || '-')}${channel ? `(${channel})` : ''}`;
}
if (event.eventType === 'binding_observation_confirmed') {
const pending = String(detail.pendingRoleName || '');
const observed = String(detail.observedRoleName || '-');
return pending && pending !== observed
? `账号已绑定 ${observed};原待确认角色 ${pending} 已失效`
: `账号已绑定 ${observed}`;
}
if (event.eventType === 'binding_pending_observation_superseded') {
return `原待确认角色 ${String(detail.pendingRoleName || '-')} 已被当前绑定 ${String(detail.observedRoleName || '-')} 替换`;
}
if (event.eventType === 'task_created') return '订单已进入直播账号履约工作台';
return '履约状态已更新';
}
@@ -1212,6 +1222,11 @@ export default function PlatformFulfillmentPage() {
<Space direction="vertical" size={2}>
<Tag>{bindingStatusLabel(task.bindingStatus)}</Tag>
<Text>{task.bindTask?.roleName || (task.bindTask?.bindPhase === 'role_ready' ? '角色待确认' : '-')}</Text>
{task.bindingStatus === 'bound' ? (
<Text type="secondary" style={{ fontSize: 12 }}>
换绑时间:{formatTime(task.account?.roleChangeAvailableAt) || '无冷却'}
</Text>
) : null}
</Space>
),
},