perf(shipping-notice): 优化发货任务性能,修复上传流程与终态问题

This commit is contained in:
hugo committed 2026-08-27 19:25:16 +08:00
1 parent 434c04ed2d
commit bcdd8285ae
29 files changed
+1074 -128

No files matched your search

@@ -440,6 +440,69 @@ def test_freight_notice_groups_reads_frozen_snapshot_po_when_extraction_projecti
assert [item['business_no'] for item in result['items']] == ['WYC26082411', 'WYC26082412']
def test_freight_notice_groups_upload_mode_reads_attempt_not_stale_column(app):
"""通知完成面的上传方式必须取自 ShippingUploadAttempt,而非恒为 None 的 Notice.upload_mode。
回归点:denormalized Notice.upload_mode 从未被写入真实值;人工确认/RPA 的成功事实
只保存在 ShippingUploadAttempt.mode。聚合投影若直接读列会导致「通知完成」卡片拿不到
「人工確認 vs RPA 上传」的徽标来源。
"""
with app.app_context():
from app import db
from app.models import (
ShippingExportArtifact, ShippingExcelTemplate, ShippingInventoryParsingProfile,
ShippingNotice, ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion,
)
from app.services.shipping_notice import query_service
from app.services.shipping_notice.upload_attempt_service import record_manual_upload
notice = ShippingNotice(task_no='SN-GROUP-MODE-1', business_no='WYC26082501', source_type='manual', user_id=11)
template = ShippingExcelTemplate(
template_code='MODE', display_name='Mode', version=1, status='published', storage_bucket='test',
storage_key='test/template.xlsx', original_filename='template.xlsx', file_checksum='a' * 64,
definition_json={},
)
profile = ShippingInventoryParsingProfile(
profile_code='MODE', display_name='Mode', version=1, status='published', file_format='xlsx',
definition_json={},
)
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
db.session.add_all([notice, template, profile, schema]); db.session.flush()
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
db.session.add(version); db.session.flush()
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted')
db.session.add(extraction); db.session.flush()
artifact = ShippingExportArtifact(
artifact_no='ART-MODE-1', task_id=notice.id, template_id=template.id, order_schema_version_id=version.id,
order_extraction_id=extraction.id, inventory_parsing_profile_id=profile.id, input_checksum='b' * 64,
file_path='/tmp/notice.xlsx', file_name='notice.xlsx', file_checksum='c' * 64, file_size=100, status='ready',
)
db.session.add(artifact); db.session.flush()
notice.export_file_name = 'notice.xlsx'
notice.export_file_path = '/tmp/notice.xlsx'
# 人为把陈旧列写成错误值,证明聚合不再消费它。
notice.upload_mode = 'rpa'
notice.upload_attempt = 99
db.session.commit()
# 一条人工确认成功 Attempt = 唯一可信的来源。
record_manual_upload(notice, artifact_id=artifact.id, operator_id=22)
db.session.commit()
original_header_reader = query_service.current_header_field_values_or_empty
query_service.current_header_field_values_or_empty = lambda _task: {'customer_po_number': 'PO-MODE'}
try:
result = list_freight_notice_groups_for_task(notice, user_id=11)
finally:
query_service.current_header_field_values_or_empty = original_header_reader
item = result['items'][0]
assert item['business_no'] == 'WYC26082501'
# 权威事实:人工确认成功 → manual;不读陈旧列('rpa')或恒 0/99 的 attempt 计数。
assert item['upload_mode'] == 'manual'
assert item['upload_attempt'] == 1
def test_list_my_todos_and_count_buckets(app):
"""list_my_todos 按 bucket 分类;count 徽标与 pending 一致。"""
with app.app_context():
@@ -848,3 +911,36 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
assert counts["done"] == 1
assert counts["processing"] == 1
assert counts["total_pending_badge"] == 3
def test_serialize_task_detail_workbench_view_drops_editor_fields(app):
"""工作台 view=workbench 剔除复核编辑器重字段,保留 ui_state/产物/行摘要,全量视图不受影响。"""
with app.app_context():
from app import db
from app.services.shipping_notice.query_service import serialize_task_detail
task = ShippingNotice(
task_no="SN-WORKBENCH-VIEW", source_type="manual", user_id=11,
export_file_name="n.xlsx", export_file_path="/tmp/n.xlsx",
)
db.session.add(task)
db.session.commit()
full = serialize_task_detail(task, viewer_user_id=11, include_stage_context=True)
wb = serialize_task_detail(
task, viewer_user_id=11, include_stage_context=True, view="workbench",
)
# full 保留编辑器重字段;workbench 剔除它们,显著缩小响应体。
for key in (
"lines", "order_header", "order_header_fields", "order_line_fields",
"events", "field_conflicts",
):
assert key in full
assert key not in wb
# workbench 仍保留工作台所需字段(ui_state/stage_context、产物、行摘要)。
assert wb["ui_state"]["task_no"] == "SN-WORKBENCH-VIEW"
assert wb["ui_state"]["stage_context"] is not None
assert wb["artifact_summary"]["export_file_name"] == "n.xlsx"
assert "notice_line_summary" in wb
assert "export_artifacts" in wb
@@ -345,6 +345,31 @@ def test_task_ui_state_keeps_resolved_download_alongside_process_gate(app, monke
assert [item['code'] for item in state['actions']['secondary']] == ['download_excel']
def test_verified_upload_complete_state_has_no_follow_up_actions(app, monkeypatch) -> None:
"""通知完成是终态,即使旧 Gate 尚未清理也不得继续下发下一步。"""
with app.app_context():
task = ShippingNotice(task_no='SN-UI-UPLOAD-COMPLETE', source_type='manual')
monkeypatch.setattr(
'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success',
lambda _task: True,
)
monkeypatch.setattr(
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
lambda _task: {
'current_gate': {'gate_code': 'manual_upload_handoff', 'evaluation_version': 3},
'current_blocking_gate': {'gate_code': 'manual_upload_handoff', 'evaluation_version': 3},
'primary_action': {'code': 'mark_manual_uploaded', 'label': '确认上传'},
'action_presentation': [],
},
)
state = build_task_ui_state(task)
# 关键断言:已核验上传成功优先于滞后的 Gate,完成态不能渲染任何下一步。
assert state['lifecycle_stage'] == 'upload_complete'
assert state['actions'] == {'primary': None, 'secondary': []}
def test_stp_facts_candidates_frozen_projected(app) -> None:
"""多候选冻结任务须投影 stp_facts.frozen_candidate_codes。"""
with app.app_context():
@@ -2188,6 +2188,48 @@ def test_eml_leaf_prefers_open_review_case_over_candidate_ready_unit(app, shippi
assert 'edit_draft' in leaf['available_actions']
def test_eml_leaf_treats_current_non_order_case_as_completed(app, shipping_user):
"""当前 Case 标记非订单后,EML 详情不得回退为旧 Unit 的处理中状态。"""
del shipping_user
with app.app_context():
from app.models import ShippingOrderCandidate
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
user, agent, session, intake, document = _seed_run_input(suffix='EML-NON-ORDER-LEAF')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no=f'OCAND-NON-ORDER-{uuid.uuid4().hex[:8]}', intake_id=intake.id,
primary_document_id=document.id, candidate_key='eml-non-order-leaf',
order_extraction_run_id=run.id, is_current_version=True,
)
db.session.add(candidate)
db.session.flush()
case = ensure_run_review_cases(run=run)[0]
case.status = 'non_order'
db.session.commit()
result = _aggregate_eml_order_task_work_items([{
'work_item_type': 'order_task', 'work_item_no': 'OT-EML-NON-ORDER',
'source_type': 'eml', 'intake_no': intake.intake_no, 'run_no': run.run_no,
'status': 'processing', 'stage': 'candidate_creating', 'user_status': 'running',
'user_stage': 'candidate_creating', 'user_group': 'processing',
'last_activity_at': '', 'available_actions': [], 'facts': {'upload_state': 'not_created'},
'source_summary': {'document_id': 0, 'filename': 'mail.eml'},
}])
aggregate = result[0]
leaf = aggregate['aggregate_children'][0]
assert leaf['case_no'] == case.case_no
assert leaf['user_status'] == 'completed'
assert leaf['user_stage'] == 'completed'
assert leaf['ui_state']['status'] == 'completed'
assert aggregate['user_status'] == 'completed'
assert aggregate['aggregate_summary']['completed'] == 1
assert aggregate['aggregate_summary']['processing'] == 0
def test_eml_aggregate_keeps_run_authorized_batch_reparse_action(app, shipping_user):
"""EML 父卡不能因叶子只有 Case 动作而遗漏按原 PDF 的批次重解析入口。"""
del shipping_user
@@ -7,8 +7,8 @@
from app.core.errors import ConflictError
def test_unknown_upload_blocks_new_idempotency_key_and_superseded_callback(app):
"""unknown 必须阻断全新重试键;Artifact superseded 后任何回调只返回冲突。"""
def test_unknown_upload_allows_fresh_retry_key_and_superseded_callback(app):
"""unknown 结果不阻断全新重试键(业务决定:允许继续尝试 RPA,避免卡死);Artifact superseded 后任何回调仍返回冲突。"""
from app import db
from app.models import ShippingExportArtifact
from app.services.shipping_notice.upload_attempt_service import (
@@ -21,12 +21,10 @@ def test_unknown_upload_blocks_new_idempotency_key_and_superseded_callback(app):
task, artifact, _reservation = _ready_artifact()
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
mark_attempt_result_unknown(attempt)
try:
start_rpa_attempt(task, artifact_id=artifact.id, idempotency_key='fresh-retry-key')
except ConflictError as exc:
assert exc.code == 'SHIPPING.UPLOAD_RETRY_FORBIDDEN_UNTIL_TERMINAL'
else:
raise AssertionError('unknown upload must block a fresh retry key')
# 业务决定:unknown(无法判断上传是否成功/失败)不再阻断重新下发 RPA,允许再次尝试。
retry = start_rpa_attempt(task, artifact_id=artifact.id, idempotency_key='fresh-retry-key')
assert retry.id != attempt.id
assert retry.status == 'running'
artifact.status = 'superseded'
db.session.flush()
@@ -53,6 +53,26 @@ def test_step1a_closes_all_gates_when_uploaded(app):
assert execution.status == 'completed'
def test_uploaded_fact_closes_gates_despite_stale_upload_pending_reason(app):
"""上传已成功时,历史 upload_rpa_pending 不得将正式 Gate 重新投影为阻断。"""
task = ShippingNotice(
task_no='SN-UPLOADED-STALE-PENDING',
upload_status='uploaded',
pending_human_reason='upload_rpa_pending',
match_status='fulfillable',
)
db.session.add(task)
db.session.flush()
execution = _mk_execution(task)
sync_fulfillment_gates_from_task(execution=execution, actor_type='user', actor_id=1)
db.session.commit()
db.session.refresh(execution)
assert execution.current_gate_code is None
assert execution.status == 'completed'
def test_missing_upload_status_keeps_gate_stuck(app):
"""upload_status != uploaded → STEP 1A 不触发,前置 Gate 保留(阶段投影可被回退)。"""
task = ShippingNotice(task_no='SN-UPLOAD-NOT-SET', upload_status='partial', match_status='fulfillable')