Merge branch 'dev' into runny827

feat(training): 新增精益培训视频与周任务管理

# Conflicts:
#	backend/app/models/__init__.py
This commit is contained in:
runny committed 2026-09-08 18:30:09 +08:00
1 parent 85d27e9ffa
commit 91b7233872
812 files changed
+73763 -18908

No files matched your search

@@ -0,0 +1,467 @@
"""
backend/tests/test_shipping_projection_gate_equivalence.py
用途:锁定「展示单源」契约 §2.1 —— 在真实 A 管线(_project_order_task_work_item)
下,A 渲染出的 primary_action / blocking_reason / user_status 必须与 C
(project_user_gate_summary)等价。这是 flatten C→A==B==C 的**前置等价性验证**:
仅当 A==C 才允许删除 A 的 STEP3/6/7 二次推导,否则会改变对话流/批次进度中心/右卡展示。
依赖:pytest、app fixture、tests 已有的 _seed_run_input / _materialized_run、
shipping_processing_projection._project_order_task_work_item、
process_gate_projection.project_user_gate_summary。
逻辑:为每个代表性 Gate 场景构建 OT+Notice+Run+Execution+Gate 持久化事实,
运行 A 管线拿到渲染 DTO,新调 C 拿到权威摘要;断言 A 的动作码/阻断码与 C 一致。
若断言失败,即为「A 与 C 漂移」,必须先修 C 侧语义再 flatten。
"""
from __future__ import annotations
import pytest
from app import db
from app.models import ShippingOrderTask
@pytest.fixture
def gate_chain(app):
"""构造挂接 Notice 的 OT + Run(复用既有 seed),返回主键供测试内重载。
与 test_shipping_workbench_service_chains.workbench_chain_ids 同构,但额外
允许测试追加 Execution/Gate 后驱动完整 A 管线。
"""
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
with app.app_context():
from app.models import ShippingNotice, ShippingOrderTask
user, agent, session, intake, _document = _seed_run_input(suffix='GATE-EQ')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
notice = ShippingNotice(
task_no='SN-GATE-EQ-1',
user_id=user.id,
conversation_id=session.session_id,
source_type='manual',
lifecycle_status='active',
)
db.session.add(notice)
db.session.flush()
order_task = ShippingOrderTask(
task_no='OT-GATE-EQ-1',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=int(run.id),
status='processing',
stage='inventory_matching',
progress_version=1,
)
db.session.add(order_task)
db.session.flush()
notice.order_task_id = int(order_task.id)
run.user_task_no = order_task.task_no
db.session.commit()
return {
'run_id': int(run.id),
'notice_id': int(notice.id),
'order_task_id': int(order_task.id),
}
def _load_chain(ids: dict[str, int]):
from app.models import ShippingNotice, ShippingOrderProcessingRun, ShippingOrderTask
run = db.session.get(ShippingOrderProcessingRun, ids['run_id'])
notice = db.session.get(ShippingNotice, ids['notice_id'])
order_task = db.session.get(ShippingOrderTask, ids['order_task_id'])
assert run is not None and notice is not None and order_task is not None
return run, notice, order_task
def _attach_execution(order_task, *, gate_code: str, status: str,
blocking_reason_code: str, next_action_code: str,
sequence_no: int = 16) -> int:
"""为 OT 挂接一个正式 Execution + 单一 Gate(回退到正式 Notice 事实源)。"""
from app.models import ShippingProcessExecution, ShippingProcessGate
execution = ShippingProcessExecution(
execution_no=f'EXE-GATE-EQ-{gate_code}',
task_id=int(order_task.id),
status='blocked',
current_gate_code=gate_code,
lock_version=1,
)
db.session.add(execution)
db.session.flush()
db.session.add(ShippingProcessGate(
execution_id=int(execution.id),
gate_code=gate_code,
sequence_no=sequence_no,
status=status,
evaluation_version=1,
blocking_reason_code=blocking_reason_code,
next_action_code=next_action_code,
))
order_task.active_process_execution_id = int(execution.id)
db.session.flush()
return int(execution.id)
def _project_a(run, order_task):
"""运行 A 管线,返回渲染 payload。
真实对外 DTO 经 `_with_processing_ui_state` 封装(含顶层 current_gate / blocking_reason /
primary_action + 子 `ui_state`)。集成层(:4757/:4863)才封装,故此处手动封装,
使顶层动作码与 `ui_state.lifecycle_stage` 均可被读取。
"""
from app.services.shipping_notice.shipping_processing_projection import (
_project_order_task_work_item,
_with_processing_ui_state,
)
payload = _project_order_task_work_item(run, order_task=order_task)
assert payload is not None, 'A 管线必须产出 work_item'
return _with_processing_ui_state(payload)
def _summary_c(execution_id: int):
"""独立重调 C(project_user_gate_summary),避免与 A 携带的 process_gate 同源污染。"""
from app.models import ShippingProcessExecution
from app.services.shipping_notice.process_gate_projection import project_user_gate_summary
execution = db.session.get(ShippingProcessExecution, execution_id)
assert execution is not None
return project_user_gate_summary(execution)
@pytest.mark.parametrize('scenario', [
# gate_code, gate.status, blocking_reason_code, next_action_code
# [CANONICAL-AGREE] 这些场景 A 与 C 当前一致:flatten 后仍必须一致。
('inventory_sufficiency', 'blocked_manual', 'inventory_shortage_review_required', 'open_shortage_review'),
('freight_upload_rpa', 'blocked_manual', 'upload_rpa_failed', 'retry_freight_upload_rpa'),
])
def test_a_primary_action_equals_c(app, gate_chain, scenario):
"""A 渲染的主动作码必须等于 C 的 next_action_code(flatten 前置等价性,规范场景)。"""
gate_code, status, reason_code, next_action = scenario
with app.app_context():
run, notice, order_task = _load_chain(gate_chain)
execution_id = _attach_execution(
order_task,
gate_code=gate_code, status=status,
blocking_reason_code=reason_code, next_action_code=next_action,
)
db.session.commit()
a = _project_a(run, order_task)
summary = _summary_c(execution_id)
a_primary = str((a.get('primary_action') or {}).get('code') or '').strip()
c_next = str(summary.get('next_action_code') or '').strip()
c_primary = str((summary.get('primary_action') or {}).get('code') or '').strip()
assert a_primary == c_next == c_primary, (
f'A={a_primary!r} C.next={c_next!r} C.primary={c_primary!r} for {gate_code}'
)
a_reason = str((a.get('blocking_reason') or {}).get('code') or '').strip()
c_reason = str(summary.get('blocking_reason_code') or '').strip()
assert a_reason == c_reason, (
f'A.reason={a_reason!r} C.reason={c_reason!r} for {gate_code}'
)
def test_a_blocking_reason_does_not_over_collapse_retryable(app, gate_chain):
"""flatten C 后:A 的 blocking_reason 必须复用 C 已裁决的具体码,不再坍缩为 technical_failure_present。"""
with app.app_context():
run, notice, order_task = _load_chain(gate_chain)
execution_id = _attach_execution(
order_task,
gate_code='inventory_preparation', status='blocked_retryable',
blocking_reason_code='inventory_preparation_failed',
next_action_code='retry_inventory_preparation',
)
db.session.commit()
a = _project_a(run, order_task)
summary = _summary_c(execution_id)
a_reason = str((a.get('blocking_reason') or {}).get('code') or '').strip()
c_reason = str(summary.get('blocking_reason_code') or '').strip()
assert a_reason == c_reason == 'inventory_preparation_failed'
def test_a_primary_action_uses_canonical_excel_code(app, gate_chain):
"""flatten C 后:A 的 primary_action.code 必须是写侧认可的规范码 regenerate_excel_artifact,而非别名。"""
with app.app_context():
run, notice, order_task = _load_chain(gate_chain)
execution_id = _attach_execution(
order_task,
gate_code='artifact_generation', status='blocked_retryable',
blocking_reason_code='artifact_generation_failed',
next_action_code='regenerate_excel_artifact',
)
db.session.commit()
a = _project_a(run, order_task)
summary = _summary_c(execution_id)
a_primary = str((a.get('primary_action') or {}).get('code') or '').strip()
c_next = str(summary.get('next_action_code') or '').strip()
c_primary = str((summary.get('primary_action') or {}).get('code') or '').strip()
assert a_primary == c_next == c_primary == 'regenerate_excel_artifact'
def test_a_primary_action_uses_same_recovery_source_as_c(app, gate_chain):
"""RPA 超时/耗尽:A 与 C 都必须回落为『优先复用已有快照重匹配(无则 RPA)』的合并动作,
而非孤立只重读或直接新开 RPA。"""
with app.app_context():
run, notice, order_task = _load_chain(gate_chain)
execution_id = _attach_execution(
order_task,
gate_code='inventory_preparation', status='blocked_retryable',
blocking_reason_code='inventory_rpa_exhausted', next_action_code='retry_inventory_matching',
)
db.session.commit()
a = _project_a(run, order_task)
summary = _summary_c(execution_id)
a_primary = str((a.get('primary_action') or {}).get('code') or '').strip()
c_next = str(summary.get('next_action_code') or '').strip()
assert a_primary == c_next == 'retry_inventory_matching'
@pytest.mark.parametrize('scenario', [
# gate_code, gate.status, blocking_reason_code, next_action_code
('inventory_sufficiency', 'blocked_manual', 'inventory_shortage_review_required', 'open_shortage_review'),
('inventory_preparation', 'blocked_retryable', 'inventory_preparation_failed', 'retry_inventory_preparation'),
('artifact_generation', 'blocked_retryable', 'artifact_generation_failed', 'regenerate_excel_artifact'),
('freight_upload_rpa', 'blocked_manual', 'upload_rpa_failed', 'retry_freight_upload_rpa'),
])
def test_b_task_ui_state_actions_equals_c(app, gate_chain, scenario):
"""B(formalTaskDetail.ui_state)的 actions 必须与 C 同源(A==B==C 的 B 半边)。
B 的 actions 由 _unified_actions(_process_gate_user_summary_for_task(task)) 产出,
而后者就是 project_user_gate_summary;因此 B.primary.code 必须== C.next_action_code,
B.secondary.code 集合必须== C.allowed_actions 集合。
"""
gate_code, status, reason_code, next_action = scenario
with app.app_context():
run, notice, order_task = _load_chain(gate_chain)
execution_id = _attach_execution(
order_task,
gate_code=gate_code, status=status,
blocking_reason_code=reason_code, next_action_code=next_action,
)
db.session.commit()
from app.services.shipping_notice.ui_state import build_task_ui_state
# B 只消费正式 OT;build_task_ui_state 直接接受 ShippingOrderTask 并按 task.id 查执行。
state = build_task_ui_state(order_task)
actions = state.get('actions') or {}
b_primary = str((actions.get('primary') or {}).get('code') or '').strip()
b_all = {
str(item.get('code') or '').strip()
for item in [actions.get('primary'), *(actions.get('secondary') or [])]
if item and str(item.get('code') or '').strip()
}
summary = _summary_c(execution_id)
c_next = str(summary.get('next_action_code') or '').strip()
c_allowed = {
str(code or '').strip()
for code in summary.get('allowed_actions') or []
if str(code or '').strip()
}
assert b_primary == c_next, (
f'B.primary={b_primary!r} C.next={c_next!r} for {gate_code}'
)
# B 把 C.allowed_actions 拆成 primary+secondary;二者并集必须等于 allowed_actions。
# 不能再要求 secondary==allowed:主动作被 C 列为 allowed 但在 B 里归到 primary。
assert b_all == c_allowed, (
f'B.all={sorted(b_all)} C.allowed={sorted(c_allowed)} for {gate_code}'
)
def test_preparation_line_emits_decisional_allowed_actions(app, gate_chain):
"""§1.5 明细按钮修复:preparation.lines[] 必须带 line_allowed_actions /
inventory_allowed_actions / inventory_file_no,否则前端 formalPreparationLineAllows 恒 false、
明细行按钮不渲染。用正式 OT + 一行 not_found 断言短缺行按钮被正确授权。"""
from app.models import (
ShippingNoticeLineInventoryMatch,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
)
from app.services.shipping_notice.ui_state import build_task_ui_state
with app.app_context():
run, notice, order_task = _load_chain(gate_chain)
# 冻结快照行 → 行级匹配(not_found,短缺)。
snapshot = ShippingOrderSnapshot(
task_id=int(order_task.id), extraction_id=1, schema_version_id=1,
order_data_version=1, header_values_json={},
)
db.session.add(snapshot)
db.session.flush()
order_task.order_snapshot_id = int(snapshot.id)
line = ShippingOrderSnapshotLine(
snapshot_id=int(snapshot.id), position=0, line_no=1,
reservation_id='RSV-EQ', part_number='PN-EQ', qty='8', field_values_json={},
)
db.session.add(line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=int(order_task.id), snapshot_line_id=int(line.id), line_no=1, line_index=0,
match_result='not_found', inventory_status='ready', required_qty='8',
available_qty='0', matched_qty='0', shortage_qty='8',
reservation_id='RSV-EQ', part_number='PN-EQ',
inventory_source_code='DBS_DUB', matched_file_no='INV-EQ', is_current=True,
))
db.session.commit()
preparation = build_task_ui_state(order_task, include_stage_context=True)['stage_context']['preparation']
assert preparation['lines'], '必须有至少一行'
line_row = preparation['lines'][0]
# 短缺行:close + release_inventory_shortage(line);retry_inventory_preparation(inventory)。
assert set(line_row['line_allowed_actions']) == {
'close_unfulfillable', 'release_inventory_shortage',
}
assert 'retry_inventory_preparation' in line_row['inventory_allowed_actions']
# 下载库存按钮依赖 inventory_file_no。
assert line_row['inventory_file_no'] == 'INV-EQ'
assert line_row['user_line_status'] == 'shortage'
def test_preparation_line_allowed_actions_are_zero_n_plus_one(app, gate_chain):
"""§5.1 N+1 守门:行级 action 字段由内存事实投影发,GET 详情 SQL 数恒定且不随行数线性放大。
行级 fact 字典只读已加载的 match_row 列 + detail_json(触库的是 `_build_stage_context`
自身的批量预取),每行并不追加查询;6 行仍须落在固定数量级。若逐行 SQL/重序列化,
SQL 数会近似=6×行查询而被本上限拦下。
"""
from sqlalchemy import event
from app.models import (
ShippingNoticeLineInventoryMatch,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
)
from app.services.shipping_notice.ui_state import build_task_ui_state
from tests.test_shipping_order_review_service import _capture_sql_statements
with app.app_context():
run, notice, order_task = _load_chain(gate_chain)
snapshot = ShippingOrderSnapshot(
task_id=int(order_task.id), extraction_id=1, schema_version_id=1,
order_data_version=1, header_values_json={},
)
db.session.add(snapshot)
db.session.flush()
order_task.order_snapshot_id = int(snapshot.id)
line_count = 6
for i in range(line_count):
line = ShippingOrderSnapshotLine(
snapshot_id=int(snapshot.id), position=i, line_no=i + 1,
reservation_id=f'RSV-{i}', part_number=f'PN-{i}', qty='8', field_values_json={},
)
db.session.add(line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=int(order_task.id), snapshot_line_id=int(line.id), line_no=i + 1, line_index=i,
match_result='matched', inventory_status='ready', required_qty='8',
available_qty='8', matched_qty='8', shortage_qty='0',
reservation_id=f'RSV-{i}', part_number=f'PN-{i}',
inventory_source_code='DBS_DUB', matched_file_no=f'INV-{i}', is_current=True,
))
db.session.commit()
task_id = int(order_task.id)
db.session.remove()
with app.test_request_context():
ot = db.session.get(ShippingOrderTask, task_id)
statements: list[str] = []
listener = _capture_sql_statements(statements)
event.listen(db.engine, 'before_cursor_execute', listener)
try:
preparation = build_task_ui_state(ot, include_stage_context=True)['stage_context']['preparation']
finally:
event.remove(db.engine, 'before_cursor_execute', listener)
assert len(preparation['lines']) == line_count
# 关键断言:6 行仍落在固定数量级;若逐行重查会显著超出(约 6×行查询)而触发。
assert len(statements) <= 40, (
f'SQL 数随行数放大: 6 行仍应固定数量级,实测 {len(statements)}'
)
@pytest.mark.parametrize('scenario', [
# gate_code, expected lifecycle stage(契约:正式 Gate 映射到五阶段业务码唯一表)
('inventory_matching', 'fulfillment_prep'),
('inventory_sufficiency', 'fulfillment_prep'),
('artifact_generation', 'fulfillment_prep'),
('freight_upload_rpa', 'freight_upload'),
('manual_upload_handoff', 'freight_upload'),
])
def test_gate_maps_to_lifecycle_stage_b(app, gate_chain, scenario):
"""五阶段门禁→生命周期 唯一映射必须正确(B 侧,真实 Notice 路径)。
`LIFECYCLE_STAGE_BY_GATE`(lifecycle_projection.py:30)是正式 Gate→五阶段业务码的唯一表。
B(build_task_ui_state on Notice,processing_stage=None)经 project_lifecycle 走 Gate 兜底,
必须按该表落到正确业务码。**freight_upload_rpa / manual_upload_handoff 必须属于 freight_upload**
—— 这是用户确认的契约(方案 A)。
"""
gate_code, expected_stage = scenario
with app.app_context():
run, notice, order_task = _load_chain(gate_chain)
execution_id = _attach_execution(
order_task,
gate_code=gate_code, status='blocked_manual',
blocking_reason_code='inventory_preparation_failed', next_action_code='retry_inventory_preparation',
)
# 让 notice 路径经 order_task_id 命中同一 execution(B 在生产中把 Notice
# 传给 build_task_ui_state;Execution.task_id 必须保持为 OT.id)。
assert int(notice.order_task_id) == int(order_task.id)
from app.services.shipping_notice.ui_state import build_task_ui_state
b = build_task_ui_state(notice)
b_stage = str((b.get('stage') or {}).get('code') or '').strip()
b_lifecycle = str(b.get('lifecycle_stage') or '').strip()
# B(Notice 路径)必须按 LIFECYCLE_STAGE_BY_GATE 落到五阶段码。
assert b_stage == b_lifecycle == expected_stage, (
f'B.stage={b_stage!r} B.lifecycle={b_lifecycle!r} expected={expected_stage!r} for {gate_code}'
)
def test_a_secondary_actions_carry_mark_manual_uploaded(app, gate_chain):
"""A(shippingProcessingProjection.ui_state.secondary_actions)必须透传原始 Gate 码 mark_manual_uploaded。
契约 §2.5 差异①:A 的 secondary_actions 用别名 open_manual_upload,B/C 用 mark_manual_uploaded。
frontend manualUploadRegistrationAuthorized 读 A 时须能匹配到 mark_manual_uploaded(否则按钮失效)。
本守卫在归一化前应 RED(记录 bug),归一化后应 GREEN。
"""
with app.app_context():
run, notice, order_task = _load_chain(gate_chain)
# freight_upload_rpa blocked_manual:C 的 gate_side_recovery_actions / 显式 append 授权手动上传。
execution_id = _attach_execution(
order_task,
gate_code='freight_upload_rpa', status='blocked_manual',
blocking_reason_code='upload_rpa_failed', next_action_code='retry_freight_upload_rpa',
)
db.session.commit()
a = _project_a(run, order_task)
ui_state = a.get('ui_state') or {}
secondary_codes = {
str(item.get('code') or '').strip()
for item in ui_state.get('secondary_actions') or []
if item
}
primary_code = str((ui_state.get('primary_action') or {}).get('code') or '').strip()
# C 是唯一授权来源:allowed_actions 必含 mark_manual_uploaded(手动上传入口)。
summary = _summary_c(execution_id)
c_allowed = {str(c or '').strip() for c in summary.get('allowed_actions') or []}
assert 'mark_manual_uploaded' in c_allowed, f'C.allowed={sorted(c_allowed)}'
# [§2.5 归一守卫] A 的 secondary_actions 必须透传原始码 mark_manual_uploaded(而非 open_manual_upload 别名),
# 且与 C.allowed_actions 同集(允许与主动作并存)。
assert 'mark_manual_uploaded' in secondary_codes or primary_code == 'mark_manual_uploaded', (
f'A.secondary={sorted(secondary_codes)} A.primary={primary_code!r} C.allowed={sorted(c_allowed)}'
)