feat(shipping, admin, workspace, docs): 迭代货代模块、补充文档并处理合并冲突问题

This commit is contained in:
hugo committed 2026-08-12 09:27:33 +08:00
1 parent 4587b56900
commit 3c0e08377c
94 files changed
+29222 -1218

No files matched your search

@@ -174,6 +174,51 @@ def test_configured_identity_evidence_api_requires_published_definition_and_disa
assert ShippingIdentityEvidence.query.count() == 1
def test_shipping_customer_detail_serializes_identity_evidence_with_multiple_published_schema_families(app, client):
"""客户详情在多个 Schema 族各自发布时仍读取标准族证据配置并返回成功响应。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
from app.services.shipping_notice.identity_rules import service as identity_rules
_create_users()
customer = ShippingCustomer(standard_name='多族客户', short_code='MFS', status='active')
db.session.add(customer)
field = _identity_field()
schema = ShippingOrderSchema(
schema_code='STANDARD_SHIPPING_NOTICE', display_name='标准发货通知',
)
db.session.add(schema)
db.session.flush()
db.session.add(ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', checksum='2' * 64,
definition_json={'fields': [{
'field_id': field.id, 'field_code': field.field_code, 'display_name': '标准收货客户',
'scope': 'header', 'value_type': 'string', 'enabled': True,
'available_for_customer_identity': True, 'normalizer_key': 'lowercase_trim',
}]},
))
db.session.commit()
definition = identity_rules.save_definition({
'definition_code': 'multi_family_customer', 'display_name': '多族客户',
'evidence_label': '客户名称', 'target_type': 'customer',
'context_field_id': field.id, 'max_automation': 'none',
}, actor_id=1)
db.session.add(ShippingIdentityEvidence(
customer_id=customer.id, definition_id=definition['id'], raw_value='多族客户',
normalized_value='多族客户', status='approved',
))
db.session.commit()
customer_id = customer.id
response = client.get(
f'/api/admin/shipping-customers/{customer_id}', headers=_headers('shipping-admin', 'admin'),
)
assert response.status_code == 200
evidence = parse_api_data(response.get_json())['identity_evidences'][0]
assert evidence['definition']['context_field']['display_name'] == '标准收货客户'
def test_shipping_customer_lifecycle_impact_api_is_admin_only(app, client):
"""生命周期影响预览返回统一结构,普通用户不能读取删除资格。"""
app.config['AUTH_JWT_REQUIRED'] = False
@@ -1,12 +1,13 @@
"""shipping_notice inventory_rpa_workflow 单测。
覆盖 RPA 库存子模块与 inventory_workflow 的委托边界:
1. ensure_inventory(mode=auto) 仅复用已有快照,绝不触发 RPA。
1. ensure_inventory(mode=auto) 优先复用已有快照,缺少快照时触发 RPA。
2. rpa_report_inventory 回调会把文件正式落到 inventory_uploads,并进入字段映射确认。
"""
from datetime import datetime
from pathlib import Path
from types import SimpleNamespace
import pytest
@@ -164,6 +165,45 @@ def _freeze_test_rpa_batch_callback_contract(monkeypatch):
monkeypatch.setitem(sys.modules[__name__].__dict__, 'rpa_report_inventory_batch', _wrapped)
def test_auto_inventory_missing_snapshot_triggers_rpa(monkeypatch):
"""库存源已确定但没有有效快照时,auto 模式必须进入库存 RPA。"""
from app.services.shipping_notice import inventory_workflow
task = SimpleNamespace(
task_no='SN-AUTO-RPA-MISSING-SNAPSHOT',
inventory_lines_json=None,
inventory_snapshot_id=None,
inventory_source_status='resolved',
)
monkeypatch.setattr(inventory_workflow, 'resolve_task_from_payload', lambda _payload: task)
monkeypatch.setattr(inventory_workflow, '_inventory_source_gate_response', lambda *_args, **_kwargs: None)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot',
lambda *_args, **_kwargs: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source',
lambda _task: {'source_code': 'DSV360_AWSDU'},
)
monkeypatch.setattr(
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
lambda _task: [],
)
trigger = {'status': 'running', 'task_id': task.task_no, 'rpa': {'attempts': 1}}
monkeypatch.setattr(
'app.services.shipping_notice.inventory_rpa_workflow.ensure_inventory_via_rpa',
lambda _task, *, mode: trigger,
)
result = inventory_workflow.ensure_inventory({
'task_id': task.task_no,
'mode': 'auto',
'_orchestrator_internal_dispatch': True,
})
assert result == trigger
def test_inventory_rpa_single_attempt_messages_hide_fraction():
"""单次自动尝试模式不应再产出 1/1 计数,避免 Dify 误判仍会继续自动重试。"""
from app.services.shipping_notice.inventory_rpa_workflow import (
@@ -10,6 +10,7 @@ backend/tests/test_shipping_order_task_stage_machine.py
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import patch
from app.services.shipping_notice.order_task_stage_machine import (
resolve_pre_confirm_stage,
@@ -128,3 +129,57 @@ def test_map_run_prefers_written_processing_stage():
# direct_pdf 即便误写入 email_* 也须 clamp。
write_run_unified_processing_stage(run, 'email_adjudicating', source_type='direct_pdf')
assert map_run_to_processing_stage(run, source_type='direct_pdf') == 'document_parsing'
def test_consumed_candidate_does_not_reapply_pre_confirm_stage():
"""正式建单后资格重算不得把 OT 改回建单前阶段。"""
from app.services.shipping_notice.order_task_stage_machine import (
sync_order_task_stage_for_candidate,
)
candidate = SimpleNamespace(id=81, consumed_task_id=13)
order_task = SimpleNamespace(stage='inventory_fetching', status='processing')
with patch(
'app.services.shipping_notice.order_task_stage_machine.resolve_order_task_for_candidate',
return_value=order_task,
), patch(
'app.services.shipping_notice.order_task_stage_machine.sync_order_task_processing_state',
) as sync_mock:
result = sync_order_task_stage_for_candidate(
candidate=candidate,
evaluation={
'gates': {'customer_confirmed': False, 'duplicate_resolved': True},
'blocking_reason_codes': ['customer_unresolved'],
},
)
assert result is order_task
assert order_task.stage == 'inventory_fetching'
sync_mock.assert_not_called()
def test_notice_bound_order_task_does_not_reapply_pre_confirm_stage():
"""OT 已挂正式 Notice 时,即使 Candidate 标志缺失也不得回退。"""
from app.services.shipping_notice.order_task_stage_machine import (
sync_order_task_stage_for_candidate,
)
candidate = SimpleNamespace(id=82, consumed_task_id=None)
order_task = SimpleNamespace(stage='inventory_matching', status='automating', shipping_notice_id=14)
with patch(
'app.services.shipping_notice.order_task_stage_machine.resolve_order_task_for_candidate',
return_value=order_task,
), patch(
'app.services.shipping_notice.order_task_stage_machine.sync_order_task_processing_state',
) as sync_mock:
result = sync_order_task_stage_for_candidate(
candidate=candidate,
evaluation={
'gates': {'customer_confirmed': False, 'duplicate_resolved': True},
'blocking_reason_codes': ['customer_unresolved'],
},
)
assert result is order_task
assert order_task.stage == 'inventory_matching'
sync_mock.assert_not_called()
@@ -267,6 +267,30 @@ def test_derive_available_actions_failed_adds_retry():
assert 'retry' in actions
def test_inventory_snapshot_missing_projects_retryable_inventory_action():
"""库存快照缺失属于可恢复技术阻断,用户态必须保留重试动作。"""
payload = apply_user_projection_fields({
'status': 'blocked',
'stage': 'inventory_preparation',
'source_type': 'order_task',
'current_gate': {
'gate_code': 'inventory_preparation',
'status': 'blocked_retryable',
'next_action_code': 'retry_inventory_preparation',
'blocking_reason_code': 'inventory_snapshot_missing',
},
'retry_decision': {
'retryable': True,
'reason_code': 'inventory_snapshot_missing',
},
'available_actions': ['retry_inventory_preparation'],
})
assert payload['user_status'] == 'retryable'
assert payload['retryable'] is True
assert payload['primary_action']['code'] == 'retry'
def test_waiting_human_reconcile_action_uses_projected_available_actions():
"""人工阻断存在统一对账动作时,主动作必须从当前投影动作列表中安全选取。"""
payload = apply_user_projection_fields({
@@ -70,6 +70,93 @@ def test_automation_queued_when_stp_job_exists():
assert result['retryable'] is False
def test_stp_failure_stays_on_order_creation_node_and_hides_review_entry():
"""STP 失败仍属于建单节点;当前复核页不得再次投影打开订单复核。"""
from app.services.shipping_notice.reconciliation_projector import (
project_case_allowed_actions,
)
case = SimpleNamespace(
id=10,
status='ready',
candidate_id=83,
disposition=None,
confirmed_task_id=None,
confirmed_task_no=None,
)
automation = {
'status': 'failed',
'retryable': True,
'reason_code': 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED',
'error_code': 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED',
}
with patch(
'app.services.shipping_notice.workflow_ledger_service.find_item_by_current_case',
return_value=None,
), patch(
'app.services.shipping_notice.tool_common.llm_review_enabled',
return_value=False,
):
actions = project_case_allowed_actions(case, automation=automation)
assert 'retry_stp_auto_create' in actions
assert 'open_order_review' not in actions
def test_stale_running_stp_job_becomes_retryable_failure():
"""超时的 running Job 不能永久遮蔽失败,必须投影为可恢复失败。"""
from datetime import datetime, timedelta, timezone
case = SimpleNamespace(
status='ready',
confirmed_task_id=None,
document_id=10,
current_draft=SimpleNamespace(draft_version=2, updated_at=None),
run=SimpleNamespace(run_no='RUN-STALE'),
updated_at=None,
)
active = SimpleNamespace(
id=1213,
status='running',
started_at=datetime.now(timezone.utc) - timedelta(hours=1),
updated_at=datetime.now(timezone.utc) - timedelta(hours=1),
)
with patch(
'app.services.shipping_notice.order_stp_auto_create_service.find_active_stp_job',
return_value=active,
), patch(
'app.services.shipping_notice.order_review_projection._stp_waiting_timeout_seconds',
return_value=120,
):
from app.services.shipping_notice.order_review_projection import _project_case_automation_status
result = _project_case_automation_status(
case,
validation={'can_build': True, 'can_auto_create': True},
post_confirm=None,
)
assert result['status'] == 'failed'
assert result['retryable'] is True
assert result['reason_code'] == 'stp_job_stale'
def test_unexpected_stp_error_has_stable_user_message():
"""自动建单技术异常对用户只返回稳定文案,不泄露数据库原始错误。"""
from app.jobs.handlers.shipping_stp_auto_create import _classify_stp_job_result
retryable, result, _ = _classify_stp_job_result(
error_code='SHIPPING.STP_AUTO_CREATE_UNEXPECTED',
message='psycopg2.errors.InvalidTextRepresentation: invalid input syntax for type integer: "f327..."',
category_hint='temporary_storage_error',
)
assert retryable is True
assert result['message'] == '自动建单失败,系统将自动重试'
assert 'psycopg2' not in result['message']
assert 'invalid input syntax' not in result['message']
def test_automation_failed_retryable_when_post_confirm_needs_retry():
"""确认后推进失败必须可重试,不能只显示已确认。"""
case = SimpleNamespace(status='confirmed', confirmed_task_id=12)