feat(shipping-notice): 增强发货通知与审计功能,支持敏感数据控制与哈希链校验
- 更新发货通知工具 API,剥离不可信的操作人身份字段,确保审计安全 - 引入审计事件的哈希链校验机制,支持数据完整性验证 - 增强订单抽取与审计功能,支持敏感快照的访问控制 - 更新相关模型与服务,确保新功能的完整性与可追溯性 - 完善文档与代码注释,反映新的业务逻辑与审计要求
This commit is contained in:
1 parent
95cdfe66b0
commit
d0fe084999
225 files changed
+25923
-6653
No files matched your search
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/api/admin/shipping_order_extraction.py
|
||||
|
||||
用途:提供订单抽取异步 Run 的管理员运维健康视图、任意 Run 取消与货代统一审计查询/导出。
|
||||
用途:提供订单抽取异步 Run 的管理员运维健康视图、任意 Run 取消与货代统一审计查询/导出/关联链/哈希校验。
|
||||
依赖:admin Blueprint、require_admin、order_extraction_run_service、order_extraction_cancel_service、audit_query_service。
|
||||
逻辑:健康/诊断只读;POST cancel 复用取消服务(代取消他人必须原因);审计接口只读查询/受控导出,访问留痕。
|
||||
逻辑:健康/诊断只读;POST cancel 复用取消服务(代取消他人必须原因);审计接口只读查询/受控导出,
|
||||
访问留痕;敏感详情受 shipping_notice.audit_sensitive_read 裁剪;筛选支持 workflow_id / workflow_item_id。
|
||||
"""
|
||||
|
||||
from flask import Response, g, request
|
||||
@@ -194,99 +195,23 @@ def _audit_filters_from_request() -> dict:
|
||||
keys = (
|
||||
'event_type', 'actor_type', 'actor_id', 'run_no', 'task_no', 'document_id',
|
||||
'operation_id', 'request_id', 'aggregate_type', 'aggregate_id', 'result',
|
||||
'conversation_id', 'session_item_id', 'review_case_no', 'owner_user_id',
|
||||
'created_from', 'created_to', 'q',
|
||||
'conversation_id', 'workflow_id', 'workflow_item_id', 'review_case_no', 'case_no',
|
||||
'owner_user_id', 'created_from', 'created_to', 'q',
|
||||
)
|
||||
return {key: str(source.get(key) or '').strip() or None for key in keys}
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/session-work-items', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_session_work_items_supervision():
|
||||
def _caller_can_read_audit_sensitive() -> bool:
|
||||
"""
|
||||
管理员监管台:跨用户筛选会话 PDF 工作项。
|
||||
判断当前管理员是否具备审计敏感快照读权限。
|
||||
|
||||
核心逻辑:投影后写访问审计(查询者、筛选条件、结果数量),审计失败则阻断响应。
|
||||
核心逻辑:读取 feature_permissions 键 shipping_notice.audit_sensitive_read;
|
||||
不新建角色,仅按用户功能权限裁剪详情。
|
||||
"""
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.session_pdf_work_item_projection import project_admin_supervision_page
|
||||
|
||||
owner_raw = request.args.get('owner_user_id')
|
||||
owner_user_id = int(owner_raw) if owner_raw not in (None, '') else None
|
||||
lifecycle_status = str(request.args.get('lifecycle_status') or '').strip() or None
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip() or None
|
||||
q = str(request.args.get('q') or '').strip() or None
|
||||
page = _query_int('page', 1)
|
||||
page_size = _query_int('page_size', 20)
|
||||
payload = project_admin_supervision_page(
|
||||
lifecycle_status=lifecycle_status,
|
||||
owner_user_id=owner_user_id,
|
||||
conversation_id=conversation_id,
|
||||
q=q,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
record_access_audit(
|
||||
action='admin_list_session_work_items',
|
||||
aggregate_type='session_pdf_work_item',
|
||||
aggregate_id='supervision',
|
||||
actor_id=int(g.current_user.id),
|
||||
actor_type='admin',
|
||||
conversation_id=conversation_id,
|
||||
owner_user_id=owner_user_id,
|
||||
metadata={
|
||||
'lifecycle_status': lifecycle_status,
|
||||
'q': q,
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'result_count': len(payload.get('items') or []),
|
||||
'total': int(payload.get('total') or 0),
|
||||
},
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/session-work-items/<item_no>/terminate', methods=['POST'])
|
||||
@require_admin
|
||||
def terminate_shipping_session_work_item(item_no: str):
|
||||
"""管理员终止工作项;必须理由 + CONFIRM_TERMINATE。"""
|
||||
from app.services.shipping_notice.session_pdf_work_item_projection import serialize_session_work_item
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import terminate_work_item_as_admin
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('JSON body must be an object')
|
||||
item = terminate_work_item_as_admin(
|
||||
admin_user_id=int(g.current_user.id),
|
||||
item_no=item_no,
|
||||
reason=str(body.get('reason') or ''),
|
||||
confirm_token=str(body.get('confirm_token') or ''),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
operation_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
return ok({'item': serialize_session_work_item(item)}, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/session-work-items/<item_no>/revoke-confirmation', methods=['POST'])
|
||||
@require_admin
|
||||
def revoke_shipping_session_work_item_confirmation(item_no: str):
|
||||
"""管理员 24 小时内撤销确认;库存匹配后拒绝并记受控异常。"""
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import revoke_review_confirmation
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('JSON body must be an object')
|
||||
payload = revoke_review_confirmation(
|
||||
admin_user_id=int(g.current_user.id),
|
||||
item_no=item_no,
|
||||
reason=str(body.get('reason') or ''),
|
||||
confirm_token=str(body.get('confirm_token') or ''),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
operation_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
user = getattr(g, 'current_user', None)
|
||||
if user is None:
|
||||
return False
|
||||
return bool(user.has_feature_permission('shipping_notice.audit_sensitive_read'))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/audit-events', methods=['GET'])
|
||||
@@ -312,13 +237,66 @@ def list_shipping_notice_audit_events():
|
||||
@admin_bp.route('/shipping-notice/audit-events/<int:event_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_notice_audit_event(event_id: int):
|
||||
"""读取单条审计详情,含白名单快照与前后差异。"""
|
||||
"""
|
||||
读取单条审计详情,含白名单快照与前后差异。
|
||||
|
||||
敏感事件的 before/after/diff 仅当具备 shipping_notice.audit_sensitive_read 时返回。
|
||||
"""
|
||||
from app.services.shipping_notice.audit_query_service import get_shipping_audit_event
|
||||
|
||||
payload = get_shipping_audit_event(
|
||||
admin_user_id=g.current_user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
event_id=event_id,
|
||||
include_sensitive=_caller_can_read_audit_sensitive(),
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/audit-events/association-chain', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_notice_audit_association_chain():
|
||||
"""
|
||||
按 Workflow / Item / Run / Document / Case / Task 关联键追溯全链审计。
|
||||
|
||||
核心逻辑:至少提供一个关联种子;敏感快照仍受 audit_sensitive_read 裁剪(列表默认无快照)。
|
||||
"""
|
||||
from app.services.shipping_notice.audit_query_service import list_shipping_audit_association_chain
|
||||
|
||||
limit = _query_int('limit', 500)
|
||||
if not 1 <= limit <= 2000:
|
||||
raise ValidationError('limit must be between 1 and 2000')
|
||||
payload = list_shipping_audit_association_chain(
|
||||
admin_user_id=g.current_user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
filters=_audit_filters_from_request(),
|
||||
limit=limit,
|
||||
include_sensitive=_caller_can_read_audit_sensitive(),
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/audit-events/verify-hash-chain', methods=['POST'])
|
||||
@require_admin
|
||||
def verify_shipping_notice_audit_hash_chain():
|
||||
"""
|
||||
校验审计哈希链完整性。
|
||||
|
||||
核心逻辑:可按 aggregate / workflow / item 定点校验,或抽样近期聚合;访问留痕。
|
||||
"""
|
||||
from app.services.shipping_notice.audit_query_service import verify_shipping_audit_hash_chain
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body and not isinstance(body, dict):
|
||||
raise ValidationError('JSON body must be an object')
|
||||
payload = verify_shipping_audit_hash_chain(
|
||||
admin_user_id=g.current_user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
aggregate_type=str(body.get('aggregate_type') or '').strip() or None,
|
||||
aggregate_id=str(body.get('aggregate_id') or '').strip() or None,
|
||||
workflow_id=str(body.get('workflow_id') or '').strip() or None,
|
||||
workflow_item_id=str(body.get('workflow_item_id') or '').strip() or None,
|
||||
sample_limit=int(body.get('sample_limit') or body.get('limit') or 200),
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
@@ -337,8 +315,8 @@ def export_shipping_notice_audit_events():
|
||||
for key in (
|
||||
'event_type', 'actor_type', 'actor_id', 'run_no', 'task_no', 'document_id',
|
||||
'operation_id', 'request_id', 'aggregate_type', 'aggregate_id', 'result',
|
||||
'conversation_id', 'session_item_id', 'review_case_no', 'owner_user_id',
|
||||
'created_from', 'created_to', 'q',
|
||||
'conversation_id', 'workflow_id', 'workflow_item_id', 'review_case_no', 'case_no',
|
||||
'owner_user_id', 'created_from', 'created_to', 'q',
|
||||
)
|
||||
}
|
||||
exported = export_shipping_audit_events(
|
||||
|
||||
@@ -14,6 +14,7 @@ from flask import g, request
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.extensions import db
|
||||
from app.models.shipping_order_schema import ShippingOrderField
|
||||
from app.services.shipping_notice.order_schema import service
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
@@ -227,6 +228,32 @@ def publish_shipping_order_schema_version(version_id: int):
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>/simulate-derivation', methods=['POST'])
|
||||
@require_admin
|
||||
def simulate_shipping_order_schema_derivation(version_id: int):
|
||||
"""
|
||||
对 Schema 版本派生规则做样本模拟(不创建或修改订单)。
|
||||
|
||||
请求体:lines[] 或 sample_ref=`extraction:<id>`;可选 derivation_rules。
|
||||
事务:服务层只写入审计实体,本路由统一 commit。
|
||||
"""
|
||||
payload = service.simulate_derivation(
|
||||
version_id,
|
||||
request.get_json(silent=True) or {},
|
||||
actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/derivation-simulate-samples', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_order_schema_derivation_simulate_samples():
|
||||
"""列出可供派生规则模拟的历史 Extraction 样本摘要。"""
|
||||
limit = request.args.get('limit', 20, type=int)
|
||||
return _ok(service.list_derivation_simulate_samples(limit=limit or 20))
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/published-contract', methods=['GET'])
|
||||
@require_admin
|
||||
def get_published_shipping_order_contract():
|
||||
|
||||
@@ -3,7 +3,8 @@ api/shipping_notice_tools.py
|
||||
|
||||
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
|
||||
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url。
|
||||
逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError。
|
||||
逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError;
|
||||
`_payload()` 剥离 body 中的操作人伪造字段,禁止集成密钥冒充用户写审计。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -106,7 +107,19 @@ def _dify_openapi_spec() -> dict:
|
||||
return build_dify_openapi_spec(_tool_api_base_url())
|
||||
|
||||
def _payload() -> dict:
|
||||
return request.get_json(silent=True) or {}
|
||||
"""
|
||||
读取 Tool API JSON 请求体,并剥离不可信的操作人身份字段。
|
||||
|
||||
核心逻辑:集成密钥调用方不得通过 body 伪造 `_trusted_user_id` /
|
||||
`operator_id` / `actor_id`;真实用户身份仅允许工作台/会话层鉴权后注入。
|
||||
"""
|
||||
raw = request.get_json(silent=True) or {}
|
||||
if not isinstance(raw, dict):
|
||||
return {}
|
||||
payload = dict(raw)
|
||||
for key in ('_trusted_user_id', 'operator_id', 'actor_id'):
|
||||
payload.pop(key, None)
|
||||
return payload
|
||||
|
||||
|
||||
def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = None, batch_no: str | None = None) -> None:
|
||||
@@ -303,6 +316,7 @@ def tool_upload_to_freight():
|
||||
"""
|
||||
上传到货代系统或确认人工上传完成。
|
||||
【AI 触发时机】:仅供后端主调度、内部恢复链路或人工上传收口调用;不是 Dify 画布正式入口。
|
||||
Agent 应优先引导用户走工作台 mark-manual-uploaded,勿在自动链中调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.upload_to_freight(_payload()))
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
backend/app/api/workspace/shipping_notice.py
|
||||
|
||||
用途:HXOPS 工作台发货通知用户态 API(任务处理工作台为履约写操作入口;Chat 仅通知/上传)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload / ui_state。
|
||||
依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload / ui_state、
|
||||
workflow_progress_projection / workflow_ledger_service(Workflow 只读与取消)。
|
||||
逻辑:薄路由层鉴权与参数校验;写接口保留乐观锁、幂等键与统一 AppError;
|
||||
人工上传强制证据资产;Chat Turn 履约写路径已废弃,请改走本 Blueprint。
|
||||
"""
|
||||
@@ -894,7 +895,13 @@ def workspace_match_shipping_inventory(task_no: str):
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint, human_options_for_checkpoint
|
||||
matched = shipping_tools.match_inventory({'task_id': task.task_no, AUTO_CHAIN_FALLBACK: True})
|
||||
matched = shipping_tools.match_inventory({
|
||||
'task_id': task.task_no,
|
||||
AUTO_CHAIN_FALLBACK: True,
|
||||
'_trusted_user_id': user.id,
|
||||
'operator_id': user.id,
|
||||
'event_source': 'workspace_api',
|
||||
})
|
||||
if not isinstance(matched, dict):
|
||||
return jsonify(matched)
|
||||
data = matched.get('data')
|
||||
@@ -914,44 +921,6 @@ def workspace_match_shipping_inventory(task_no: str):
|
||||
return jsonify(matched)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/upload-inventory', methods=['POST'])
|
||||
def workspace_upload_shipping_inventory(task_no: str):
|
||||
"""为当前任务上传正式库存文件;工作台直连既有确定性库存解析链路。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
upload = request.files.get('file')
|
||||
if upload is None:
|
||||
raise ValidationError('file is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
|
||||
def workspace_mark_manual_uploaded(task_no: str):
|
||||
"""登记人工货代上传;必须提交当前用户已上传的截图或回执 FileAsset 编号。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {
|
||||
'task_id': task.task_no, 'mode': 'manual_confirm', 'operator_id': user.id,
|
||||
'evidence_asset_no': data.get('evidence_asset_no'), 'freight_ref_no': data.get('freight_ref_no'),
|
||||
'artifact_id': data.get('artifact_id'),
|
||||
}
|
||||
return jsonify(shipping_tools.upload_to_freight(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST'])
|
||||
def workspace_retry_shipping_upload(task_no: str):
|
||||
"""首期禁用货代 RPA 重试上传;引导用户改走人工凭据登记。"""
|
||||
_require_user()
|
||||
raise ValidationError(
|
||||
'首期不支持货代 RPA 上传重试。请下载 Excel,在货代系统人工上传后提交截图/PDF 凭据。',
|
||||
code='SHIPPING.FREIGHT_RPA_UPLOAD_DISABLED',
|
||||
)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST'])
|
||||
def workspace_generate_shipping_excel(task_no: str):
|
||||
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
|
||||
@@ -969,6 +938,41 @@ def workspace_generate_shipping_excel(task_no: str):
|
||||
data['download_url'] = f'/api/workspace/shipping-tasks/{task.task_no}/export'
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
|
||||
def workspace_mark_manual_uploaded(task_no: str):
|
||||
"""
|
||||
登记人工货代上传;必须提交当前用户已上传的截图或回执 FileAsset 编号。
|
||||
|
||||
核心逻辑:委托 upload_to_freight(mode=manual_confirm);禁止 RPA。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {
|
||||
'task_id': task.task_no,
|
||||
'mode': 'manual_confirm',
|
||||
'operator_id': user.id,
|
||||
'evidence_asset_no': data.get('evidence_asset_no'),
|
||||
'freight_ref_no': data.get('freight_ref_no'),
|
||||
'artifact_id': data.get('artifact_id'),
|
||||
}
|
||||
return jsonify(shipping_tools.upload_to_freight(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST'])
|
||||
def workspace_retry_shipping_upload(task_no: str):
|
||||
"""首期禁用货代 RPA 重试上传;引导用户改走人工凭据登记。"""
|
||||
_require_user()
|
||||
raise ValidationError(
|
||||
'首期不支持货代 RPA 上传重试。请下载 Excel,在货代系统人工上传后提交截图/PDF 凭据。',
|
||||
code='SHIPPING.FREIGHT_RPA_UPLOAD_DISABLED',
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。"""
|
||||
@@ -1164,12 +1168,34 @@ def workspace_get_shipping_order_review_case(case_no: str):
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
def _review_draft_payload() -> dict:
|
||||
"""读取复核草稿 JSON 请求体;写接口统一要求对象,避免字段类型在路由层歧义。"""
|
||||
def _review_draft_payload(
|
||||
*,
|
||||
user_id: int,
|
||||
case_no: str,
|
||||
action: str,
|
||||
kind: str = 'draft',
|
||||
) -> dict:
|
||||
"""
|
||||
读取复核写接口 JSON 请求体;非对象时按 Case 写拒绝审计。
|
||||
|
||||
核心逻辑:写接口统一要求对象;Case 可定位时落 rejected 审计再抛 VALIDATION.INVALID_PARAM,
|
||||
避免路由层静默丢拒绝痕迹。confirm 走确认审计族,其余走草稿审计族。
|
||||
"""
|
||||
payload = request.get_json(silent=True)
|
||||
if not isinstance(payload, dict):
|
||||
raise ValidationError('Review draft payload must be an object', code='VALIDATION.INVALID_PARAM')
|
||||
return payload
|
||||
if isinstance(payload, dict):
|
||||
return payload
|
||||
if kind == 'confirm':
|
||||
from app.core.errors import ValidationError as _ValidationError
|
||||
from app.services.shipping_notice.order_review_confirmation_service import reject_confirm_precondition
|
||||
|
||||
reject_confirm_precondition(
|
||||
user_id=int(user_id),
|
||||
case_no=case_no,
|
||||
error=_ValidationError('Review draft payload must be an object', code='VALIDATION.INVALID_PARAM'),
|
||||
)
|
||||
from app.services.shipping_notice.order_review_draft_service import reject_invalid_draft_request_payload
|
||||
|
||||
reject_invalid_draft_request_payload(user_id=int(user_id), case_no=case_no, action=action)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/header-fields/<field_id>', methods=['PATCH'])
|
||||
@@ -1178,7 +1204,7 @@ def workspace_patch_shipping_order_review_header_field(case_no: str, field_id: s
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import patch_header_field
|
||||
|
||||
payload = _review_draft_payload()
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='header_field_changed')
|
||||
result = patch_header_field(
|
||||
user_id=user.id, case_no=case_no, field_id=field_id, value=payload.get('value'),
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
@@ -1194,11 +1220,13 @@ def workspace_patch_shipping_order_review_line_field(case_no: str, line_key: str
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import patch_line_field
|
||||
|
||||
payload = _review_draft_payload()
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_field_changed')
|
||||
result = patch_line_field(
|
||||
user_id=user.id, case_no=case_no, line_key=line_key, field_id=field_id, value=payload.get('value'),
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
restore_machine=bool(payload.get('restore_machine')),
|
||||
override_reason_code=payload.get('override_reason_code'),
|
||||
override_reason_text=payload.get('override_reason_text'),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
@@ -1210,7 +1238,8 @@ def workspace_add_shipping_order_review_line(case_no: str):
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import add_line
|
||||
|
||||
result = add_line(user_id=user.id, case_no=case_no, expected_draft_version=_review_draft_payload().get('expected_draft_version'))
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_added')
|
||||
result = add_line(user_id=user.id, case_no=case_no, expected_draft_version=payload.get('expected_draft_version'))
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
@@ -1221,7 +1250,11 @@ def workspace_copy_shipping_order_review_line(case_no: str, line_key: str):
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import copy_line
|
||||
|
||||
result = copy_line(user_id=user.id, case_no=case_no, line_key=line_key, expected_draft_version=_review_draft_payload().get('expected_draft_version'))
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_copied')
|
||||
result = copy_line(
|
||||
user_id=user.id, case_no=case_no, line_key=line_key,
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
@@ -1232,7 +1265,11 @@ def workspace_delete_shipping_order_review_line(case_no: str, line_key: str):
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import delete_line
|
||||
|
||||
result = delete_line(user_id=user.id, case_no=case_no, line_key=line_key, expected_draft_version=_review_draft_payload().get('expected_draft_version'))
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_deleted')
|
||||
result = delete_line(
|
||||
user_id=user.id, case_no=case_no, line_key=line_key,
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
@@ -1243,7 +1280,38 @@ def workspace_validate_shipping_order_review_draft(case_no: str):
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import validate_draft
|
||||
|
||||
result = validate_draft(user_id=user.id, case_no=case_no, expected_draft_version=_review_draft_payload().get('expected_draft_version'))
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='draft_validated')
|
||||
result = validate_draft(
|
||||
user_id=user.id, case_no=case_no, expected_draft_version=payload.get('expected_draft_version'),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>/inventory-candidates',
|
||||
methods=['PUT'],
|
||||
)
|
||||
def workspace_set_shipping_order_review_inventory_candidates(case_no: str, line_key: str):
|
||||
"""
|
||||
人工为明细选择一个或多个已启用库存源候选。
|
||||
|
||||
核心逻辑:强制 reason;写入 Draft 行级覆盖后重跑资格校验。
|
||||
"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import set_line_inventory_candidates
|
||||
|
||||
payload = _review_draft_payload(
|
||||
user_id=user.id, case_no=case_no, action='line_inventory_candidates_selected',
|
||||
)
|
||||
result = set_line_inventory_candidates(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
line_key=line_key,
|
||||
source_codes=list(payload.get('source_codes') or []),
|
||||
reason=str(payload.get('reason') or ''),
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
@@ -1257,7 +1325,9 @@ def workspace_confirm_shipping_order_review_case(case_no: str):
|
||||
trigger_auto_progress_after_review_confirm,
|
||||
)
|
||||
|
||||
payload = _review_draft_payload()
|
||||
payload = _review_draft_payload(
|
||||
user_id=user.id, case_no=case_no, action='confirm_review_case', kind='confirm',
|
||||
)
|
||||
result = confirm_review_case(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
@@ -1289,7 +1359,7 @@ def workspace_create_shipping_order_review_manual_draft(case_no: str):
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_disposition_service import create_manual_draft
|
||||
|
||||
payload = _review_draft_payload()
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='create_manual_draft')
|
||||
result = create_manual_draft(user_id=user.id, case_no=case_no, comment=payload.get('comment'))
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
@@ -1301,7 +1371,7 @@ def workspace_mark_shipping_order_review_non_order(case_no: str):
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_disposition_service import mark_non_order
|
||||
|
||||
payload = _review_draft_payload()
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='mark_non_order')
|
||||
result = mark_non_order(user_id=user.id, case_no=case_no, reason=payload.get('reason'), comment=payload.get('comment'))
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
@@ -1313,7 +1383,7 @@ def workspace_mark_shipping_order_review_quality_issue(case_no: str):
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_disposition_service import mark_quality_issue
|
||||
|
||||
payload = _review_draft_payload()
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='mark_quality_issue')
|
||||
result = mark_quality_issue(user_id=user.id, case_no=case_no, reason=payload.get('reason'), comment=payload.get('comment'))
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
@@ -1326,7 +1396,7 @@ def workspace_reparse_shipping_order_review_document(case_no: str):
|
||||
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_run
|
||||
from app.services.shipping_notice.order_review_disposition_service import reparse_case_document
|
||||
|
||||
payload = _review_draft_payload()
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='reparse_document')
|
||||
run, reused = reparse_case_document(
|
||||
user_id=user.id, case_no=case_no, reason=payload.get('reason'), comment=payload.get('comment'),
|
||||
)
|
||||
@@ -1340,7 +1410,7 @@ def workspace_create_shipping_order_review_replacement_intake(case_no: str):
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_disposition_service import create_replacement_upload_intake
|
||||
|
||||
payload = _review_draft_payload()
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='replacement_intake')
|
||||
intake = create_replacement_upload_intake(user_id=user.id, case_no=case_no, asset_no=payload.get('asset_no'))
|
||||
db.session.commit()
|
||||
return _ok(intake, status=202)
|
||||
@@ -1353,7 +1423,7 @@ def workspace_create_shipping_order_review_replacement_run(case_no: str):
|
||||
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_run
|
||||
from app.services.shipping_notice.order_review_disposition_service import create_replacement_document_run
|
||||
|
||||
payload = _review_draft_payload()
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='replacement_run')
|
||||
run, reused = create_replacement_document_run(
|
||||
user_id=user.id, case_no=case_no, intake_no=payload.get('intake_no'),
|
||||
)
|
||||
@@ -1634,6 +1704,132 @@ def workspace_list_shipping_order_extraction_runs():
|
||||
return _ok({'items': [serialize_order_extraction_run(row) for row in rows]})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/workflows', methods=['GET'])
|
||||
def workspace_list_shipping_notice_workflows():
|
||||
"""列出会话开放 Workflow 与 Items;版面阶段 Item 已存在;访问留痕。"""
|
||||
user = _require_user()
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip()
|
||||
if not conversation_id:
|
||||
raise ValidationError('conversation_id is required')
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.workflow_progress_projection import project_conversation_workflows
|
||||
|
||||
payload = project_conversation_workflows(user_id=user.id, conversation_id=conversation_id)
|
||||
record_access_audit(
|
||||
action='view_workflows',
|
||||
aggregate_type='shipping_notice_workflow',
|
||||
aggregate_id=conversation_id,
|
||||
actor_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
metadata={
|
||||
'workflow_count': len(payload.get('workflows') or []),
|
||||
'poll': True,
|
||||
},
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/workflows/<workflow_no>', methods=['GET'])
|
||||
def workspace_get_shipping_notice_workflow(workflow_no: str):
|
||||
"""读取当前用户的 Workflow 详情与 Items;访问留痕。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.workflow_progress_projection import (
|
||||
get_workflow_for_user,
|
||||
serialize_workflow,
|
||||
)
|
||||
|
||||
workflow = get_workflow_for_user(user_id=user.id, workflow_no=workflow_no)
|
||||
payload = serialize_workflow(workflow, user_id=user.id, include_items=True)
|
||||
record_access_audit(
|
||||
action='view_workflow',
|
||||
aggregate_type='shipping_notice_workflow',
|
||||
aggregate_id=str(workflow.workflow_no),
|
||||
actor_id=user.id,
|
||||
conversation_id=workflow.conversation_id,
|
||||
metadata={'status': str(workflow.status or ''), 'poll': True},
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/workflow-items/<item_no>', methods=['GET'])
|
||||
def workspace_get_shipping_notice_workflow_item(item_no: str):
|
||||
"""读取当前用户的 WorkflowItem 详情(含事件);访问留痕。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.workflow_progress_projection import get_workflow_item_dto_for_user
|
||||
|
||||
payload = get_workflow_item_dto_for_user(user_id=user.id, item_no=item_no, include_events=True)
|
||||
record_access_audit(
|
||||
action='view_workflow_item',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id=str(payload.get('item_no') or item_no),
|
||||
actor_id=user.id,
|
||||
conversation_id=str(payload.get('conversation_id') or '') or None,
|
||||
metadata={
|
||||
'lifecycle_status': str(payload.get('lifecycle_status') or ''),
|
||||
'poll': True,
|
||||
},
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/workflow-items/<item_no>/cancel', methods=['POST'])
|
||||
def workspace_cancel_shipping_notice_workflow_item(item_no: str):
|
||||
"""
|
||||
用户取消单个 WorkflowItem。
|
||||
|
||||
核心逻辑:必填 reason;委托 cancel_workflow_item_for_user;返回关闭后的 Item 投影。
|
||||
"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body and not isinstance(body, dict):
|
||||
raise ValidationError('Request body must be an object')
|
||||
from app.services.shipping_notice.workflow_ledger_service import cancel_workflow_item_for_user
|
||||
from app.services.shipping_notice.workflow_progress_projection import serialize_workflow_item
|
||||
|
||||
item = cancel_workflow_item_for_user(
|
||||
user_id=user.id,
|
||||
item_no=item_no,
|
||||
reason=body.get('reason'),
|
||||
expected_lock_version=body.get('expected_lock_version'),
|
||||
request_id=str(getattr(g, 'request_id', '') or '') or None,
|
||||
operation_id=str(body.get('operation_id') or getattr(g, 'request_id', '') or '') or None,
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok({'item': serialize_workflow_item(item, include_events=False)})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/workflow-items/<item_no>/reparse', methods=['POST'])
|
||||
def workspace_reparse_shipping_notice_workflow_item(item_no: str):
|
||||
"""
|
||||
用户对单个 WorkflowItem 发起重试/重新识别。
|
||||
|
||||
核心逻辑:必填 reason;有 Case 走单 PDF 重识别(新 Version);无 Case 且 Run 失败则重试入队;
|
||||
返回最新 Item 投影与 reused 标记。
|
||||
"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body and not isinstance(body, dict):
|
||||
raise ValidationError('Request body must be an object')
|
||||
from app.services.shipping_notice.workflow_ledger_service import reparse_workflow_item_for_user
|
||||
from app.services.shipping_notice.workflow_progress_projection import serialize_workflow_item
|
||||
|
||||
item, reused = reparse_workflow_item_for_user(
|
||||
user_id=user.id,
|
||||
item_no=item_no,
|
||||
reason=body.get('reason'),
|
||||
comment=body.get('comment'),
|
||||
request_id=str(getattr(g, 'request_id', '') or '') or None,
|
||||
operation_id=str(body.get('operation_id') or getattr(g, 'request_id', '') or '') or None,
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok({
|
||||
'item': serialize_workflow_item(item, include_events=False),
|
||||
'reused': bool(reused),
|
||||
})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['POST'])
|
||||
def workspace_create_shipping_notice_intake():
|
||||
"""基于 FileAsset 创建发货通知接入记录并投递预解析任务。"""
|
||||
@@ -1865,101 +2061,3 @@ def workspace_retry_shipping_batch_pending(batch_no: str):
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
|
||||
return jsonify(retry_batch_pending_tasks(batch.batch_no))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/session-work-items', methods=['GET'])
|
||||
def workspace_list_session_work_items():
|
||||
"""
|
||||
会话 PDF 工作台读模型:未关闭/已关闭分组与统计。
|
||||
|
||||
核心逻辑:仅按 conversation_id 聚合工作项,禁止用最新 Run 充当本次处理范围;
|
||||
敏感读取写入访问审计(查询者、会话、结果数量、请求关联)。
|
||||
"""
|
||||
user = _require_user()
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip()
|
||||
if not conversation_id:
|
||||
raise ValidationError('conversation_id is required', code='SHIPPING_NOTICE.SESSION_WORK_ITEM_CONVERSATION_REQUIRED')
|
||||
open_only = str(request.args.get('open_only') or '').strip().lower() in {'1', 'true', 'yes'}
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.session_pdf_work_item_projection import project_session_workbench
|
||||
payload = project_session_workbench(
|
||||
user_id=int(user.id),
|
||||
conversation_id=conversation_id,
|
||||
open_only=open_only,
|
||||
include_closed=not open_only,
|
||||
)
|
||||
record_access_audit(
|
||||
action='list_session_work_items',
|
||||
aggregate_type='shipping_conversation',
|
||||
aggregate_id=conversation_id,
|
||||
actor_id=user.id,
|
||||
owner_user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
metadata={
|
||||
'open_count': int(payload.get('open_count') or 0),
|
||||
'closed_count': int(payload.get('closed_count') or 0),
|
||||
'open_only': open_only,
|
||||
},
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/session-work-items/<item_no>/versions', methods=['GET'])
|
||||
def workspace_list_session_work_item_versions(item_no: str):
|
||||
"""只读版本历史;旧版不可编辑或确认;访问写入审计。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.session_pdf_work_item_projection import list_session_work_item_versions
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import get_work_item_for_user
|
||||
item = get_work_item_for_user(user_id=int(user.id), item_no=item_no)
|
||||
versions = list_session_work_item_versions(item=item)
|
||||
record_access_audit(
|
||||
action='list_session_work_item_versions',
|
||||
aggregate_type='session_pdf_work_item',
|
||||
aggregate_id=str(item.item_no),
|
||||
actor_id=user.id,
|
||||
owner_user_id=item.owner_user_id,
|
||||
conversation_id=item.conversation_id,
|
||||
session_item_id=item.item_no,
|
||||
document_id=item.current_document_id,
|
||||
review_case_no=item.current_case_no,
|
||||
metadata={'version_count': len(versions)},
|
||||
)
|
||||
return _ok({
|
||||
'item_no': item.item_no,
|
||||
'current_case_no': item.current_case_no,
|
||||
'current_version_no': int(item.current_version_no or 1),
|
||||
'versions': versions,
|
||||
})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/session-work-items/<item_no>/close', methods=['POST'])
|
||||
def workspace_close_session_work_item(item_no: str):
|
||||
"""用户关闭工作项(取消确认);须填写原因。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('JSON body must be an object')
|
||||
reason = str(body.get('reason') or '').strip()
|
||||
if not reason:
|
||||
raise ValidationError('reason is required', code='SHIPPING_NOTICE.SESSION_WORK_ITEM_CLOSE_REASON_REQUIRED')
|
||||
expected_lock = body.get('expected_lock_version')
|
||||
from app.services.shipping_notice.session_pdf_work_item_projection import serialize_session_work_item
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import (
|
||||
close_work_item,
|
||||
get_work_item_for_user,
|
||||
)
|
||||
item = get_work_item_for_user(user_id=int(user.id), item_no=item_no, for_update=True)
|
||||
close_work_item(
|
||||
item=item,
|
||||
closed_reason='user_cancelled',
|
||||
actor_type='user',
|
||||
actor_id=int(user.id),
|
||||
reason=reason,
|
||||
expected_lock_version=int(expected_lock) if expected_lock is not None else None,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
operation_id=getattr(g, 'request_id', None),
|
||||
event_type='session_work_item_cancelled',
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok({'item': serialize_session_work_item(item)})
|
||||
@@ -241,6 +241,10 @@ class Config:
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS = int(
|
||||
os.getenv('SHIPPING_NOTICE_AUDIT_RETENTION_DAYS') or '1095'
|
||||
)
|
||||
# 保留任务是否抽样校验审计哈希链;默认开启,可按环境关闭以免遗留无 hash 行刷屏。
|
||||
SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED', 'false').lower() == 'true'
|
||||
)
|
||||
@@ -301,7 +305,9 @@ class Config:
|
||||
'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN',
|
||||
'shipment_{task_no}_{ts}.xlsx',
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'false').lower() == 'true'
|
||||
# Phase 设计禁止自动货代上传:强制 False,忽略环境变量布尔值(仍可读 env 仅供运维对照)。
|
||||
_SHIPPING_NOTICE_AUTO_UPLOAD_ENV = os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'false')
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = False
|
||||
# Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/jobs/handlers/shipping_document_layout.py
|
||||
|
||||
用途:独立执行单份 ShippingNoticeDocument 的 MinerU 布局解析任务。
|
||||
依赖:Layout lifecycle/runtime、FileAsset、通用 Job queue。
|
||||
逻辑:按 job attempt 领取版本 lease,读取对象存储调用 MinerU;收口时旧 lease 无权覆盖新版本。
|
||||
依赖:Layout lifecycle/runtime、FileAsset、通用 Job queue、audit_service、workflow_ledger(尽力引用)。
|
||||
逻辑:按 job attempt 领取版本 lease,读取对象存储调用 MinerU;收口时旧 lease 无权覆盖新版本;
|
||||
起止与异常轻量写统一审计(若能定位 WorkflowItem 则带软引用)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,6 +27,69 @@ from app.services.shipping_notice.document_layout.runtime import build_mineru_ta
|
||||
LAYOUT_JOB_ERROR = 'shipping_document_layout_provider_failed'
|
||||
|
||||
|
||||
def _layout_job_audit(
|
||||
*,
|
||||
event_type: str,
|
||||
job: Job,
|
||||
version: ShippingDocumentLayoutVersion | None,
|
||||
result: str = 'success',
|
||||
error_code: str | None = None,
|
||||
metadata: dict | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
版面 Job 起止/异常轻量审计;能定位 Item 时写入 workflow 软引用。
|
||||
|
||||
Args:
|
||||
event_type: 审计事件类型。
|
||||
job: 当前 Job。
|
||||
version: 布局版本(可空)。
|
||||
result/error_code/metadata: 结果与脱敏元数据。
|
||||
"""
|
||||
try:
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.document_layout.lifecycle import _conversation_id_for_document
|
||||
from app.services.shipping_notice.workflow_ledger_service import find_item_by_root
|
||||
|
||||
document_id = int(version.document_id) if version is not None else None
|
||||
workflow_id = None
|
||||
workflow_item_id = None
|
||||
conversation_id = None
|
||||
owner_user_id = None
|
||||
if document_id:
|
||||
conversation_id = _conversation_id_for_document(document_id)
|
||||
if conversation_id:
|
||||
item = find_item_by_root(
|
||||
conversation_id=conversation_id,
|
||||
root_document_id=document_id,
|
||||
)
|
||||
if item is not None:
|
||||
workflow_id = str(item.workflow_no)
|
||||
workflow_item_id = str(item.item_no)
|
||||
owner_user_id = item.owner_user_id
|
||||
append_shipping_audit_event(
|
||||
event_type=event_type,
|
||||
aggregate_type='shipping_document_layout_version',
|
||||
aggregate_id=str(getattr(version, 'id', None) or job.id),
|
||||
actor_type='system',
|
||||
actor_id=f'job:{job.id}',
|
||||
conversation_id=conversation_id,
|
||||
document_id=document_id,
|
||||
workflow_id=workflow_id,
|
||||
workflow_item_id=workflow_item_id,
|
||||
owner_user_id=owner_user_id,
|
||||
result=result,
|
||||
error_code=error_code,
|
||||
source='shipping_document_layout',
|
||||
metadata={
|
||||
'job_id': int(job.id),
|
||||
'attempt': int(job.attempts or 0),
|
||||
**(metadata or {}),
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_DOCUMENT_LAYOUT)
|
||||
def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
@@ -56,6 +120,12 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
finish_job(job.id, result={'status': 'stale', 'skipped': True}, owned_attempt=owned_attempt)
|
||||
return
|
||||
version, lease = claimed
|
||||
_layout_job_audit(
|
||||
event_type='document_layout_job_started',
|
||||
job=job,
|
||||
version=version,
|
||||
metadata={'lease': True},
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_progress import record_layout_document_progress
|
||||
|
||||
record_layout_document_progress(document_id=int(version.document_id), event_code='layout_parsing_started')
|
||||
@@ -79,6 +149,12 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
}
|
||||
if complete_layout_version(version.id, lease_token=lease, snapshot=snapshot):
|
||||
record_layout_document_progress(document_id=int(document.id), event_code='layout_parsing_completed')
|
||||
_layout_job_audit(
|
||||
event_type='document_layout_job_completed',
|
||||
job=job,
|
||||
version=version,
|
||||
metadata={'status': str(snapshot.get('status') or 'failed')},
|
||||
)
|
||||
finish_job(
|
||||
job.id, result={'status': str(snapshot.get('status') or 'failed')},
|
||||
message='文档版面解析完成', owned_attempt=owned_attempt,
|
||||
@@ -92,6 +168,14 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
ctx.logger.exception(
|
||||
'shipping_document_layout_failed job_id=%s version_id=%s', job.id, version.id,
|
||||
)
|
||||
_layout_job_audit(
|
||||
event_type='document_layout_job_failed',
|
||||
job=job,
|
||||
version=version,
|
||||
result='error',
|
||||
error_code=LAYOUT_JOB_ERROR,
|
||||
metadata={'error': str(exc)[:200]},
|
||||
)
|
||||
fail_job(job.id, error=LAYOUT_JOB_ERROR, retryable=True, owned_attempt=owned_attempt)
|
||||
sync_layout_after_job_failure(job.id)
|
||||
# 仅当重试已耗尽时版本才会转 failed;此时需要唤醒等待中的 Run,
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
|
||||
用途:消费订单抽取 Run,使用固定模板确定性解析并持久化可复核结果。
|
||||
依赖:Job queue、冻结 Run/Plan、确定性路由和解析、统一审计服务、版面排程。
|
||||
依赖:Job queue、冻结 Run/Plan、确定性路由和解析、统一审计服务、版面排程、
|
||||
ensure_workflow_items_for_run(物化后兜底建 Item)。
|
||||
逻辑:物化附件与排版面 Job 均在主 try 内执行,失败时同步收口 Run;每个 Unit 再确定性解析或标记人工复核;不调用 Dify、Provider 或 Runtime Binding。
|
||||
"""
|
||||
|
||||
@@ -35,6 +36,7 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
mark_order_extraction_persistence_started,
|
||||
order_extraction_layout_prerequisite_issues,
|
||||
materialize_order_extraction_run_inputs,
|
||||
ensure_workflow_items_for_run,
|
||||
progress_ready_extraction_unit,
|
||||
schedule_order_extraction_layouts,
|
||||
transition_order_extraction_run,
|
||||
@@ -534,6 +536,8 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
# [STEP 1] 邮件附件先物化成 Document,再排布局 Job;发送阶段没有 PDF Document。
|
||||
# 必须落在本 try 内:MinerU 关闭/排程失败时 ValidationError 需同步收口 Run,避免 Job 重试耗尽前 UI 一直 queued。
|
||||
materialize_order_extraction_run_inputs(run, finalize_plan=False)
|
||||
# materialize 已 ensure;此处兜底保证 EML 物化路径与幂等重入均有 Item。
|
||||
ensure_workflow_items_for_run(run, stage_when_ready='extracting')
|
||||
schedule_order_extraction_layouts(run, created_by_id=run.user_id)
|
||||
|
||||
# [STEP 2] 订单解析绝不能把仍在生成或缺失的版面快照当作“没有订单表”。
|
||||
|
||||
@@ -75,7 +75,7 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
||||
from app.services.knowledge_cleaning.queue_service import recover_stale_running_jobs
|
||||
|
||||
recover_stale_running_jobs()
|
||||
if 'shipping_notice_run' in allowed_types or 'shipping_notice_parse' in allowed_types:
|
||||
if allowed_types & QUEUE_KB_JOB_TYPES['shipping']:
|
||||
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
|
||||
|
||||
recover_stale_shipping_notice_jobs()
|
||||
|
||||
@@ -73,7 +73,12 @@ from app.models.shipping_order_extraction_run import (
|
||||
ShippingOrderExtractionUnit,
|
||||
)
|
||||
from app.models.shipping_audit_event import ShippingAuditEvent
|
||||
from app.models.shipping_session_pdf_work_item import ShippingSessionPdfWorkItem
|
||||
from app.models.shipping_notice_workflow import (
|
||||
ShippingNoticeWorkflow,
|
||||
ShippingNoticeWorkflowEvent,
|
||||
ShippingNoticeWorkflowItem,
|
||||
ShippingNoticeWorkflowItemVersion,
|
||||
)
|
||||
from app.models.shipping_order_document_profile import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
@@ -198,7 +203,10 @@ __all__ = [
|
||||
'ShippingOrderExtractionProgressEvent',
|
||||
'ShippingOrderExtractionDiagnosticAudit',
|
||||
'ShippingAuditEvent',
|
||||
'ShippingSessionPdfWorkItem',
|
||||
'ShippingNoticeWorkflow',
|
||||
'ShippingNoticeWorkflowItem',
|
||||
'ShippingNoticeWorkflowItemVersion',
|
||||
'ShippingNoticeWorkflowEvent',
|
||||
'ShippingOrderExtractionQualityBatch',
|
||||
'ShippingOrderExtractionQualityLabel',
|
||||
'ShippingOrderDocumentProfile',
|
||||
|
||||
@@ -2,11 +2,17 @@
|
||||
backend/app/models/shipping_audit_event.py
|
||||
|
||||
用途:定义货代领域统一、仅追加的审计事件。
|
||||
依赖:SQLAlchemy Base、货代 Run/Task/Intake/会话 PDF 工作项的稳定业务编号。
|
||||
依赖:SQLAlchemy Base;Workflow / Run / Task / Intake 等稳定业务编号(软引用)。
|
||||
逻辑:各业务服务通过 audit_service 追加事件;事件不依赖可级联删除的业务外键,保留跨生命周期追溯事实。
|
||||
进度审计阶段扩展 operation_id、对象关联、白名单前后快照、证据引用、结果与保留到期时间;
|
||||
会话工作项阶段追加 owner_user_id、session_item_id 与脱敏 client_ip_hash/user_agent_hash;
|
||||
Workflow 阶段以 workflow_id / workflow_item_id / workflow_item_version_id 软引用批次与 PDF 项,
|
||||
并写入 previous_event_hash / event_hash 哈希链与 diff_json;另含 owner_user_id 与脱敏
|
||||
client_ip_hash/user_agent_hash;
|
||||
项次派生阶段使用 LINE_DERIVATION_AUDIT_EVENT_TYPES(FIELD_DERIVED / LINE_NO_OVERRIDDEN /
|
||||
DERIVATION_SIMULATED / EXPORT_GENERATED 等),元数据仅存脱敏摘要与规则校验和;
|
||||
禁止存储 PDF/邮件正文、模型原文、对象存储 URL、原始 IP/UA 或密钥。
|
||||
ORM before_update/before_delete 拒绝改删;PostgreSQL 另有 append-only 触发器
|
||||
(迁移 a0e1f2b3c4d5);到期清理须 set_config('hxops.shipping_audit_purge','1')。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -45,7 +51,9 @@ class ShippingAuditEvent(Base):
|
||||
Index('ix_shipping_audit_events_actor_created', 'actor_type', 'actor_id', 'created_at'),
|
||||
Index('ix_shipping_audit_events_event_type_created', 'event_type', 'created_at'),
|
||||
Index('ix_shipping_audit_events_retention_expires', 'retention_expires_at', 'id'),
|
||||
Index('ix_shipping_audit_events_session_item_created', 'session_item_id', 'created_at'),
|
||||
Index('ix_shipping_audit_events_workflow_created', 'workflow_id', 'created_at'),
|
||||
Index('ix_shipping_audit_events_workflow_item_created', 'workflow_item_id', 'created_at'),
|
||||
Index('ix_shipping_audit_events_event_hash', 'event_hash'),
|
||||
Index('ix_shipping_audit_events_owner_created', 'owner_user_id', 'created_at'),
|
||||
)
|
||||
|
||||
@@ -59,6 +67,8 @@ class ShippingAuditEvent(Base):
|
||||
actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system')
|
||||
actor_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
actor_role: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
# 操作者展示名(可选);与 actor_id 并存,禁止写入敏感联系方式。
|
||||
actor_display: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
request_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
operation_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
correlation_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
@@ -69,8 +79,11 @@ class ShippingAuditEvent(Base):
|
||||
unit_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
document_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
review_case_no: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
# 会话 PDF 工作项稳定编号(item_no);软引用,避免级联删除抹除审计。
|
||||
session_item_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
# Workflow 软引用:workflow_no / item_no / version id(字符串),避免级联删除抹除审计。
|
||||
workflow_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
workflow_item_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
workflow_item_version_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
version_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
# 业务属主(非操作者);代操作场景与 actor_id 区分。
|
||||
owner_user_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
# 仅存哈希,禁止写入原始 IP / User-Agent。
|
||||
@@ -84,6 +97,12 @@ class ShippingAuditEvent(Base):
|
||||
after_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
before_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
after_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
# 白名单前后快照差异;与哈希链一并支撑离线校验。
|
||||
diff_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
previous_event_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
event_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
# 敏感等级:normal | sensitive;用于查询脱敏与访问审计分级。
|
||||
sensitivity_level: Mapped[str | None] = mapped_column(String(16), nullable=True)
|
||||
evidence_refs_json: Mapped[Optional[list[dict[str, Any]]]] = mapped_column(JSON, nullable=True)
|
||||
artifact_refs_json: Mapped[Optional[list[dict[str, Any]]]] = mapped_column(JSON, nullable=True)
|
||||
context_refs_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
"""
|
||||
backend/app/models/shipping_notice_workflow.py
|
||||
|
||||
用途:定义货代发货通知 Workflow / Item / Version / Event 四层事实源。
|
||||
依赖:users、agents、shipping_notice_documents、shipping_order_extraction_runs、
|
||||
shipping_order_review_cases、shipping_tasks。
|
||||
逻辑:一次上传批次 = Workflow;每个 PDF 创建时即有 WorkflowItem;
|
||||
重识别只新增 ItemVersion 并切换 current 指针;用户可见节点写入 WorkflowEvent;
|
||||
审计通过业务编号软引用本表,禁止级联删除抹除追溯。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
JSON,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingNoticeWorkflow(Base):
|
||||
"""一次上传/识别批次;重新打开对话复用未关闭 Workflow,不新建。"""
|
||||
|
||||
__tablename__ = 'shipping_notice_workflows'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('workflow_no', name='uq_shipping_notice_workflows_no'),
|
||||
CheckConstraint(
|
||||
"status IN ("
|
||||
"'open', 'completed', 'cancelled', 'failed'"
|
||||
")",
|
||||
name='ck_shipping_notice_workflows_status',
|
||||
),
|
||||
CheckConstraint('lock_version >= 1', name='ck_shipping_notice_workflows_lock_version'),
|
||||
Index(
|
||||
'ix_shipping_notice_workflows_conversation_status',
|
||||
'conversation_id',
|
||||
'status',
|
||||
'updated_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflows_owner_status',
|
||||
'owner_user_id',
|
||||
'status',
|
||||
'updated_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflows_open_conversation',
|
||||
'conversation_id',
|
||||
'updated_at',
|
||||
postgresql_where=text("status = 'open'"),
|
||||
sqlite_where=text("status = 'open'"),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
workflow_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
|
||||
owner_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='open', server_default='open')
|
||||
current_stage: Mapped[str] = mapped_column(
|
||||
String(64), nullable=False, default='queued', server_default='queued',
|
||||
)
|
||||
last_activity_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
closed_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
|
||||
|
||||
class ShippingNoticeWorkflowItem(Base):
|
||||
"""PDF 级稳定实体;识别开始前即存在,覆盖解析到 Excel 全阶段。"""
|
||||
|
||||
__tablename__ = 'shipping_notice_workflow_items'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('item_no', name='uq_shipping_notice_workflow_items_no'),
|
||||
UniqueConstraint(
|
||||
'workflow_id',
|
||||
'root_document_id',
|
||||
name='uq_shipping_notice_workflow_items_workflow_root_doc',
|
||||
),
|
||||
UniqueConstraint(
|
||||
'current_case_id',
|
||||
name='uq_shipping_notice_workflow_items_current_case',
|
||||
),
|
||||
CheckConstraint(
|
||||
"lifecycle_status IN ("
|
||||
"'queued', 'layout_parsing', 'extracting', 'pending_review', "
|
||||
"'building_order', 'inventory_matching', 'generating_excel', "
|
||||
"'manual_upload_pending', 'reparse_failed', "
|
||||
"'cancelled', 'failed', 'closed'"
|
||||
")",
|
||||
name='ck_shipping_notice_workflow_items_lifecycle',
|
||||
),
|
||||
CheckConstraint(
|
||||
"closed_reason IS NULL OR closed_reason IN ("
|
||||
"'confirmed', 'non_order', 'user_cancelled', 'admin_terminated', 'failed'"
|
||||
")",
|
||||
name='ck_shipping_notice_workflow_items_closed_reason',
|
||||
),
|
||||
CheckConstraint('lock_version >= 1', name='ck_shipping_notice_workflow_items_lock_version'),
|
||||
CheckConstraint(
|
||||
'current_version_no >= 1',
|
||||
name='ck_shipping_notice_workflow_items_version_no',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_items_workflow_lifecycle',
|
||||
'workflow_id',
|
||||
'lifecycle_status',
|
||||
'updated_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_items_conversation_lifecycle',
|
||||
'conversation_id',
|
||||
'lifecycle_status',
|
||||
'updated_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_items_owner_lifecycle',
|
||||
'owner_user_id',
|
||||
'lifecycle_status',
|
||||
'updated_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
'conversation_id',
|
||||
'updated_at',
|
||||
postgresql_where=text(
|
||||
"lifecycle_status NOT IN ('closed', 'cancelled')"
|
||||
),
|
||||
sqlite_where=text(
|
||||
"lifecycle_status NOT IN ('closed', 'cancelled')"
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
item_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
workflow_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_workflows.id'), nullable=False, index=True,
|
||||
)
|
||||
workflow_no: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
|
||||
# 同源 PDF 稳定身份:首次纳入时的 Document;替换文件不改变本字段。
|
||||
root_document_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_documents.id'), nullable=False, index=True,
|
||||
)
|
||||
current_document_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_documents.id'), nullable=False, index=True,
|
||||
)
|
||||
# 软指针:避免与 Version.workflow_item_id 形成循环外键;由 ledger 保证一致性。
|
||||
current_version_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True, index=True)
|
||||
current_version_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
current_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
current_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
current_case_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_review_cases.id'), nullable=True,
|
||||
)
|
||||
current_case_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
current_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
lifecycle_status: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default='queued', server_default='queued',
|
||||
)
|
||||
current_stage: Mapped[str] = mapped_column(
|
||||
String(64), nullable=False, default='queued', server_default='queued',
|
||||
)
|
||||
closed_reason: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
last_activity_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
|
||||
|
||||
class ShippingNoticeWorkflowItemVersion(Base):
|
||||
"""重识别版本链;关联 Run / Case / Task / Excel,旧版本只读留存。"""
|
||||
|
||||
__tablename__ = 'shipping_notice_workflow_item_versions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'workflow_item_id',
|
||||
'version_no',
|
||||
name='uq_shipping_notice_workflow_item_versions_item_no',
|
||||
),
|
||||
CheckConstraint('version_no >= 1', name='ck_shipping_notice_workflow_item_versions_no'),
|
||||
CheckConstraint(
|
||||
"status IN ("
|
||||
"'active', 'superseded', 'failed', 'cancelled'"
|
||||
")",
|
||||
name='ck_shipping_notice_workflow_item_versions_status',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_item_versions_item_created',
|
||||
'workflow_item_id',
|
||||
'created_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_item_versions_run',
|
||||
'run_id',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_item_versions_case',
|
||||
'case_id',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
workflow_item_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_workflow_items.id'), nullable=False, index=True,
|
||||
)
|
||||
item_no: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
workflow_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_workflows.id'), nullable=False, index=True,
|
||||
)
|
||||
workflow_no: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
version_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
document_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_documents.id'), nullable=False, index=True,
|
||||
)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
case_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_review_cases.id'), nullable=True,
|
||||
)
|
||||
case_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
task_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_tasks.id'), nullable=True,
|
||||
)
|
||||
task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
excel_artifact_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default='active', server_default='active',
|
||||
)
|
||||
is_current: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default='true')
|
||||
is_readonly: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default='false')
|
||||
superseded_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
|
||||
|
||||
class ShippingNoticeWorkflowEvent(Base):
|
||||
"""用户可见、按 Workflow 顺序递增的节点事件(与审计账本并存)。"""
|
||||
|
||||
__tablename__ = 'shipping_notice_workflow_events'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'workflow_id',
|
||||
'seq_no',
|
||||
name='uq_shipping_notice_workflow_events_seq',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_events_workflow_occurred',
|
||||
'workflow_id',
|
||||
'occurred_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_notice_workflow_events_item_occurred',
|
||||
'workflow_item_id',
|
||||
'occurred_at',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
workflow_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_workflows.id'), nullable=False, index=True,
|
||||
)
|
||||
workflow_no: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
workflow_item_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_notice_workflow_items.id'), nullable=True, index=True,
|
||||
)
|
||||
item_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
workflow_item_version_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_notice_workflow_item_versions.id'), nullable=True,
|
||||
)
|
||||
version_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
seq_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
event_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
stage_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
message_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system')
|
||||
actor_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
occurred_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
@@ -4,6 +4,7 @@ backend/app/models/shipping_order_schema.py
|
||||
用途:定义货代字段资产、Schema 族/不可变版本、配置审计及动态订单解析结果。
|
||||
依赖:models.base.Base、shipping_tasks、shipping_notice_intakes、users。
|
||||
逻辑:字段资产全局存活(标准只读、扩展可弃用);Schema 族版本仅采用资产并冻结 definition_json;
|
||||
definition_json 含 fields / auto_creation_policy / derivation_rules(及 checksum);
|
||||
写操作追加审计;解析链锁定发布版本。表名保留历史命名以降低迁移耦合。
|
||||
"""
|
||||
|
||||
@@ -73,14 +74,16 @@ class ShippingOrderField(Base):
|
||||
|
||||
__tablename__ = 'shipping_order_fields'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('field_code', name='uq_shipping_order_fields_field_code'),
|
||||
# Header/Line may intentionally share a business code (for example
|
||||
# reservation_id); scope is part of the asset identity.
|
||||
UniqueConstraint('field_code', 'scope', name='uq_shipping_order_fields_code_scope'),
|
||||
CheckConstraint("scope IN ('header', 'line')", name='ck_shipping_order_fields_scope'),
|
||||
CheckConstraint(
|
||||
"field_category IN ('order_header', 'order_line')",
|
||||
"field_category IN ('general_context', 'order_header', 'order_line')",
|
||||
name='ck_shipping_order_fields_category',
|
||||
),
|
||||
CheckConstraint(
|
||||
"collection_mode IN ('llm_extraction')",
|
||||
"collection_mode IN ('deterministic_context', 'llm_extraction')",
|
||||
name='ck_shipping_order_fields_collection_mode',
|
||||
),
|
||||
CheckConstraint(
|
||||
@@ -129,7 +132,15 @@ ShippingFieldAsset = ShippingOrderField
|
||||
|
||||
|
||||
class ShippingOrderSchemaVersion(Base):
|
||||
"""订单 Schema 版本;草稿与发布版本统一以完整 definition_json 为配置真相。"""
|
||||
"""
|
||||
订单 Schema 版本;草稿与发布版本统一以完整 definition_json 为配置真相。
|
||||
|
||||
definition_json 契约要点:
|
||||
- fields[]:字段采用与识别规则
|
||||
- auto_creation_policy:自动建单策略
|
||||
- derivation_rules[]:同行明细字段派生(首期 copy_if_empty → line_no)
|
||||
- derivation_rules_checksum:派生规则稳定校验和
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_order_schema_versions'
|
||||
__table_args__ = (
|
||||
|
||||
@@ -4,6 +4,8 @@ backend/app/models/shipping_order_snapshot.py
|
||||
用途:保存从订单解析候选冻结而来的不可变履约订单快照及人工复核审计。
|
||||
依赖:shipping_order_schema 的 Extraction、shipping_tasks、shipping_customers 与 users。
|
||||
逻辑:order_freeze_service 将已接受 Extraction 的字段按稳定 field_id 冻结为 Snapshot;库存、导出和上传阶段只消费本模块的快照。
|
||||
Phase 0+ 扩展约定:rule_versions_json 可含 derivation_rules_snapshot / derivation_rules_checksum;
|
||||
source_manifest_json 可含 field_lineage(值来源、规则引用、覆盖原因、证据引用)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -35,8 +37,10 @@ class ShippingOrderSnapshot(Base):
|
||||
customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True, index=True)
|
||||
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
order_data_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
# 可含 derivation_rules_snapshot / derivation_rules_checksum 等规则版本投影。
|
||||
rule_versions_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
# 冻结时固化字段裁决、文档哈希、页码坐标及人工复核,避免下游回读可变解析事实。
|
||||
# 冻结时固化字段裁决、文档哈希、页码坐标及人工复核,避免下游回读可变解析事实;
|
||||
# 可含 field_lineage(按 field_code 记录 value_source / rule_id / override_reason / evidence_refs)。
|
||||
source_manifest_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
# 保留所有已发布 Header 字段;核心字段同时写入下方强类型列,扩展字段由业务配置按 field_id 消费。
|
||||
header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
"""
|
||||
backend/app/models/shipping_session_pdf_work_item.py
|
||||
|
||||
用途:定义聊天会话内「PDF 工作项」聚合实体,作为本次处理的唯一业务边界。
|
||||
依赖:users、shipping_notice_documents、shipping_order_extraction_runs、shipping_order_review_cases。
|
||||
逻辑:同会话同源 PDF 仅一条工作项;重识别只切换 current_* 版本指针,不新建工作项;
|
||||
关闭后默认折叠。阶段 0 仅落库契约;写路径与读模型在阶段 1 实现。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import (
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
String,
|
||||
UniqueConstraint,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingSessionPdfWorkItem(Base):
|
||||
"""会话级 PDF 工作项;当前有效 Run/Case 仅由本表指针表达,禁止前端按最新 Run 猜测。"""
|
||||
|
||||
__tablename__ = 'shipping_session_pdf_work_items'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('item_no', name='uq_shipping_session_pdf_work_items_no'),
|
||||
UniqueConstraint(
|
||||
'conversation_id',
|
||||
'root_document_id',
|
||||
name='uq_shipping_session_pdf_work_items_conversation_root_doc',
|
||||
),
|
||||
# 同一 Case 最多作为一条工作项的当前有效版本,防止双指针并发确认。
|
||||
UniqueConstraint(
|
||||
'current_case_id',
|
||||
name='uq_shipping_session_pdf_work_items_current_case',
|
||||
),
|
||||
CheckConstraint(
|
||||
"lifecycle_status IN ("
|
||||
"'pending_review', 'extracting', 'reparse_failed', 'closed'"
|
||||
")",
|
||||
name='ck_shipping_session_pdf_work_items_lifecycle',
|
||||
),
|
||||
CheckConstraint(
|
||||
"closed_reason IS NULL OR closed_reason IN ("
|
||||
"'confirmed', 'non_order', 'user_cancelled', 'admin_terminated'"
|
||||
")",
|
||||
name='ck_shipping_session_pdf_work_items_closed_reason',
|
||||
),
|
||||
CheckConstraint('lock_version >= 1', name='ck_shipping_session_pdf_work_items_lock_version'),
|
||||
CheckConstraint(
|
||||
'current_version_no >= 1',
|
||||
name='ck_shipping_session_pdf_work_items_version_no',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_session_pdf_work_items_conversation_lifecycle',
|
||||
'conversation_id',
|
||||
'lifecycle_status',
|
||||
'updated_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_session_pdf_work_items_owner_lifecycle',
|
||||
'owner_user_id',
|
||||
'lifecycle_status',
|
||||
'updated_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_session_pdf_work_items_open_conversation',
|
||||
'conversation_id',
|
||||
'updated_at',
|
||||
postgresql_where=text("lifecycle_status <> 'closed'"),
|
||||
sqlite_where=text("lifecycle_status <> 'closed'"),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
item_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
|
||||
# 同源 PDF 稳定身份:首次纳入会话时的 Document;替换文件不改变本字段。
|
||||
root_document_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_documents.id'), nullable=False, index=True,
|
||||
)
|
||||
current_document_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_documents.id'), nullable=False, index=True,
|
||||
)
|
||||
current_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
current_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
current_case_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_review_cases.id'), nullable=True,
|
||||
)
|
||||
current_case_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
# 面向用户的版本序号(V1/V2);重识别成功递增,失败回退不递增。
|
||||
current_version_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
lifecycle_status: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default='pending_review', server_default='pending_review',
|
||||
)
|
||||
closed_reason: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
@@ -91,6 +91,8 @@ class User(Base):
|
||||
'training_hr_manage': self.role in {'admin', 'hr'},
|
||||
# 发货通知强制新建重复单据:admin 默认开;其他角色默认关,可显式授予
|
||||
'shipping_notice_force_create': self.role == 'admin',
|
||||
# 货代审计敏感快照/前后 Diff 读取:admin 默认开;不新建角色,可显式关闭或授予
|
||||
'shipping_notice.audit_sensitive_read': self.role == 'admin',
|
||||
}
|
||||
|
||||
def get_feature_permissions(self) -> dict[str, bool]:
|
||||
|
||||
@@ -146,15 +146,48 @@ def _register_builtin_platform_jobs() -> None:
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="shipping-audit-retention",
|
||||
label="货代审计到期清理",
|
||||
label="货代审计到期清理与哈希校验",
|
||||
handler=run_shipping_audit_retention_schedule,
|
||||
description="按三年保留期分批清理到期的货代统一审计事件;支持 dry_run 观测。",
|
||||
description=(
|
||||
"分批清理 retention_expires_at 已到期的历史审计行(新写入永久保留);"
|
||||
"并按 SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED 抽样校验近期聚合哈希链。"
|
||||
"建议每日调度一次。"
|
||||
),
|
||||
category="shipping",
|
||||
params_schema=(
|
||||
{"key": "limit", "type": "number", "label": "单批上限", "required": False, "default": 1000},
|
||||
{"key": "limit", "type": "number", "label": "清理单批上限", "required": False, "default": 1000},
|
||||
{"key": "dry_run", "type": "boolean", "label": "仅演练", "required": False, "default": False},
|
||||
{
|
||||
"key": "hash_sample_limit",
|
||||
"type": "number",
|
||||
"label": "哈希链抽样条数",
|
||||
"required": False,
|
||||
"default": 200,
|
||||
},
|
||||
),
|
||||
defaults={"limit": 1000, "dry_run": False},
|
||||
defaults={"limit": 1000, "dry_run": False, "hash_sample_limit": 200},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="shipping-audit-hash-verify",
|
||||
label="货代审计哈希链日检",
|
||||
handler=run_shipping_audit_retention_schedule,
|
||||
description=(
|
||||
"每日抽样校验货代统一审计 previous_event_hash / event_hash 链完整性;"
|
||||
"默认 dry_run=true 不执行清理,仅返回 hash_verify 结果。"
|
||||
),
|
||||
category="shipping",
|
||||
params_schema=(
|
||||
{
|
||||
"key": "hash_sample_limit",
|
||||
"type": "number",
|
||||
"label": "哈希链抽样条数",
|
||||
"required": False,
|
||||
"default": 500,
|
||||
},
|
||||
{"key": "dry_run", "type": "boolean", "label": "仅演练(建议 true)", "required": False, "default": True},
|
||||
{"key": "limit", "type": "number", "label": "清理单批上限", "required": False, "default": 1},
|
||||
),
|
||||
defaults={"hash_sample_limit": 500, "dry_run": True, "limit": 1},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="shipping-inventory-rpa",
|
||||
|
||||
@@ -1,26 +1,88 @@
|
||||
"""
|
||||
services/schedule/shipping_audit_retention_job.py
|
||||
|
||||
用途:货代统一审计到期清理的 platform Job 入口。
|
||||
依赖:audit_query_service.purge_expired_shipping_audit_events、progress_feature_flags.audit_retention_days。
|
||||
逻辑:platform_api_path=shipping-audit-retention 时由 job_registry 调用;保留期读
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS(写入 retention_expires_at);支持 dry_run。
|
||||
用途:货代统一审计到期清理与哈希链抽样校验的 platform Job 入口。
|
||||
依赖:audit_query_service.purge_expired_shipping_audit_events、
|
||||
audit_snapshot_service.verify_event_hash_chain、progress_feature_flags.audit_retention_days。
|
||||
逻辑:platform_api_path=shipping-audit-retention 时由 job_registry 调用;仅清理
|
||||
retention_expires_at 非空且已到期的事件;新写入事件永久保留(expires=None)永不删除;
|
||||
PostgreSQL 上 purge 在同事务设置 hxops.shipping_audit_purge=1,配合 append-only DELETE 触发器;
|
||||
可选对近期聚合抽样校验 previous_event_hash / event_hash 链完整性。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_query_service import purge_expired_shipping_audit_events
|
||||
from app.services.shipping_notice.audit_snapshot_service import verify_event_hash_chain
|
||||
from app.services.shipping_notice.progress_feature_flags import audit_retention_days
|
||||
|
||||
|
||||
def _verify_recent_hash_chains(*, sample_limit: int, failures_cap: int = 10) -> dict[str, Any]:
|
||||
"""
|
||||
抽样校验近期审计事件所属聚合的哈希链。
|
||||
|
||||
核心逻辑:取最近 sample_limit 条事件,按 aggregate_type+aggregate_id 去重后整链校验。
|
||||
|
||||
Args:
|
||||
sample_limit: 参与抽样的最近事件条数上限。
|
||||
failures_cap: 返回 failures_sample 的最大聚合数。
|
||||
|
||||
Returns:
|
||||
{checked_chains, failed_chains, failures_sample}。
|
||||
"""
|
||||
safe_limit = min(5000, max(1, int(sample_limit or 200)))
|
||||
recent = (
|
||||
ShippingAuditEvent.query
|
||||
.order_by(ShippingAuditEvent.id.desc())
|
||||
.limit(safe_limit)
|
||||
.all()
|
||||
)
|
||||
aggregates: dict[tuple[str, str], None] = {}
|
||||
for event in recent:
|
||||
aggregates[(str(event.aggregate_type), str(event.aggregate_id))] = None
|
||||
|
||||
checked_chains = 0
|
||||
failed_chains = 0
|
||||
failures_sample: list[dict[str, Any]] = []
|
||||
for aggregate_type, aggregate_id in aggregates:
|
||||
chain = (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(aggregate_type=aggregate_type, aggregate_id=aggregate_id)
|
||||
.order_by(ShippingAuditEvent.id.asc())
|
||||
.all()
|
||||
)
|
||||
ok, failures = verify_event_hash_chain(chain)
|
||||
checked_chains += 1
|
||||
if not ok:
|
||||
failed_chains += 1
|
||||
if len(failures_sample) < failures_cap:
|
||||
failures_sample.append({
|
||||
'aggregate_type': aggregate_type,
|
||||
'aggregate_id': aggregate_id,
|
||||
'failures': failures[:5],
|
||||
})
|
||||
return {
|
||||
'checked_chains': checked_chains,
|
||||
'failed_chains': failed_chains,
|
||||
'failures_sample': failures_sample,
|
||||
}
|
||||
|
||||
|
||||
def run_shipping_audit_retention_schedule(task: Any, run: Any) -> dict[str, Any]:
|
||||
"""
|
||||
按可配置保留期分批清理到期审计事件。
|
||||
按可配置保留期分批清理到期审计事件,并可选抽样校验哈希链。
|
||||
|
||||
核心逻辑:读取 job_params.limit / dry_run;保留天数来自 SHIPPING_NOTICE_AUDIT_RETENTION_DAYS;
|
||||
正式删除前可先 dry_run 观测扫描量。
|
||||
核心逻辑:读取 job_params.limit / dry_run / hash_sample_limit;
|
||||
保留天数来自 SHIPPING_NOTICE_AUDIT_RETENTION_DAYS;正式删除前可先 dry_run 观测扫描量;
|
||||
哈希校验受 SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED 控制。
|
||||
|
||||
Returns:
|
||||
清理结果 dict,并附带 hash_verify 子对象。
|
||||
"""
|
||||
_ = run
|
||||
params = getattr(task, 'job_params', None) or {}
|
||||
@@ -32,4 +94,19 @@ def run_shipping_audit_retention_schedule(task: Any, run: Any) -> dict[str, Any]
|
||||
actor_id=f'schedule:{getattr(task, "id", "unknown")}',
|
||||
)
|
||||
result['retention_days'] = audit_retention_days()
|
||||
|
||||
hash_verify_enabled = bool(
|
||||
current_app.config.get('SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED', True)
|
||||
)
|
||||
if hash_verify_enabled:
|
||||
result['hash_verify'] = _verify_recent_hash_chains(
|
||||
sample_limit=int(params.get('hash_sample_limit') or params.get('limit') or 200),
|
||||
)
|
||||
else:
|
||||
result['hash_verify'] = {
|
||||
'checked_chains': 0,
|
||||
'failed_chains': 0,
|
||||
'failures_sample': [],
|
||||
'skipped': True,
|
||||
}
|
||||
return result
|
||||
@@ -1,10 +1,13 @@
|
||||
"""
|
||||
services/shipping_notice/audit_query_service.py
|
||||
|
||||
用途:管理员货代审计查询、前后差异投影、受控导出与到期清理。
|
||||
依赖:ShippingAuditEvent、audit_service 投影规则、fulfillment_audit、progress_audit_contract、SQLAlchemy。
|
||||
逻辑:由 admin API 调用;列表/详情/导出均做管理员访问审计(失败阻断查询);清理使用 Core DELETE
|
||||
绕过 ORM 不可变守卫并写清理审计。
|
||||
用途:管理员货代审计查询、关联链追溯、权限裁剪脱敏详情、哈希链校验、受控导出与到期清理。
|
||||
依赖:ShippingAuditEvent、audit_service、audit_snapshot_service、fulfillment_audit、
|
||||
progress_audit_contract、SQLAlchemy。
|
||||
逻辑:由 admin API 调用;列表/详情/导出/关联链均做管理员访问审计(失败阻断查询);
|
||||
敏感 before/after/diff 仅当调用方具备 shipping_notice.audit_sensitive_read;
|
||||
PostgreSQL 清理前在同事务 set_config('hxops.shipping_audit_purge','1'),
|
||||
以便 DB 触发器仅放行已到期行的 DELETE;SQLite/测试仍用 Core DELETE + ORM 守卫。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,15 +18,26 @@ import json
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import delete, or_
|
||||
from sqlalchemy import delete, or_, text
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ServiceUnavailableError, ValidationError
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.audit_snapshot_service import verify_event_hash_chain
|
||||
from app.services.shipping_notice.fulfillment_audit import resolve_request_audit_context
|
||||
from app.services.shipping_notice.progress_audit_contract import AUDIT_SNAPSHOT_ALLOWED_KEYS
|
||||
|
||||
# 关联链可追溯的稳定业务键(与前端审计中心筛选对齐)。
|
||||
_ASSOCIATION_KEYS = (
|
||||
'workflow_id',
|
||||
'workflow_item_id',
|
||||
'run_no',
|
||||
'document_id',
|
||||
'review_case_no',
|
||||
'task_no',
|
||||
)
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
"""UTC datetime → ISO8601 Z。"""
|
||||
@@ -67,8 +81,32 @@ def _diff_snapshots(
|
||||
return rows
|
||||
|
||||
|
||||
def serialize_shipping_audit_event(event: ShippingAuditEvent, *, include_snapshots: bool = False) -> dict[str, Any]:
|
||||
"""序列化管理员可读审计事件;默认不含完整快照,详情/导出按需打开。"""
|
||||
def _is_sensitive_event(event: ShippingAuditEvent) -> bool:
|
||||
"""判断事件是否标记为敏感(需 audit_sensitive_read 才可看快照/Diff)。"""
|
||||
return str(event.sensitivity_level or '').strip().lower() == 'sensitive'
|
||||
|
||||
|
||||
def serialize_shipping_audit_event(
|
||||
event: ShippingAuditEvent,
|
||||
*,
|
||||
include_snapshots: bool = False,
|
||||
include_sensitive: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
序列化管理员可读审计事件。
|
||||
|
||||
核心逻辑:默认不含完整快照;详情按需打开;敏感事件的 before/after/diff
|
||||
仅在 include_sensitive=True(调用方具备 shipping_notice.audit_sensitive_read)时返回,
|
||||
否则脱敏为空并标记 sensitive_redacted。
|
||||
|
||||
Args:
|
||||
event: 审计事件 ORM。
|
||||
include_snapshots: True 时附带白名单快照与 diff 列表。
|
||||
include_sensitive: True 时允许返回 sensitivity_level=sensitive 的快照正文。
|
||||
|
||||
Returns:
|
||||
管理员可读 dict;列表场景勿传 include_snapshots。
|
||||
"""
|
||||
payload: dict[str, Any] = {
|
||||
'id': int(event.id),
|
||||
'event_type': event.event_type,
|
||||
@@ -90,8 +128,12 @@ def serialize_shipping_audit_event(event: ShippingAuditEvent, *, include_snapsho
|
||||
'unit_id': event.unit_id,
|
||||
'document_id': event.document_id,
|
||||
'review_case_no': event.review_case_no,
|
||||
'session_item_id': event.session_item_id,
|
||||
'workflow_id': event.workflow_id,
|
||||
'workflow_item_id': event.workflow_item_id,
|
||||
'workflow_item_version_id': event.workflow_item_version_id,
|
||||
'version_no': event.version_no,
|
||||
'owner_user_id': event.owner_user_id,
|
||||
'actor_display': event.actor_display,
|
||||
'client_ip_hash': event.client_ip_hash,
|
||||
'user_agent_hash': event.user_agent_hash,
|
||||
'attempt_no': event.attempt_no,
|
||||
@@ -100,6 +142,10 @@ def serialize_shipping_audit_event(event: ShippingAuditEvent, *, include_snapsho
|
||||
'reason': event.reason,
|
||||
'before_hash': event.before_hash,
|
||||
'after_hash': event.after_hash,
|
||||
'diff_json': event.diff_json if isinstance(event.diff_json, dict) else None,
|
||||
'previous_event_hash': event.previous_event_hash,
|
||||
'event_hash': event.event_hash,
|
||||
'sensitivity_level': event.sensitivity_level,
|
||||
'metadata': event.metadata_json if isinstance(event.metadata_json, dict) else {},
|
||||
'evidence_refs': event.evidence_refs_json if isinstance(event.evidence_refs_json, list) else [],
|
||||
'artifact_refs': event.artifact_refs_json if isinstance(event.artifact_refs_json, list) else [],
|
||||
@@ -107,13 +153,23 @@ def serialize_shipping_audit_event(event: ShippingAuditEvent, *, include_snapsho
|
||||
'retention_expires_at': _iso(event.retention_expires_at),
|
||||
'created_at': _iso(event.created_at),
|
||||
'has_snapshots': bool(event.before_snapshot_json or event.after_snapshot_json),
|
||||
'sensitive_redacted': False,
|
||||
}
|
||||
if include_snapshots:
|
||||
before = event.before_snapshot_json if isinstance(event.before_snapshot_json, dict) else None
|
||||
after = event.after_snapshot_json if isinstance(event.after_snapshot_json, dict) else None
|
||||
payload['before_snapshot'] = before
|
||||
payload['after_snapshot'] = after
|
||||
payload['diff'] = _diff_snapshots(before, after)
|
||||
# [STEP 1] 敏感事件无权限时脱敏:不回传 before/after/diff 正文。
|
||||
if _is_sensitive_event(event) and not include_sensitive:
|
||||
payload['before_snapshot'] = None
|
||||
payload['after_snapshot'] = None
|
||||
payload['diff'] = []
|
||||
payload['sensitive_redacted'] = True
|
||||
payload['diff_json'] = None
|
||||
else:
|
||||
before = event.before_snapshot_json if isinstance(event.before_snapshot_json, dict) else None
|
||||
after = event.after_snapshot_json if isinstance(event.after_snapshot_json, dict) else None
|
||||
payload['before_snapshot'] = before
|
||||
payload['after_snapshot'] = after
|
||||
# 详情 diff 保持列表投影供管理端 UI;diff_json 为写入侧哈希链差异结构。
|
||||
payload['diff'] = _diff_snapshots(before, after)
|
||||
return payload
|
||||
|
||||
|
||||
@@ -143,8 +199,10 @@ def _apply_filters(query, *, filters: dict[str, Any]):
|
||||
query = query.filter(ShippingAuditEvent.result == str(filters['result'])[:16])
|
||||
if filters.get('conversation_id'):
|
||||
query = query.filter(ShippingAuditEvent.conversation_id == str(filters['conversation_id'])[:100])
|
||||
if filters.get('session_item_id'):
|
||||
query = query.filter(ShippingAuditEvent.session_item_id == str(filters['session_item_id'])[:64])
|
||||
if filters.get('workflow_id'):
|
||||
query = query.filter(ShippingAuditEvent.workflow_id == str(filters['workflow_id'])[:64])
|
||||
if filters.get('workflow_item_id'):
|
||||
query = query.filter(ShippingAuditEvent.workflow_item_id == str(filters['workflow_item_id'])[:64])
|
||||
if filters.get('review_case_no'):
|
||||
query = query.filter(ShippingAuditEvent.review_case_no == str(filters['review_case_no'])[:64])
|
||||
if filters.get('owner_user_id'):
|
||||
@@ -167,7 +225,8 @@ def _apply_filters(query, *, filters: dict[str, Any]):
|
||||
ShippingAuditEvent.request_id.ilike(like),
|
||||
ShippingAuditEvent.aggregate_id.ilike(like),
|
||||
ShippingAuditEvent.document_id.ilike(like),
|
||||
ShippingAuditEvent.session_item_id.ilike(like),
|
||||
ShippingAuditEvent.workflow_id.ilike(like),
|
||||
ShippingAuditEvent.workflow_item_id.ilike(like),
|
||||
ShippingAuditEvent.review_case_no.ilike(like),
|
||||
ShippingAuditEvent.conversation_id.ilike(like),
|
||||
)
|
||||
@@ -175,6 +234,62 @@ def _apply_filters(query, *, filters: dict[str, Any]):
|
||||
return query
|
||||
|
||||
|
||||
def _seed_association_values(filters: dict[str, Any]) -> dict[str, set[str]]:
|
||||
"""
|
||||
从请求筛选中提取关联链种子键。
|
||||
|
||||
Returns:
|
||||
{key: {values}};无种子时为空 dict。
|
||||
"""
|
||||
seeds: dict[str, set[str]] = {}
|
||||
for key in _ASSOCIATION_KEYS:
|
||||
raw = str(filters.get(key) or '').strip()
|
||||
if raw:
|
||||
seeds.setdefault(key, set()).add(raw[:128])
|
||||
# 兼容 case_no 别名 → review_case_no
|
||||
case_no = str(filters.get('case_no') or '').strip()
|
||||
if case_no:
|
||||
seeds.setdefault('review_case_no', set()).add(case_no[:64])
|
||||
return seeds
|
||||
|
||||
|
||||
def _expand_association_keys(seed_rows: list[ShippingAuditEvent]) -> dict[str, set[str]]:
|
||||
"""
|
||||
从种子事件扩张关联键集合,供全链 OR 查询。
|
||||
|
||||
核心逻辑:收集 workflow / item / run / document / case / task 上出现过的稳定编号。
|
||||
"""
|
||||
expanded: dict[str, set[str]] = {key: set() for key in _ASSOCIATION_KEYS}
|
||||
for row in seed_rows:
|
||||
for key in _ASSOCIATION_KEYS:
|
||||
value = getattr(row, key, None)
|
||||
text = str(value or '').strip()
|
||||
if text:
|
||||
expanded[key].add(text)
|
||||
return {key: values for key, values in expanded.items() if values}
|
||||
|
||||
|
||||
def _association_or_clause(expanded: dict[str, set[str]]):
|
||||
"""将扩张后的关联键拼成 OR 过滤条件。"""
|
||||
clauses = []
|
||||
column_map = {
|
||||
'workflow_id': ShippingAuditEvent.workflow_id,
|
||||
'workflow_item_id': ShippingAuditEvent.workflow_item_id,
|
||||
'run_no': ShippingAuditEvent.run_no,
|
||||
'document_id': ShippingAuditEvent.document_id,
|
||||
'review_case_no': ShippingAuditEvent.review_case_no,
|
||||
'task_no': ShippingAuditEvent.task_no,
|
||||
}
|
||||
for key, values in expanded.items():
|
||||
column = column_map.get(key)
|
||||
if column is None or not values:
|
||||
continue
|
||||
clauses.append(column.in_(sorted(values)))
|
||||
if not clauses:
|
||||
return None
|
||||
return or_(*clauses)
|
||||
|
||||
|
||||
def _write_access_audit(
|
||||
*,
|
||||
admin_user_id: int,
|
||||
@@ -253,7 +368,8 @@ def list_shipping_audit_events(
|
||||
key: (filters or {}).get(key)
|
||||
for key in (
|
||||
'event_type', 'actor_type', 'run_no', 'task_no', 'document_id',
|
||||
'operation_id', 'request_id', 'result', 'created_from', 'created_to',
|
||||
'operation_id', 'request_id', 'result', 'workflow_id', 'workflow_item_id',
|
||||
'review_case_no', 'created_from', 'created_to',
|
||||
)
|
||||
if (filters or {}).get(key)
|
||||
},
|
||||
@@ -267,21 +383,256 @@ def get_shipping_audit_event(
|
||||
admin_user_id: int,
|
||||
request_id: str | None,
|
||||
event_id: int,
|
||||
include_sensitive: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""读取单条审计详情(含白名单快照与 diff)。"""
|
||||
"""
|
||||
读取单条审计详情(含白名单快照与 diff)。
|
||||
|
||||
Args:
|
||||
admin_user_id: 管理员用户 ID。
|
||||
request_id: 请求关联 ID。
|
||||
event_id: 审计事件主键。
|
||||
include_sensitive: 调用方是否具备 shipping_notice.audit_sensitive_read。
|
||||
|
||||
Returns:
|
||||
详情 dict;敏感无权限时 sensitive_redacted=True 且快照/Diff 为空。
|
||||
"""
|
||||
event = ShippingAuditEvent.query.filter_by(id=int(event_id)).first()
|
||||
if event is None:
|
||||
raise NotFoundError('Shipping audit event not found', code='SHIPPING_NOTICE.AUDIT_EVENT_NOT_FOUND')
|
||||
payload = serialize_shipping_audit_event(event, include_snapshots=True)
|
||||
payload = serialize_shipping_audit_event(
|
||||
event,
|
||||
include_snapshots=True,
|
||||
include_sensitive=bool(include_sensitive),
|
||||
)
|
||||
_write_access_audit(
|
||||
admin_user_id=admin_user_id,
|
||||
action='get_audit_event',
|
||||
request_id=request_id,
|
||||
summary={'event_id': int(event.id), 'event_type': event.event_type, 'run_no': event.run_no},
|
||||
summary={
|
||||
'event_id': int(event.id),
|
||||
'event_type': event.event_type,
|
||||
'run_no': event.run_no,
|
||||
'include_sensitive': bool(include_sensitive),
|
||||
'sensitive_redacted': bool(payload.get('sensitive_redacted')),
|
||||
},
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def list_shipping_audit_association_chain(
|
||||
*,
|
||||
admin_user_id: int,
|
||||
request_id: str | None,
|
||||
filters: dict[str, Any] | None = None,
|
||||
limit: int = 500,
|
||||
include_sensitive: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
按 Workflow / Item / Run / Document / Case / Task 关联键追溯全链审计事件。
|
||||
|
||||
核心逻辑:
|
||||
[STEP 1] 用种子键定位事件;
|
||||
[STEP 2] 从种子扩张全部关联编号;
|
||||
[STEP 3] OR 查询全链,按时间升序返回;敏感快照受权限裁剪。
|
||||
|
||||
Args:
|
||||
admin_user_id: 管理员用户 ID。
|
||||
request_id: 请求关联 ID。
|
||||
filters: 至少提供一个关联键(workflow_id / workflow_item_id / run_no /
|
||||
document_id / review_case_no|case_no / task_no)。
|
||||
limit: 返回上限 1–2000。
|
||||
include_sensitive: 是否具备敏感读权限。
|
||||
|
||||
Returns:
|
||||
{items, total, association_keys, truncated}。
|
||||
|
||||
Raises:
|
||||
ValidationError: 未提供任何关联种子键。
|
||||
"""
|
||||
safe_filters = filters or {}
|
||||
seeds = _seed_association_values(safe_filters)
|
||||
if not seeds:
|
||||
raise ValidationError(
|
||||
'association chain requires at least one of workflow_id, workflow_item_id, '
|
||||
'run_no, document_id, review_case_no/case_no, task_no',
|
||||
code='SHIPPING_NOTICE.AUDIT_ASSOCIATION_SEED_REQUIRED',
|
||||
)
|
||||
safe_limit = min(2000, max(1, int(limit or 500)))
|
||||
|
||||
# [STEP 1] 种子查询
|
||||
seed_clauses = []
|
||||
column_map = {
|
||||
'workflow_id': ShippingAuditEvent.workflow_id,
|
||||
'workflow_item_id': ShippingAuditEvent.workflow_item_id,
|
||||
'run_no': ShippingAuditEvent.run_no,
|
||||
'document_id': ShippingAuditEvent.document_id,
|
||||
'review_case_no': ShippingAuditEvent.review_case_no,
|
||||
'task_no': ShippingAuditEvent.task_no,
|
||||
}
|
||||
for key, values in seeds.items():
|
||||
column = column_map.get(key)
|
||||
if column is not None and values:
|
||||
seed_clauses.append(column.in_(sorted(values)))
|
||||
seed_rows = (
|
||||
ShippingAuditEvent.query
|
||||
.filter(or_(*seed_clauses))
|
||||
.order_by(ShippingAuditEvent.id.asc())
|
||||
.limit(safe_limit)
|
||||
.all()
|
||||
)
|
||||
|
||||
# [STEP 2] 扩张关联键
|
||||
expanded = _expand_association_keys(seed_rows)
|
||||
for key, values in seeds.items():
|
||||
expanded.setdefault(key, set()).update(values)
|
||||
clause = _association_or_clause(expanded)
|
||||
if clause is None:
|
||||
items: list[dict[str, Any]] = []
|
||||
total = 0
|
||||
else:
|
||||
# [STEP 3] 全链查询(时间升序便于追溯)
|
||||
query = ShippingAuditEvent.query.filter(clause)
|
||||
total = query.count()
|
||||
rows = (
|
||||
query.order_by(ShippingAuditEvent.created_at.asc(), ShippingAuditEvent.id.asc())
|
||||
.limit(safe_limit)
|
||||
.all()
|
||||
)
|
||||
items = [
|
||||
serialize_shipping_audit_event(
|
||||
row,
|
||||
include_snapshots=False,
|
||||
include_sensitive=bool(include_sensitive),
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
|
||||
association_keys = {key: sorted(values) for key, values in expanded.items()}
|
||||
payload = {
|
||||
'items': items,
|
||||
'total': total,
|
||||
'association_keys': association_keys,
|
||||
'truncated': total > len(items),
|
||||
'limit': safe_limit,
|
||||
}
|
||||
_write_access_audit(
|
||||
admin_user_id=admin_user_id,
|
||||
action='list_audit_association_chain',
|
||||
request_id=request_id,
|
||||
summary={
|
||||
'seeds': {key: sorted(values) for key, values in seeds.items()},
|
||||
'association_keys': association_keys,
|
||||
'total': total,
|
||||
'returned': len(items),
|
||||
},
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def verify_shipping_audit_hash_chain(
|
||||
*,
|
||||
admin_user_id: int,
|
||||
request_id: str | None,
|
||||
aggregate_type: str | None = None,
|
||||
aggregate_id: str | None = None,
|
||||
workflow_id: str | None = None,
|
||||
workflow_item_id: str | None = None,
|
||||
sample_limit: int = 200,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
校验指定聚合或抽样近期聚合的 event_hash 哈希链。
|
||||
|
||||
核心逻辑:优先按 aggregate_type+aggregate_id;否则按 workflow / item 定位;
|
||||
再否则抽样最近 sample_limit 条事件所属聚合整链校验。
|
||||
|
||||
Returns:
|
||||
{ok, checked_chains, failed_chains, failures_sample}。
|
||||
"""
|
||||
from app.services.schedule.shipping_audit_retention_job import _verify_recent_hash_chains
|
||||
|
||||
agg_type = str(aggregate_type or '').strip()
|
||||
agg_id = str(aggregate_id or '').strip()
|
||||
wf_id = str(workflow_id or '').strip()
|
||||
item_id = str(workflow_item_id or '').strip()
|
||||
|
||||
if agg_type and agg_id:
|
||||
chain = (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(aggregate_type=agg_type, aggregate_id=agg_id)
|
||||
.order_by(ShippingAuditEvent.id.asc())
|
||||
.all()
|
||||
)
|
||||
ok, failures = verify_event_hash_chain(chain)
|
||||
result = {
|
||||
'ok': bool(ok),
|
||||
'checked_chains': 1,
|
||||
'failed_chains': 0 if ok else 1,
|
||||
'failures_sample': [] if ok else [{
|
||||
'aggregate_type': agg_type,
|
||||
'aggregate_id': agg_id,
|
||||
'failures': failures[:10],
|
||||
}],
|
||||
'mode': 'aggregate',
|
||||
}
|
||||
elif wf_id or item_id:
|
||||
query = ShippingAuditEvent.query
|
||||
if wf_id:
|
||||
query = query.filter_by(workflow_id=wf_id)
|
||||
if item_id:
|
||||
query = query.filter_by(workflow_item_id=item_id)
|
||||
# 按聚合分组校验
|
||||
rows = query.order_by(ShippingAuditEvent.id.asc()).all()
|
||||
aggregates: dict[tuple[str, str], list[ShippingAuditEvent]] = {}
|
||||
for row in rows:
|
||||
key = (str(row.aggregate_type), str(row.aggregate_id))
|
||||
aggregates.setdefault(key, []).append(row)
|
||||
checked = 0
|
||||
failed = 0
|
||||
failures_sample: list[dict[str, Any]] = []
|
||||
for (atype, aid), chain in aggregates.items():
|
||||
checked += 1
|
||||
ok, failures = verify_event_hash_chain(chain)
|
||||
if not ok:
|
||||
failed += 1
|
||||
if len(failures_sample) < 10:
|
||||
failures_sample.append({
|
||||
'aggregate_type': atype,
|
||||
'aggregate_id': aid,
|
||||
'failures': failures[:5],
|
||||
})
|
||||
result = {
|
||||
'ok': failed == 0,
|
||||
'checked_chains': checked,
|
||||
'failed_chains': failed,
|
||||
'failures_sample': failures_sample,
|
||||
'mode': 'workflow_scope',
|
||||
}
|
||||
else:
|
||||
sampled = _verify_recent_hash_chains(sample_limit=int(sample_limit or 200))
|
||||
result = {
|
||||
'ok': int(sampled.get('failed_chains') or 0) == 0,
|
||||
**sampled,
|
||||
'mode': 'sample',
|
||||
}
|
||||
|
||||
_write_access_audit(
|
||||
admin_user_id=admin_user_id,
|
||||
action='verify_audit_hash_chain',
|
||||
request_id=request_id,
|
||||
summary={
|
||||
'mode': result.get('mode'),
|
||||
'checked_chains': result.get('checked_chains'),
|
||||
'failed_chains': result.get('failed_chains'),
|
||||
'aggregate_type': agg_type or None,
|
||||
'aggregate_id': agg_id or None,
|
||||
'workflow_id': wf_id or None,
|
||||
'workflow_item_id': item_id or None,
|
||||
},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def export_shipping_audit_events(
|
||||
*,
|
||||
admin_user_id: int,
|
||||
@@ -328,7 +679,8 @@ def export_shipping_audit_events(
|
||||
buffer = io.StringIO()
|
||||
fieldnames = [
|
||||
'id', 'created_at', 'event_type', 'action', 'result', 'actor_type', 'actor_id',
|
||||
'run_no', 'task_no', 'document_id', 'operation_id', 'request_id', 'reason_code', 'error_code',
|
||||
'run_no', 'task_no', 'document_id', 'workflow_id', 'workflow_item_id', 'review_case_no',
|
||||
'operation_id', 'request_id', 'reason_code', 'error_code',
|
||||
]
|
||||
writer = csv.DictWriter(buffer, fieldnames=fieldnames, extrasaction='ignore')
|
||||
writer.writeheader()
|
||||
@@ -352,7 +704,9 @@ def purge_expired_shipping_audit_events(
|
||||
"""
|
||||
清理已过保留期的审计事件。
|
||||
|
||||
核心逻辑:先统计候选;dry_run 不删除;正式删除使用 Core DELETE(绕过 ORM append-only 守卫),
|
||||
核心逻辑:先统计候选;dry_run 不删除;正式删除使用 Core DELETE。
|
||||
PostgreSQL 须在同事务 set_config('hxops.shipping_audit_purge','1'),
|
||||
触发器才允许删除 retention_expires_at 已到期的行;UPDATE 始终禁止。
|
||||
并写入一条 system 清理审计说明批次规模。
|
||||
|
||||
Args:
|
||||
@@ -392,6 +746,9 @@ def purge_expired_shipping_audit_events(
|
||||
for eid in candidate_ids
|
||||
if (obj := db.session.get(ShippingAuditEvent, eid)) is not None
|
||||
]
|
||||
# [STEP 2] PostgreSQL:开启 purge GUC,使 append-only DELETE 触发器放行到期行。
|
||||
if db.engine.dialect.name == 'postgresql':
|
||||
db.session.execute(text("SELECT set_config('hxops.shipping_audit_purge', '1', true)"))
|
||||
result = db.session.execute(
|
||||
delete(ShippingAuditEvent).where(ShippingAuditEvent.id.in_(candidate_ids))
|
||||
)
|
||||
@@ -399,7 +756,7 @@ def purge_expired_shipping_audit_events(
|
||||
for obj in tracked:
|
||||
db.session.expunge(obj)
|
||||
|
||||
# [STEP 2] 写入系统清理审计(新行),与删除同事务提交。
|
||||
# [STEP 3] 写入系统清理审计(新行),与删除同事务提交。
|
||||
append_shipping_audit_event(
|
||||
event_type='audit_retention_purged',
|
||||
aggregate_type='shipping_audit',
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/audit_service.py
|
||||
|
||||
用途:集中追加货代领域审计事件并拒绝含敏感业务载荷的元数据与快照。
|
||||
依赖:ShippingAuditEvent、progress_audit_contract、SQLAlchemy 会话。
|
||||
逻辑:Run、Task、会话 PDF 工作项、库存和 Chatflow 服务调用本模块写入状态与决策事实;
|
||||
用途:货代领域统一审计事件的唯一写入入口;要求操作上下文与前后快照(可为空),
|
||||
写入 Workflow 软引用与哈希链字段。
|
||||
依赖:ShippingAuditEvent、progress_audit_contract、audit_snapshot_service(在 append 内导入以避免环)、
|
||||
SQLAlchemy 会话。
|
||||
逻辑:Run、Task、Workflow Item、库存和 Chatflow 服务调用本模块写入状态与决策事实;
|
||||
写入前投影白名单快照 → 计算 diff → 解析同聚合 previous_event_hash → 计算 event_hash;
|
||||
本服务不提交事务,由调用方保证业务与审计原子性。支持 operation_id、白名单前后快照、
|
||||
证据引用、会话工作项关联、属主与三年保留到期;IP / User-Agent 仅持久化哈希。
|
||||
证据引用、Workflow 软引用(非 session_item)、属主;货代全业务审计事件永久保留
|
||||
(retention_expires_at=None),清理 Job 仅处理历史遗留的到期行。IP / User-Agent 仅持久化哈希。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,6 +26,7 @@ from app.services.shipping_notice.progress_audit_contract import (
|
||||
AUDIT_FORBIDDEN_KEYS,
|
||||
AUDIT_SNAPSHOT_ALLOWED_KEYS,
|
||||
is_forbidden_audit_key,
|
||||
is_permanent_audit_event_type,
|
||||
)
|
||||
from app.services.shipping_notice.progress_feature_flags import audit_retention_days
|
||||
|
||||
@@ -172,6 +177,7 @@ def append_shipping_audit_event(
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
actor_role: str | None = None,
|
||||
actor_display: str | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
correlation_id: str | None = None,
|
||||
@@ -182,7 +188,10 @@ def append_shipping_audit_event(
|
||||
unit_id: str | int | None = None,
|
||||
document_id: str | int | None = None,
|
||||
review_case_no: str | None = None,
|
||||
session_item_id: str | None = None,
|
||||
workflow_id: str | None = None,
|
||||
workflow_item_id: str | None = None,
|
||||
workflow_item_version_id: str | None = None,
|
||||
version_no: int | None = None,
|
||||
owner_user_id: str | int | None = None,
|
||||
client_ip: str | None = None,
|
||||
user_agent: str | None = None,
|
||||
@@ -198,20 +207,26 @@ def append_shipping_audit_event(
|
||||
artifact_refs: list[dict[str, Any]] | None = None,
|
||||
context_refs: dict[str, Any] | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
sensitivity_level: str | None = None,
|
||||
retention_expires_at: datetime | None = None,
|
||||
persist_snapshots: bool = True,
|
||||
) -> ShippingAuditEvent:
|
||||
"""
|
||||
追加一条货代审计事实。
|
||||
追加一条货代审计事实(唯一写入口)。
|
||||
|
||||
Args:
|
||||
event_type: 稳定业务事件名,例如 ``session_work_item_created``;禁止传入用户自由文本。
|
||||
event_type: 稳定业务事件名,例如 ``workflow_item_created``;禁止传入用户自由文本。
|
||||
aggregate_type/aggregate_id: 业务聚合类型与稳定编号,不使用可删除记录的外键。
|
||||
operation_id: 同一次用户/系统操作的关联键,与 request_id 共同贯通事件链。
|
||||
session_item_id: 会话 PDF 工作项 item_no;软引用。
|
||||
workflow_id: Workflow.workflow_no 软引用。
|
||||
workflow_item_id: WorkflowItem.item_no 软引用。
|
||||
workflow_item_version_id: ItemVersion 主键或稳定编号的字符串软引用。
|
||||
version_no: 当前版本号(可选)。
|
||||
actor_display: 操作者展示名(可选)。
|
||||
sensitivity_level: ``normal`` / ``sensitive`` 等分级标签。
|
||||
owner_user_id: 业务属主,与 actor_id(实际操作者)区分,支撑代操作审计。
|
||||
client_ip/user_agent: 原始客户端上下文,仅哈希后入库;也可直接传 *_hash。
|
||||
before/after: 可复现的受控状态投影;持久化白名单快照及其哈希。
|
||||
before/after: 可复现的受控状态投影;持久化白名单快照及其哈希,并计算 diff_json。
|
||||
evidence_refs/artifact_refs: FileAsset ID、SHA-256、版本与证据坐标,禁止 URL/正文。
|
||||
metadata: 仅允许原因码、计数、版本等脱敏诊断事实。
|
||||
persist_snapshots: False 时只写哈希(兼容历史调用方仅传 before/after 哈希语义)。
|
||||
@@ -222,47 +237,118 @@ def append_shipping_audit_event(
|
||||
Raises:
|
||||
ValidationError: actor 类型、元数据或快照包含正文、凭据等敏感字段。
|
||||
"""
|
||||
# 延迟导入:audit_snapshot_service.sanitize_snapshot 会回引 project_audit_snapshot,避免模块环。
|
||||
from app.services.shipping_notice.audit_snapshot_service import (
|
||||
build_event_hash_payload,
|
||||
compute_event_hash,
|
||||
compute_snapshot_diff,
|
||||
resolve_previous_event_hash,
|
||||
)
|
||||
|
||||
allowed_actor_types = {'user', 'system', 'rpa', 'chatflow', 'admin'}
|
||||
if actor_type not in allowed_actor_types:
|
||||
raise ValidationError('Invalid shipping audit actor type', code='SHIPPING_NOTICE.AUDIT_ACTOR_INVALID')
|
||||
if result is not None and result not in {'success', 'failure', 'rejected', 'ignored'}:
|
||||
raise ValidationError('Invalid shipping audit result', code='SHIPPING_NOTICE.AUDIT_RESULT_INVALID')
|
||||
|
||||
# [STEP 1] 投影白名单快照并计算 diff。
|
||||
before_snapshot = project_audit_snapshot(before) if before is not None else None
|
||||
after_snapshot = project_audit_snapshot(after) if after is not None else None
|
||||
diff_json = compute_snapshot_diff(before_snapshot, after_snapshot)
|
||||
if context_refs is not None:
|
||||
_sanitize_metadata(context_refs)
|
||||
|
||||
resolved_ip_hash = client_ip_hash or hash_client_context_value(client_ip)
|
||||
resolved_ua_hash = user_agent_hash or hash_client_context_value(user_agent)
|
||||
|
||||
resolved_workflow_id = str(workflow_id)[:64] if workflow_id else None
|
||||
resolved_workflow_item_id = str(workflow_item_id)[:64] if workflow_item_id else None
|
||||
resolved_workflow_item_version_id = (
|
||||
str(workflow_item_version_id)[:64] if workflow_item_version_id else None
|
||||
)
|
||||
resolved_version_no = int(version_no) if version_no is not None else None
|
||||
resolved_actor_id = str(actor_id)[:128] if actor_id is not None else None
|
||||
resolved_operation_id = str(operation_id)[:64] if operation_id else None
|
||||
resolved_request_id = str(request_id)[:64] if request_id else None
|
||||
resolved_run_no = str(run_no)[:64] if run_no else None
|
||||
resolved_task_no = str(task_no)[:64] if task_no else None
|
||||
resolved_document_id = str(document_id)[:64] if document_id is not None else None
|
||||
resolved_review_case_no = str(review_case_no)[:64] if review_case_no else None
|
||||
resolved_action = str(action)[:64] if action else None
|
||||
resolved_reason_code = str(reason_code)[:128] if reason_code else None
|
||||
resolved_sensitivity = str(sensitivity_level)[:16] if sensitivity_level else None
|
||||
|
||||
# [STEP 2] flush 同事务先前事件,保证哈希链前驱可查。
|
||||
db.session.flush()
|
||||
previous_event_hash = resolve_previous_event_hash(
|
||||
aggregate_type=str(aggregate_type)[:64],
|
||||
aggregate_id=str(aggregate_id)[:128],
|
||||
)
|
||||
hash_payload = build_event_hash_payload(
|
||||
event_type=str(event_type)[:64],
|
||||
aggregate_type=str(aggregate_type)[:64],
|
||||
aggregate_id=str(aggregate_id)[:128],
|
||||
action=resolved_action,
|
||||
result=result,
|
||||
reason_code=resolved_reason_code,
|
||||
workflow_id=resolved_workflow_id,
|
||||
workflow_item_id=resolved_workflow_item_id,
|
||||
workflow_item_version_id=resolved_workflow_item_version_id,
|
||||
version_no=resolved_version_no,
|
||||
run_no=resolved_run_no,
|
||||
document_id=resolved_document_id,
|
||||
review_case_no=resolved_review_case_no,
|
||||
task_no=resolved_task_no,
|
||||
operation_id=resolved_operation_id,
|
||||
request_id=resolved_request_id,
|
||||
actor_type=actor_type,
|
||||
actor_id=resolved_actor_id,
|
||||
before_snapshot=before_snapshot if persist_snapshots else None,
|
||||
after_snapshot=after_snapshot if persist_snapshots else None,
|
||||
diff_json=diff_json,
|
||||
previous_event_hash=previous_event_hash,
|
||||
sensitivity_level=resolved_sensitivity,
|
||||
)
|
||||
event_hash = compute_event_hash(hash_payload)
|
||||
|
||||
# [STEP 3] 货代统一审计账本:全业务节点永久保留,忽略调用方传入的到期时间。
|
||||
# default_retention_expires_at 仅保留给遗留清理 Job / 运维工具兼容,新写入一律为 None。
|
||||
resolved_retention: datetime | None = None
|
||||
if not is_permanent_audit_event_type(str(event_type)) and retention_expires_at is not None:
|
||||
resolved_retention = retention_expires_at
|
||||
elif not is_permanent_audit_event_type(str(event_type)):
|
||||
resolved_retention = default_retention_expires_at()
|
||||
event = ShippingAuditEvent(
|
||||
event_type=str(event_type)[:64],
|
||||
aggregate_type=str(aggregate_type)[:64],
|
||||
aggregate_id=str(aggregate_id)[:128],
|
||||
run_no=str(run_no)[:64] if run_no else None,
|
||||
task_no=str(task_no)[:64] if task_no else None,
|
||||
run_no=resolved_run_no,
|
||||
task_no=resolved_task_no,
|
||||
intake_no=str(intake_no)[:64] if intake_no else None,
|
||||
actor_type=actor_type,
|
||||
actor_id=str(actor_id)[:128] if actor_id is not None else None,
|
||||
actor_id=resolved_actor_id,
|
||||
actor_role=str(actor_role)[:64] if actor_role else None,
|
||||
request_id=str(request_id)[:64] if request_id else None,
|
||||
operation_id=str(operation_id)[:64] if operation_id else None,
|
||||
actor_display=str(actor_display)[:128] if actor_display else None,
|
||||
request_id=resolved_request_id,
|
||||
operation_id=resolved_operation_id,
|
||||
correlation_id=str(correlation_id)[:64] if correlation_id else None,
|
||||
source=str(source)[:32] if source else None,
|
||||
result=result,
|
||||
error_code=str(error_code)[:64] if error_code else None,
|
||||
conversation_id=str(conversation_id)[:100] if conversation_id else None,
|
||||
unit_id=str(unit_id)[:64] if unit_id is not None else None,
|
||||
document_id=str(document_id)[:64] if document_id is not None else None,
|
||||
review_case_no=str(review_case_no)[:64] if review_case_no else None,
|
||||
session_item_id=str(session_item_id)[:64] if session_item_id else None,
|
||||
document_id=resolved_document_id,
|
||||
review_case_no=resolved_review_case_no,
|
||||
workflow_id=resolved_workflow_id,
|
||||
workflow_item_id=resolved_workflow_item_id,
|
||||
workflow_item_version_id=resolved_workflow_item_version_id,
|
||||
version_no=resolved_version_no,
|
||||
owner_user_id=str(owner_user_id)[:64] if owner_user_id is not None else None,
|
||||
client_ip_hash=str(resolved_ip_hash)[:64] if resolved_ip_hash else None,
|
||||
user_agent_hash=str(resolved_ua_hash)[:64] if resolved_ua_hash else None,
|
||||
attempt_no=int(attempt_no) if attempt_no is not None else None,
|
||||
action=str(action)[:64] if action else None,
|
||||
reason_code=str(reason_code)[:128] if reason_code else None,
|
||||
action=resolved_action,
|
||||
reason_code=resolved_reason_code,
|
||||
reason=str(reason)[:2000] if reason else None,
|
||||
before_hash=_stable_hash(before_snapshot if before_snapshot is not None else before)
|
||||
if before is not None else None,
|
||||
@@ -270,11 +356,15 @@ def append_shipping_audit_event(
|
||||
if after is not None else None,
|
||||
before_snapshot_json=before_snapshot if persist_snapshots else None,
|
||||
after_snapshot_json=after_snapshot if persist_snapshots else None,
|
||||
diff_json=diff_json,
|
||||
previous_event_hash=previous_event_hash,
|
||||
event_hash=event_hash,
|
||||
sensitivity_level=resolved_sensitivity,
|
||||
evidence_refs_json=_sanitize_refs(evidence_refs, field_name='evidence_refs'),
|
||||
artifact_refs_json=_sanitize_refs(artifact_refs, field_name='artifact_refs'),
|
||||
context_refs_json=dict(context_refs) if context_refs else None,
|
||||
metadata_json=_sanitize_metadata(metadata),
|
||||
retention_expires_at=retention_expires_at or default_retention_expires_at(),
|
||||
retention_expires_at=resolved_retention,
|
||||
)
|
||||
db.session.add(event)
|
||||
return event
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
"""
|
||||
services/shipping_notice/audit_snapshot_service.py
|
||||
|
||||
用途:审计快照标准化、敏感字段脱敏、前后差异与哈希链计算。
|
||||
依赖:progress_audit_contract、hashlib/json;由 audit_service 写入前调用。
|
||||
逻辑:业务写路径先投影白名单快照 → 计算 diff → 读取同聚合上一条 event_hash
|
||||
作为 previous_event_hash → 再计算本条 event_hash;保留任务可离线校验链完整性。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
AUDIT_SNAPSHOT_ALLOWED_KEYS,
|
||||
is_forbidden_audit_key,
|
||||
)
|
||||
|
||||
|
||||
def _canonical_json(value: Any) -> str:
|
||||
"""将对象序列化为稳定 JSON 字符串,供哈希计算。"""
|
||||
return json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str)
|
||||
|
||||
|
||||
def stable_content_hash(value: Any) -> str:
|
||||
"""
|
||||
对任意可 JSON 化对象计算 SHA-256。
|
||||
|
||||
Args:
|
||||
value: 快照、差异或事件载荷。
|
||||
|
||||
Returns:
|
||||
64 位十六进制哈希。
|
||||
"""
|
||||
return hashlib.sha256(_canonical_json(value).encode('ascii')).hexdigest()
|
||||
|
||||
|
||||
def sanitize_snapshot(value: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
"""
|
||||
标准化审计前后快照(白名单 + 敏感键拒绝)。
|
||||
|
||||
核心逻辑:委托 audit_service.project_audit_snapshot,保证同一规则。
|
||||
|
||||
Args:
|
||||
value: 原始业务状态 dict。
|
||||
|
||||
Returns:
|
||||
脱敏后的白名单快照,或 None。
|
||||
"""
|
||||
from app.services.shipping_notice.audit_service import project_audit_snapshot
|
||||
|
||||
return project_audit_snapshot(value)
|
||||
|
||||
|
||||
def compute_snapshot_diff(
|
||||
before: dict[str, Any] | None,
|
||||
after: dict[str, Any] | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
计算前后快照差异(仅白名单顶层键)。
|
||||
|
||||
核心逻辑:输出 changed/added/removed 三段;值本身必须已脱敏。
|
||||
|
||||
Args:
|
||||
before/after: 已投影或待投影的快照。
|
||||
|
||||
Returns:
|
||||
差异对象;无变化时返回 None。
|
||||
"""
|
||||
left = sanitize_snapshot(before) or {}
|
||||
right = sanitize_snapshot(after) or {}
|
||||
keys = sorted(set(left) | set(right))
|
||||
changed: dict[str, Any] = {}
|
||||
added: dict[str, Any] = {}
|
||||
removed: dict[str, Any] = {}
|
||||
for key in keys:
|
||||
if key not in AUDIT_SNAPSHOT_ALLOWED_KEYS:
|
||||
continue
|
||||
if is_forbidden_audit_key(key):
|
||||
continue
|
||||
in_left = key in left
|
||||
in_right = key in right
|
||||
if in_left and in_right and left[key] != right[key]:
|
||||
changed[key] = {'from': left[key], 'to': right[key]}
|
||||
elif in_right and not in_left:
|
||||
added[key] = right[key]
|
||||
elif in_left and not in_right:
|
||||
removed[key] = left[key]
|
||||
if not changed and not added and not removed:
|
||||
return None
|
||||
return {'changed': changed, 'added': added, 'removed': removed}
|
||||
|
||||
|
||||
def resolve_previous_event_hash(
|
||||
*,
|
||||
aggregate_type: str,
|
||||
aggregate_id: str,
|
||||
) -> str | None:
|
||||
"""
|
||||
读取同聚合最新一条事件的 event_hash,作为哈希链前驱。
|
||||
|
||||
核心逻辑:按 id 倒序取一条;缺失或旧数据无 hash 时返回 None(链从本条起锚)。
|
||||
|
||||
Args:
|
||||
aggregate_type/aggregate_id: 业务聚合键。
|
||||
|
||||
Returns:
|
||||
前驱 event_hash 或 None。
|
||||
"""
|
||||
previous = (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(
|
||||
aggregate_type=str(aggregate_type)[:64],
|
||||
aggregate_id=str(aggregate_id)[:128],
|
||||
)
|
||||
.order_by(ShippingAuditEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
if previous is None:
|
||||
return None
|
||||
return str(previous.event_hash) if previous.event_hash else None
|
||||
|
||||
|
||||
def build_event_hash_payload(
|
||||
*,
|
||||
event_type: str,
|
||||
aggregate_type: str,
|
||||
aggregate_id: str,
|
||||
action: str | None,
|
||||
result: str | None,
|
||||
reason_code: str | None,
|
||||
workflow_id: str | None,
|
||||
workflow_item_id: str | None,
|
||||
workflow_item_version_id: str | None,
|
||||
version_no: int | None,
|
||||
run_no: str | None,
|
||||
document_id: str | None,
|
||||
review_case_no: str | None,
|
||||
task_no: str | None,
|
||||
operation_id: str | None,
|
||||
request_id: str | None,
|
||||
actor_type: str,
|
||||
actor_id: str | None,
|
||||
before_snapshot: dict[str, Any] | None,
|
||||
after_snapshot: dict[str, Any] | None,
|
||||
diff_json: dict[str, Any] | None,
|
||||
previous_event_hash: str | None,
|
||||
sensitivity_level: str | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
组装参与 event_hash 计算的稳定字段集合。
|
||||
|
||||
Args:
|
||||
各审计核心字段与快照。
|
||||
|
||||
Returns:
|
||||
供 stable_content_hash 使用的 dict。
|
||||
"""
|
||||
return {
|
||||
'event_type': event_type,
|
||||
'aggregate_type': aggregate_type,
|
||||
'aggregate_id': aggregate_id,
|
||||
'action': action,
|
||||
'result': result,
|
||||
'reason_code': reason_code,
|
||||
'workflow_id': workflow_id,
|
||||
'workflow_item_id': workflow_item_id,
|
||||
'workflow_item_version_id': workflow_item_version_id,
|
||||
'version_no': version_no,
|
||||
'run_no': run_no,
|
||||
'document_id': document_id,
|
||||
'review_case_no': review_case_no,
|
||||
'task_no': task_no,
|
||||
'operation_id': operation_id,
|
||||
'request_id': request_id,
|
||||
'actor_type': actor_type,
|
||||
'actor_id': actor_id,
|
||||
'before_snapshot': before_snapshot,
|
||||
'after_snapshot': after_snapshot,
|
||||
'diff': diff_json,
|
||||
'previous_event_hash': previous_event_hash,
|
||||
'sensitivity_level': sensitivity_level,
|
||||
}
|
||||
|
||||
|
||||
def compute_event_hash(payload: dict[str, Any]) -> str:
|
||||
"""
|
||||
计算审计事件哈希。
|
||||
|
||||
Args:
|
||||
payload: build_event_hash_payload 的返回值。
|
||||
|
||||
Returns:
|
||||
SHA-256 十六进制。
|
||||
"""
|
||||
return stable_content_hash(payload)
|
||||
|
||||
|
||||
def verify_event_hash_chain(
|
||||
events: list[ShippingAuditEvent],
|
||||
) -> tuple[bool, list[dict[str, Any]]]:
|
||||
"""
|
||||
校验按 id 升序排列的事件哈希链。
|
||||
|
||||
核心逻辑:逐条重算 event_hash,并核对 previous_event_hash 与上一条一致;
|
||||
缺少 event_hash 的遗留行记为 failure。
|
||||
|
||||
Args:
|
||||
events: 同聚合、按 id 升序的事件列表。
|
||||
|
||||
Returns:
|
||||
(全部通过, 失败明细列表)。
|
||||
"""
|
||||
failures: list[dict[str, Any]] = []
|
||||
previous_hash: str | None = None
|
||||
for event in events:
|
||||
if not event.event_hash:
|
||||
failures.append({
|
||||
'event_id': event.id,
|
||||
'reason': 'missing_event_hash',
|
||||
})
|
||||
previous_hash = None
|
||||
continue
|
||||
expected_previous = previous_hash
|
||||
if (event.previous_event_hash or None) != expected_previous:
|
||||
failures.append({
|
||||
'event_id': event.id,
|
||||
'reason': 'previous_hash_mismatch',
|
||||
'expected_previous': expected_previous,
|
||||
'actual_previous': event.previous_event_hash,
|
||||
})
|
||||
payload = build_event_hash_payload(
|
||||
event_type=event.event_type,
|
||||
aggregate_type=event.aggregate_type,
|
||||
aggregate_id=event.aggregate_id,
|
||||
action=event.action,
|
||||
result=event.result,
|
||||
reason_code=event.reason_code,
|
||||
workflow_id=event.workflow_id,
|
||||
workflow_item_id=event.workflow_item_id,
|
||||
workflow_item_version_id=event.workflow_item_version_id,
|
||||
version_no=event.version_no,
|
||||
run_no=event.run_no,
|
||||
document_id=event.document_id,
|
||||
review_case_no=event.review_case_no,
|
||||
task_no=event.task_no,
|
||||
operation_id=event.operation_id,
|
||||
request_id=event.request_id,
|
||||
actor_type=event.actor_type,
|
||||
actor_id=event.actor_id,
|
||||
before_snapshot=event.before_snapshot_json,
|
||||
after_snapshot=event.after_snapshot_json,
|
||||
diff_json=event.diff_json,
|
||||
previous_event_hash=event.previous_event_hash,
|
||||
sensitivity_level=event.sensitivity_level,
|
||||
)
|
||||
expected_hash = compute_event_hash(payload)
|
||||
if expected_hash != event.event_hash:
|
||||
failures.append({
|
||||
'event_id': event.id,
|
||||
'reason': 'event_hash_mismatch',
|
||||
'expected': expected_hash,
|
||||
'actual': event.event_hash,
|
||||
})
|
||||
previous_hash = event.event_hash
|
||||
return (len(failures) == 0, failures)
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/services/shipping_notice/candidate_validation.py
|
||||
|
||||
用途:统一校验并标准化人工修订或建批前的订单 Candidate 业务摘要。
|
||||
依赖:notice_lines、po_number、reservation_id、core.errors。
|
||||
逻辑:Candidate API 与建批门禁共用,确保至少一条 SKU+Qty 有效订单行,避免空摘要绕过审核。
|
||||
依赖:notice_lines、po_number、reservation_id、field_rules、core.errors。
|
||||
逻辑:Candidate API 与建批门禁共用,确保至少一条 SKU+Qty 有效订单行,避免空摘要绕过审核;
|
||||
流程门禁使用有效 Reservation(行 ?? 头),库存源候选由资格服务另行裁决。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,6 +13,7 @@ from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.notice_lines import non_atomic_part_number_field, normalize_notice_line
|
||||
from app.services.shipping_notice.order_schema.field_rules import compute_effective_reservation_id
|
||||
from app.services.shipping_notice.po_number import normalize_atomic_po_number
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
@@ -23,8 +25,8 @@ def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[st
|
||||
"""
|
||||
评估规则/LLM订单结果是否达到自动建单最低条件,同时保留不完整内容供自然对话修订。
|
||||
|
||||
核心逻辑:原子 part_number + 正数 Qty 是建单硬条件;Reservation ID 是唯一流程门禁字段。
|
||||
inventory_source_hint 仅保留为可选库存源路由线索,缺失时不阻断建单或后续流程。
|
||||
核心逻辑:原子 part_number + 正数 Qty 是建单硬条件;有效 Reservation(行优先回退头)
|
||||
是流程门禁字段。inventory_source_hint 仅保留为可选路由线索,缺失时不阻断本评估。
|
||||
|
||||
Args:
|
||||
summary: 单个订单的业务摘要。
|
||||
@@ -34,6 +36,7 @@ def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[st
|
||||
missing_process_fields、invalid_lines 与 blocking_issues 的评估结果。
|
||||
"""
|
||||
raw = dict(summary) if isinstance(summary, dict) else {}
|
||||
header_reservation = raw.get('reservation_id')
|
||||
raw_lines = raw.get('lines') if isinstance(raw.get('lines'), list) else []
|
||||
normalized_lines: list[dict[str, Any]] = []
|
||||
invalid_lines: list[dict[str, Any]] = []
|
||||
@@ -55,6 +58,13 @@ def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[st
|
||||
if raw_reservation and not validated_reservation_id(raw_reservation):
|
||||
invalid_lines.append({'line_index': index, 'reason': 'invalid_reservation_id'})
|
||||
continue
|
||||
effective = compute_effective_reservation_id(
|
||||
line_reservation_id=normalized.get('reservation_id'),
|
||||
header_reservation_id=header_reservation,
|
||||
)
|
||||
if effective:
|
||||
normalized['reservation_id'] = effective
|
||||
normalized['effective_reservation_id'] = effective
|
||||
normalized_lines.append(normalized)
|
||||
|
||||
normalized_summary = dict(raw)
|
||||
@@ -66,18 +76,22 @@ def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[st
|
||||
normalized_summary['reservation_ids'] = sorted({
|
||||
normalized
|
||||
for line in normalized_lines
|
||||
if (normalized := validated_reservation_id(line.get('reservation_id')))
|
||||
if (normalized := validated_reservation_id(
|
||||
line.get('effective_reservation_id') or line.get('reservation_id')
|
||||
))
|
||||
})
|
||||
|
||||
missing_required: list[str] = []
|
||||
if not normalized_lines:
|
||||
missing_required.extend(BUILD_REQUIRED_FIELDS)
|
||||
# Reservation 是逐行匹配键;任一有效订单行缺失都必须保留流程字段门禁。
|
||||
# 有效 Reservation 是逐行匹配键;头级可回填行级缺失。
|
||||
missing_process = [
|
||||
field
|
||||
for field in PROCESS_FIELDS
|
||||
if any(
|
||||
not validated_reservation_id(line.get(field))
|
||||
not validated_reservation_id(
|
||||
line.get('effective_reservation_id') or line.get(field)
|
||||
)
|
||||
for line in normalized_lines
|
||||
)
|
||||
]
|
||||
|
||||
+75
-28
@@ -1,8 +1,9 @@
|
||||
"""
|
||||
从 PDF 原生字符坐标重建被 HTML 网格错误拆分的订单表格候选。
|
||||
|
||||
依赖:布局 bbox 契约和 PositionedCharacter。调用方必须先提供已人工确认的列锚点;本模块
|
||||
只按几何、有限内容形态和相邻行连续性生成可审计的 needs_review 候选,绝不自动接受。
|
||||
依赖:布局 bbox 契约、PositionedCharacter、order_schema.field_rules。
|
||||
逻辑:调用方提供已确认的列锚点与可配置起行字段;本模块按几何与起行值生成可审计候选;
|
||||
默认起行锚点为 customer_po_line_no;line_no 作为可识别内部项次亦可绑定。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,8 +19,40 @@ from app.services.shipping_notice.document_layout.text_cell_alignment import Pos
|
||||
from app.services.shipping_notice.document_layout.order_profile_extractors import extract_profile_field_value
|
||||
|
||||
|
||||
# 客户 PO 行号常见形态(含前导零);起行锚点默认按此形态识别,不做数值归一化。
|
||||
_LINE_NUMBER_PATTERN = re.compile(r'^(?:0{2,}\d+|\d{1,6})$')
|
||||
_DELETED_PATTERN = re.compile(r'^\*+itemdeleted\*+$', re.IGNORECASE)
|
||||
DEFAULT_LINE_START_FIELD_CODE = 'customer_po_line_no'
|
||||
|
||||
|
||||
def resolve_line_start_field_code(value: Any = None) -> str:
|
||||
"""
|
||||
规范化模板起行锚点字段编码。
|
||||
|
||||
核心逻辑:缺省为客户 PO 行号;字段编码由已冻结的模板定义决定。
|
||||
|
||||
Args:
|
||||
value: 模板配置或调用方传入的字段编码。
|
||||
|
||||
Returns:
|
||||
可用于重建的稳定字段编码。
|
||||
|
||||
Raises:
|
||||
ValueError: 编码为空。
|
||||
"""
|
||||
code = str(value or DEFAULT_LINE_START_FIELD_CODE).strip() or DEFAULT_LINE_START_FIELD_CODE
|
||||
return code
|
||||
|
||||
|
||||
def is_valid_line_start_value(raw: Any) -> bool:
|
||||
"""
|
||||
判断抽取文本是否可作为逻辑明细起行值。
|
||||
|
||||
核心逻辑:仅折叠空白后做形态校验,保留 ``00010`` 等前导零;不做整数转换。
|
||||
"""
|
||||
text = re.sub(r'\s+', '', str(raw or ''))
|
||||
return bool(text and _LINE_NUMBER_PATTERN.fullmatch(text))
|
||||
|
||||
|
||||
|
||||
class CoordinateReconstructionModel(BaseModel):
|
||||
@@ -230,15 +263,19 @@ def reconstruct_coordinate_profile_rows(
|
||||
initial_fields: dict[str, str] | None = None,
|
||||
initial_next_offset: int = 0,
|
||||
include_deleted: bool = False,
|
||||
line_start_field_code: str | None = None,
|
||||
include_unanchored_rows: bool = False,
|
||||
) -> list[CoordinateProfileLogicalRow]:
|
||||
"""
|
||||
按 v2 物理行和字段区域合并逻辑明细,不使用 MinerU 的行列结果。
|
||||
|
||||
主行必须在其已绑定 ``line_no`` 区域中出现有效行号才启动明细;未满足此条件的
|
||||
视觉行不会被猜测为新行。随后只按连续 ``row_offset`` 消费 continuation,避免描述
|
||||
换行、合计或相邻无关表区静默混入当前订单行。``include_deleted`` 仅供标注预览
|
||||
返回删除行证据;正式解析保持默认值,删除行不会进入业务结果。
|
||||
主行必须在其已绑定起行锚点字段(默认 ``customer_po_line_no``)中出现有效值才启动明细;
|
||||
未满足此条件的视觉行不会被猜测为新行。随后只按连续 ``row_offset`` 消费 continuation,
|
||||
避免描述换行、合计或相邻无关表区静默混入当前订单行。``include_deleted`` 仅供标注预览
|
||||
返回删除行证据;正式解析保持默认值,删除行不会进入业务结果。仅管理员预览可开启
|
||||
``include_unanchored_rows``,在没有任何有效起行值时返回待复核的主行字段,不能用于正式解析。
|
||||
"""
|
||||
start_field_code = resolve_line_start_field_code(line_start_field_code)
|
||||
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
|
||||
ordered_layouts = sorted((item for item in line_layouts if isinstance(item, dict)), key=lambda item: item.get('row_offset', -1))
|
||||
if not ordered_layouts or [item.get('row_offset') for item in ordered_layouts] != list(range(len(ordered_layouts))):
|
||||
@@ -291,6 +328,8 @@ def reconstruct_coordinate_profile_rows(
|
||||
termination_rules=termination_rules or [],
|
||||
initial_fields=initial_fields,
|
||||
include_deleted=include_deleted,
|
||||
line_start_field_code=start_field_code,
|
||||
include_unanchored_rows=include_unanchored_rows,
|
||||
)
|
||||
if relative_y_rows is not None:
|
||||
return relative_y_rows
|
||||
@@ -346,12 +385,14 @@ def reconstruct_coordinate_profile_rows(
|
||||
flush(role='deleted')
|
||||
continue
|
||||
main_values, main_issues = values_for(band, ordered_layouts[0])
|
||||
line_no = re.sub(r'\s+', '', main_values.get('line_no', ''))
|
||||
if _LINE_NUMBER_PATTERN.fullmatch(line_no):
|
||||
if is_valid_line_start_value(main_values.get(start_field_code, '')):
|
||||
flush()
|
||||
current, sources, next_offset, current_issues = main_values, [row_index], 1, main_issues
|
||||
continue
|
||||
if current is None or next_offset >= len(ordered_layouts):
|
||||
if include_unanchored_rows and main_values:
|
||||
flush()
|
||||
current, sources, next_offset, current_issues = main_values, [row_index], 1, main_issues
|
||||
continue
|
||||
if not layout_order_valid:
|
||||
current_issues.append('coordinate_profile_layout_region_mismatch')
|
||||
@@ -386,15 +427,17 @@ def _reconstruct_relative_y_profile_rows(
|
||||
termination_rules: list[dict[str, Any]],
|
||||
initial_fields: dict[str, str] | None,
|
||||
include_deleted: bool,
|
||||
line_start_field_code: str,
|
||||
include_unanchored_rows: bool,
|
||||
) -> list[CoordinateProfileLogicalRow] | None:
|
||||
"""
|
||||
将单个多视觉行物理框按父行内相对 Y 投影到每条重复明细。
|
||||
|
||||
只有字段框明确切分了父物理行的纵向子带时才启用;旧模板的整高字段和多物理行
|
||||
row_offset 继续走原有逐视觉行算法。运行时先用 ``line_no`` 找到每条明细起点,再把
|
||||
row_offset 继续走原有逐视觉行算法。运行时先用可配置起行字段找到每条明细起点,再把
|
||||
样例字段的相对 Y 映射到相邻起点之间,避免料号尾数污染下方数量、单位和日期。
|
||||
"""
|
||||
if initial_fields or len(ordered_layouts) != 1:
|
||||
if include_unanchored_rows or initial_fields or len(ordered_layouts) != 1:
|
||||
return None
|
||||
layout = ordered_layouts[0]
|
||||
parent = layout.get('region')
|
||||
@@ -404,8 +447,11 @@ def _reconstruct_relative_y_profile_rows(
|
||||
]
|
||||
if not isinstance(parent, dict) or not _has_relative_y_subregions(parent, fields):
|
||||
return None
|
||||
line_field = next((field for field in fields if str(field.get('field_code') or '') == 'line_no'), None)
|
||||
if line_field is None:
|
||||
start_field = next(
|
||||
(field for field in fields if str(field.get('field_code') or '') == line_start_field_code),
|
||||
None,
|
||||
)
|
||||
if start_field is None:
|
||||
return None
|
||||
bands = _group_visual_rows(glyphs)
|
||||
usable_bands: list[tuple[int, list[tuple[int, PositionedCharacter]]]] = []
|
||||
@@ -417,11 +463,11 @@ def _reconstruct_relative_y_profile_rows(
|
||||
if not usable_bands:
|
||||
return []
|
||||
|
||||
line_region = _absolute_relative_region(table_bbox, line_field['region'])
|
||||
start_region = _absolute_relative_region(table_bbox, start_field['region'])
|
||||
anchors: list[int] = []
|
||||
for index, (_, band) in enumerate(usable_bands):
|
||||
line_text = re.sub(r'\s+', '', _text_in_horizontal_region(band, line_region))
|
||||
if _LINE_NUMBER_PATTERN.fullmatch(line_text):
|
||||
start_text = _text_in_horizontal_region(band, start_region)
|
||||
if is_valid_line_start_value(start_text):
|
||||
anchors.append(index)
|
||||
if not anchors:
|
||||
return []
|
||||
@@ -445,6 +491,7 @@ def _reconstruct_relative_y_profile_rows(
|
||||
record=record,
|
||||
expected_indices=field_band_indices,
|
||||
table_bbox=table_bbox,
|
||||
line_start_field_code=line_start_field_code,
|
||||
)
|
||||
issues.extend(alignment_issues)
|
||||
for field in fields:
|
||||
@@ -467,8 +514,7 @@ def _reconstruct_relative_y_profile_rows(
|
||||
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
|
||||
else:
|
||||
values[extracted_code] = extracted_value
|
||||
line_no = re.sub(r'\s+', '', values.get('line_no', ''))
|
||||
if _LINE_NUMBER_PATTERN.fullmatch(line_no):
|
||||
if is_valid_line_start_value(values.get(line_start_field_code, '')):
|
||||
results.append(CoordinateProfileLogicalRow(
|
||||
fields=values,
|
||||
source_row_indices=[row_index for row_index, _ in record],
|
||||
@@ -513,7 +559,7 @@ def suggest_multi_subrow_layouts(
|
||||
从实际物理行和文本起始位置自动建议动态多行版式。
|
||||
|
||||
AI/调用方触发时机:管理员打开坐标重建且不清楚相对边界时调用。算法只负责把
|
||||
同一明细中的第 1..N 行分组并建议列区间;除可确定的 ``line_no`` 外不猜业务字段,
|
||||
同一明细中的第 1..N 行分组并建议列区间;除可确定的起行锚点字段外不猜业务字段,
|
||||
建议结果仍须管理员结合示例文字确认。
|
||||
|
||||
Args:
|
||||
@@ -572,7 +618,7 @@ def suggest_multi_subrow_layouts(
|
||||
y1=min(1, (y1 - bbox.y0) / (bbox.y1 - bbox.y0)),
|
||||
column_samples=column_samples,
|
||||
suggested_field_codes=[
|
||||
'line_no' if row_offset == 0 and index == line_column else None
|
||||
DEFAULT_LINE_START_FIELD_CODE if row_offset == 0 and index == line_column else None
|
||||
for index in range(len(boundaries) - 1)
|
||||
],
|
||||
))
|
||||
@@ -726,29 +772,30 @@ def reconstruct_multi_subrow_table(
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
table_bbox: LayoutBBox,
|
||||
subrow_layouts: list[CoordinateSubrowLayout | dict[str, Any]],
|
||||
line_start_field_code: str = 'line_no',
|
||||
line_start_field_code: str = DEFAULT_LINE_START_FIELD_CODE,
|
||||
) -> list[ReconstructedLogicalRow]:
|
||||
"""
|
||||
使用每种子行的独立边界,将重叠版式的多条物理行合并为订单明细。
|
||||
|
||||
核心逻辑:每个视觉行先按主行布局寻找行号;命中后开始新明细。后续物理行按
|
||||
核心逻辑:每个视觉行先按主行布局寻找起行锚点;命中后开始新明细。后续物理行按
|
||||
``row_offset`` 选择第 2..N 行布局,将值直接合并到固定字段,而不是沿用首行列号。
|
||||
|
||||
Args:
|
||||
characters: 表格范围内的原生或 OCR 字符坐标。
|
||||
table_bbox: 当前数据表页面范围。
|
||||
subrow_layouts: 主行、补充行和属性行的独立边界及字段映射。
|
||||
line_start_field_code: 标记新明细的固定字段,默认 ``line_no``。
|
||||
line_start_field_code: 标记新明细的可配置字段,默认 ``customer_po_line_no``。
|
||||
Returns:
|
||||
合并后的逻辑明细;纯表头、说明和合计区域不会返回。
|
||||
"""
|
||||
start_field_code = resolve_line_start_field_code(line_start_field_code)
|
||||
layouts = [
|
||||
item if isinstance(item, CoordinateSubrowLayout) else CoordinateSubrowLayout.model_validate(item)
|
||||
for item in subrow_layouts
|
||||
]
|
||||
by_offset = {item.row_offset: item for item in layouts}
|
||||
main = by_offset.get(0)
|
||||
if main is None or not any(code == line_start_field_code for code in main.column_field_codes):
|
||||
if main is None or not any(code == start_field_code for code in main.column_field_codes):
|
||||
raise ValueError('multi-subrow reconstruction requires a main row line-start field')
|
||||
glyphs = _table_glyphs(characters, table_bbox)
|
||||
if not glyphs:
|
||||
@@ -787,8 +834,7 @@ def reconstruct_multi_subrow_table(
|
||||
continue
|
||||
|
||||
main_values = _band_field_values(band, anchors[0])
|
||||
line_value = re.sub(r'\s+', '', main_values.get(line_start_field_code, ''))
|
||||
if _LINE_NUMBER_PATTERN.fullmatch(line_value):
|
||||
if is_valid_line_start_value(main_values.get(start_field_code, '')):
|
||||
flush()
|
||||
current_fields = main_values
|
||||
current_sources = [row_index]
|
||||
@@ -1008,6 +1054,7 @@ def _match_field_band_groups(
|
||||
record: list[tuple[int, list[tuple[int, PositionedCharacter]]]],
|
||||
expected_indices: dict[int, int],
|
||||
table_bbox: LayoutBBox,
|
||||
line_start_field_code: str = DEFAULT_LINE_START_FIELD_CODE,
|
||||
) -> tuple[dict[int, int], list[str]]:
|
||||
"""将样例纵向字段组单调对齐到运行时 bands;额外换行可插入但组顺序不可倒退。"""
|
||||
if not record:
|
||||
@@ -1019,7 +1066,7 @@ def _match_field_band_groups(
|
||||
issues: list[str] = []
|
||||
previous_index = -1
|
||||
for expected_index, group_fields in sorted(groups.items()):
|
||||
if any(str(field.get('field_code') or '') == 'line_no' for field in group_fields):
|
||||
if any(str(field.get('field_code') or '') == line_start_field_code for field in group_fields):
|
||||
selected_index = 0
|
||||
else:
|
||||
candidates: list[tuple[float, int]] = []
|
||||
@@ -1216,8 +1263,8 @@ def _field_content_score(text: str, field_code: str | None) -> float:
|
||||
if not value or not field_code:
|
||||
return 0.0
|
||||
compact = value.replace(',', '').replace(' ', '')
|
||||
if field_code == 'line_no':
|
||||
return 1.0 if _LINE_NUMBER_PATTERN.fullmatch(compact) else -1.0
|
||||
if field_code in {'line_no', DEFAULT_LINE_START_FIELD_CODE, 'customer_po_line_no'}:
|
||||
return 1.0 if is_valid_line_start_value(compact) else -1.0
|
||||
if field_code in {'qty', 'unit_price', 'amount', 'line_amount_before_tax', 'line_amount_with_tax'}:
|
||||
return 1.0 if re.fullmatch(r'[-+]?\d+(?:\.\d+)?', compact) else -1.0
|
||||
if field_code == 'uom':
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
backend/app/services/shipping_notice/document_layout/lifecycle.py
|
||||
|
||||
用途:管理 ShippingNoticeDocument 的版面版本、checksum、大小门禁和当前成功快照。
|
||||
依赖:ShippingDocumentLayoutVersion、Flask 配置、SQLAlchemy Session。
|
||||
依赖:ShippingDocumentLayoutVersion、Flask 配置、SQLAlchemy Session、workflow_ledger_service
|
||||
(claim/complete/recovery 尽力同步 WorkflowItem,缺 Item 不阻断版面收口)。
|
||||
逻辑:相同内容/parser/checksum 幂等复用;失败版本保留审计,只有可用终态更新 Document 当前引用。
|
||||
"""
|
||||
|
||||
@@ -10,6 +11,7 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
@@ -19,6 +21,8 @@ from sqlalchemy import and_, func, or_, update
|
||||
from app.extensions import db
|
||||
from app.models import ShippingDocumentLayoutVersion, ShippingNoticeDocument, ShippingNoticeIntake
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
LAYOUT_PARSER_NAME = 'mineru'
|
||||
LAYOUT_BACKEND = 'pipeline'
|
||||
@@ -27,6 +31,97 @@ CURRENT_LAYOUT_STATUSES = frozenset({'ready', 'needs_review'})
|
||||
TERMINAL_LAYOUT_STATUSES = frozenset({'ready', 'needs_review', 'failed', 'unsupported'})
|
||||
|
||||
|
||||
def _conversation_id_for_document(document_id: int) -> str | None:
|
||||
"""
|
||||
从 Document → Intake 解析会话 ID,供 WorkflowItem 定位。
|
||||
|
||||
Args:
|
||||
document_id: ShippingNoticeDocument 主键。
|
||||
|
||||
Returns:
|
||||
conversation_id 或 None。
|
||||
"""
|
||||
row = (
|
||||
db.session.query(ShippingNoticeIntake.conversation_id)
|
||||
.join(ShippingNoticeDocument, ShippingNoticeDocument.intake_id == ShippingNoticeIntake.id)
|
||||
.filter(ShippingNoticeDocument.id == int(document_id))
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
text = str(row[0] or '').strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def _sync_workflow_item_for_layout(
|
||||
*,
|
||||
document_id: int,
|
||||
lifecycle_status: str | None = None,
|
||||
event_code: str | None = None,
|
||||
reason: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
尽力同步版面阶段的 WorkflowItem 状态/事件;Item 缺失时仅记日志。
|
||||
|
||||
Args:
|
||||
document_id: 版面所属 Document。
|
||||
lifecycle_status: 可选目标生命周期(queued/layout_parsing/failed 等)。
|
||||
event_code: 可选用户可见事件码(如 layout_completed)。
|
||||
reason: 迁移理由。
|
||||
"""
|
||||
try:
|
||||
from app.models.shipping_notice_workflow import ShippingNoticeWorkflow
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
append_workflow_event,
|
||||
find_item_by_root,
|
||||
transition_item_status,
|
||||
)
|
||||
|
||||
conversation_id = _conversation_id_for_document(int(document_id))
|
||||
if not conversation_id:
|
||||
return
|
||||
item = find_item_by_root(
|
||||
conversation_id=conversation_id,
|
||||
root_document_id=int(document_id),
|
||||
for_update=True,
|
||||
)
|
||||
if item is None:
|
||||
return
|
||||
if lifecycle_status and str(item.lifecycle_status or '') != str(lifecycle_status):
|
||||
if str(item.lifecycle_status or '') not in {
|
||||
'closed', 'cancelled', 'manual_upload_pending', 'pending_review',
|
||||
}:
|
||||
transition_item_status(
|
||||
item=item,
|
||||
lifecycle_status=str(lifecycle_status),
|
||||
stage=str(lifecycle_status),
|
||||
actor_type='system',
|
||||
actor_id='layout',
|
||||
reason=reason or f'layout:{lifecycle_status}',
|
||||
)
|
||||
if event_code:
|
||||
workflow = db.session.get(ShippingNoticeWorkflow, int(item.workflow_id))
|
||||
if workflow is not None:
|
||||
append_workflow_event(
|
||||
workflow=workflow,
|
||||
item=item,
|
||||
event_code=str(event_code),
|
||||
stage_code=str(item.current_stage or item.lifecycle_status),
|
||||
message_code=f'shipping.workflow_item.{event_code}',
|
||||
actor_type='system',
|
||||
actor_id='layout',
|
||||
payload={'document_id': int(document_id)},
|
||||
reason=reason,
|
||||
)
|
||||
except Exception:
|
||||
_LOGGER.exception(
|
||||
'layout workflow sync skipped document_id=%s status=%s event=%s',
|
||||
document_id,
|
||||
lifecycle_status,
|
||||
event_code,
|
||||
)
|
||||
|
||||
|
||||
def current_layout_parser_key() -> str:
|
||||
"""生成运维可轮转的 parser 身份;Provider/模型升级必须提升 revision 防止复用旧结果。"""
|
||||
revision = str(current_app.config.get(
|
||||
@@ -136,6 +231,32 @@ def record_inline_layout_snapshot(
|
||||
return version
|
||||
|
||||
|
||||
def _clone_reusable_layout_for_document(
|
||||
document: ShippingNoticeDocument,
|
||||
reusable: ShippingDocumentLayoutVersion,
|
||||
) -> ShippingDocumentLayoutVersion | None:
|
||||
"""
|
||||
将同一所有者的已完成布局快照本地化到目标 Document。
|
||||
|
||||
LayoutVersion 的 document_id 是不可跨文档共享的外键语义;相同内容只能复用
|
||||
已冻结 payload,不能让目标 Document 指向源 Document 的版本记录。
|
||||
"""
|
||||
payload = reusable.payload_json
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
copied_payload = dict(payload)
|
||||
copied_payload['status'] = str(reusable.status or copied_payload.get('status') or 'failed')
|
||||
copied_payload.setdefault('provider', reusable.parser_name or LAYOUT_PARSER_NAME)
|
||||
copied_payload.setdefault('provider_version', reusable.parser_version)
|
||||
copied_payload.setdefault('backend', reusable.backend or LAYOUT_BACKEND)
|
||||
copied_payload.setdefault('snapshot_version', reusable.contract_version or LAYOUT_CONTRACT_VERSION)
|
||||
return record_inline_layout_snapshot(
|
||||
document,
|
||||
copied_payload,
|
||||
parser_key=str(reusable.parser_key or current_layout_parser_key()),
|
||||
)
|
||||
|
||||
|
||||
def schedule_layout_version(
|
||||
document: ShippingNoticeDocument,
|
||||
*,
|
||||
@@ -175,8 +296,9 @@ def schedule_layout_version(
|
||||
.first()
|
||||
)
|
||||
if reusable_from_owner is not None:
|
||||
document.current_layout_version_id = reusable_from_owner.id
|
||||
return reusable_from_owner
|
||||
localized = _clone_reusable_layout_for_document(document, reusable_from_owner)
|
||||
if localized is not None:
|
||||
return localized
|
||||
active = ShippingDocumentLayoutVersion.query.filter(
|
||||
ShippingDocumentLayoutVersion.document_id == int(document.id),
|
||||
ShippingDocumentLayoutVersion.status.in_({'queued', 'running'}),
|
||||
@@ -357,6 +479,19 @@ def claim_layout_version(
|
||||
return None
|
||||
db.session.commit()
|
||||
version = db.session.get(ShippingDocumentLayoutVersion, int(version_id))
|
||||
if version is not None:
|
||||
# [STEP] claim 成功后迁 Item 到 layout_parsing,供工作台在版面阶段可见。
|
||||
_sync_workflow_item_for_layout(
|
||||
document_id=int(version.document_id),
|
||||
lifecycle_status='layout_parsing',
|
||||
event_code='layout_parsing_started',
|
||||
reason='claim_layout_version',
|
||||
)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
_LOGGER.exception('layout claim workflow commit failed version_id=%s', version_id)
|
||||
return (version, lease) if version is not None else None
|
||||
|
||||
|
||||
@@ -395,6 +530,25 @@ def complete_layout_version(
|
||||
if status in CURRENT_LAYOUT_STATUSES:
|
||||
version.document.current_layout_version_id = version.id
|
||||
db.session.commit()
|
||||
# [STEP] 版面完成写用户可见事件;失败版本同步 Item failed。
|
||||
if status in CURRENT_LAYOUT_STATUSES:
|
||||
_sync_workflow_item_for_layout(
|
||||
document_id=int(version.document_id),
|
||||
event_code='layout_completed',
|
||||
reason='complete_layout_version',
|
||||
)
|
||||
elif status in {'failed', 'unsupported'}:
|
||||
_sync_workflow_item_for_layout(
|
||||
document_id=int(version.document_id),
|
||||
lifecycle_status='failed',
|
||||
event_code='layout_failed',
|
||||
reason='complete_layout_version',
|
||||
)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
_LOGGER.exception('layout complete workflow commit failed version_id=%s', version_id)
|
||||
return True
|
||||
|
||||
|
||||
@@ -407,12 +561,24 @@ def sync_layout_after_job_recovery(job: Any) -> None:
|
||||
version.updated_at = datetime.utcnow()
|
||||
if str(job.status or '') == 'queued':
|
||||
version.status = 'queued'
|
||||
_sync_workflow_item_for_layout(
|
||||
document_id=int(version.document_id),
|
||||
lifecycle_status='queued',
|
||||
event_code='layout_retry_queued',
|
||||
reason='layout_job_recovery:queued',
|
||||
)
|
||||
elif str(job.status or '') in {'failed', 'cancelled'}:
|
||||
version.status = 'failed'
|
||||
version.finished_at = datetime.utcnow()
|
||||
version.issues_json = sorted(set(list(version.issues_json or []) + [
|
||||
'shipping_document_layout_job_exhausted',
|
||||
]))
|
||||
_sync_workflow_item_for_layout(
|
||||
document_id=int(version.document_id),
|
||||
lifecycle_status='failed',
|
||||
event_code='layout_failed',
|
||||
reason=f'layout_job_recovery:{job.status}',
|
||||
)
|
||||
|
||||
|
||||
def sync_layout_after_job_failure(job_id: int) -> None:
|
||||
|
||||
@@ -34,6 +34,7 @@ class OrderFieldExtraction(BaseModel):
|
||||
|
||||
field_id: str
|
||||
field_code: str
|
||||
scope: Literal['header']
|
||||
value: Any = None
|
||||
status: Literal['confirmed', 'needs_review', 'unavailable']
|
||||
source: Literal['pdf_coordinate', 'ocr_coordinate'] | None = None
|
||||
@@ -112,7 +113,10 @@ def _extract_layout(
|
||||
fallback=True,
|
||||
))
|
||||
continue
|
||||
matches = _find_anchor_matches(glyphs, layout.anchor, page_width=width, page_height=height)
|
||||
matches = _find_anchor_matches(
|
||||
glyphs, layout.anchor, page_width=width, page_height=height,
|
||||
ignore_reference_region=_uses_movable_anchor_value_region(layout=layout, width=width, height=height),
|
||||
)
|
||||
if not matches:
|
||||
reference_anchor = (
|
||||
_anchor_from_reference_region(
|
||||
@@ -135,7 +139,7 @@ def _extract_layout(
|
||||
continue
|
||||
if len(matches) != 1:
|
||||
results.append(OrderFieldExtraction(
|
||||
field_id=layout.field_id, field_code=layout.field_code, status='needs_review', source=source,
|
||||
field_id=layout.field_id, field_code=layout.field_code, scope=layout.scope, status='needs_review', source=source,
|
||||
page_no=page_no, issues=['order_field_anchor_ambiguous'],
|
||||
))
|
||||
continue
|
||||
@@ -179,7 +183,7 @@ def _read_value_region(
|
||||
if layout.value_mode != 'multi_line':
|
||||
text = text.split('\n', 1)[0].strip()
|
||||
if layout.value_mode == 'right_of_anchor':
|
||||
text = text.lstrip(':: ').strip()
|
||||
text = text.lstrip('::# ').strip()
|
||||
if str(config.get('value_type') or '') == 'date':
|
||||
text = _recover_trailing_date_glyph(text=text, glyphs=glyphs, region=region)
|
||||
if not text:
|
||||
@@ -197,7 +201,7 @@ def _read_value_region(
|
||||
if review_issue:
|
||||
issues.append(review_issue)
|
||||
return OrderFieldExtraction(
|
||||
field_id=layout.field_id, field_code=layout.field_code, value=value, status=status, source=source,
|
||||
field_id=layout.field_id, field_code=layout.field_code, scope=layout.scope, value=value, status=status, source=source,
|
||||
page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=region,
|
||||
glyph_indices=[index for index, _item in selected], issues=issues,
|
||||
)
|
||||
@@ -272,6 +276,7 @@ def _recover_trailing_date_glyph(*, text: str, glyphs: list[dict[str, Any]], reg
|
||||
|
||||
def _find_anchor_matches(
|
||||
glyphs: list[dict[str, Any]], anchor: AnchorRule, *, page_width: float | None = None, page_height: float | None = None,
|
||||
ignore_reference_region: bool = False,
|
||||
) -> list[tuple[LayoutBBox, list[int]]]:
|
||||
"""在每个视觉行内执行精确标签匹配,返回去重后的字符联合框。"""
|
||||
expected = [anchor.text, *anchor.aliases]
|
||||
@@ -285,9 +290,12 @@ def _find_anchor_matches(
|
||||
row_text = ''.join(str(item.get('text') or '') for _index, item in compact)
|
||||
# Field anchors are part of the frozen Schema/Profile contract; matching
|
||||
# them case-sensitively prevents one label from being mistaken for another.
|
||||
folded = row_text
|
||||
# PDF text case is not stable across generators (for example ``Billto``
|
||||
# versus a canvas label ``Bill To``). Whitespace remains folded and exact
|
||||
# word boundaries below still prevent partial-word matches.
|
||||
folded = row_text.casefold()
|
||||
for label in expected:
|
||||
normalized = re.sub(r'\s+', '', label)
|
||||
normalized = re.sub(r'\s+', '', label).casefold()
|
||||
start = 0
|
||||
while normalized and (position := folded.find(normalized, start)) >= 0:
|
||||
consumed = compact[position:position + len(normalized)]
|
||||
@@ -295,7 +303,7 @@ def _find_anchor_matches(
|
||||
compact, position=position, length=len(normalized), anchor=anchor,
|
||||
):
|
||||
bbox = _union_bbox([item for _index, item in consumed])
|
||||
if _anchor_bbox_in_reference_region(
|
||||
if ignore_reference_region or _anchor_bbox_in_reference_region(
|
||||
bbox, anchor=anchor, page_width=page_width, page_height=page_height,
|
||||
):
|
||||
matches.append((bbox, [index for index, _item in consumed]))
|
||||
@@ -303,7 +311,20 @@ def _find_anchor_matches(
|
||||
unique: dict[tuple[float, float, float, float], tuple[LayoutBBox, list[int]]] = {}
|
||||
for bbox, indices in matches:
|
||||
unique[(bbox.x0, bbox.y0, bbox.x1, bbox.y1)] = (bbox, indices)
|
||||
return list(unique.values())
|
||||
resolved = list(unique.values())
|
||||
# An unlocked label may shift between documents, so its reference box must
|
||||
# not suppress a sole match. When the same label occurs multiple times,
|
||||
# however, the saved canvas position is decisive evidence for this sample.
|
||||
if len(resolved) > 1 and anchor.region is not None and page_width and page_height:
|
||||
positioned = [
|
||||
item for item in resolved
|
||||
if _anchor_bbox_in_reference_region(
|
||||
item[0], anchor=anchor, page_width=page_width, page_height=page_height, enforce=True,
|
||||
)
|
||||
]
|
||||
if len(positioned) == 1:
|
||||
return positioned
|
||||
return resolved
|
||||
|
||||
|
||||
def _anchor_occurrence_is_exact(
|
||||
@@ -331,9 +352,10 @@ def _glyph_gap_is_word_boundary(left: dict[str, Any], right: dict[str, Any]) ->
|
||||
|
||||
def _anchor_bbox_in_reference_region(
|
||||
bbox: LayoutBBox, *, anchor: AnchorRule, page_width: float | None, page_height: float | None,
|
||||
enforce: bool = False,
|
||||
) -> bool:
|
||||
"""锚点配置了参考区时只接受该页相对位置内的命中,避免页眉重复标签干扰。"""
|
||||
if anchor.region is None:
|
||||
if anchor.region is None or (not enforce and not anchor.position_locked):
|
||||
return True
|
||||
if page_width is None or page_height is None or page_width <= 0 or page_height <= 0:
|
||||
return False
|
||||
@@ -448,10 +470,50 @@ def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutB
|
||||
|
||||
|
||||
def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, width: float, height: float) -> LayoutBBox:
|
||||
"""优先使用管理员画布绝对值框;旧模板才按锚点偏移投影。"""
|
||||
"""读取值区;旧版“标签右侧/下方”绝对框自动转换为可移动相对框。"""
|
||||
if layout.value_region is not None:
|
||||
region = _absolute_anchor_region(layout.value_region, anchor)
|
||||
if layout.value_mode == 'right_of_anchor':
|
||||
# The left edge of a right-side field is semantic, not a canvas
|
||||
# gap: start at the matched label so font-width differences cannot
|
||||
# discard the first value character on another document.
|
||||
return LayoutBBox(x0=anchor.x1, y0=region.y0, x1=region.x1, y1=region.y1)
|
||||
return region
|
||||
if _uses_movable_anchor_value_region(layout=layout, width=width, height=height):
|
||||
# Historical canvas persisted a page box even when the UI said "right of
|
||||
# anchor". Rebase it onto the actual label to retain that relationship.
|
||||
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height)
|
||||
saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height)
|
||||
reference_width = reference.x1 - reference.x0
|
||||
reference_height = reference.y1 - reference.y0
|
||||
relative = AnchorRelativeRegion(
|
||||
# The old canvas selected a page box, whose left gap depends on
|
||||
# preceding text. The mode itself is the durable intent: begin at
|
||||
# the matched label's right edge and retain the configured extent.
|
||||
x0=1,
|
||||
y0=0,
|
||||
x1=1 + (saved.x1 - reference.x1) / reference_width,
|
||||
y1=1,
|
||||
)
|
||||
return _absolute_anchor_region(relative, anchor)
|
||||
if layout.absolute_value_region is not None:
|
||||
return _absolute_relative_region(layout.absolute_value_region, width=width, height=height)
|
||||
return _absolute_anchor_region(layout.value_region, anchor)
|
||||
raise ValueError('anchored order field has no value region')
|
||||
|
||||
|
||||
def _uses_movable_anchor_value_region(*, layout: OrderFieldLayout, width: float, height: float) -> bool:
|
||||
"""判断新相对规则或同一行的旧右侧框是否应跟随实际标签移动。"""
|
||||
if layout.value_region is not None:
|
||||
return True
|
||||
if (
|
||||
layout.absolute_value_region is None or layout.anchor is None or layout.anchor.region is None
|
||||
or layout.value_mode not in {'right_of_anchor', 'below_anchor'}
|
||||
):
|
||||
return False
|
||||
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height)
|
||||
saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height)
|
||||
tolerance = max(reference.y1 - reference.y0, saved.y1 - saved.y0) * 2
|
||||
return saved.y0 <= reference.y1 + tolerance and reference.y0 <= saved.y1 + tolerance
|
||||
|
||||
|
||||
def _glyph_bbox(glyph: dict[str, Any]) -> LayoutBBox:
|
||||
@@ -479,7 +541,7 @@ def _unavailable(
|
||||
anchor_bbox: LayoutBBox | None = None, value_bbox: LayoutBBox | None = None,
|
||||
) -> OrderFieldExtraction:
|
||||
"""构造无可用坐标证据的失败关闭结果。"""
|
||||
return OrderFieldExtraction(field_id=layout.field_id, field_code=layout.field_code, status='unavailable', source=source, page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=value_bbox, issues=[issue])
|
||||
return OrderFieldExtraction(field_id=layout.field_id, field_code=layout.field_code, scope=layout.scope, status='unavailable', source=source, page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=value_bbox, issues=[issue])
|
||||
|
||||
|
||||
def _review(
|
||||
@@ -488,7 +550,7 @@ def _review(
|
||||
) -> OrderFieldExtraction:
|
||||
"""构造带最小证据索引的人工复核候选。"""
|
||||
return OrderFieldExtraction(
|
||||
field_id=layout.field_id, field_code=layout.field_code, status='needs_review', source=source,
|
||||
field_id=layout.field_id, field_code=layout.field_code, scope=layout.scope, status='needs_review', source=source,
|
||||
page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=value_bbox,
|
||||
glyph_indices=[index for index, _item in selected], issues=[issue],
|
||||
)
|
||||
@@ -88,6 +88,7 @@ class AnchorRule(OrderProfileModel):
|
||||
aliases: list[str] = Field(default_factory=list, max_length=16)
|
||||
match_mode: Literal['exact', 'contains'] = 'contains'
|
||||
region: RelativeRegion | None = None
|
||||
position_locked: bool = True
|
||||
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
|
||||
|
||||
@model_validator(mode='after')
|
||||
@@ -107,6 +108,7 @@ class OrderFieldLayout(OrderProfileModel):
|
||||
layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
field_id: str = Field(min_length=1, max_length=128)
|
||||
field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
scope: Literal['header']
|
||||
page_scope: Literal['first_page', 'all_pages', 'exact_page'] = 'first_page'
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
anchor: AnchorRule | None = None
|
||||
@@ -149,6 +151,7 @@ class FieldRegion(OrderProfileModel):
|
||||
|
||||
field_id: str = Field(min_length=1, max_length=128)
|
||||
field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
scope: Literal['header', 'line']
|
||||
region: RelativeRegion
|
||||
extractor_key: Literal['direct', 'temp_internal_parts', 'quantity_uom', 'amount_currency', 'price_currency'] = 'direct'
|
||||
allowed_sources: list[Literal['pdf_coordinate', 'ocr_coordinate']] = Field(min_length=1)
|
||||
@@ -161,8 +164,11 @@ class FieldRegion(OrderProfileModel):
|
||||
if len(self.allowed_sources) != len(set(self.allowed_sources)):
|
||||
raise ValueError('field region sources must be unique')
|
||||
if self.target_fields:
|
||||
codes = [str(item.get('field_code') or '') for item in self.target_fields]
|
||||
if len(codes) != len(set(codes)) or self.field_code not in codes:
|
||||
identities = [
|
||||
(str(item.get('scope') or ''), str(item.get('field_code') or ''))
|
||||
for item in self.target_fields
|
||||
]
|
||||
if len(identities) != len(set(identities)) or (self.scope, self.field_code) not in identities:
|
||||
raise ValueError('field region targets must be unique and include field_code')
|
||||
return self
|
||||
|
||||
@@ -242,6 +248,8 @@ class DraftUnboundOrderFieldLayout(OrderProfileModel):
|
||||
"""复用订单字段的区域互斥与页作用域规则,避免迁移草稿保存坏坐标。"""
|
||||
OrderFieldLayout(
|
||||
layout_id=self.layout_id, field_id='draft_unbound', field_code='draft_unbound',
|
||||
# 未绑定草稿仅保留坐标证据,不属于任何 Schema scope。
|
||||
scope='header',
|
||||
page_scope=self.page_scope, page_no=self.page_no, anchor=self.anchor,
|
||||
value_region=self.value_region, absolute_value_region=self.absolute_value_region,
|
||||
fallback_value_region=self.fallback_value_region,
|
||||
@@ -258,6 +266,8 @@ class TableRegionProfile(OrderProfileModel):
|
||||
page_scope: Literal['first_page', 'all_pages', 'continuation_pages', 'exact_page'] = 'all_pages'
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
region: RelativeRegion
|
||||
# 逻辑明细起行锚点;默认客户 PO 行号,可使用任一已绑定明细字段。
|
||||
line_start_field_code: str = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
header_layouts: list[HeaderLayout] = Field(default_factory=list)
|
||||
line_layouts: list[LineLayout] = Field(default_factory=list)
|
||||
continuation_rule: ContinuationRule = Field(default_factory=ContinuationRule)
|
||||
@@ -289,6 +299,11 @@ class TableRegionProfile(OrderProfileModel):
|
||||
fields = [field.field_code for item in self.line_layouts for field in item.field_regions]
|
||||
if len(fields) != len(set(fields)):
|
||||
raise ValueError('field_code may bind to only one coordinate region per table')
|
||||
# 草稿可先框物理行;一旦主行开始绑字段,就必须包含起行锚点。
|
||||
if self.line_layouts and self.line_layouts[0].field_regions and self.line_start_field_code not in {
|
||||
field.field_code for field in self.line_layouts[0].field_regions
|
||||
}:
|
||||
raise ValueError('main line layout must bind the configured line-start field')
|
||||
# A physical text band must have exactly one layout interpretation. Allowing
|
||||
# overlapping header/line regions would reintroduce the cross-row ambiguity
|
||||
# that v2 coordinate profiles are intended to eliminate.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
services/shipping_notice/document_profile_quality_service.py
|
||||
|
||||
用途:治理订单文档 Profile 的盲测样本、执行结果和确定性自动建单资格。
|
||||
用途:治理订单文档 Profile 的盲测候选、样本、执行结果和确定性自动建单资格。
|
||||
依赖:Profile 服务、MinerU 当前布局快照、Profile 纯解析器与质量 ORM 模型。
|
||||
逻辑:管理员先固化一份独立样本的期望行,服务按冻结 Profile 执行比对;样本通过并批准后才放行自动建单。
|
||||
"""
|
||||
@@ -135,6 +135,11 @@ def _ensure_order_field_evidence(
|
||||
return layout
|
||||
|
||||
|
||||
def _order_field_review_key(*, scope: str, field_code: str) -> str:
|
||||
"""返回 scope 加字段编码的盲测复核键,避免同编码字段相互覆盖。"""
|
||||
return f'{scope}:{field_code}'
|
||||
|
||||
|
||||
def _has_matching_key_order_field(
|
||||
*, parser: OrderCoordinateProfileV2, schema_fields: dict[str, dict[str, Any]], layout: dict[str, Any],
|
||||
) -> bool:
|
||||
@@ -148,15 +153,15 @@ def _has_matching_key_order_field(
|
||||
# existing compatibility path; their evidence remains needs_review.
|
||||
return True
|
||||
extracted = {
|
||||
item.field_code: item
|
||||
item.field_id: item
|
||||
for item in extract_order_fields(
|
||||
profile=parser, schema_fields=schema_fields,
|
||||
coordinate_evidence=layout.get('coordinate_evidence') or {},
|
||||
)
|
||||
}
|
||||
return any(
|
||||
extracted.get(item.field_code) is not None
|
||||
and extracted[item.field_code].status != 'unavailable'
|
||||
extracted.get(item.field_id) is not None
|
||||
and extracted[item.field_id].status != 'unavailable'
|
||||
for item in key_layouts
|
||||
)
|
||||
|
||||
@@ -178,7 +183,10 @@ def _order_field_quality_failures(
|
||||
else:
|
||||
config = schema_fields.get(candidate.field_id)
|
||||
try:
|
||||
expected = normalize_order_field_value(expected_values.get(candidate.field_code), config or {})
|
||||
expected = normalize_order_field_value(
|
||||
expected_values.get(_order_field_review_key(scope=candidate.scope, field_code=candidate.field_code)),
|
||||
config or {},
|
||||
)
|
||||
except Exception:
|
||||
expected = None
|
||||
if candidate.value != expected:
|
||||
@@ -194,14 +202,14 @@ def _expected_rows(raw: Any) -> list[dict[str, Any]]:
|
||||
|
||||
|
||||
def _expected_order_fields(raw: Any, *, parser: Any) -> dict[str, Any]:
|
||||
"""校验订单字段盲测真值;有订单布局时要求按 stable field_code 提供完整映射。"""
|
||||
"""校验订单字段盲测真值;有订单布局时要求按 scope 与字段编码提供完整映射。"""
|
||||
layouts = parser.order_field_layouts if isinstance(parser, OrderCoordinateProfileV2) else []
|
||||
if not layouts:
|
||||
return {}
|
||||
if not isinstance(raw, dict):
|
||||
raise ValidationError('expected_order_fields is required for order field layouts', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
|
||||
expected_codes = {item.field_code for item in layouts}
|
||||
if set(raw) != expected_codes or any(value in (None, '') for value in raw.values()):
|
||||
expected_keys = {_order_field_review_key(scope=item.scope, field_code=item.field_code) for item in layouts}
|
||||
if set(raw) != expected_keys or any(value in (None, '') for value in raw.values()):
|
||||
raise ValidationError('expected_order_fields must contain every configured order field', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
|
||||
return dict(raw)
|
||||
|
||||
@@ -249,10 +257,12 @@ def _candidate_for_sample(
|
||||
line_layouts=[item.model_dump() for item in region.line_layouts], table_region=region.region.model_dump(),
|
||||
termination_rules=[item.model_dump() for item in region.termination_rules],
|
||||
exclusion_regions=[item.model_dump() for item in region.exclusion_regions],
|
||||
line_start_field_code=region.line_start_field_code,
|
||||
) if not item.issues)
|
||||
order_fields = [
|
||||
{
|
||||
'field_code': item.field_code, 'value': _json_value(item.value), 'status': item.status,
|
||||
'field_id': item.field_id, 'scope': item.scope,
|
||||
'page_no': item.page_no, 'issues': list(item.issues),
|
||||
}
|
||||
for item in extract_order_fields(profile=parser, schema_fields=schema_fields, coordinate_evidence=evidence)
|
||||
@@ -274,10 +284,17 @@ def _json_value(value: Any) -> Any:
|
||||
|
||||
|
||||
def list_independent_samples(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
"""列出可用于当前盲测的同类专用订单,严格排除建模和已加入盲测的文档。
|
||||
"""列出可用于当前盲测的专用订单与同模板族历史样本。
|
||||
|
||||
列表阶段只读取已存布局摘要,不能为每个候选触发 OCR/坐标证据补齐;用户选中
|
||||
某份样本后,再由候选预览执行完整的坐标和订单字段校验。
|
||||
核心逻辑:普通专用上传与同一 ``profile_code`` 历史版本的 annotation/training/旧新盲测
|
||||
绑定共同组成候选;当前版本建模样本和当前套件样本仍严格排除。重复上传按内容哈希和
|
||||
表格身份收敛,历史来源不受最近上传数量限制。当前版本仍须重新预览、人工复核并确认。
|
||||
|
||||
Args:
|
||||
suite_id: 当前草稿盲测套件 ID。
|
||||
actor_id: 当前管理员 ID,仅用于既有权限调用链身份约束。
|
||||
Returns:
|
||||
只含安全表格摘要的候选列表,不返回正文、坐标、HTML 或历史真值。
|
||||
"""
|
||||
suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id))
|
||||
if suite is None:
|
||||
@@ -287,12 +304,44 @@ def list_independent_samples(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
item.document_id for item in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all()
|
||||
} | {item.document_id for item in suite.samples}
|
||||
result: list[dict[str, Any]] = []
|
||||
candidate_keys: set[tuple[str, int, int, int, int, tuple[str, ...]]] = set()
|
||||
documents = ShippingNoticeDocument.query.join(
|
||||
ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeDocument.intake_id,
|
||||
).filter(
|
||||
ShippingNoticeIntake.purpose == 'order_document_profile_sample',
|
||||
).order_by(ShippingNoticeDocument.created_at.desc()).limit(200).all()
|
||||
for document in documents:
|
||||
).order_by(ShippingNoticeDocument.created_at.desc()).all()
|
||||
historical_profile_ids = {
|
||||
int(profile_id)
|
||||
for (profile_id,) in db.session.query(ShippingOrderDocumentProfile.id).filter(
|
||||
ShippingOrderDocumentProfile.profile_code == profile.profile_code,
|
||||
ShippingOrderDocumentProfile.id != profile.id,
|
||||
).all()
|
||||
}
|
||||
historical_bound_document_ids = {
|
||||
int(document_id)
|
||||
for (document_id,) in db.session.query(ShippingOrderDocumentProfileSample.document_id).filter(
|
||||
ShippingOrderDocumentProfileSample.profile_id.in_(historical_profile_ids),
|
||||
).distinct().all()
|
||||
} if historical_profile_ids else set()
|
||||
historical_blind_document_ids = {
|
||||
int(document_id)
|
||||
for (document_id,) in db.session.query(ShippingDocumentProfileTestSample.document_id).join(
|
||||
ShippingDocumentProfileTestSuite,
|
||||
ShippingDocumentProfileTestSuite.id == ShippingDocumentProfileTestSample.suite_id,
|
||||
).join(
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfile.id == ShippingDocumentProfileTestSuite.profile_id,
|
||||
).filter(
|
||||
ShippingOrderDocumentProfile.profile_code == profile.profile_code,
|
||||
ShippingOrderDocumentProfile.id != profile.id,
|
||||
).distinct().all()
|
||||
}
|
||||
documents_by_id = {document.id: document for document in documents}
|
||||
historical_document_ids = historical_bound_document_ids | historical_blind_document_ids
|
||||
for document in ShippingNoticeDocument.query.filter(ShippingNoticeDocument.id.in_(historical_document_ids)).all():
|
||||
documents_by_id.setdefault(document.id, document)
|
||||
|
||||
for document in documents_by_id.values():
|
||||
if document.id in excluded:
|
||||
continue
|
||||
layout = current_layout_snapshot(document) or {}
|
||||
@@ -312,13 +361,23 @@ def list_independent_samples(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
slot.text for slot in (grid.rows[0] if grid.rows else [])
|
||||
if slot is not None and slot.text
|
||||
][:3]
|
||||
table_index = sum(
|
||||
1 for item in tables[:tables.index(table) + 1]
|
||||
if isinstance(item, dict) and int(item.get('page_no') or 1) == int(table.get('page_no') or 1)
|
||||
)
|
||||
# 同内容重复上传会产生不同 document_id/table_id;表格在文件内的位置与结构才是选择身份。
|
||||
content_identity = str(document.content_hash or '').strip().lower() or f'document:{document.id}'
|
||||
candidate_key = (
|
||||
content_identity, int(table.get('page_no') or 1), table_index,
|
||||
grid.row_count, grid.column_count, tuple(header_preview),
|
||||
)
|
||||
if candidate_key in candidate_keys:
|
||||
continue
|
||||
candidate_keys.add(candidate_key)
|
||||
result.append({
|
||||
'document_id': document.id, 'table_id': table_id,
|
||||
'page_no': int(table.get('page_no') or 1), 'filename': document.filename or '',
|
||||
'table_index': sum(
|
||||
1 for item in tables[:tables.index(table) + 1]
|
||||
if isinstance(item, dict) and int(item.get('page_no') or 1) == int(table.get('page_no') or 1)
|
||||
),
|
||||
'table_index': table_index,
|
||||
'row_count': grid.row_count, 'column_count': grid.column_count,
|
||||
'header_preview': header_preview,
|
||||
})
|
||||
@@ -356,13 +415,16 @@ def confirm_sample_reviews(*, suite_id: int, document_id: int, table_id: str, ro
|
||||
expected_rows.append(dict(values))
|
||||
expected_order_fields: dict[str, Any] = {}
|
||||
for field in candidate['order_fields']:
|
||||
review = order_field_reviews.get(field['field_code']) if isinstance(order_field_reviews, dict) else None
|
||||
review_key = _order_field_review_key(
|
||||
scope=str(field['scope']), field_code=str(field['field_code']),
|
||||
)
|
||||
review = order_field_reviews.get(review_key) if isinstance(order_field_reviews, dict) else None
|
||||
if not isinstance(review, dict) or review.get('correct') not in {True, False}:
|
||||
raise ValidationError('Every order field requires a review', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
|
||||
value = field['value'] if review['correct'] else review.get('value')
|
||||
if value in (None, ''):
|
||||
raise ValidationError('Incorrect order field requires a corrected value', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
|
||||
expected_order_fields[field['field_code']] = value
|
||||
expected_order_fields[review_key] = value
|
||||
return add_sample(
|
||||
suite_id=suite_id, document_id=document_id, table_id=table_id, expected_rows=expected_rows,
|
||||
expected_order_fields=expected_order_fields, actor_id=actor_id,
|
||||
@@ -521,6 +583,7 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
line_layouts=[item.model_dump() for item in region.line_layouts], table_region=region.region.model_dump(),
|
||||
termination_rules=[item.model_dump() for item in region.termination_rules],
|
||||
exclusion_regions=[item.model_dump() for item in region.exclusion_regions],
|
||||
line_start_field_code=region.line_start_field_code,
|
||||
) if not item.issues)
|
||||
if actual_rows == list(sample.expected_rows_json or []):
|
||||
passed += 1
|
||||
|
||||
@@ -35,7 +35,9 @@ from app.services.file_assets.storage import file_asset_storage
|
||||
ALLOWED_SOURCE_KINDS = {'order_field', 'inventory_field', 'system_fact', 'constant'}
|
||||
ALLOWED_ROW_MODES = {'header', 'line'}
|
||||
ALLOWED_FORMATTERS = {'text', 'upper', 'lower', 'date_mmddyyyy', 'integer', 'decimal'}
|
||||
ALLOWED_SYSTEM_FACTS = {'task_no', 'business_no', 'warehouse_id', 'inventory_source_code', 'export_date'}
|
||||
ALLOWED_SYSTEM_FACTS = {
|
||||
'task_no', 'business_no', 'warehouse_id', 'inventory_source_code', 'export_date', 'export_sequence',
|
||||
}
|
||||
|
||||
|
||||
def _storage_key(template_code: str, version: int) -> str:
|
||||
|
||||
@@ -3,7 +3,9 @@ services/shipping_notice/export.py
|
||||
|
||||
用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。
|
||||
依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。
|
||||
逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板。
|
||||
逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板;
|
||||
在最终导出行集上注入 `__export_sequence=1..N`,仅供 system_fact:export_sequence 消费;
|
||||
订单内部项次 line_no 只能通过 order_field 映射,不得再作为系统事实。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -56,14 +58,25 @@ def order_field_id_values(task: ShippingTask) -> tuple[dict[str, Any], list[dict
|
||||
return header, lines
|
||||
|
||||
|
||||
def _system_fact(task: ShippingTask, key: str) -> Any:
|
||||
"""读取受控任务事实,模板不能通过任意属性路径访问 ORM。"""
|
||||
def _system_fact(task: ShippingTask, key: str, *, export_sequence: int | None = None) -> Any:
|
||||
"""
|
||||
读取受控任务事实,模板不能通过任意属性路径访问 ORM。
|
||||
|
||||
Args:
|
||||
task: 发货任务。
|
||||
key: 系统事实键;仅允许白名单内键。
|
||||
export_sequence: 本次最终导出行集上的连续序号(1..N);仅 export_sequence 键使用。
|
||||
|
||||
Returns:
|
||||
对应系统事实值;未知键返回 None。
|
||||
"""
|
||||
values = {
|
||||
'task_no': task.task_no,
|
||||
'business_no': task.shipping_case.business_no if task.shipping_case else None,
|
||||
'warehouse_id': task.inventory_warehouse_id,
|
||||
'inventory_source_code': task.inventory_source_code,
|
||||
'export_date': datetime.now(ZoneInfo('Asia/Shanghai')).date(),
|
||||
'export_sequence': export_sequence,
|
||||
}
|
||||
return values.get(key)
|
||||
|
||||
@@ -95,9 +108,25 @@ def _format_value(value: Any, formatter: str) -> Any:
|
||||
|
||||
def _mapping_value(
|
||||
mapping: dict[str, Any], *, task: ShippingTask, order_values: dict[str, Any], inventory_values: dict[str, Any],
|
||||
header_values: dict[str, Any] | None = None,
|
||||
header_values: dict[str, Any] | None = None, export_sequence: int | None = None,
|
||||
) -> Any:
|
||||
"""按映射来源类型读取值;未知来源已在模板发布时被拒绝。"""
|
||||
"""
|
||||
按映射来源类型读取值;未知来源已在模板发布时被拒绝。
|
||||
|
||||
核心逻辑:order_field 读订单快照;inventory_field 读库存行;system_fact 仅读白名单事实;
|
||||
export_sequence 优先用调用方传入值,缺失时回退行上注入的 ``__export_sequence``。
|
||||
|
||||
Args:
|
||||
mapping: 已发布模板映射项。
|
||||
task: 发货任务。
|
||||
order_values: 当前行或表头订单字段值。
|
||||
inventory_values: 当前行库存字段值。
|
||||
header_values: 明细行模式下可回退的表头字段。
|
||||
export_sequence: 本次导出行序号(1..N)。
|
||||
|
||||
Returns:
|
||||
经 formatter 处理后的单元格值。
|
||||
"""
|
||||
kind = mapping['source_kind']
|
||||
key = mapping['source_key']
|
||||
if kind == 'order_field':
|
||||
@@ -107,7 +136,12 @@ def _mapping_value(
|
||||
elif kind == 'inventory_field':
|
||||
value = inventory_values.get(str(key))
|
||||
elif kind == 'system_fact':
|
||||
value = _system_fact(task, key)
|
||||
value = _system_fact(
|
||||
task, key,
|
||||
export_sequence=export_sequence if key == 'export_sequence' else None,
|
||||
)
|
||||
if key == 'export_sequence' and value is None:
|
||||
value = order_values.get('__export_sequence')
|
||||
else:
|
||||
value = key
|
||||
return _format_value(value, mapping['formatter'])
|
||||
@@ -302,10 +336,14 @@ def generate_shipment_excel(task: ShippingTask) -> tuple[str, str, ShippingExpor
|
||||
reserve_available_for_artifact,
|
||||
)
|
||||
verification, available_line_ids = current_available_snapshot_line_ids(task)
|
||||
line_values = [
|
||||
values for line, values in zip(snapshot.lines, all_line_values, strict=True)
|
||||
if line.id in available_line_ids
|
||||
]
|
||||
# [STEP 1] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。
|
||||
line_values = []
|
||||
for line, values in zip(snapshot.lines, all_line_values, strict=True):
|
||||
if line.id not in available_line_ids:
|
||||
continue
|
||||
line_values.append(dict(values))
|
||||
for index, row in enumerate(line_values, start=1):
|
||||
row['__export_sequence'] = index
|
||||
inventory_lines = [item for item in (task.inventory_lines_json or []) if isinstance(item, dict)]
|
||||
definition = template.definition_json or {}
|
||||
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
|
||||
@@ -350,6 +388,7 @@ def generate_shipment_excel(task: ShippingTask) -> tuple[str, str, ShippingExpor
|
||||
ws.cell(start_row + index, column).value = _mapping_value(
|
||||
mapping, task=task, order_values=order_line, inventory_values=inventory_line,
|
||||
header_values=header_values,
|
||||
export_sequence=int(order_line.get('__export_sequence') or (index + 1)),
|
||||
)
|
||||
wb.save(path)
|
||||
finally:
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/field_asset_service.py
|
||||
|
||||
用途:货代字段资产治理——列表/详情、扩展创建与弃用恢复、标准只读校验、审计写入。
|
||||
用途:货代字段资产治理——列表/详情、扩展创建与弃用恢复、标准/上下文字段种子、审计写入。
|
||||
依赖:ShippingOrderField、standard_field_registry、ShippingOrderSchemaAuditEvent、db。
|
||||
逻辑:由 admin 字段资产 API 与 Schema 采用校验调用;禁止物理删除与标准字段弃用;
|
||||
禁止将 mail/context 类编码登记为订单字段资产。
|
||||
禁止将 mail/context 类编码经 create_extension 登记;sender_email/domain 仅由种子写入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -34,6 +34,20 @@ FORBIDDEN_CONTEXT_CODES = frozenset({
|
||||
'mail_from', 'mail_domain',
|
||||
})
|
||||
|
||||
# 系统种子上下文字段:禁止经 create_extension 登记,仅由 ensure_context_assets_seeded 写入。
|
||||
CONTEXT_FIELD_SPECS: tuple[dict[str, str], ...] = (
|
||||
{
|
||||
'field_code': 'sender_email',
|
||||
'display_name': '发件人邮箱',
|
||||
'semantic_description': '从原始 EML From 确定性采集的发件人邮箱;不可经扩展资产 API 创建。',
|
||||
},
|
||||
{
|
||||
'field_code': 'sender_domain',
|
||||
'display_name': '发件人域名',
|
||||
'semantic_description': '从原始 EML From 确定性采集的发件人域名;不可经扩展资产 API 创建。',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
"""将可空时间转换为 API ISO 字符串。"""
|
||||
@@ -160,7 +174,7 @@ def _storage_descriptor(field: ShippingOrderField) -> dict[str, str]:
|
||||
|
||||
def ensure_standard_assets_seeded(*, actor_id: int | None = None) -> int:
|
||||
"""
|
||||
确保 57 项标准资产已落库;缺失则补齐;已存在则强制校验锁定属性与注册表一致。
|
||||
确保 58 项标准资产已落库;缺失则补齐;已存在则强制校验锁定属性与注册表一致。
|
||||
|
||||
Returns:
|
||||
本次新插入的标准字段数量。
|
||||
@@ -170,12 +184,12 @@ def ensure_standard_assets_seeded(*, actor_id: int | None = None) -> int:
|
||||
"""
|
||||
assert_registry_consistent()
|
||||
existing = {
|
||||
row.field_code: row
|
||||
(row.scope, row.field_code): row
|
||||
for row in ShippingOrderField.query.filter_by(asset_kind='system_standard').all()
|
||||
}
|
||||
inserted = 0
|
||||
for sequence, spec in enumerate(STANDARD_FIELD_SPECS.values(), start=1):
|
||||
row = existing.get(spec.field_code)
|
||||
row = existing.get((spec.scope, spec.field_code))
|
||||
if row is not None:
|
||||
# [STEP] 注册表是唯一事实:已存在行必须与锁定属性一致,禁止静默沿用脏数据。
|
||||
mismatches: list[str] = []
|
||||
@@ -224,6 +238,62 @@ def ensure_standard_assets_seeded(*, actor_id: int | None = None) -> int:
|
||||
return inserted
|
||||
|
||||
|
||||
def ensure_context_assets_seeded(*, actor_id: int | None = None) -> int:
|
||||
"""
|
||||
幂等补齐邮件确定性上下文字段资产(sender_email / sender_domain)。
|
||||
|
||||
核心逻辑:仅允许本函数写入 FORBIDDEN_CONTEXT_CODES;create_extension 仍拒绝同名编码。
|
||||
collection_mode=deterministic_context,供 Schema 发布快照与运行时 mail_header 链路使用。
|
||||
|
||||
Returns:
|
||||
本次新插入的上下文字段数量。
|
||||
"""
|
||||
existing = {
|
||||
row.field_code: row
|
||||
for row in ShippingOrderField.query.filter(
|
||||
ShippingOrderField.field_code.in_([item['field_code'] for item in CONTEXT_FIELD_SPECS]),
|
||||
).all()
|
||||
}
|
||||
next_sequence = (db.session.query(func.max(ShippingOrderField.display_sequence)).scalar() or 0) + 1
|
||||
inserted = 0
|
||||
for spec in CONTEXT_FIELD_SPECS:
|
||||
code = spec['field_code']
|
||||
row = existing.get(code)
|
||||
if row is not None:
|
||||
# [STEP] 已存在行纠偏为确定性上下文形态,避免治理迁移后脏成 llm_extraction。
|
||||
row.scope = 'header'
|
||||
row.value_type = 'string'
|
||||
row.field_category = 'general_context'
|
||||
row.collection_mode = 'deterministic_context'
|
||||
row.storage_mode = 'json_only'
|
||||
row.storage_column = None
|
||||
row.status = 'active'
|
||||
if not row.display_name_default:
|
||||
row.display_name_default = spec['display_name']
|
||||
if not row.semantic_description:
|
||||
row.semantic_description = spec['semantic_description']
|
||||
continue
|
||||
db.session.add(ShippingOrderField(
|
||||
field_code=code,
|
||||
scope='header',
|
||||
value_type='string',
|
||||
field_category='general_context',
|
||||
collection_mode='deterministic_context',
|
||||
asset_kind='extension',
|
||||
storage_mode='json_only',
|
||||
storage_column=None,
|
||||
semantic_description=spec['semantic_description'],
|
||||
display_name_default=spec['display_name'],
|
||||
display_sequence=next_sequence + inserted,
|
||||
status='active',
|
||||
created_by_id=actor_id,
|
||||
))
|
||||
inserted += 1
|
||||
if inserted:
|
||||
db.session.flush()
|
||||
return inserted
|
||||
|
||||
|
||||
def list_assets(
|
||||
*,
|
||||
q: str | None = None,
|
||||
@@ -233,6 +303,7 @@ def list_assets(
|
||||
) -> dict[str, Any]:
|
||||
"""列出字段资产,支持搜索与筛选。"""
|
||||
ensure_standard_assets_seeded()
|
||||
ensure_context_assets_seeded()
|
||||
query = ShippingOrderField.query
|
||||
if asset_kind in {'system_standard', 'extension'}:
|
||||
query = query.filter_by(asset_kind=asset_kind)
|
||||
|
||||
@@ -1,16 +1,46 @@
|
||||
"""货代撤销完成后的版本链解除服务。"""
|
||||
"""
|
||||
services/shipping_notice/freight_cancellation_service.py
|
||||
|
||||
用途:货代撤销回执登记,以及建单后取消时的只读 / 待作废软处置(禁止物理删除)。
|
||||
依赖:ShippingFreightCancellation、ShippingTask、ShippingTaskEvent、Workflow Item Version、
|
||||
fulfillment_audit。
|
||||
逻辑:complete_freight_cancellation 登记回执并作废旧任务;mark_cancelled_task_readonly
|
||||
在用户取消已建单 WorkflowItem 时将 Task 置 pending_void、Excel/Version 只读,
|
||||
并写前后快照审计。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import ShippingFreightCancellation, ShippingTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
|
||||
def complete_freight_cancellation(*, cancellation_id: int, actor_id: int, freight_receipt_no: str, receipt_asset_id: int, note: str | None = None) -> ShippingFreightCancellation:
|
||||
"""登记可追溯的货代撤销回执,随后作废旧任务并解除新版本的履约阻断。"""
|
||||
def complete_freight_cancellation(
|
||||
*,
|
||||
cancellation_id: int,
|
||||
actor_id: int,
|
||||
freight_receipt_no: str,
|
||||
receipt_asset_id: int,
|
||||
note: str | None = None,
|
||||
) -> ShippingFreightCancellation:
|
||||
"""
|
||||
登记可追溯的货代撤销回执,随后作废旧任务并解除新版本的履约阻断。
|
||||
|
||||
Args:
|
||||
cancellation_id: 撤销单主键。
|
||||
actor_id: 操作人。
|
||||
freight_receipt_no: 货代回执号。
|
||||
receipt_asset_id: 回执 FileAsset。
|
||||
note: 可选备注。
|
||||
|
||||
Returns:
|
||||
更新后的 ShippingFreightCancellation。
|
||||
"""
|
||||
row = ShippingFreightCancellation.query.filter_by(id=int(cancellation_id)).with_for_update().one_or_none()
|
||||
if row is None:
|
||||
raise NotFoundError('Freight cancellation not found', code='SHIPPING.FREIGHT_CANCELLATION_NOT_FOUND')
|
||||
@@ -39,3 +69,98 @@ def complete_freight_cancellation(*, cancellation_id: int, actor_id: int, freigh
|
||||
db.session.add(ShippingTaskEvent(task_id=old.id, event_type='freight_cancellation_completed', actor_id=actor_id, detail_json={'cancellation_id': row.id, 'receipt_no': receipt, 'new_task_no': new.task_no}))
|
||||
db.session.add(ShippingTaskEvent(task_id=new.id, event_type='supersession_unblocked', actor_id=actor_id, detail_json={'cancellation_id': row.id, 'old_task_no': old.task_no}))
|
||||
return row
|
||||
|
||||
|
||||
def _task_cancel_snapshot(task: ShippingTask) -> dict[str, Any]:
|
||||
"""构造取消处置前后快照(白名单字段)。"""
|
||||
return {
|
||||
'task_no': str(task.task_no),
|
||||
'lifecycle_status': str(task.lifecycle_status or ''),
|
||||
'process_status': str(task.process_status or ''),
|
||||
'export_file_name': task.export_file_name,
|
||||
'void_reason': task.void_reason,
|
||||
'pending_human_reason': task.pending_human_reason,
|
||||
}
|
||||
|
||||
|
||||
def mark_cancelled_task_readonly(
|
||||
*,
|
||||
task: ShippingTask,
|
||||
actor_id: int,
|
||||
reason: str,
|
||||
workflow_item_no: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
建单后取消:Task 置 pending_void、Excel/Version 只读,禁止物理删除。
|
||||
|
||||
核心逻辑:不 unlink 导出文件、不 purge 任务行;写统一审计(reason + before/after)。
|
||||
|
||||
Args:
|
||||
task: 已加载且加锁的 ShippingTask。
|
||||
actor_id: 取消操作人。
|
||||
reason: 必填取消原因。
|
||||
workflow_item_no: 可选关联 WorkflowItem 编号。
|
||||
|
||||
Returns:
|
||||
含 before/after 的处置摘要。
|
||||
|
||||
Raises:
|
||||
ValidationError: 原因为空。
|
||||
"""
|
||||
reason_text = str(reason or '').strip()
|
||||
if not reason_text:
|
||||
raise ValidationError('reason is required', code='SHIPPING.TASK_CANCEL_REASON_REQUIRED')
|
||||
before = _task_cancel_snapshot(task)
|
||||
# 已作废/待作废幂等:保持只读,不重复覆盖原因以外的业务字段。
|
||||
if str(task.lifecycle_status or '').strip().lower() not in {'voided', 'pending_void'}:
|
||||
task.lifecycle_status = 'pending_void'
|
||||
task.void_reason = reason_text
|
||||
task.pending_human_reason = 'pending_void'
|
||||
# Version / Excel 只读:按任务号定位当前 Workflow Version。
|
||||
from app.models.shipping_notice_workflow import ShippingNoticeWorkflowItemVersion
|
||||
|
||||
versions = (
|
||||
ShippingNoticeWorkflowItemVersion.query
|
||||
.filter_by(task_no=str(task.task_no))
|
||||
.all()
|
||||
)
|
||||
for version in versions:
|
||||
version.is_readonly = True
|
||||
version.updated_at = datetime.utcnow()
|
||||
after = _task_cancel_snapshot(task)
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=int(task.id),
|
||||
event_type='task_pending_void',
|
||||
actor_id=int(actor_id),
|
||||
detail_json={
|
||||
'reason': reason_text,
|
||||
'workflow_item_no': workflow_item_no,
|
||||
'before': before,
|
||||
'after': after,
|
||||
},
|
||||
))
|
||||
record_fulfillment_audit(
|
||||
event_type='task_pending_void',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=str(task.task_no),
|
||||
action='cancel_after_order_created',
|
||||
actor_type='user',
|
||||
actor_id=int(actor_id),
|
||||
task_no=str(task.task_no),
|
||||
workflow_item_id=workflow_item_no,
|
||||
conversation_id=task.conversation_id,
|
||||
reason=reason_text,
|
||||
before=before,
|
||||
after=after,
|
||||
metadata={'physical_delete': False, 'excel_readonly': True},
|
||||
source='workspace_api',
|
||||
)
|
||||
db.session.flush()
|
||||
return {
|
||||
'task_no': task.task_no,
|
||||
'lifecycle_status': task.lifecycle_status,
|
||||
'before': before,
|
||||
'after': after,
|
||||
'readonly': True,
|
||||
'physical_delete': False,
|
||||
}
|
||||
@@ -3,9 +3,9 @@ services/shipping_notice/fulfillment_audit.py
|
||||
|
||||
用途:履约关键节点与敏感访问写入统一审计事件的轻量封装。
|
||||
依赖:audit_service.append_shipping_audit_event、Flask g.request_id / request、AppError。
|
||||
逻辑:由 candidate / decision / fulfillment_workflow / workspace 读取与导出 / 工作项写路径调用;
|
||||
逻辑:由 candidate / decision / fulfillment_workflow / workspace 读取与导出 / Workflow 写路径调用;
|
||||
默认 strict=True,审计写入失败时抛错,禁止业务成功而审计缺失;访问审计逐次留痕;
|
||||
自动附带 request_id 与客户端 IP/UA(仅哈希入库)。
|
||||
自动附带 request_id 与客户端 IP/UA(仅哈希入库);透传 Workflow 软引用字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -74,26 +74,34 @@ def record_fulfillment_audit(
|
||||
document_id: str | int | None = None,
|
||||
review_case_no: str | None = None,
|
||||
conversation_id: str | None = None,
|
||||
session_item_id: str | None = None,
|
||||
workflow_id: str | None = None,
|
||||
workflow_item_id: str | None = None,
|
||||
workflow_item_version_id: str | None = None,
|
||||
version_no: int | None = None,
|
||||
owner_user_id: str | int | None = None,
|
||||
reason_code: str | None = None,
|
||||
reason: str | None = None,
|
||||
result: str = 'success',
|
||||
error_code: str | None = None,
|
||||
before: dict[str, Any] | None = None,
|
||||
after: dict[str, Any] | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
source: str = 'api',
|
||||
strict: bool = True,
|
||||
sensitivity_level: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
追加履约审计。
|
||||
|
||||
核心逻辑:默认与业务同事务写入;strict=True 时失败抛错,保证必须留存;
|
||||
自动附带 request_id 与客户端 IP/UA 哈希。
|
||||
自动附带 request_id 与客户端 IP/UA 哈希;透传 Workflow 软引用。
|
||||
|
||||
Args:
|
||||
event_type/action: 稳定事件与动作码。
|
||||
workflow_id/workflow_item_id/workflow_item_version_id/version_no: Workflow 软引用。
|
||||
before/after: 必须已是白名单可投影的状态摘要。
|
||||
error_code: 拒绝/失败时的稳定业务错误码。
|
||||
sensitivity_level: 可选敏感分级(如 sensitive),透传审计表。
|
||||
strict: True 时审计失败阻断调用方;False 时仅记日志(仅限显式降级场景)。
|
||||
"""
|
||||
request_id = _request_id()
|
||||
@@ -113,17 +121,22 @@ def record_fulfillment_audit(
|
||||
document_id=document_id,
|
||||
review_case_no=review_case_no,
|
||||
conversation_id=conversation_id,
|
||||
session_item_id=session_item_id,
|
||||
workflow_id=workflow_id,
|
||||
workflow_item_id=workflow_item_id,
|
||||
workflow_item_version_id=workflow_item_version_id,
|
||||
version_no=version_no,
|
||||
owner_user_id=owner_user_id,
|
||||
client_ip=client_ip,
|
||||
user_agent=user_agent,
|
||||
reason_code=reason_code,
|
||||
reason=reason,
|
||||
result=result,
|
||||
error_code=error_code,
|
||||
before=before,
|
||||
after=after,
|
||||
metadata=metadata or {},
|
||||
source=source,
|
||||
sensitivity_level=sensitivity_level,
|
||||
)
|
||||
except Exception as exc:
|
||||
_LOGGER.exception('fulfillment audit append failed event_type=%s aggregate_id=%s', event_type, aggregate_id)
|
||||
@@ -147,7 +160,10 @@ def record_access_audit(
|
||||
document_id: str | int | None = None,
|
||||
review_case_no: str | None = None,
|
||||
conversation_id: str | None = None,
|
||||
session_item_id: str | None = None,
|
||||
workflow_id: str | None = None,
|
||||
workflow_item_id: str | None = None,
|
||||
workflow_item_version_id: str | None = None,
|
||||
version_no: int | None = None,
|
||||
owner_user_id: str | int | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
strict: bool = True,
|
||||
@@ -179,7 +195,10 @@ def record_access_audit(
|
||||
document_id=document_id,
|
||||
review_case_no=review_case_no,
|
||||
conversation_id=conversation_id,
|
||||
session_item_id=session_item_id,
|
||||
workflow_id=workflow_id,
|
||||
workflow_item_id=workflow_item_id,
|
||||
workflow_item_version_id=workflow_item_version_id,
|
||||
version_no=version_no,
|
||||
owner_user_id=owner_user_id,
|
||||
client_ip=client_ip,
|
||||
user_agent=user_agent,
|
||||
@@ -187,6 +206,7 @@ def record_access_audit(
|
||||
metadata=metadata or {'access': True},
|
||||
source='api',
|
||||
persist_snapshots=False,
|
||||
sensitivity_level='sensitive',
|
||||
)
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
"""
|
||||
services/shipping_notice/fulfillment_workflow.py
|
||||
|
||||
用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传/RPA 与自动串联编排。
|
||||
依赖:customer_identity_gate、reservation_gate、match、export、rpa、query_service、inventory_workflow、inventory_mapping_workflow、动态订单字段、tool_common、tool_response。
|
||||
用途:发货通知履约阶段 — 库存匹配、Excel 导出、人工上传凭据登记与自动串联编排。
|
||||
依赖:customer_identity_gate、reservation_gate、match、export、query_service、inventory_workflow、
|
||||
inventory_mapping_workflow、stp_line_inventory_match、upload_attempt_service、动态订单字段、
|
||||
tool_common、tool_response、fulfillment_audit。
|
||||
逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match;
|
||||
订单行按锁定 Schema 的业务用途从当前 Extraction FieldValue 读取;
|
||||
STP:auto_progress / try_auto_chain_after_match 止于 Excel 待人工上传;
|
||||
无论 AUTO_UPLOAD 开关为何值,自动链均不调用 upload_to_freight。
|
||||
STP 多候选:跨文件匹配后仅全部 ok 记 completed+100% 并自动 Excel;partial/冲突记 needs_human;
|
||||
STP:auto_progress / try_auto_chain_after_match 止于 Excel 后待人工上传登记(manual_upload_pending);
|
||||
工作台操作人经 operator_id / actor_id / _trusted_user_id 写入匹配与审计事件;
|
||||
upload_to_freight 仅允许 mode=manual_confirm(工作台 mark-manual-uploaded);禁止 RPA auto/retry。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,7 +24,7 @@ from flask import current_app
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.constants import CP_UPLOADED, PH_UPLOAD_RPA_PENDING, PH_UPLOAD_RESULT_UNKNOWN
|
||||
from app.services.shipping_notice.constants import CP_UPLOADED
|
||||
from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
|
||||
from app.services.shipping_notice.inventory_workflow import (
|
||||
@@ -38,14 +41,7 @@ from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.order_field_purposes import task_line_purpose_values
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
|
||||
from app.services.shipping_notice.rpa import write_upload_trigger
|
||||
from app.services.shipping_notice.upload_attempt_service import (
|
||||
complete_attempt,
|
||||
current_upload_artifact,
|
||||
mark_attempt_result_unknown,
|
||||
record_manual_upload,
|
||||
start_rpa_attempt,
|
||||
)
|
||||
from app.services.shipping_notice.upload_attempt_service import complete_attempt, record_manual_upload
|
||||
from app.services.shipping_notice.rpa_attempts import (
|
||||
max_rpa_upload_attempts,
|
||||
upload_rpa_attempts,
|
||||
@@ -160,28 +156,114 @@ def _auto_upload_enabled() -> bool:
|
||||
return _cfg_bool("SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED", False)
|
||||
|
||||
|
||||
def _rpa_upload_timeout_seconds() -> int:
|
||||
return _cfg_int("SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS", 30, min_value=5)
|
||||
|
||||
|
||||
def _event_actor_id(payload: dict[str, Any]) -> int | None:
|
||||
"""解析工作台传入的操作人;缺失时明确按系统自动动作记录。"""
|
||||
"""
|
||||
解析工作台传入的操作人;缺失时明确按系统自动动作记录。
|
||||
|
||||
核心逻辑:兼容 operator_id / actor_id / _trusted_user_id(工作台 API 统一注入)。
|
||||
"""
|
||||
try:
|
||||
value = payload.get('operator_id') or payload.get('actor_id')
|
||||
value = (
|
||||
payload.get('operator_id')
|
||||
or payload.get('actor_id')
|
||||
or payload.get('_trusted_user_id')
|
||||
)
|
||||
return int(value) if value is not None else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def match_completed(task: ShippingTask) -> bool:
|
||||
"""滚动履约只要求至少一个预约单完整满足,partial 也可进入本轮制单。"""
|
||||
return bool(
|
||||
task.match_status in {"fulfillable", "partial"}
|
||||
and isinstance(task.line_results_json, list)
|
||||
and any(str(item.get('line_status') or '') == 'ok' for item in task.line_results_json if isinstance(item, dict))
|
||||
def _sync_workflow_stage(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
lifecycle_status: str,
|
||||
event_code: str,
|
||||
actor_id: int | None = None,
|
||||
payload: dict[str, Any] | None = None,
|
||||
excel_artifact_no: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
将任务绑定的 WorkflowItem 推进到履约阶段;未绑定则静默跳过。
|
||||
|
||||
Args:
|
||||
task: 当前任务。
|
||||
lifecycle_status: 目标 Item 生命周期。
|
||||
event_code: WorkflowEvent 事件码。
|
||||
actor_id: 可选操作人。
|
||||
payload / excel_artifact_no: 可选事件载荷与 Excel 工件号。
|
||||
"""
|
||||
from app.services.shipping_notice.workflow_ledger_service import sync_workflow_item_stage_for_task
|
||||
|
||||
sync_workflow_item_stage_for_task(
|
||||
task_no=str(task.task_no),
|
||||
lifecycle_status=lifecycle_status,
|
||||
event_code=event_code,
|
||||
actor_type='user' if actor_id else 'system',
|
||||
actor_id=actor_id,
|
||||
payload=payload,
|
||||
excel_artifact_no=excel_artifact_no,
|
||||
)
|
||||
|
||||
|
||||
def match_completed(task: ShippingTask) -> bool:
|
||||
"""
|
||||
STP 制单门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时允许生成 Excel。
|
||||
|
||||
核心逻辑:禁止 partial / 任意一行短缺、冲突、未命中进入自动制单或 Excel 门禁。
|
||||
"""
|
||||
if str(task.match_status or '').strip() != 'fulfillable':
|
||||
return False
|
||||
lines = task.line_results_json
|
||||
if not isinstance(lines, list) or not lines:
|
||||
return False
|
||||
return all(
|
||||
isinstance(item, dict)
|
||||
and str(item.get('line_status') or item.get('disposition') or '').strip() == 'ok'
|
||||
for item in lines
|
||||
)
|
||||
|
||||
|
||||
def _match_step_progress_fields(
|
||||
*,
|
||||
match_status: str,
|
||||
line_results: list[Any],
|
||||
lang: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构造库存匹配步骤的 status / 进度 / 明细文案。
|
||||
|
||||
核心逻辑:仅 fulfillable 记 completed+100%;partial 与 unfulfillable 一律 needs_human,
|
||||
进度按 ok 行占比封顶 99,避免 UI 误判为匹配完成。
|
||||
"""
|
||||
status_value = str(match_status or '').strip()
|
||||
total = len(line_results)
|
||||
ok_count = sum(
|
||||
1
|
||||
for item in line_results
|
||||
if isinstance(item, dict)
|
||||
and str(item.get('line_status') or item.get('disposition') or '').strip() == 'ok'
|
||||
)
|
||||
fully_ok = status_value == 'fulfillable'
|
||||
if fully_ok:
|
||||
return {
|
||||
'status': 'completed',
|
||||
'progress_percent': 100,
|
||||
'current': total,
|
||||
'total': total or None,
|
||||
'message': t('workflow.fulfillment.match_completed', lang=lang),
|
||||
'detail': t('workflow.fulfillment.match_completed_ok_detail', lang=lang).format(count=total),
|
||||
}
|
||||
progress_percent = min(99, int((ok_count * 100) / total)) if total else 0
|
||||
return {
|
||||
'status': 'needs_human',
|
||||
'progress_percent': progress_percent,
|
||||
'current': total,
|
||||
'total': total or None,
|
||||
'message': t('workflow.fulfillment.match_completed_shortage_detail', lang=lang).format(count=total),
|
||||
'detail': t('workflow.fulfillment.match_completed_shortage_detail', lang=lang).format(count=total),
|
||||
}
|
||||
|
||||
|
||||
def excel_gate_error(task: ShippingTask) -> str | None:
|
||||
"""校验 generate_excel 前置条件;不满足时返回中文错误提示,满足时返回 None。"""
|
||||
if task.process_status == "uploaded" and task.export_file_path:
|
||||
@@ -192,15 +274,6 @@ def excel_gate_error(task: ShippingTask) -> str | None:
|
||||
|
||||
|
||||
|
||||
def latest_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent | None:
|
||||
"""按 event_type 查询任务最近一条 ShippingTaskEvent(RPA 超时/重试判定用)。"""
|
||||
if task.id is None:
|
||||
return None
|
||||
return (
|
||||
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type=event_type)
|
||||
.order_by(ShippingTaskEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
def should_auto_chain_after_match(payload: dict[str, Any] | None) -> bool:
|
||||
"""是否应在 match 成功后自动串联低风险履约步骤。
|
||||
|
||||
@@ -219,10 +292,10 @@ def try_auto_chain_after_match(
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
匹配成功后自动串联 Excel 导出,并停在待人工上传(STP)。
|
||||
匹配成功后自动串联 Excel 导出,并停在 wait_manual_upload(待人工上传登记)。
|
||||
|
||||
核心逻辑:match_result 为 ok 后默认自动生成 Excel;无论
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 为何值,首期硬禁止自动货代 RPA 上传。
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 为何值,硬禁止自动货代 RPA 上传。
|
||||
|
||||
Args:
|
||||
task: 当前 ShippingTask。
|
||||
@@ -262,7 +335,10 @@ def try_auto_chain_after_match(
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message=str(result.get("message") or "发货 Excel 已生成,请在任务处理工作台完成人工上传凭据。"),
|
||||
message=str(
|
||||
result.get("message")
|
||||
or "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。"
|
||||
),
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint,
|
||||
@@ -365,6 +441,13 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
order_line['__display_part_number'] = purpose_line.get('part_number')
|
||||
order_line['__display_reservation_id'] = purpose_line.get('reservation_id')
|
||||
total_notice_lines = len(order_field_lines)
|
||||
_sync_workflow_stage(
|
||||
task,
|
||||
lifecycle_status='inventory_matching',
|
||||
event_code='inventory_match_started',
|
||||
actor_id=actor_id,
|
||||
payload={'task_no': task.task_no},
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
@@ -388,7 +471,111 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
# [STEP 3] 执行匹配并按结果分流;partial 有完整满足预约单时也可滚动制单。
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
from app.services.shipping_notice.stp_line_inventory_match import (
|
||||
apply_forced_match_source_filter,
|
||||
apply_line_inventory_resolutions,
|
||||
match_order_lines_across_candidates,
|
||||
snapshot_header_reservation_id,
|
||||
)
|
||||
|
||||
# [STEP 3] STP:冻结多候选时按 Reservation+PartNumber 跨文件匹配,禁止回读路由。
|
||||
# 人工指定源后仅保留 forced_match_source_code 对应库存行,消解多源/多文件冲突。
|
||||
inventory_lines = apply_forced_match_source_filter(inventory_lines or [], task=task)
|
||||
use_stp_cross_match = (
|
||||
str(task.inventory_source_status or '').strip() == 'candidates_frozen'
|
||||
or len(task_frozen_inventory_source_codes(task)) > 1
|
||||
or any(isinstance(row, dict) and row.get('__source_code') for row in (inventory_lines or []))
|
||||
)
|
||||
if use_stp_cross_match:
|
||||
header_reservation = None
|
||||
snapshot = None
|
||||
if task.order_snapshot_id:
|
||||
from app.models import ShippingOrderSnapshot
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
|
||||
if snapshot is not None:
|
||||
header_reservation = snapshot_header_reservation_id(snapshot)
|
||||
stp_order_lines = []
|
||||
for index, purpose_line in enumerate(purpose_lines):
|
||||
stp_order_lines.append({
|
||||
**purpose_line,
|
||||
'__required_qty': purpose_line.get('quantity'),
|
||||
'__display_part_number': purpose_line.get('part_number'),
|
||||
'__display_reservation_id': purpose_line.get('reservation_id'),
|
||||
'line_key': (order_field_lines[index] if index < len(order_field_lines) else {}).get('line_key'),
|
||||
})
|
||||
match_payload = match_order_lines_across_candidates(
|
||||
order_lines=stp_order_lines,
|
||||
inventory_lines=inventory_lines or [],
|
||||
header_reservation_id=header_reservation,
|
||||
)
|
||||
apply_line_inventory_resolutions(task, match_payload)
|
||||
match_status = str(match_payload.get('match_status') or 'unfulfillable')
|
||||
line_results = list(match_payload.get('line_results') or [])
|
||||
from app.services.shipping_notice.reservation_service import record_inventory_verification
|
||||
verification = record_inventory_verification(
|
||||
task, inventory_snapshot_id=task.inventory_snapshot_id,
|
||||
source_config_version=task.inventory_source_config_version, line_results=line_results,
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
step_title="匹配库存",
|
||||
**_match_step_progress_fields(
|
||||
match_status=match_status,
|
||||
line_results=line_results,
|
||||
lang=lang,
|
||||
),
|
||||
)
|
||||
match_summary = format_match_summary(
|
||||
match_status,
|
||||
line_results,
|
||||
task_no=task.task_no,
|
||||
lang=lang,
|
||||
)
|
||||
# STP:仅全部明细 ok(match_completed)且已投影库存源时自动制单。
|
||||
if match_completed(task) and task.inventory_source_code:
|
||||
apply_task_transition(task, TaskTransition.MATCHED_FULFILLABLE)
|
||||
log_task_event(
|
||||
task,
|
||||
"matched_stp_candidates",
|
||||
{
|
||||
"match_status": match_status,
|
||||
"verification_id": verification.id,
|
||||
"resolved_ok_source_codes": (task.step_payload_json or {}).get('resolved_ok_source_codes'),
|
||||
"excel_binding_source_code": task.inventory_source_code,
|
||||
},
|
||||
actor_id=actor_id,
|
||||
source='workspace_api' if actor_id else 'system',
|
||||
)
|
||||
db.session.commit()
|
||||
match_result = tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
message=match_summary,
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
return try_auto_chain_after_match(task, match_result, payload=payload)
|
||||
apply_task_transition(task, TaskTransition.MATCH_SHORTAGE)
|
||||
log_task_event(
|
||||
task,
|
||||
"matched_multi_file_conflict" if any(str(item.get('disposition') or '') == 'multi_file_conflict' for item in line_results) else "matched_shortage",
|
||||
{"match_status": match_status},
|
||||
actor_id=actor_id,
|
||||
source='workspace_api' if actor_id else 'system',
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=match_summary,
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint="shortage_review",
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
|
||||
)
|
||||
|
||||
# [STEP 3b] 单源历史路径:按 published Profile match_keys 匹配。
|
||||
def _on_match_progress(processed: int, total: int) -> None:
|
||||
percent = 10 if total <= 0 else min(95, max(10, int(processed * 100 / total)))
|
||||
set_task_step_progress(
|
||||
@@ -440,15 +627,10 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
step_title="匹配库存",
|
||||
status="needs_human" if match_status == "unfulfillable" else "completed",
|
||||
message=t("workflow.fulfillment.match_completed", lang=lang),
|
||||
progress_percent=100,
|
||||
current=len(line_results),
|
||||
total=len(line_results),
|
||||
detail=(
|
||||
t("workflow.fulfillment.match_completed_ok_detail", lang=lang).format(count=len(line_results))
|
||||
if match_status in {"fulfillable", "partial"}
|
||||
else t("workflow.fulfillment.match_completed_shortage_detail", lang=lang).format(count=len(line_results))
|
||||
**_match_step_progress_fields(
|
||||
match_status=match_status,
|
||||
line_results=line_results,
|
||||
lang=lang,
|
||||
),
|
||||
)
|
||||
match_summary = format_match_summary(
|
||||
@@ -458,7 +640,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
lang=lang,
|
||||
)
|
||||
|
||||
if match_status in {"fulfillable", "partial"} and match_completed(task):
|
||||
if match_completed(task):
|
||||
apply_task_transition(task, TaskTransition.MATCHED_FULFILLABLE)
|
||||
log_task_event(task, "matched_rolling_available", {"match_status": match_status, "verification_id": verification.id}, actor_id=actor_id, source='workspace_api' if actor_id else 'system')
|
||||
db.session.commit()
|
||||
@@ -589,6 +771,13 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
progress_percent=60,
|
||||
detail=t("workflow.fulfillment.generate_running_detail", lang=lang),
|
||||
)
|
||||
_sync_workflow_stage(
|
||||
task,
|
||||
lifecycle_status='generating_excel',
|
||||
event_code='excel_generate_started',
|
||||
actor_id=actor_id,
|
||||
payload={'task_no': task.task_no},
|
||||
)
|
||||
|
||||
# [STEP 3] 生成文件并把任务推进到等待上传阶段。
|
||||
# 导出文件路径会成为后续 RPA 上传或人工下载的唯一输入。
|
||||
@@ -630,6 +819,15 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
metadata={'artifact_no': artifact.artifact_no},
|
||||
source='workspace_api' if actor_id else 'system',
|
||||
)
|
||||
# Phase 3:自动链停点 — Excel 后进入待人工上传登记;永不触发货代 RPA。
|
||||
_sync_workflow_stage(
|
||||
task,
|
||||
lifecycle_status='manual_upload_pending',
|
||||
event_code='manual_upload_pending',
|
||||
actor_id=actor_id,
|
||||
payload={'task_no': task.task_no, 'artifact_no': artifact.artifact_no},
|
||||
excel_artifact_no=str(artifact.artifact_no),
|
||||
)
|
||||
_commit_generated_export(path)
|
||||
return tool_response(
|
||||
status="ok",
|
||||
@@ -644,10 +842,11 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
登记人工货代上传完成(首期唯一上传收口)。
|
||||
【AI 触发时机】:禁止调用;仅工作台 mark-manual-uploaded 以 mode=manual_confirm 调用。
|
||||
|
||||
核心逻辑:首期硬拒绝 auto/retry_upload(不触发货代 RPA);manual_confirm 校验凭据后标记 UPLOADED。
|
||||
核心逻辑:硬拒绝 auto/retry_upload(不触发货代 RPA);manual_confirm 校验凭据后标记 UPLOADED,
|
||||
写履约审计并将 WorkflowItem 以 closed_reason=confirmed 收口。
|
||||
|
||||
Args:
|
||||
payload: 须含 task_id;mode 必须为 manual_confirm;须传 evidence_asset_no。
|
||||
payload: 须含 task_id;mode 必须为 manual_confirm;须含 evidence_asset_no、operator_id。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: status 可为 ok / failed。
|
||||
@@ -690,8 +889,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if gen.get("status") != "ok":
|
||||
return gen
|
||||
|
||||
# [STEP 2] 区分人工确认与 RPA 上传两种路径。
|
||||
# 首期 STP:仅允许 manual_confirm(外部货代上传后登记凭据);禁止 auto/retry_upload 触发 RPA。
|
||||
# [STEP 2] 仅允许 manual_confirm;禁止 auto/retry_upload 触发 RPA。
|
||||
artifact_id = payload.get('artifact_id')
|
||||
try:
|
||||
artifact_id = int(artifact_id) if artifact_id is not None else None
|
||||
@@ -703,224 +901,84 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
message="首期不支持货代 RPA 自动上传。请下载 Excel,在货代系统人工上传后,于任务处理工作台提交截图/PDF 凭据。",
|
||||
message=(
|
||||
"首期不支持货代 RPA 自动上传。请下载 Excel,在货代系统人工上传后,"
|
||||
"于任务处理工作台提交截图/PDF 凭据。"
|
||||
),
|
||||
data=serialize_task_for_tool(task),
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
stop_agent_turn=True,
|
||||
next_required_action="请在任务处理工作台使用「登记人工上传」。",
|
||||
)
|
||||
|
||||
# manual_confirm 需要私有回执;auto/retry_upload 已在上方拒绝。
|
||||
if mode == "manual_confirm":
|
||||
operator_id = payload.get('operator_id')
|
||||
try:
|
||||
attempt = record_manual_upload(
|
||||
task, artifact_id=artifact_id, evidence_asset_no=str(payload.get('evidence_asset_no') or ''),
|
||||
operator_id=int(operator_id), freight_ref_no=str(payload.get('freight_ref_no') or ''),
|
||||
)
|
||||
except (ConflictError, ValidationError) as exc:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
log_task_event(task, 'upload_manual_confirmed', {'artifact_id': attempt.artifact_id, 'attempt_id': attempt.id}, actor_id=attempt.operator_id, source='workspace_api')
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.fulfillment.manual_done_message", lang=lang).format(task_no=task.task_no),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOADED if task.process_status == 'uploaded' else None,
|
||||
human_options=[] if task.process_status == 'uploaded' else None,
|
||||
operator_id = payload.get('operator_id')
|
||||
evidence_asset_no = str(payload.get('evidence_asset_no') or '')
|
||||
freight_ref_no = str(payload.get('freight_ref_no') or '')
|
||||
before_status = str(task.process_status or '')
|
||||
try:
|
||||
attempt = record_manual_upload(
|
||||
task,
|
||||
artifact_id=artifact_id,
|
||||
evidence_asset_no=evidence_asset_no,
|
||||
operator_id=int(operator_id),
|
||||
freight_ref_no=freight_ref_no,
|
||||
)
|
||||
except (ConflictError, ValidationError, TypeError, ValueError) as exc:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
|
||||
# [STEP 3] 处理 RPA 上传状态机。
|
||||
# 包括超时检测、最大重试次数限制、触发上传和最终人工兜底提示。
|
||||
if mode == "retry_upload" or mode == "auto":
|
||||
timeout_seconds = _rpa_upload_timeout_seconds()
|
||||
max_attempts = max_rpa_upload_attempts()
|
||||
if (
|
||||
task.pending_human_reason == PH_UPLOAD_RPA_PENDING
|
||||
and task.process_status == "waiting_upload"
|
||||
and task.export_file_path
|
||||
and task.process_status != "uploaded"
|
||||
):
|
||||
last_trigger = latest_event(task, "upload_rpa_triggered")
|
||||
if last_trigger and isinstance(last_trigger.created_at, datetime):
|
||||
elapsed = int((datetime.utcnow() - last_trigger.created_at).total_seconds())
|
||||
if elapsed < timeout_seconds:
|
||||
attempts = upload_rpa_attempts(task)
|
||||
remaining = max(timeout_seconds - elapsed, 1)
|
||||
return tool_response(
|
||||
status="running",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.fulfillment.upload_running", lang=lang).format(
|
||||
attempt=max(attempts, 1),
|
||||
max_attempts=max_attempts,
|
||||
elapsed=elapsed,
|
||||
timeout=timeout_seconds,
|
||||
remaining=remaining,
|
||||
),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"rpa": {
|
||||
"attempts": max(attempts, 1),
|
||||
"max_attempts": max_attempts,
|
||||
"elapsed_seconds": elapsed,
|
||||
"timeout_seconds": timeout_seconds,
|
||||
"retry_after_seconds": remaining,
|
||||
},
|
||||
},
|
||||
)
|
||||
last_failed = latest_event(task, "upload_rpa_failed")
|
||||
if not last_failed or (last_failed.created_at < last_trigger.created_at):
|
||||
attempt_id = (last_trigger.detail_json or {}).get('attempt_id') if isinstance(last_trigger.detail_json, dict) else None
|
||||
from app.models import ShippingUploadAttempt
|
||||
timed_out_attempt = db.session.get(ShippingUploadAttempt, attempt_id) if attempt_id else None
|
||||
if timed_out_attempt is not None:
|
||||
mark_attempt_result_unknown(timed_out_attempt)
|
||||
task.error_message = t("workflow.fulfillment.upload_timeout_error", lang=lang).format(
|
||||
timeout=timeout_seconds
|
||||
)
|
||||
task.pending_human_reason = PH_UPLOAD_RESULT_UNKNOWN
|
||||
task.upload_status = 'unknown'
|
||||
log_task_event(
|
||||
task,
|
||||
"upload_rpa_result_unknown",
|
||||
{"error": "timeout", "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message='货代上传结果未知,已冻结重试;请先核对货代结果并登记回执或明确拒绝。',
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
attempts = upload_rpa_attempts(task)
|
||||
if attempts >= max_attempts:
|
||||
apply_task_transition(task, TaskTransition.UPLOAD_FAILED)
|
||||
task.error_message = t("workflow.fulfillment.upload_exhausted", lang=lang).format(attempts=attempts)
|
||||
log_task_event(task, "upload_rpa_exhausted", {"attempts": attempts, "max_attempts": max_attempts})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=task.error_message,
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
try:
|
||||
attempt = start_rpa_attempt(task, artifact_id=artifact_id, idempotency_key=payload.get('idempotency_key'))
|
||||
artifact = current_upload_artifact(task, attempt.artifact_id)
|
||||
except (ConflictError, ValidationError) as exc:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
upload_connector_type = str(task.inventory_connector_type or '').strip().lower()
|
||||
upload_entry_url = ''
|
||||
if upload_connector_type == 'dbs' and task.inventory_source_code:
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
|
||||
source = get_rpa_trigger_inventory_source(task.inventory_source_code, enabled_only=False) or {}
|
||||
upload_entry_url = str(source.get('login_url') or source.get('entry_url') or '').strip()
|
||||
try:
|
||||
queued, trigger = write_upload_trigger(task.task_no, artifact.file_path, payload={
|
||||
'artifact_id': artifact.id, 'attempt_id': attempt.id, 'callback_id': f'rpa:{attempt.id}',
|
||||
'inventory_connector_type': upload_connector_type,
|
||||
'inventory_entry_url': upload_entry_url,
|
||||
})
|
||||
except OSError:
|
||||
queued, trigger = None, None
|
||||
if queued and trigger:
|
||||
apply_task_transition(task, TaskTransition.UPLOAD_RPA_PENDING)
|
||||
attempt_no = attempt.attempt_no
|
||||
task.upload_started_at = datetime.utcnow()
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step7_upload_freight",
|
||||
step_title="上传货代",
|
||||
status="running",
|
||||
message=t("workflow.fulfillment.upload_triggered_wait", lang=lang),
|
||||
current=attempt_no,
|
||||
total=max_attempts,
|
||||
detail=t("workflow.fulfillment.upload_triggered_detail", lang=lang).format(
|
||||
attempt=attempt_no,
|
||||
max_attempts=max_attempts,
|
||||
),
|
||||
)
|
||||
log_task_event(
|
||||
task,
|
||||
"upload_rpa_triggered",
|
||||
{
|
||||
"queue_file": queued,
|
||||
"trigger": trigger,
|
||||
"attempt": attempt_no,
|
||||
'attempt_id': attempt.id,
|
||||
'artifact_id': artifact.id,
|
||||
"timeout_seconds": timeout_seconds,
|
||||
"max_attempts": max_attempts,
|
||||
},
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
record_fulfillment_audit(
|
||||
event_type='rpa_upload_triggered',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=task.task_no,
|
||||
action='upload_rpa_triggered',
|
||||
actor_type='system',
|
||||
task_no=task.task_no,
|
||||
conversation_id=task.conversation_id,
|
||||
before={'status': 'waiting_upload'},
|
||||
after={'status': 'uploading'},
|
||||
metadata={
|
||||
'attempt_no': attempt_no,
|
||||
'max_attempts': max_attempts,
|
||||
'timeout_seconds': timeout_seconds,
|
||||
'attempt_id': int(attempt.id),
|
||||
'artifact_id': int(artifact.id),
|
||||
},
|
||||
source='rpa',
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="running",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.fulfillment.upload_triggered_message", lang=lang).format(
|
||||
attempt=attempt_no,
|
||||
max_attempts=max_attempts,
|
||||
timeout=timeout_seconds,
|
||||
),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"queue_file": queued,
|
||||
"rpa": {"attempts": attempt_no, "max_attempts": max_attempts, "timeout_seconds": timeout_seconds},
|
||||
},
|
||||
)
|
||||
|
||||
# Trigger 写入失败时,不能遗留 running Attempt / uploading Artifact;否则下一次
|
||||
# retry_upload 会被假性进行中的状态阻断。以独立 callback id 记录本地投递失败。
|
||||
complete_attempt(
|
||||
attempt,
|
||||
success=False,
|
||||
callback_id=f'trigger_failed:{attempt.id}',
|
||||
error_message='RPA upload trigger could not be written',
|
||||
)
|
||||
|
||||
apply_task_transition(task, TaskTransition.UPLOAD_FAILED)
|
||||
set_task_step_progress(
|
||||
log_task_event(
|
||||
task,
|
||||
step_key="step7_upload_freight",
|
||||
step_title="上传货代",
|
||||
status="needs_human",
|
||||
message=t("workflow.fulfillment.upload_takeover", lang=lang),
|
||||
progress_percent=100,
|
||||
detail=t("workflow.fulfillment.upload_takeover_detail", lang=lang),
|
||||
'upload_manual_confirmed',
|
||||
{'artifact_id': attempt.artifact_id, 'attempt_id': attempt.id},
|
||||
actor_id=attempt.operator_id,
|
||||
source='workspace_api',
|
||||
)
|
||||
task.error_message = t("workflow.fulfillment.upload_trigger_failed", lang=lang)
|
||||
log_task_event(task, "upload_rpa_trigger_failed", {'attempt_id': attempt.id if 'attempt' in locals() else None})
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
record_fulfillment_audit(
|
||||
event_type='upload_manual_confirmed',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=task.task_no,
|
||||
action='manual_confirm_upload',
|
||||
actor_type='user',
|
||||
actor_id=attempt.operator_id,
|
||||
task_no=task.task_no,
|
||||
conversation_id=task.conversation_id,
|
||||
before={'process_status': before_status or 'waiting_upload'},
|
||||
after={'process_status': str(task.process_status or 'uploaded')},
|
||||
metadata={
|
||||
'attempt_id': attempt.id,
|
||||
'artifact_id': attempt.artifact_id,
|
||||
'evidence_asset_no': evidence_asset_no,
|
||||
'freight_ref_no': freight_ref_no or None,
|
||||
},
|
||||
source='workspace_api',
|
||||
sensitivity_level='sensitive',
|
||||
)
|
||||
# [STEP 3] 任务已 uploaded 后关闭绑定的 WorkflowItem(confirmed)。
|
||||
# 未绑定则跳过;绑定后关闭失败须抛出,避免任务 uploaded 而 Workflow 仍待登记。
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
close_workflow_item,
|
||||
find_item_by_current_task_no,
|
||||
)
|
||||
item = find_item_by_current_task_no(task_no=str(task.task_no), for_update=True)
|
||||
if item is not None and str(item.lifecycle_status or '') not in {'closed', 'cancelled'}:
|
||||
close_workflow_item(
|
||||
item=item,
|
||||
closed_reason='confirmed',
|
||||
actor_type='user',
|
||||
actor_id=attempt.operator_id,
|
||||
task_no=str(task.task_no),
|
||||
event_type='upload_manual_confirmed',
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
status="ok",
|
||||
task=task,
|
||||
message=t("workflow.fulfillment.upload_takeover_message", lang=lang),
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.fulfillment.manual_done_message", lang=lang).format(task_no=task.task_no),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOADED if task.process_status == 'uploaded' else None,
|
||||
human_options=[] if task.process_status == 'uploaded' else None,
|
||||
)
|
||||
|
||||
|
||||
@@ -928,6 +986,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
RPA 上传货代回调入口,报告成功或失败并更新任务终态。
|
||||
【AI 触发时机】:仅由 RPA 回调 HTTP 调用,Agent 禁止主动调用。
|
||||
说明:本期主流程不触发货代 RPA 上传;本回调仅保留兼容,不应由业务主动调用。
|
||||
|
||||
核心逻辑:success=True → UPLOADED + freight_ref_no;失败 → UPLOAD_FAILED,达最大重试转人工。
|
||||
|
||||
@@ -1046,7 +1105,7 @@ def run_auto_progress_fulfillment_steps(
|
||||
"""
|
||||
auto_progress 中匹配→导出编排;有早停响应时返回 dict,否则返回 None。
|
||||
|
||||
核心逻辑:自动匹配与生成 Excel;Phase 0 STP 硬禁止自动货代上传(含 RPA),
|
||||
核心逻辑:自动匹配与生成 Excel;硬禁止自动货代上传(含 RPA),
|
||||
停在 wait_manual_upload。无论 SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 为何值,
|
||||
本函数永不调用 upload_to_freight;货代 RPA 上传不在自动链范围内。
|
||||
"""
|
||||
@@ -1072,11 +1131,11 @@ def run_auto_progress_fulfillment_steps(
|
||||
if ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or (
|
||||
task.export_file_path and task.process_status != "uploaded"
|
||||
):
|
||||
steps.append("等待人工上传货代")
|
||||
steps.append("等待人工上传登记")
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message="发货 Excel 已生成,请下载后在货代系统上传,并提交截图/PDF 凭据。",
|
||||
message="Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint,
|
||||
|
||||
@@ -4,6 +4,7 @@ services/shipping_notice/inventory_routing_engine.py
|
||||
用途:执行已发布的通用库存源路由规则并生成可解释的 Source 候选。
|
||||
依赖:库存路由模型、冻结订单 Snapshot、routing_operators。
|
||||
逻辑:只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。
|
||||
多候选为建单前正常结果(can_build=True);零候选或 require_manual_review 才阻断建单。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,13 +22,32 @@ ALLOWED_ACTIONS = frozenset({'add_source_candidates', 'exclude_source_candidates
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InventoryRoutingResult:
|
||||
"""路由引擎输出;evidence 可持久化到任务审计快照。"""
|
||||
"""
|
||||
路由引擎输出;evidence 可持久化到任务审计快照。
|
||||
|
||||
status 保留历史取值(resolved/ambiguous/unresolved/conflicted)供任务级裁决兼容;
|
||||
建单资格请以 can_build / block_reason 为准——ambiguous(多候选)允许建单。
|
||||
"""
|
||||
|
||||
status: str
|
||||
source_codes: tuple[str, ...]
|
||||
matched_rule_ids: tuple[int, ...]
|
||||
evidence: dict[str, Any]
|
||||
|
||||
@property
|
||||
def can_build(self) -> bool:
|
||||
"""是否满足「至少一枚有效库存源候选且非强制人工复核」的建单库存门禁。"""
|
||||
return bool(self.source_codes) and self.status != 'conflicted'
|
||||
|
||||
@property
|
||||
def block_reason(self) -> str | None:
|
||||
"""建单阻断原因码;可建单时为 None。"""
|
||||
if self.status == 'conflicted':
|
||||
return 'require_manual_review'
|
||||
if not self.source_codes:
|
||||
return 'no_inventory_source_candidates'
|
||||
return None
|
||||
|
||||
|
||||
def _condition_value(condition: Any, *, task: Any, line: dict[str, Any] | None) -> Any:
|
||||
"""只读取冻结 Snapshot;履约路由不得回读动态 FieldValue。"""
|
||||
@@ -46,10 +66,33 @@ def _condition_value(condition: Any, *, task: Any, line: dict[str, Any] | None)
|
||||
return (target.field_values_json or {}).get(str(condition.order_field_id)) if target is not None else None
|
||||
|
||||
|
||||
def _rule_matches(rule: ShippingInventoryRoutingRule, *, task: Any, line: dict[str, Any] | None) -> bool:
|
||||
def _condition_value_from_maps(
|
||||
condition: Any,
|
||||
*,
|
||||
header_field_values: dict[str, Any],
|
||||
line_field_values: dict[str, Any] | None,
|
||||
) -> Any:
|
||||
"""
|
||||
从 field_id→值 映射读取条件(建单前 Draft / 资格评估)。
|
||||
|
||||
核心逻辑:行级规则优先读 line_field_values;任务/表头级读 header。
|
||||
"""
|
||||
if condition.source_kind != 'order_field':
|
||||
return None
|
||||
field_id = str(condition.order_field_id or '')
|
||||
if line_field_values is not None:
|
||||
return line_field_values.get(field_id)
|
||||
return header_field_values.get(field_id)
|
||||
|
||||
|
||||
def _rule_matches(
|
||||
rule: ShippingInventoryRoutingRule,
|
||||
*,
|
||||
value_reader,
|
||||
) -> bool:
|
||||
"""判断规则条件按 all/any 语义是否命中。"""
|
||||
results = [
|
||||
matches_operator(_condition_value(condition, task=task, line=line), condition.operator, condition.expected_value_json)
|
||||
matches_operator(value_reader(condition), condition.operator, condition.expected_value_json)
|
||||
for condition in rule.conditions
|
||||
]
|
||||
if not results:
|
||||
@@ -57,37 +100,24 @@ def _rule_matches(rule: ShippingInventoryRoutingRule, *, task: Any, line: dict[s
|
||||
return all(results) if rule.match_mode == 'all' else any(results)
|
||||
|
||||
|
||||
def evaluate_inventory_source_rules(*, task: Any, line: dict[str, Any] | None = None, now: datetime | None = None) -> InventoryRoutingResult:
|
||||
def _evaluate_matched_rules(top_rules: list[ShippingInventoryRoutingRule], *, priority: int) -> InventoryRoutingResult:
|
||||
"""
|
||||
评估已发布规则并返回最高优先级的 Source 候选集合。
|
||||
将同优先级命中规则折叠为候选集合与建单资格。
|
||||
|
||||
Args:
|
||||
task: 已解析的货代任务。
|
||||
line: 行级规则的订单行;任务级规则传 None。
|
||||
now: 测试可注入的评估时间,默认当前 UTC 时间。
|
||||
|
||||
Returns:
|
||||
InventoryRoutingResult: resolved/unresolved/ambiguous/conflicted 状态及可审计证据。
|
||||
核心逻辑:add/exclude 合并候选;任一 require_manual_review → conflicted 且不可建单;
|
||||
多候选标记 ambiguous 但仍 can_build。
|
||||
"""
|
||||
moment = now or datetime.utcnow()
|
||||
scope = 'line' if line is not None else 'task'
|
||||
query = ShippingInventoryRoutingRule.query.filter_by(status='published', scope=scope)
|
||||
rules = [
|
||||
rule for rule in query.order_by(ShippingInventoryRoutingRule.priority.desc(), ShippingInventoryRoutingRule.id.asc()).all()
|
||||
if (rule.effective_from is None or rule.effective_from <= moment)
|
||||
and (rule.effective_to is None or rule.effective_to >= moment)
|
||||
]
|
||||
matched = [rule for rule in rules if _rule_matches(rule, task=task, line=line)]
|
||||
if not matched:
|
||||
return InventoryRoutingResult('unresolved', (), (), {'matched_rules': []})
|
||||
priority = matched[0].priority
|
||||
top_rules = [rule for rule in matched if rule.priority == priority]
|
||||
source_codes: set[str] = set()
|
||||
excluded: set[str] = set()
|
||||
manual = False
|
||||
for rule in top_rules:
|
||||
if rule.action_type not in ALLOWED_ACTIONS:
|
||||
return InventoryRoutingResult('conflicted', (), tuple(item.id for item in top_rules), {'reason': 'unsupported_action'})
|
||||
return InventoryRoutingResult(
|
||||
'conflicted',
|
||||
(),
|
||||
tuple(item.id for item in top_rules),
|
||||
{'reason': 'unsupported_action', 'priority': priority},
|
||||
)
|
||||
payload = rule.action_payload_json if isinstance(rule.action_payload_json, dict) else {}
|
||||
codes = {str(code or '').strip().upper() for code in payload.get('source_codes', []) if str(code or '').strip()}
|
||||
if rule.action_type == 'add_source_candidates':
|
||||
@@ -104,3 +134,91 @@ def evaluate_inventory_source_rules(*, task: Any, line: dict[str, Any] | None =
|
||||
tuple(rule.id for rule in top_rules),
|
||||
{'priority': priority, 'matched_rules': [rule.rule_code for rule in top_rules]},
|
||||
)
|
||||
|
||||
|
||||
def _published_rules(*, scope: str, now: datetime) -> list[ShippingInventoryRoutingRule]:
|
||||
"""加载当前时刻有效的已发布规则,按优先级降序。"""
|
||||
query = ShippingInventoryRoutingRule.query.filter_by(status='published', scope=scope)
|
||||
return [
|
||||
rule for rule in query.order_by(
|
||||
ShippingInventoryRoutingRule.priority.desc(),
|
||||
ShippingInventoryRoutingRule.id.asc(),
|
||||
).all()
|
||||
if (rule.effective_from is None or rule.effective_from <= now)
|
||||
and (rule.effective_to is None or rule.effective_to >= now)
|
||||
]
|
||||
|
||||
|
||||
def _evaluate_with_reader(*, scope: str, value_reader, now: datetime | None = None) -> InventoryRoutingResult:
|
||||
"""按 value_reader 评估指定 scope 的最高优先级规则层。"""
|
||||
moment = now or datetime.utcnow()
|
||||
rules = _published_rules(scope=scope, now=moment)
|
||||
matched = [rule for rule in rules if _rule_matches(rule, value_reader=value_reader)]
|
||||
if not matched:
|
||||
return InventoryRoutingResult('unresolved', (), (), {'matched_rules': []})
|
||||
priority = matched[0].priority
|
||||
top_rules = [rule for rule in matched if rule.priority == priority]
|
||||
return _evaluate_matched_rules(top_rules, priority=priority)
|
||||
|
||||
|
||||
def evaluate_inventory_source_rules(
|
||||
*,
|
||||
task: Any,
|
||||
line: dict[str, Any] | None = None,
|
||||
now: datetime | None = None,
|
||||
) -> InventoryRoutingResult:
|
||||
"""
|
||||
评估已发布规则并返回最高优先级的 Source 候选集合(冻结 Snapshot 路径)。
|
||||
|
||||
Args:
|
||||
task: 已解析的货代任务(须有 order_snapshot_id)。
|
||||
line: 行级规则的订单行;任务级规则传 None。
|
||||
now: 测试可注入的评估时间,默认当前 UTC 时间。
|
||||
|
||||
Returns:
|
||||
InventoryRoutingResult: 含 status / source_codes / can_build。
|
||||
"""
|
||||
scope = 'line' if line is not None else 'task'
|
||||
return _evaluate_with_reader(
|
||||
scope=scope,
|
||||
value_reader=lambda condition: _condition_value(condition, task=task, line=line),
|
||||
now=now,
|
||||
)
|
||||
|
||||
|
||||
def evaluate_inventory_source_rules_for_field_values(
|
||||
*,
|
||||
header_field_values: dict[str, Any] | None = None,
|
||||
line_field_values: dict[str, Any] | None = None,
|
||||
scope: str | None = None,
|
||||
now: datetime | None = None,
|
||||
) -> InventoryRoutingResult:
|
||||
"""
|
||||
基于 field_id→值映射评估路由(建单前 Draft / 资格服务)。
|
||||
|
||||
核心逻辑:未传 scope 时,有 line_field_values 则评 line,否则评 task;
|
||||
不依赖 ShippingTask / Snapshot,便于复核草稿阶段投影候选。
|
||||
|
||||
Args:
|
||||
header_field_values: Header 字段值,键为稳定 field_id。
|
||||
line_field_values: Line 字段值;行级规则必填。
|
||||
scope: 显式规则作用域 ``line`` / ``task``;缺省按是否有行值推断。
|
||||
now: 可选评估时间。
|
||||
|
||||
Returns:
|
||||
InventoryRoutingResult。
|
||||
"""
|
||||
header = dict(header_field_values or {})
|
||||
resolved_scope = scope or ('line' if line_field_values is not None else 'task')
|
||||
if resolved_scope not in {'line', 'task'}:
|
||||
raise ValueError('inventory routing scope must be line or task')
|
||||
line_values = dict(line_field_values or {}) if resolved_scope == 'line' else None
|
||||
return _evaluate_with_reader(
|
||||
scope=resolved_scope,
|
||||
value_reader=lambda condition: _condition_value_from_maps(
|
||||
condition,
|
||||
header_field_values=header,
|
||||
line_field_values=line_values,
|
||||
),
|
||||
now=now,
|
||||
)
|
||||
@@ -13,7 +13,7 @@ import hashlib
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -904,21 +904,97 @@ def _validate_batch_callback_worker_identity(item: dict[str, Any], source: dict[
|
||||
|
||||
def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
确认当前任务的库存来源,并在门禁通过后等待库存文件可用。
|
||||
确认当前任务的库存来源;库存源门禁或匹配多源阻断均可调用。
|
||||
|
||||
【AI 触发时机】:当用户完成解析确认并在库存源检查点选择 source_code 后调用。
|
||||
【AI 触发时机】:用户在库存源检查点或匹配多源冲突待办中选择 source_code 后调用。
|
||||
核心逻辑:原门禁路径确认后进入库存准备;shortage + 多源/多文件冲突路径写入
|
||||
forced_match_source_code 并立即重匹配,消除多源 Excel 阻断。
|
||||
"""
|
||||
from app.services.shipping_notice.constants import PH_SHORTAGE, RS_SHORTAGE_REVIEW
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.stp_line_inventory_match import (
|
||||
multi_source_recovery_source_codes,
|
||||
needs_multi_source_manual_recovery,
|
||||
)
|
||||
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
if str(task.pending_human_reason or "").strip() != PH_INVENTORY_SOURCE_UNRESOLVED:
|
||||
return tool_response(status="failed", task=task, message="当前任务不在库存源确认节点")
|
||||
source_code = str(payload.get("source_code") or "").strip().upper()
|
||||
if not source_code:
|
||||
return tool_response(status="failed", task=task, message="请提供库存源编码 source_code")
|
||||
|
||||
pending = str(task.pending_human_reason or "").strip()
|
||||
on_source_gate = pending == PH_INVENTORY_SOURCE_UNRESOLVED
|
||||
on_multi_source_block = (
|
||||
(task.review_status == RS_SHORTAGE_REVIEW or pending == PH_SHORTAGE)
|
||||
and needs_multi_source_manual_recovery(task)
|
||||
)
|
||||
if not on_source_gate and not on_multi_source_block:
|
||||
return tool_response(status="failed", task=task, message="当前任务不在库存源确认节点")
|
||||
|
||||
if on_multi_source_block:
|
||||
allowed = set(multi_source_recovery_source_codes(task))
|
||||
if source_code not in allowed:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
message=f"库存源 {source_code} 不在可指定候选内:{', '.join(sorted(allowed)) or '-'}",
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
source = get_database_inventory_source(source_code)
|
||||
if source is None:
|
||||
return tool_response(status="failed", task=task, message=f"库存源配置不存在:{source_code}")
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
step_payload['forced_match_source_code'] = source_code
|
||||
step_payload['multi_source_excel_block'] = False
|
||||
step_payload['resolved_ok_source_codes'] = [source_code]
|
||||
step_payload['inventory_source_resolution'] = {
|
||||
'status': 'resolved',
|
||||
'candidates': [{'source_code': source_code, 'display_name': source.get('display_name') or source_code}],
|
||||
'selected_source_code': source_code,
|
||||
'reason': 'manual_multi_source_resolve',
|
||||
}
|
||||
task.step_payload_json = step_payload
|
||||
task.inventory_source_code = source_code
|
||||
task.inventory_connector_type = str(source.get('connector_type') or '') or None
|
||||
if str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed':
|
||||
task.inventory_warehouse_id = str(source.get('fixed_warehouse_id') or '').upper() or None
|
||||
# 与门禁确认路径对齐:resolved 属 STABLE;保留既有 fingerprint/config_version。
|
||||
task.inventory_source_status = 'resolved'
|
||||
task.inventory_source_method = 'manual_multi_source_resolve'
|
||||
task.inventory_source_confirmed_by = payload.get('_trusted_user_id')
|
||||
task.inventory_source_confirmed_at = datetime.now(timezone.utc)
|
||||
task.pending_human_reason = None
|
||||
task.review_status = None
|
||||
task.error_message = None
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_source_confirmed",
|
||||
{
|
||||
"source_code": source_code,
|
||||
"connector_type": task.inventory_connector_type,
|
||||
"warehouse_id": task.inventory_warehouse_id,
|
||||
"confirmed_by": payload.get("_trusted_user_id") or "integration_tool",
|
||||
"reason_code": "manual_multi_source_resolve",
|
||||
"resolved_ok_source_codes": [source_code],
|
||||
},
|
||||
actor_id=payload.get("_trusted_user_id"),
|
||||
source='workspace_api' if payload.get("_trusted_user_id") else 'system',
|
||||
)
|
||||
apply_task_transition(task, TaskTransition.REMATCH_REQUESTED)
|
||||
task.current_step = "step5_match_inventory"
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_inventory
|
||||
trusted_uid = payload.get("_trusted_user_id")
|
||||
return match_inventory({
|
||||
"task_id": task.task_no,
|
||||
"_trusted_user_id": trusted_uid,
|
||||
"operator_id": trusted_uid,
|
||||
"actor_id": trusted_uid,
|
||||
"event_source": "workspace_api" if trusted_uid else "system",
|
||||
})
|
||||
|
||||
adjudication = confirm_task_inventory_source(
|
||||
task,
|
||||
source_code,
|
||||
@@ -953,6 +1029,8 @@ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"warehouse_id": task.inventory_warehouse_id,
|
||||
"confirmed_by": confirmed_by or "integration_tool",
|
||||
},
|
||||
actor_id=confirmed_by,
|
||||
source='workspace_api' if confirmed_by else 'system',
|
||||
)
|
||||
|
||||
apply_task_transition(task, TaskTransition.PARSED)
|
||||
|
||||
@@ -3,8 +3,8 @@ services/shipping_notice/inventory_source_gate.py
|
||||
|
||||
用途:库存源稳定性门禁、独立字段写入与路由指纹管理。
|
||||
依赖:inventory_source_rules、inventory_source_repository、models.ShippingTask、core.errors。
|
||||
逻辑:动态订单抽取先裁决线索;解析确认通过后未稳定才进入 inventory_source_review;
|
||||
RPA/库存/匹配/导出统一经本模块硬门禁,禁止散落判断。
|
||||
逻辑:动态订单抽取先裁决线索;STP 建单可冻结单/多候选(candidates_frozen 视为可进入库存准备);
|
||||
解析确认通过后未稳定才进入 inventory_source_review;RPA/库存/匹配/导出统一经本模块硬门禁。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -28,7 +28,7 @@ from app.services.shipping_notice.inventory_source_repository import (
|
||||
)
|
||||
|
||||
|
||||
STABLE_INVENTORY_SOURCE_STATUSES = frozenset({"resolved", "user_confirmed"})
|
||||
STABLE_INVENTORY_SOURCE_STATUSES = frozenset({"resolved", "user_confirmed", "candidates_frozen"})
|
||||
|
||||
INVENTORY_SOURCE_ERROR_CODES = {
|
||||
"unresolved": "SHIPPING.INVENTORY_SOURCE_UNRESOLVED",
|
||||
@@ -54,13 +54,28 @@ def _inventory_source_config_current(task: ShippingTask) -> bool:
|
||||
def is_inventory_source_stable(task: ShippingTask) -> bool:
|
||||
"""
|
||||
判断任务库存源是否稳定,可供后续库存/RPA/匹配流程使用。
|
||||
核心逻辑:Source、Driver 与数据库配置一致即可稳定;动态 Warehouse 在库存行匹配后再确定。
|
||||
|
||||
核心逻辑:单源须 Source/Driver/配置一致;STP 多候选冻结(candidates_frozen)
|
||||
在配置版本与指纹有效且候选非空时亦视为稳定,可进入库存准备。
|
||||
"""
|
||||
status = str(task.inventory_source_status or "").strip()
|
||||
if status not in STABLE_INVENTORY_SOURCE_STATUSES:
|
||||
return False
|
||||
if not _inventory_source_config_current(task):
|
||||
return False
|
||||
fingerprint = str(task.inventory_routing_fingerprint or "").strip()
|
||||
if not fingerprint:
|
||||
return False
|
||||
context = extract_routing_context(task)
|
||||
if fingerprint != compute_routing_fingerprint(context):
|
||||
return False
|
||||
|
||||
if status == "candidates_frozen":
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
|
||||
codes = task_frozen_inventory_source_codes(task)
|
||||
return bool(codes) and all(get_database_inventory_source(code) for code in codes)
|
||||
|
||||
code = str(task.inventory_source_code or "").strip().upper()
|
||||
if not code:
|
||||
return False
|
||||
@@ -79,13 +94,6 @@ def is_inventory_source_stable(task: ShippingTask) -> bool:
|
||||
if mode == 'fixed' and task_warehouse != fixed_warehouse:
|
||||
return False
|
||||
|
||||
fingerprint = str(task.inventory_routing_fingerprint or "").strip()
|
||||
if not fingerprint:
|
||||
return False
|
||||
context = extract_routing_context(task)
|
||||
if fingerprint != compute_routing_fingerprint(context):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
@@ -340,7 +348,7 @@ def assert_inventory_source_gate(
|
||||
|
||||
|
||||
def task_inventory_identity(task: ShippingTask) -> dict[str, str | None]:
|
||||
"""返回任务当前正式库存身份,供库存文件绑定与匹配校验。"""
|
||||
"""返回任务当前正式库存身份;多候选冻结时 source 摘要可为空。"""
|
||||
return {
|
||||
"inventory_source_code": str(task.inventory_source_code or "").strip().upper() or None,
|
||||
"inventory_warehouse_id": str(task.inventory_warehouse_id or "").strip().upper() or None,
|
||||
@@ -353,13 +361,28 @@ def inventory_identities_match(
|
||||
source_code: str | None,
|
||||
warehouse_id: str | None,
|
||||
) -> bool:
|
||||
"""校验库存文件 Source;固定仓严格匹配,动态仓允许从库存文件中解析。"""
|
||||
identity = task_inventory_identity(task)
|
||||
"""
|
||||
校验库存文件 Source;固定仓严格匹配,动态仓允许从库存文件中解析。
|
||||
|
||||
核心逻辑:单源任务要求与 task.inventory_source_code 一致;
|
||||
candidates_frozen 时允许文件源属于冻结候选集合。
|
||||
"""
|
||||
if not is_inventory_source_stable(task):
|
||||
return False
|
||||
expected_code = str(source_code or "").strip().upper()
|
||||
if expected_code != identity["inventory_source_code"]:
|
||||
if not expected_code:
|
||||
return False
|
||||
identity = task_inventory_identity(task)
|
||||
task_code = identity["inventory_source_code"]
|
||||
if task_code:
|
||||
if expected_code != task_code:
|
||||
return False
|
||||
else:
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
|
||||
frozen = set(task_frozen_inventory_source_codes(task))
|
||||
if expected_code not in frozen:
|
||||
return False
|
||||
|
||||
file_wh = str(warehouse_id or "").strip().upper()
|
||||
if not file_wh:
|
||||
|
||||
@@ -3,7 +3,8 @@ services/shipping_notice/inventory_source_rules.py
|
||||
|
||||
用途:将通用路由规则的 Source 候选转为任务可持久化的裁决结果。
|
||||
依赖:inventory_routing_engine、inventory_source_repository、order_field_purposes。
|
||||
逻辑:规则只决定 Source;fixed Warehouse 由 Source 给出,inventory_match Warehouse 延后到库存行匹配。
|
||||
逻辑:规则只决定 Source;建单前多候选由资格服务按 can_build 放行;
|
||||
本模块仍负责任务级裁决与快照消歧(履约阶段);Warehouse 由 Source/匹配决定。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -262,8 +263,17 @@ def resolve_inventory_source(task: ShippingTask) -> InventorySourceAdjudication:
|
||||
|
||||
|
||||
def task_rpa_inventory_source(task: ShippingTask) -> dict[str, Any] | None:
|
||||
"""按任务 Source 从数据库读取 RPA 配置;动态仓由回调库存文件确定。"""
|
||||
return get_database_inventory_source(task.inventory_source_code)
|
||||
"""按任务 Source 或冻结多候选中的首个可用源读取 RPA/快照配置。"""
|
||||
primary = get_database_inventory_source(task.inventory_source_code)
|
||||
if primary is not None:
|
||||
return primary
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
|
||||
for code in task_frozen_inventory_source_codes(task):
|
||||
item = get_database_inventory_source(code)
|
||||
if item is not None:
|
||||
return item
|
||||
return None
|
||||
|
||||
|
||||
def save_task_rpa_inventory_source(task: ShippingTask, source: dict[str, Any], *, resolution: InventorySourceAdjudication | None = None) -> None:
|
||||
|
||||
@@ -270,6 +270,72 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if mode == "auto":
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import _try_reuse_inventory_snapshot
|
||||
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines
|
||||
|
||||
# [STEP] STP 多候选:准备全部冻结源快照;缺文件则停在库存等待,不隐式触发 RPA。
|
||||
frozen_codes = task_frozen_inventory_source_codes(task)
|
||||
if len(frozen_codes) > 1 or str(task.inventory_source_status or '').strip() == 'candidates_frozen':
|
||||
prep = prepare_candidate_inventory_lines(task)
|
||||
if prep.get('status') == 'missing_files':
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message=t("workflow.inventory.unavailable", lang=lang),
|
||||
progress_percent=0,
|
||||
detail=t("workflow.inventory.unavailable", lang=lang),
|
||||
)
|
||||
log_task_event(task, "inventory_candidate_files_missing", {
|
||||
'missing_source_codes': prep.get('missing_source_codes') or [],
|
||||
})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=t("workflow.inventory.unavailable", lang=lang),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
'missing_source_codes': prep.get('missing_source_codes') or [],
|
||||
},
|
||||
)
|
||||
if prep.get('status') == 'partial_missing':
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message=t("workflow.inventory.unavailable", lang=lang),
|
||||
progress_percent=0,
|
||||
detail=t("workflow.inventory.unavailable", lang=lang),
|
||||
)
|
||||
log_task_event(task, "inventory_candidate_files_partial", {
|
||||
'missing_source_codes': prep.get('missing_source_codes') or [],
|
||||
'loaded_source_codes': prep.get('loaded_source_codes') or [],
|
||||
})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=t("workflow.inventory.unavailable", lang=lang),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
'missing_source_codes': prep.get('missing_source_codes') or [],
|
||||
'loaded_source_codes': prep.get('loaded_source_codes') or [],
|
||||
},
|
||||
)
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
|
||||
return inventory_loaded_response(
|
||||
task,
|
||||
list(prep.get('lines') or []),
|
||||
column_meta={'source': 'stp_candidate_prep'},
|
||||
source='stp_candidate_prep',
|
||||
event_type='inventory_candidates_prepared',
|
||||
)
|
||||
|
||||
reused = _try_reuse_inventory_snapshot(
|
||||
task,
|
||||
|
||||
@@ -0,0 +1,449 @@
|
||||
"""
|
||||
services/shipping_notice/order_build_eligibility_service.py
|
||||
|
||||
用途:汇总建单前资格:客户/订单字段、有效 Reservation、行级库存源候选,以及
|
||||
自动建单五门禁(批准模板 / 字段完整 / 证据通过 / 无冲突重复 / 质量门禁)。
|
||||
依赖:candidate_validation、field_rules、inventory_routing_engine、inventory_source_repository、
|
||||
ShippingNoticeCandidate / ShippingOrderExtractionUnit / ShippingOrderExtractionRun。
|
||||
逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核阻断;
|
||||
人工已选候选(含原因)可覆盖规则零候选;五门禁失败仅阻断自动建单,落入 Review Case,
|
||||
不替代人工确认路径的 can_build(库存/Reservation)门禁。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
|
||||
from app.services.shipping_notice.inventory_routing_engine import (
|
||||
InventoryRoutingResult,
|
||||
evaluate_inventory_source_rules_for_field_values,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
get_database_inventory_source,
|
||||
list_database_inventory_sources,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.field_rules import compute_effective_reservation_id
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
# 自动建单五门禁稳定键;失败 → 仅 Review Case,禁止 STP 自动建单。
|
||||
AUTO_BUILD_GATE_KEYS: tuple[str, ...] = (
|
||||
'approved_template',
|
||||
'fields_complete',
|
||||
'evidence_passed',
|
||||
'no_conflict_or_duplicate',
|
||||
'quality_gate_passed',
|
||||
)
|
||||
|
||||
|
||||
def _field_id_maps(
|
||||
*,
|
||||
fields: dict[str, dict[str, Any]],
|
||||
header_by_code: dict[str, Any],
|
||||
line_by_code: dict[str, Any],
|
||||
) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
"""
|
||||
将 field_code→值 转为 field_id→值,供路由条件读取。
|
||||
|
||||
Args:
|
||||
fields: Schema field_id → 字段配置。
|
||||
header_by_code / line_by_code: 按 field_code 投影的当前值。
|
||||
"""
|
||||
header: dict[str, Any] = {}
|
||||
line: dict[str, Any] = {}
|
||||
for field_id, field in fields.items():
|
||||
code = str(field.get('field_code') or '')
|
||||
scope = str(field.get('scope') or '')
|
||||
if scope == 'header' and code in header_by_code:
|
||||
header[str(field_id)] = header_by_code.get(code)
|
||||
elif scope == 'line' and code in line_by_code:
|
||||
line[str(field_id)] = line_by_code.get(code)
|
||||
return header, line
|
||||
|
||||
|
||||
def _normalize_manual_codes(raw: Any) -> list[str]:
|
||||
"""规范化人工候选编码列表。"""
|
||||
if not isinstance(raw, (list, tuple)):
|
||||
return []
|
||||
codes: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for item in raw:
|
||||
code = str(item or '').strip().upper()
|
||||
if not code or code in seen:
|
||||
continue
|
||||
seen.add(code)
|
||||
codes.append(code)
|
||||
return codes
|
||||
|
||||
|
||||
def _validate_enabled_sources(codes: list[str]) -> tuple[list[str], list[str]]:
|
||||
"""
|
||||
校验库存源已启用;返回 (valid_codes, invalid_codes)。
|
||||
"""
|
||||
valid: list[str] = []
|
||||
invalid: list[str] = []
|
||||
for code in codes:
|
||||
source = get_database_inventory_source(code)
|
||||
if source is None:
|
||||
invalid.append(code)
|
||||
else:
|
||||
valid.append(code)
|
||||
return valid, invalid
|
||||
|
||||
|
||||
def project_line_inventory_candidates(
|
||||
*,
|
||||
fields: dict[str, dict[str, Any]],
|
||||
header_by_code: dict[str, Any],
|
||||
line_by_code: dict[str, Any],
|
||||
line_meta: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为单条明细投影库存源候选与建单库存门禁。
|
||||
|
||||
核心逻辑:先跑行级规则;行级 unresolved 时回退任务级规则;人工选择优先于规则零候选。
|
||||
|
||||
Args:
|
||||
fields: 冻结 Schema 字段。
|
||||
header_by_code / line_by_code: 当前头/行值。
|
||||
line_meta: Draft 行上可选的 inventory_routing 人工覆盖。
|
||||
|
||||
Returns:
|
||||
含 candidate_inventory_source_codes、can_build、routing_status、证据摘要的字典。
|
||||
"""
|
||||
meta = line_meta if isinstance(line_meta, dict) else {}
|
||||
routing_overlay = meta.get('inventory_routing') if isinstance(meta.get('inventory_routing'), dict) else {}
|
||||
manual_codes = _normalize_manual_codes(routing_overlay.get('candidate_inventory_source_codes'))
|
||||
manual_reason = str(routing_overlay.get('manual_reason') or '').strip()
|
||||
selection_mode = str(routing_overlay.get('selection_mode') or '').strip().lower()
|
||||
|
||||
header_ids, line_ids = _field_id_maps(
|
||||
fields=fields, header_by_code=header_by_code, line_by_code=line_by_code,
|
||||
)
|
||||
line_result = evaluate_inventory_source_rules_for_field_values(
|
||||
header_field_values=header_ids,
|
||||
line_field_values=line_ids,
|
||||
scope='line',
|
||||
)
|
||||
task_result = evaluate_inventory_source_rules_for_field_values(
|
||||
header_field_values=header_ids,
|
||||
line_field_values=None,
|
||||
scope='task',
|
||||
)
|
||||
# [STEP 1] 行级有结论优先;否则用任务级规则。
|
||||
rule_result: InventoryRoutingResult = line_result if line_result.status != 'unresolved' else task_result
|
||||
|
||||
if selection_mode == 'manual' and manual_codes:
|
||||
valid, invalid = _validate_enabled_sources(manual_codes)
|
||||
if not manual_reason:
|
||||
return {
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': valid,
|
||||
'routing_status': 'conflicted',
|
||||
'can_build': False,
|
||||
'block_reason': 'manual_inventory_source_reason_required',
|
||||
'matched_rule_ids': list(rule_result.matched_rule_ids),
|
||||
'rule_source_codes': list(rule_result.source_codes),
|
||||
'invalid_source_codes': invalid,
|
||||
'evidence': {'manual_override': True, 'rule': rule_result.evidence},
|
||||
}
|
||||
if invalid or not valid:
|
||||
return {
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': valid,
|
||||
'routing_status': 'unresolved',
|
||||
'can_build': False,
|
||||
'block_reason': 'manual_inventory_source_invalid',
|
||||
'matched_rule_ids': list(rule_result.matched_rule_ids),
|
||||
'rule_source_codes': list(rule_result.source_codes),
|
||||
'invalid_source_codes': invalid,
|
||||
'evidence': {'manual_override': True, 'rule': rule_result.evidence},
|
||||
}
|
||||
return {
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': valid,
|
||||
'routing_status': 'resolved' if len(valid) == 1 else 'ambiguous',
|
||||
'can_build': True,
|
||||
'block_reason': None,
|
||||
'manual_reason': manual_reason,
|
||||
'matched_rule_ids': list(rule_result.matched_rule_ids),
|
||||
'rule_source_codes': list(rule_result.source_codes),
|
||||
'invalid_source_codes': [],
|
||||
'evidence': {'manual_override': True, 'rule': rule_result.evidence},
|
||||
}
|
||||
|
||||
return {
|
||||
'selection_mode': 'rule',
|
||||
'candidate_inventory_source_codes': list(rule_result.source_codes),
|
||||
'routing_status': rule_result.status,
|
||||
'can_build': rule_result.can_build,
|
||||
'block_reason': rule_result.block_reason,
|
||||
'matched_rule_ids': list(rule_result.matched_rule_ids),
|
||||
'rule_source_codes': list(rule_result.source_codes),
|
||||
'invalid_source_codes': [],
|
||||
'evidence': dict(rule_result.evidence),
|
||||
}
|
||||
|
||||
|
||||
def assess_auto_build_gates(
|
||||
*,
|
||||
fields_complete: bool,
|
||||
candidate: Any | None = None,
|
||||
unit: Any | None = None,
|
||||
run: Any | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
评估自动建单五门禁;任一失败则只能进入 Review Case,禁止 STP 自动建单。
|
||||
|
||||
核心逻辑:批准模板读 Unit 路由;字段完整由调用方汇总;证据/冲突/重复读 Candidate;
|
||||
质量门禁读 Run 冻结的 auto_freeze_policy.enabled(经质量批次批准后才为 True)。
|
||||
|
||||
Args:
|
||||
fields_complete: Schema 必填与建单字段是否已齐备。
|
||||
candidate: 可选 ShippingNoticeCandidate。
|
||||
unit: 可选 ShippingOrderExtractionUnit(含 route_decision_json)。
|
||||
run: 可选 ShippingOrderExtractionRun(含 auto_freeze_policy_json)。
|
||||
|
||||
Returns:
|
||||
gates(五键 bool)、can_auto_create、failed_gates。
|
||||
"""
|
||||
# [STEP 1] 批准模板:Unit 路由 auto_create_approved,或 Candidate 已 automatic 接受。
|
||||
route = {}
|
||||
if unit is not None and isinstance(getattr(unit, 'route_decision_json', None), dict):
|
||||
route = dict(unit.route_decision_json or {})
|
||||
approved_template = bool(route.get('auto_create_approved'))
|
||||
if not approved_template and candidate is not None:
|
||||
approved_template = (
|
||||
str(getattr(candidate, 'acceptance_mode', '') or '') == 'automatic'
|
||||
and str(getattr(candidate, 'candidate_status', '') or '') == 'accepted'
|
||||
)
|
||||
|
||||
# [STEP 2] 证据:Candidate 须有非空 evidence_json。
|
||||
evidence_passed = True
|
||||
if candidate is not None:
|
||||
evidence = getattr(candidate, 'evidence_json', None)
|
||||
evidence_passed = isinstance(evidence, list) and len(evidence) > 0
|
||||
|
||||
# [STEP 3] 冲突/重复:阻断冲突或未解决重复均失败。
|
||||
no_conflict_or_duplicate = True
|
||||
if candidate is not None:
|
||||
if getattr(candidate, 'conflicts_json', None):
|
||||
no_conflict_or_duplicate = False
|
||||
dup_status = str(getattr(candidate, 'duplicate_status', '') or 'unchecked')
|
||||
dup_resolution = str(getattr(candidate, 'duplicate_resolution', '') or '')
|
||||
if dup_status not in {'none', 'unchecked', ''} and dup_resolution != 'open_existing':
|
||||
no_conflict_or_duplicate = False
|
||||
|
||||
# [STEP 4] 质量门禁:Run 冻结策略 enabled=True 才视为通过;缺 Run 时视为未通过。
|
||||
quality_gate_passed = False
|
||||
if run is not None:
|
||||
policy = getattr(run, 'auto_freeze_policy_json', None)
|
||||
if isinstance(policy, dict):
|
||||
quality_gate_passed = bool(policy.get('enabled'))
|
||||
|
||||
gates = {
|
||||
'approved_template': bool(approved_template),
|
||||
'fields_complete': bool(fields_complete),
|
||||
'evidence_passed': bool(evidence_passed),
|
||||
'no_conflict_or_duplicate': bool(no_conflict_or_duplicate),
|
||||
'quality_gate_passed': bool(quality_gate_passed),
|
||||
}
|
||||
failed = [key for key in AUTO_BUILD_GATE_KEYS if not gates.get(key)]
|
||||
return {
|
||||
'gates': gates,
|
||||
'failed_gates': failed,
|
||||
'can_auto_create': not failed,
|
||||
}
|
||||
|
||||
|
||||
def assess_order_build_eligibility(
|
||||
*,
|
||||
fields: dict[str, dict[str, Any]],
|
||||
header_by_code: dict[str, Any],
|
||||
lines: list[dict[str, Any]],
|
||||
line_metas: list[dict[str, Any]] | None = None,
|
||||
customer_resolved: bool = True,
|
||||
candidate: Any | None = None,
|
||||
unit: Any | None = None,
|
||||
run: Any | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
汇总整单建单资格与自动建单五门禁。
|
||||
|
||||
核心逻辑:复用 Candidate 基础评估;逐行补有效 Reservation 与库存源候选门禁;
|
||||
任一阻断则 can_build=False(人工确认仍可读该门禁);五门禁失败仅置
|
||||
can_auto_create=False,强制落入 Review Case,禁止自动建单。
|
||||
|
||||
Args:
|
||||
fields: Schema field_id → 配置。
|
||||
header_by_code: Header field_code → 值。
|
||||
lines: 行 field_code → 值列表(与 line_metas 对齐)。
|
||||
line_metas: Draft 行原始对象(含 line_key / inventory_routing)。
|
||||
customer_resolved: 客户是否已唯一命中或人工确认;缺省 True 由调用方保证。
|
||||
candidate / unit / run: 可选门禁上下文(自动建单五门)。
|
||||
|
||||
Returns:
|
||||
can_build、can_auto_create、gates、issues、line_projections、assessment 摘要。
|
||||
"""
|
||||
metas = list(line_metas or [])
|
||||
while len(metas) < len(lines):
|
||||
metas.append({})
|
||||
|
||||
header_reservation = header_by_code.get('reservation_id')
|
||||
enriched_lines: list[dict[str, Any]] = []
|
||||
line_projections: list[dict[str, Any]] = []
|
||||
issues: list[dict[str, Any]] = []
|
||||
|
||||
if not customer_resolved:
|
||||
issues.append({'code': 'customer_unresolved', 'severity': 'blocking'})
|
||||
|
||||
for index, line in enumerate(lines):
|
||||
raw_line = dict(line) if isinstance(line, dict) else {}
|
||||
meta = metas[index] if isinstance(metas[index], dict) else {}
|
||||
effective = compute_effective_reservation_id(
|
||||
line_reservation_id=raw_line.get('reservation_id'),
|
||||
header_reservation_id=header_reservation,
|
||||
)
|
||||
projected_line = dict(raw_line)
|
||||
if effective:
|
||||
projected_line['reservation_id'] = effective
|
||||
enriched_lines.append(projected_line)
|
||||
|
||||
routing = project_line_inventory_candidates(
|
||||
fields=fields,
|
||||
header_by_code=header_by_code,
|
||||
line_by_code=raw_line,
|
||||
line_meta=meta,
|
||||
)
|
||||
projection = {
|
||||
'line_key': meta.get('line_key'),
|
||||
'line_index': index,
|
||||
'effective_reservation_id': effective,
|
||||
'inventory_source_hint': raw_line.get('inventory_source_hint'),
|
||||
**routing,
|
||||
}
|
||||
line_projections.append(projection)
|
||||
|
||||
if not effective:
|
||||
issues.append({
|
||||
'code': 'effective_reservation_missing',
|
||||
'line_key': meta.get('line_key'),
|
||||
'line_index': index,
|
||||
'severity': 'blocking',
|
||||
})
|
||||
if not routing.get('can_build'):
|
||||
issues.append({
|
||||
'code': str(routing.get('block_reason') or 'inventory_source_unresolved'),
|
||||
'line_key': meta.get('line_key'),
|
||||
'line_index': index,
|
||||
'severity': 'blocking',
|
||||
'candidate_inventory_source_codes': routing.get('candidate_inventory_source_codes') or [],
|
||||
})
|
||||
|
||||
assessment = assess_candidate_business_summary({**header_by_code, 'lines': enriched_lines})
|
||||
for item in assessment.get('blocking_issues') or []:
|
||||
issues.append({
|
||||
'code': str(item.get('code') or 'invalid_order_line'),
|
||||
'line_index': item.get('line_index'),
|
||||
'severity': 'blocking',
|
||||
})
|
||||
for field_code in assessment.get('missing_required_fields') or []:
|
||||
issues.append({'code': 'required_field_missing', 'field_code': field_code, 'severity': 'blocking'})
|
||||
|
||||
# 有效 Reservation 已在上方按行检查;不再用 line-only process_field_missing 重复阻断。
|
||||
reservations = [
|
||||
validated_reservation_id(item.get('effective_reservation_id'))
|
||||
for item in line_projections
|
||||
if validated_reservation_id(item.get('effective_reservation_id'))
|
||||
]
|
||||
if len(reservations) != len(set(reservations)):
|
||||
issues.append({'code': 'reservation_duplicated_in_order', 'severity': 'blocking'})
|
||||
|
||||
can_build = (
|
||||
bool(customer_resolved)
|
||||
and bool(assessment.get('can_create_task'))
|
||||
and not issues
|
||||
and all(item.get('can_build') and item.get('effective_reservation_id') for item in line_projections)
|
||||
and bool(line_projections)
|
||||
)
|
||||
fields_complete = (
|
||||
bool(assessment.get('can_create_task'))
|
||||
and not assessment.get('missing_required_fields')
|
||||
and not assessment.get('invalid_lines')
|
||||
and not any(str(item.get('code') or '') == 'required_field_missing' for item in issues)
|
||||
)
|
||||
# [STEP] 五门禁:失败只阻断自动建单,不改写人工确认 can_build。
|
||||
gate_result = assess_auto_build_gates(
|
||||
fields_complete=fields_complete and can_build,
|
||||
candidate=candidate,
|
||||
unit=unit,
|
||||
run=run,
|
||||
)
|
||||
can_auto_create = bool(can_build and gate_result.get('can_auto_create'))
|
||||
if not gate_result.get('can_auto_create'):
|
||||
for gate_key in gate_result.get('failed_gates') or []:
|
||||
issues.append({
|
||||
'code': f'auto_build_gate_{gate_key}',
|
||||
'severity': 'auto_create_blocking',
|
||||
'gate': gate_key,
|
||||
})
|
||||
|
||||
enabled_codes = [
|
||||
str(item.get('source_code') or '').strip().upper()
|
||||
for item in list_database_inventory_sources(enabled_only=True)
|
||||
if str(item.get('source_code') or '').strip()
|
||||
]
|
||||
return {
|
||||
'can_build': can_build,
|
||||
'can_auto_create': can_auto_create,
|
||||
'gates': dict(gate_result.get('gates') or {}),
|
||||
'failed_gates': list(gate_result.get('failed_gates') or []),
|
||||
'status': 'ready' if can_build else 'needs_review',
|
||||
'issues': issues,
|
||||
'line_projections': line_projections,
|
||||
# 零规则候选时供复核台从已启用库存源人工选择(须填原因)。
|
||||
'enabled_inventory_source_codes': enabled_codes,
|
||||
'assessment': {
|
||||
'can_create_task': bool(assessment.get('can_create_task')),
|
||||
'missing_required_fields': list(assessment.get('missing_required_fields') or []),
|
||||
'invalid_lines': list(assessment.get('invalid_lines') or []),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def apply_manual_inventory_candidates(
|
||||
*,
|
||||
line_meta: dict[str, Any],
|
||||
source_codes: list[str],
|
||||
reason: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将人工候选选择写入 Draft 行 inventory_routing 覆盖层。
|
||||
|
||||
Args:
|
||||
line_meta: Draft 行对象(会被就地更新并返回)。
|
||||
source_codes: 已启用库存源编码(1..N)。
|
||||
reason: 强制人工原因。
|
||||
|
||||
Returns:
|
||||
更新后的 inventory_routing 片段。
|
||||
|
||||
Raises:
|
||||
ValueError: 原因或候选无效。
|
||||
"""
|
||||
codes = _normalize_manual_codes(source_codes)
|
||||
text = str(reason or '').strip()
|
||||
if not text:
|
||||
raise ValueError('manual_inventory_source_reason_required')
|
||||
if not codes:
|
||||
raise ValueError('manual_inventory_source_empty')
|
||||
valid, invalid = _validate_enabled_sources(codes)
|
||||
if invalid or not valid:
|
||||
raise ValueError('manual_inventory_source_invalid')
|
||||
overlay = {
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': valid,
|
||||
'manual_reason': text,
|
||||
}
|
||||
line_meta['inventory_routing'] = overlay
|
||||
return overlay
|
||||
@@ -358,7 +358,7 @@ def _compare_field_region(
|
||||
"""比较单个字段区域。"""
|
||||
previous = before or {}
|
||||
current = after or {}
|
||||
changes = _scalar_changes(previous, current, ('field_id', 'field_code', 'extractor_key', 'minimum_evidence_level'))
|
||||
changes = _scalar_changes(previous, current, ('field_id', 'field_code', 'scope', 'extractor_key', 'minimum_evidence_level'))
|
||||
allowed_sources = _set_change('allowed_sources', previous.get('allowed_sources'), current.get('allowed_sources'))
|
||||
if allowed_sources:
|
||||
changes.append(allowed_sources)
|
||||
|
||||
@@ -4,7 +4,7 @@ backend/app/services/shipping_notice/order_document_profile_service.py
|
||||
用途:管理订单文档模板 Profile 的草稿、发布、退役和 Run 冻结快照。
|
||||
依赖:ShippingOrderDocumentProfile、盲测套件模型、订单 Schema 版本、document_layout.order_profile 纯契约。
|
||||
逻辑:草稿保存时把目标 field_code 转成稳定 field_id;发布时重新校验绑定 Schema 并原子替换当前版本;
|
||||
删除草稿前先清理关联盲测套件,避免 suites.profile_id 外键 500。
|
||||
删除草稿前清理全部盲测套件与自动冻结资格,避免无 CASCADE 外键导致 500。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,6 +26,7 @@ from app.extensions import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingDocumentProfileAutoFreezeQualification,
|
||||
ShippingDocumentProfileTestSample,
|
||||
ShippingDocumentProfileTestSuite,
|
||||
ShippingNoticeDocument,
|
||||
@@ -239,21 +240,43 @@ def _schema_fields(version: ShippingOrderSchemaVersion) -> dict[str, dict[str, A
|
||||
return result
|
||||
|
||||
|
||||
def _schema_profile_fields(version: ShippingOrderSchemaVersion) -> dict[str, dict[str, Any]]:
|
||||
"""返回 Profile 可冻结的启用字段;主区域仍限制为明细字段,复合输出可含 Header。"""
|
||||
def _schema_profile_fields(version: ShippingOrderSchemaVersion) -> dict[tuple[str, str], dict[str, Any]]:
|
||||
"""按 ``(scope, field_code)`` 返回 Profile 字段,允许表头和明细使用同一业务编码。"""
|
||||
definition = version.definition_json if isinstance(version.definition_json, dict) else {}
|
||||
result: dict[str, dict[str, Any]] = {}
|
||||
for raw in definition.get('fields') or []:
|
||||
for index, raw in enumerate(definition.get('fields') or []):
|
||||
if not isinstance(raw, dict) or not raw.get('enabled', True):
|
||||
continue
|
||||
code = str(raw.get('field_code') or '').strip()
|
||||
field_id = str(raw.get('field_id') or '').strip()
|
||||
if not code or not field_id or code in result:
|
||||
if not code or not field_id:
|
||||
raise ValidationError(
|
||||
'Order profile Schema fields are invalid',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SCHEMA_INVALID',
|
||||
details={'reason': 'field_identity_missing', 'field_index': index},
|
||||
)
|
||||
result[code] = dict(raw)
|
||||
scope = str(raw.get('scope') or '').strip()
|
||||
identity = (scope, code)
|
||||
if scope not in {'header', 'line'}:
|
||||
raise ValidationError(
|
||||
'Order profile Schema fields are invalid',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SCHEMA_INVALID',
|
||||
details={'reason': 'field_scope_invalid', 'field_id': field_id},
|
||||
)
|
||||
if identity in result:
|
||||
raise ValidationError(
|
||||
'Order profile Schema has duplicate field codes',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SCHEMA_INVALID',
|
||||
details={
|
||||
'reason': 'duplicate_field_code',
|
||||
'field_code': code,
|
||||
'existing_field_id': str(result[identity].get('field_id') or ''),
|
||||
'existing_scope': scope,
|
||||
'duplicate_field_id': field_id,
|
||||
'duplicate_scope': str(raw.get('scope') or ''),
|
||||
},
|
||||
)
|
||||
result[identity] = dict(raw)
|
||||
return result
|
||||
|
||||
|
||||
@@ -316,7 +339,10 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio
|
||||
# A physical detail row can carry a stable Header value (for example
|
||||
# Incoterm or currency). Runtime later requires all rows to agree
|
||||
# before promoting it to Header scope, so do not coerce it to Line.
|
||||
field = profile_fields.get(code)
|
||||
scope = str(field_region.get('scope') or '').strip()
|
||||
if scope not in {'header', 'line'}:
|
||||
raise ValidationError('Coordinate field scope is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID')
|
||||
field = profile_fields.get((scope, code))
|
||||
if field is None or not isinstance(allowed_sources, list) or not allowed_sources:
|
||||
raise ValidationError('Coordinate field binding is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID')
|
||||
schema_sources = field.get('allowed_sources')
|
||||
@@ -325,27 +351,35 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio
|
||||
outputs = registered_extractor_output_codes(
|
||||
extractor_key=str(field_region.get('extractor_key') or 'direct'), field_code=code,
|
||||
)
|
||||
if not outputs or not outputs.issubset(profile_fields):
|
||||
output_fields = {
|
||||
output: profile_fields.get((scope, output))
|
||||
for output in outputs
|
||||
}
|
||||
if not outputs or any(output_field is None for output_field in output_fields.values()):
|
||||
raise ValidationError('Coordinate extractor targets are invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID')
|
||||
# A composite parser may emit auxiliary Header fields (such as currency).
|
||||
# Every emitted field must independently authorize this coordinate evidence.
|
||||
for output in outputs:
|
||||
output_sources = profile_fields[output].get('allowed_sources')
|
||||
output_sources = output_fields[output].get('allowed_sources')
|
||||
if not isinstance(output_sources, list) or not set(allowed_sources).issubset(set(output_sources)):
|
||||
raise ValidationError('Schema extractor target does not allow coordinate source', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID')
|
||||
field_region['field_id'] = str(field['field_id'])
|
||||
field_region['scope'] = scope
|
||||
field_region['target_fields'] = [
|
||||
{'field_id': str(profile_fields[target]['field_id']), 'field_code': target}
|
||||
{'field_id': str(output_fields[target]['field_id']), 'field_code': target, 'scope': scope}
|
||||
for target in sorted(outputs)
|
||||
]
|
||||
for order_field in normalized['order_field_layouts']:
|
||||
if not isinstance(order_field, dict):
|
||||
continue
|
||||
if order_field.get('scope') != 'header':
|
||||
raise ValidationError('Order field scope must be header', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID')
|
||||
code = str(order_field.get('field_code') or '').strip()
|
||||
field = profile_fields.get(code)
|
||||
if field is None or field.get('scope') != 'header':
|
||||
field = profile_fields.get(('header', code))
|
||||
if field is None:
|
||||
raise ValidationError('Order field binding must target a header Schema field', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID')
|
||||
order_field['field_id'] = str(field['field_id'])
|
||||
order_field['scope'] = 'header'
|
||||
normalizer = order_field.get('normalizer_key')
|
||||
if normalizer is not None and normalizer != field.get('normalizer_key'):
|
||||
raise ValidationError('Order field normalizer must match Schema', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID')
|
||||
@@ -727,7 +761,7 @@ def preview_profile_region(
|
||||
if field_code and field_code not in seen_field_codes:
|
||||
seen_field_codes.add(field_code)
|
||||
involved_field_codes.append(field_code)
|
||||
rows.extend(reconstruct_coordinate_profile_rows(
|
||||
reconstructed_rows = reconstruct_coordinate_profile_rows(
|
||||
characters=[item for item in characters if isinstance(item, dict)], table_bbox=page_bbox,
|
||||
line_layouts=[item.model_dump() for item in table_region.line_layouts],
|
||||
table_region=table_region.region.model_dump(),
|
||||
@@ -735,7 +769,22 @@ def preview_profile_region(
|
||||
exclusion_regions=[item.model_dump() for item in table_region.exclusion_regions],
|
||||
# 预览保留删除证据,供管理员核对;正式订单运行仍使用默认排除规则。
|
||||
include_deleted=True,
|
||||
))
|
||||
line_start_field_code=table_region.line_start_field_code,
|
||||
)
|
||||
# Preview must expose coordinate reads for correction even when the current
|
||||
# sample's start marker is missing; the production extraction path remains strict.
|
||||
if not reconstructed_rows:
|
||||
reconstructed_rows = reconstruct_coordinate_profile_rows(
|
||||
characters=[item for item in characters if isinstance(item, dict)], table_bbox=page_bbox,
|
||||
line_layouts=[item.model_dump() for item in table_region.line_layouts],
|
||||
table_region=table_region.region.model_dump(),
|
||||
termination_rules=[item.model_dump() for item in table_region.termination_rules],
|
||||
exclusion_regions=[item.model_dump() for item in table_region.exclusion_regions],
|
||||
include_deleted=True,
|
||||
line_start_field_code=table_region.line_start_field_code,
|
||||
include_unanchored_rows=True,
|
||||
)
|
||||
rows.extend(reconstructed_rows)
|
||||
# 复合解析器可能生成未显式列在 target_fields 的附加字段,仍需纳入本次候选。
|
||||
for row in rows:
|
||||
for field_code in row.fields:
|
||||
@@ -1695,7 +1744,7 @@ def create_sample_intake(*, asset_no: str, actor_id: int | None) -> dict[str, An
|
||||
|
||||
|
||||
def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""返回模板样本的最小处理状态;拒绝读取业务 Intake 或解析正文。"""
|
||||
"""返回模板样本的可建模状态;Intake 解析完成不等于坐标布局已可用。"""
|
||||
if actor_id is None:
|
||||
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
intake = ShippingNoticeIntake.query.filter_by(
|
||||
@@ -1704,11 +1753,35 @@ def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[st
|
||||
).first()
|
||||
if intake is None:
|
||||
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
documents = ShippingNoticeDocument.query.filter_by(intake_id=intake.id).all()
|
||||
latest_layouts = {
|
||||
document.id: ShippingDocumentLayoutVersion.query.filter_by(document_id=document.id).order_by(
|
||||
ShippingDocumentLayoutVersion.version.desc(),
|
||||
).first()
|
||||
for document in documents
|
||||
}
|
||||
failed_layout = next((item for item in latest_layouts.values() if item is not None and item.status in {'failed', 'unsupported'}), None)
|
||||
layout_ready = bool(documents) and all(
|
||||
item is not None and item.status == 'ready' for item in latest_layouts.values()
|
||||
)
|
||||
if failed_layout is not None:
|
||||
status = 'failed'
|
||||
error_code = next(iter(failed_layout.issues_json or []), 'shipping_document_layout_failed')
|
||||
elif intake.parse_status in {'failed', 'error'}:
|
||||
status = intake.parse_status
|
||||
error_code = intake.error_code
|
||||
elif layout_ready:
|
||||
status = 'parsed'
|
||||
error_code = None
|
||||
else:
|
||||
# The source document may be parsed while its required coordinate layout is queued or running.
|
||||
status = 'parsing'
|
||||
error_code = None
|
||||
return {
|
||||
'intake_no': intake.intake_no,
|
||||
'parse_status': intake.parse_status,
|
||||
'document_count': ShippingNoticeDocument.query.filter_by(intake_id=intake.id).count(),
|
||||
'error_code': intake.error_code,
|
||||
'parse_status': status,
|
||||
'document_count': len(documents),
|
||||
'error_code': error_code,
|
||||
}
|
||||
|
||||
|
||||
@@ -2323,6 +2396,7 @@ def create_schema_migration_draft(
|
||||
raise ValidationError('Replacement field is not contract-compatible', code='SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_INVALID')
|
||||
field['field_id'] = replacement_id
|
||||
field['field_code'] = str(replacement.get('field_code') or '')
|
||||
field['scope'] = str(replacement.get('scope') or '')
|
||||
retained_order_fields.append(field)
|
||||
elif isinstance(resolution, dict) and resolution.get('action') == 'unbind':
|
||||
unbound_order_fields.append({
|
||||
@@ -2382,7 +2456,12 @@ def create_schema_migration_draft(
|
||||
)
|
||||
field['field_id'] = replacement_id
|
||||
field['field_code'] = str(replacement.get('field_code') or '')
|
||||
field['target_fields'] = [{'field_id': replacement_id, 'field_code': field['field_code']}]
|
||||
field['scope'] = str(replacement.get('scope') or '')
|
||||
field['target_fields'] = [{
|
||||
'field_id': replacement_id,
|
||||
'field_code': field['field_code'],
|
||||
'scope': field['scope'],
|
||||
}]
|
||||
retained.append(field)
|
||||
elif isinstance(resolution, dict) and resolution.get('action') == 'unbind':
|
||||
unbound.append({
|
||||
@@ -2399,6 +2478,38 @@ def create_schema_migration_draft(
|
||||
)
|
||||
layout['field_regions'] = retained
|
||||
table['draft_unbound_field_regions'] = unbound
|
||||
# A line-start field is the only deterministic row boundary. It cannot be
|
||||
# unbound without replacing it, otherwise the migrated draft would contain
|
||||
# a structurally invalid table profile that no editor can safely execute.
|
||||
for table in definition.get('table_regions') or []:
|
||||
if not isinstance(table, dict):
|
||||
continue
|
||||
main_layout = next(
|
||||
(
|
||||
item for item in (table.get('line_layouts') or [])
|
||||
if isinstance(item, dict) and item.get('role') == 'main' and int(item.get('row_offset') or 0) == 0
|
||||
),
|
||||
None,
|
||||
)
|
||||
if main_layout is None:
|
||||
continue
|
||||
bound_codes = {
|
||||
str(item.get('field_code') or '')
|
||||
for item in (main_layout.get('field_regions') or [])
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
line_start_code = str(table.get('line_start_field_code') or '')
|
||||
if bound_codes and line_start_code not in bound_codes:
|
||||
raise ValidationError(
|
||||
'The line-start field must be replaced before migration',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_REQUIRED',
|
||||
details={
|
||||
'reason': 'line_start_field_unbound',
|
||||
'table_region_id': str(table.get('region_id') or ''),
|
||||
'line_start_field_code': line_start_code,
|
||||
'available_field_codes': sorted(bound_codes),
|
||||
},
|
||||
)
|
||||
normalized = _normalize_definition(definition, schema_version=target_schema)
|
||||
version = int(db.session.query(func.max(ShippingOrderDocumentProfile.version)).filter_by(
|
||||
profile_code=source.profile_code,
|
||||
@@ -2432,10 +2543,27 @@ def create_schema_migration_draft(
|
||||
created_by_id=actor_id,
|
||||
))
|
||||
_refresh_training_sample_count(clone)
|
||||
# A migration is a new editable baseline, not a continuation of the source's revisions.
|
||||
# This keeps restore and publish-check workflows scoped to the target Schema snapshot.
|
||||
revision = ShippingOrderDocumentProfileDraftRevision(
|
||||
profile_id=clone.id,
|
||||
revision_no=1,
|
||||
base_lock_version=0,
|
||||
result_lock_version=clone.lock_version,
|
||||
definition_checksum=clone.structure_fingerprint,
|
||||
change_source='wizard_created',
|
||||
actor_id=actor_id,
|
||||
browser_session_id=None,
|
||||
operation_id=secrets.token_hex(16),
|
||||
change_summary_json=_definition_audit_summary(clone.definition_json),
|
||||
definition_snapshot_json=dict(clone.definition_json or {}),
|
||||
)
|
||||
db.session.add(revision)
|
||||
_audit(profile_id=clone.id, event_type='schema_migration_draft_created', actor_id=actor_id, detail={
|
||||
'source_profile_id': source.id,
|
||||
'source_schema_version_id': source.schema_version_id,
|
||||
'target_schema_version_id': target_schema.id,
|
||||
'revision_no': revision.revision_no,
|
||||
'breaking_field_count': len(breaking_ids),
|
||||
'unbound_field_count': sum(
|
||||
1 for item in resolutions.values() if isinstance(item, dict) and item.get('action') == 'unbind'
|
||||
@@ -2556,10 +2684,10 @@ def retire(profile_id: int, *, actor_id: int | None = None) -> dict[str, Any]:
|
||||
|
||||
def delete_draft(profile_id: int) -> None:
|
||||
"""
|
||||
删除未发布草稿及其草稿盲测集;已发布/退役版本永久保留审计。
|
||||
删除未发布草稿及其关联盲测套件/自动冻结资格;已发布/退役版本永久保留审计。
|
||||
|
||||
核心逻辑:草稿允许绑定独立盲测套件,但 suites.profile_id 外键无 CASCADE;
|
||||
删除前先移除 suite(samples/runs 由 ORM cascade 清理),避免 IntegrityError 500。
|
||||
核心逻辑:checksum 版本化后同一 profile 可有多条 suites,且 suites/auto_freeze
|
||||
对 profile_id 均无 DB CASCADE;删除前必须清掉全部子表,避免 IntegrityError 500。
|
||||
"""
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
if profile is None:
|
||||
@@ -2569,12 +2697,17 @@ def delete_draft(profile_id: int) -> None:
|
||||
'Only draft order document profile can be deleted',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_DELETE_BLOCKED',
|
||||
)
|
||||
# [STEP 1] 先清盲测套件;samples/runs 随 suite cascade delete-orphan
|
||||
suite = ShippingDocumentProfileTestSuite.query.filter_by(profile_id=profile.id).first()
|
||||
if suite is not None:
|
||||
# [STEP 1] 先清自动冻结资格(quality_suite_id 无 CASCADE,会挡住 suite 删除)
|
||||
ShippingDocumentProfileAutoFreezeQualification.query.filter_by(
|
||||
profile_id=profile.id,
|
||||
).delete(synchronize_session=False)
|
||||
# [STEP 2] 删除该 Profile 下全部盲测套件(含 superseded);samples/runs 随 ORM cascade
|
||||
suites = ShippingDocumentProfileTestSuite.query.filter_by(profile_id=profile.id).all()
|
||||
for suite in suites:
|
||||
db.session.delete(suite)
|
||||
if suites:
|
||||
db.session.flush()
|
||||
# [STEP 2] 删除草稿 Profile 本体(样本表已有 DB CASCADE)
|
||||
# [STEP 3] 删除草稿 Profile 本体(样本表等已有 DB CASCADE)
|
||||
db.session.delete(profile)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@@ -13,7 +13,11 @@ from typing import Any
|
||||
|
||||
from app.core.errors import NotFoundError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingDocumentProfileTestSuite, ShippingOrderDocumentProfile
|
||||
from app.models import (
|
||||
ShippingDocumentProfileTestSuite,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
|
||||
@@ -126,7 +130,8 @@ def _source_version_summary(profile: ShippingOrderDocumentProfile) -> dict[str,
|
||||
|
||||
|
||||
def list_profile_families() -> list[dict[str, Any]]:
|
||||
"""按 profile_code 聚合模板族摘要,并返回默认选版信息。"""
|
||||
"""按 profile_code 聚合模板族摘要,并标识是否需要迁移至当前 Schema。"""
|
||||
current_schema = ShippingOrderSchemaVersion.query.filter_by(status='published').first()
|
||||
rows = ShippingOrderDocumentProfile.query.order_by(
|
||||
ShippingOrderDocumentProfile.profile_code.asc(),
|
||||
ShippingOrderDocumentProfile.version.desc(),
|
||||
@@ -150,6 +155,10 @@ def list_profile_families() -> list[dict[str, Any]]:
|
||||
'draft_version': draft.version if draft is not None else None,
|
||||
'published_profile_id': published.id if published is not None else None,
|
||||
'published_version': published.version if published is not None else None,
|
||||
'published_schema_version_id': published.schema_version_id if published is not None else None,
|
||||
'published_schema_version': published.schema_version.version if published and published.schema_version else None,
|
||||
'current_schema_version_id': current_schema.id if current_schema is not None else None,
|
||||
'current_schema_version': current_schema.version if current_schema is not None else None,
|
||||
'latest_profile_id': latest.id,
|
||||
'latest_version': latest.version,
|
||||
'default_profile_id': default.id,
|
||||
|
||||
@@ -211,6 +211,7 @@ def persist_order_extraction_result(
|
||||
frozen_evidence_text_by_document: dict[int, str] | None = None,
|
||||
auto_create_enabled: bool = False,
|
||||
allow_orphaned_consumed_reparse: bool = False,
|
||||
allow_same_run_consumed_continuation: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
持久化后台订单抽取 Run 的结构化结果,并执行后端裁决、判重与自动建单。
|
||||
@@ -259,7 +260,7 @@ def persist_order_extraction_result(
|
||||
replay['idempotent_replay'] = True
|
||||
return replay
|
||||
if any(row.parse_status == 'consumed' for row in intakes) and not (
|
||||
allow_orphaned_consumed_reparse
|
||||
(allow_orphaned_consumed_reparse or allow_same_run_consumed_continuation)
|
||||
and all(
|
||||
row.parse_status == 'consumed'
|
||||
and row.consumed_at is not None
|
||||
@@ -971,6 +972,9 @@ def submit_order_extraction_run_result(
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
|
||||
ensure_run_review_cases(run=run)
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import maybe_stp_auto_create_for_run
|
||||
|
||||
result['stp_auto_create'] = maybe_stp_auto_create_for_run(run=run)
|
||||
_store_run_submission_result(
|
||||
intakes=current_intakes,
|
||||
snapshot_hash=str(run.input_snapshot_hash),
|
||||
@@ -1081,11 +1085,21 @@ def submit_order_extraction_unit_result(
|
||||
return result
|
||||
|
||||
session = db.session.query(ChatSession).filter_by(session_id=run.conversation_id).one()
|
||||
# A prior PDF Unit may validly consume the shared Intake before its sibling Unit
|
||||
# persists. Only reuse that Intake when this exact Run wrote the submission and
|
||||
# no Task or Batch has consumed it.
|
||||
is_same_run_consumed_continuation = (
|
||||
intake.parse_status == 'consumed'
|
||||
and intake.consumed_at is not None
|
||||
and intake.consumed_task_id is None
|
||||
and intake.consumed_batch_id is None
|
||||
and str(_order_extraction_submission(intake).get('request_id') or '') == str(run.run_no)
|
||||
)
|
||||
current_intakes = _load_intakes(
|
||||
session=session,
|
||||
intake_nos=[str(intake.intake_no)],
|
||||
lock=True,
|
||||
allow_consumed=False,
|
||||
allow_consumed=is_same_run_consumed_continuation,
|
||||
)
|
||||
current_documents = [row for row in _load_documents(current_intakes, lock=True) if int(row.id) == unit_document_id]
|
||||
if len(current_intakes) != 1 or len(current_documents) != 1:
|
||||
@@ -1125,10 +1139,14 @@ def submit_order_extraction_unit_result(
|
||||
frozen_layout_candidates_by_document=frozen_layout_candidates_by_document,
|
||||
frozen_evidence_text_by_document=frozen_evidence_text_by_document,
|
||||
auto_create_enabled=bool(((run.auto_freeze_policy_json or {}).get('enabled', False))),
|
||||
allow_same_run_consumed_continuation=is_same_run_consumed_continuation,
|
||||
)
|
||||
result['unit_id'] = int(unit.id)
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
ensure_run_review_cases(run=run)
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import maybe_stp_auto_create_for_run
|
||||
|
||||
result['stp_auto_create'] = maybe_stp_auto_create_for_run(run=run)
|
||||
_store_run_submission_result(
|
||||
intakes=current_intakes,
|
||||
snapshot_hash=str(run.input_snapshot_hash),
|
||||
|
||||
@@ -3,7 +3,8 @@ services/shipping_notice/order_extraction_merge.py
|
||||
|
||||
用途:在 HXOPS 内按稳定业务身份合并文档单元订单,并保留全部字段证据供后续裁决。
|
||||
依赖:Run 冻结动态 Schema field_id/field_code 映射。
|
||||
逻辑:同 Intake 下仅 PO 一致或 Line 的 part_number+reservation_id 一致时合并;不可靠身份保持拆分。
|
||||
逻辑:同 Intake 下仅 PO 一致或 Line 的 part_number+reservation_id 一致时合并;
|
||||
跨文档 Reservation 补全优先使用 part_number / customer_po_line_no(兼容历史 line_no)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -49,7 +50,7 @@ def _single_valid_reservation(line: dict[str, Any], codes: dict[str, str]) -> st
|
||||
def _completion_anchor_values(line: dict[str, Any], codes: dict[str, str]) -> dict[str, str]:
|
||||
"""读取可用于 PDF/邮件行补全的强锚点;只接受单一原子值。"""
|
||||
anchors: dict[str, str] = {}
|
||||
for field_code in ('part_number', 'line_no'):
|
||||
for field_code in ('part_number', 'customer_po_line_no', 'line_no'):
|
||||
values = _field_values(line.get('fields'), field_code, codes)
|
||||
if len(values) == 1:
|
||||
anchors[field_code] = next(iter(values))
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
services/shipping_notice/order_extraction_progress.py
|
||||
|
||||
用途:记录订单抽取 Run/Unit 的确定性业务事件,作为用户态进度与管理员诊断的共同事实源。
|
||||
依赖:ShippingOrderExtractionRun/Unit/ProgressEvent ORM、统一数据库会话、progress_audit_contract。
|
||||
依赖:ShippingOrderExtractionRun/Unit/ProgressEvent ORM、统一数据库会话、progress_audit_contract、
|
||||
workflow_ledger_service(进度事件尽力同步 Workflow 状态,缺 Item 不阻断进度写入)。
|
||||
逻辑:调用方只能写入受控 event_code;服务负责幂等、顺序号、终态保护和最小化 Run 投影。
|
||||
阶段 0 冻结 cancellation_* 事件码与 mapping v3;写入取消事实在阶段 1 与 Worker 检查点实现。
|
||||
"""
|
||||
@@ -175,6 +176,88 @@ def _apply_run_projection(run: ShippingOrderExtractionRun, *, event_code: str, o
|
||||
run.progress_version = int(run.progress_version or 0) + 1
|
||||
|
||||
|
||||
def _sync_workflow_from_progress_event(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
event_code: str,
|
||||
document_id: int | None,
|
||||
) -> None:
|
||||
"""
|
||||
将清晰映射的进度事件尽力同步到 WorkflowItem(缺 Item 仅记日志,不抛错)。
|
||||
|
||||
核心逻辑:layout_parsing_started → layout_parsing;抽取中事件 → extracting;
|
||||
candidate_ready/review_required → pending_review;technical_failed → failed。
|
||||
"""
|
||||
mapping = {
|
||||
'layout_parsing_started': 'layout_parsing',
|
||||
'layout_parsing_completed': 'extracting',
|
||||
'document_queued': 'extracting',
|
||||
'profile_matching': 'extracting',
|
||||
'profile_matched': 'extracting',
|
||||
'table_reconstructed': 'extracting',
|
||||
'order_fields_extracted': 'extracting',
|
||||
'email_supplement_merged': 'extracting',
|
||||
'initial_wave_started': 'extracting',
|
||||
'expansion_wave_started': 'extracting',
|
||||
'candidate_ready': 'pending_review',
|
||||
'review_required': 'pending_review',
|
||||
'technical_failed': 'failed',
|
||||
}
|
||||
target = mapping.get(str(event_code or '').strip())
|
||||
if not target:
|
||||
return
|
||||
try:
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
find_item_by_root,
|
||||
transition_item_status,
|
||||
)
|
||||
|
||||
resolved_document_id = int(document_id or 0)
|
||||
if resolved_document_id <= 0:
|
||||
return
|
||||
item = find_item_by_root(
|
||||
conversation_id=str(run.conversation_id),
|
||||
root_document_id=resolved_document_id,
|
||||
for_update=True,
|
||||
)
|
||||
if item is None:
|
||||
return
|
||||
if str(item.lifecycle_status or '') in {
|
||||
'closed', 'cancelled', 'manual_upload_pending', 'pending_review', 'failed',
|
||||
} and target != 'failed':
|
||||
# 终态/复核态/待人工上传不因迟到进度回退;失败仍可覆盖 extracting 等。
|
||||
if str(item.lifecycle_status or '') == target:
|
||||
return
|
||||
if str(item.lifecycle_status or '') in {
|
||||
'closed', 'cancelled', 'manual_upload_pending',
|
||||
}:
|
||||
return
|
||||
if str(item.lifecycle_status or '') == 'pending_review' and target != 'failed':
|
||||
return
|
||||
if str(item.lifecycle_status or '') == target:
|
||||
return
|
||||
# 禁止从复核回退到抽取;允许 failed 覆盖早期态。
|
||||
if str(item.lifecycle_status or '') == 'pending_review' and target in {
|
||||
'layout_parsing', 'extracting', 'queued',
|
||||
}:
|
||||
return
|
||||
transition_item_status(
|
||||
item=item,
|
||||
lifecycle_status=target,
|
||||
stage=target,
|
||||
actor_type='system',
|
||||
actor_id='progress',
|
||||
reason=f'progress:{event_code}',
|
||||
)
|
||||
except Exception:
|
||||
_LOGGER.exception(
|
||||
'workflow progress sync skipped run_no=%s document_id=%s event_code=%s',
|
||||
getattr(run, 'run_no', None),
|
||||
document_id,
|
||||
event_code,
|
||||
)
|
||||
|
||||
|
||||
def record_order_extraction_progress_event(
|
||||
*,
|
||||
run_no: str,
|
||||
@@ -248,6 +331,12 @@ def record_order_extraction_progress_event(
|
||||
)
|
||||
db.session.add(row)
|
||||
_apply_run_projection(run, event_code=event_code, occurred_at=occurred_at)
|
||||
# [STEP] 进度事实尽力驱动 WorkflowItem;Item 缺失不回滚进度写入。
|
||||
_sync_workflow_from_progress_event(
|
||||
run=run,
|
||||
event_code=event_code,
|
||||
document_id=document_id,
|
||||
)
|
||||
if commit:
|
||||
db.session.commit()
|
||||
else:
|
||||
|
||||
@@ -3,9 +3,11 @@ backend/app/services/shipping_notice/order_extraction_run_service.py
|
||||
|
||||
用途:创建、查询和序列化建单前订单抽取领域 Run;Unit 完成后独立触发 Candidate/STP 下游。
|
||||
依赖:Agent/ChatSession、ShippingNoticeIntake/Document、已发布订单 Schema、SQLAlchemy 事务、
|
||||
order_extraction.submit_order_extraction_unit_result、progress_workflow.auto_progress。
|
||||
order_extraction.submit_order_extraction_unit_result、progress_workflow.auto_progress、
|
||||
workflow_ledger_service(物化后幂等建 WorkflowItem)。
|
||||
逻辑:服务端校验用户与会话权限,冻结 Intake/Document/Schema 输入,并以数据库唯一约束保证幂等与单 Intake 单活跃 Run;
|
||||
progress_ready_extraction_unit 供 Worker 在每 PDF candidate_ready 后立即落库并推进。
|
||||
progress_ready_extraction_unit 供 Worker 在每 PDF candidate_ready 后立即落库并推进;
|
||||
Document 物化后立即 ensure WorkflowItem,使版面阶段即有 Item(解决 Run>0 / Item=0)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -553,6 +555,123 @@ def order_extraction_layouts_failed(run: ShippingOrderExtractionRun) -> bool:
|
||||
).first() is not None
|
||||
|
||||
|
||||
def ensure_workflow_items_for_run(
|
||||
run: ShippingOrderExtractionRun,
|
||||
*,
|
||||
stage_when_ready: str = 'extracting',
|
||||
) -> list:
|
||||
"""
|
||||
为 Run 快照内每份 PDF Document 幂等创建/绑定 WorkflowItem,并按版面状态迁移生命周期。
|
||||
|
||||
核心逻辑:新上传批次 ``create_workflow`` 一次再挂 Item;重识别复用原 Item 所属
|
||||
Workflow(只加 Version,不新建批次);幂等重入时按 current_run_id 找回已有 Workflow。
|
||||
版面仍待完成时迁到 layout_parsing,否则迁到 stage_when_ready。
|
||||
|
||||
Args:
|
||||
run: 已物化或快照已含 document_id 的订单抽取 Run。
|
||||
stage_when_ready: 版面已就绪时的目标生命周期;默认 extracting。
|
||||
|
||||
Returns:
|
||||
本轮处理到的 WorkflowItem 列表(可能为空)。
|
||||
"""
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
create_workflow,
|
||||
ensure_workflow_item_for_document,
|
||||
find_item_by_current_case,
|
||||
find_item_by_root,
|
||||
find_workflow_for_run,
|
||||
is_reparse_extraction_run,
|
||||
transition_item_status,
|
||||
)
|
||||
from app.models import ShippingOrderReviewCase
|
||||
|
||||
conversation_id = str(run.conversation_id or '').strip()
|
||||
if not conversation_id:
|
||||
return []
|
||||
layouts_pending = order_extraction_layouts_pending(run)
|
||||
target_ready = str(stage_when_ready or 'extracting').strip().lower() or 'extracting'
|
||||
target = 'layout_parsing' if layouts_pending else target_ready
|
||||
# 仅允许从早期流水线状态迁入;禁止把 pending_review / closed 等回退。
|
||||
early_statuses = frozenset({'queued', 'layout_parsing', 'extracting'})
|
||||
|
||||
# [STEP 1] 批次边界:新上传 create;重识别/幂等重入复用已有 Workflow。
|
||||
from app.models.shipping_notice_workflow import ShippingNoticeWorkflow
|
||||
|
||||
owner_agent_id = int(run.owner_agent_id) if getattr(run, 'owner_agent_id', None) else None
|
||||
workflow = find_workflow_for_run(run=run)
|
||||
reparse = is_reparse_extraction_run(run)
|
||||
|
||||
# [STEP 2] 重识别:解析同源 root,避免把替换 PDF 当成新 root 另建 Item。
|
||||
source_root_id: int | None = None
|
||||
marker = (run.input_snapshot_json or {}).get('review_reparse') if isinstance(run.input_snapshot_json, dict) else None
|
||||
if reparse and isinstance(marker, dict):
|
||||
source_case_no = str(marker.get('source_case_no') or '').strip().upper()
|
||||
if source_case_no:
|
||||
source_case = ShippingOrderReviewCase.query.filter_by(case_no=source_case_no).first()
|
||||
if source_case is not None:
|
||||
existing = find_item_by_current_case(case_id=int(source_case.id))
|
||||
if existing is None:
|
||||
existing = find_item_by_root(
|
||||
conversation_id=conversation_id,
|
||||
root_document_id=int(source_case.document_id),
|
||||
)
|
||||
if existing is not None:
|
||||
source_root_id = int(existing.root_document_id)
|
||||
workflow = db.session.get(ShippingNoticeWorkflow, int(existing.workflow_id)) or workflow
|
||||
|
||||
if workflow is None:
|
||||
# 新上传必须新建;重识别极端兜底也不挂到无关旧 open 批次。
|
||||
workflow = create_workflow(
|
||||
conversation_id=conversation_id,
|
||||
owner_user_id=int(run.user_id),
|
||||
owner_agent_id=owner_agent_id,
|
||||
actor_type='system',
|
||||
actor_id=run.user_id,
|
||||
)
|
||||
|
||||
items: list = []
|
||||
for document in _run_layout_documents(run):
|
||||
if Path(str(document.filename or '')).suffix.lower() != '.pdf':
|
||||
continue
|
||||
root_id = source_root_id if (
|
||||
source_root_id is not None
|
||||
and isinstance(marker, dict)
|
||||
and int(marker.get('document_id') or 0) == int(document.id)
|
||||
) else int(document.id)
|
||||
try:
|
||||
item = ensure_workflow_item_for_document(
|
||||
workflow=workflow,
|
||||
conversation_id=conversation_id,
|
||||
owner_user_id=int(run.user_id),
|
||||
document_id=int(document.id),
|
||||
root_document_id=root_id,
|
||||
run=run,
|
||||
owner_agent_id=owner_agent_id,
|
||||
actor_type='system',
|
||||
actor_id=run.user_id,
|
||||
)
|
||||
if (
|
||||
str(item.lifecycle_status or '') in early_statuses
|
||||
and str(item.lifecycle_status or '') != target
|
||||
):
|
||||
item = transition_item_status(
|
||||
item=item,
|
||||
lifecycle_status=target,
|
||||
stage=target,
|
||||
actor_type='system',
|
||||
actor_id=run.user_id,
|
||||
reason='ensure_workflow_items_for_run',
|
||||
)
|
||||
items.append(item)
|
||||
except Exception:
|
||||
_LOGGER.exception(
|
||||
'ensure_workflow_items_for_run failed run_no=%s document_id=%s',
|
||||
run.run_no,
|
||||
getattr(document, 'id', None),
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def schedule_order_extraction_layouts(
|
||||
run: ShippingOrderExtractionRun, *, created_by_id: int | None,
|
||||
) -> bool:
|
||||
@@ -719,9 +838,13 @@ def materialize_order_extraction_run_inputs(
|
||||
run.input_snapshot_json = materialized
|
||||
run.input_snapshot_hash = _sha256(materialized)
|
||||
db.session.flush()
|
||||
# [STEP] Document ID 已写入快照后立即建 WorkflowItem,使版面 Job 阶段即可投影 Item。
|
||||
ensure_workflow_items_for_run(run, stage_when_ready='extracting')
|
||||
if not finalize_plan:
|
||||
return None
|
||||
return ensure_order_extraction_plan(run)
|
||||
|
||||
|
||||
def _active_run_for_intakes(intake_ids: list[int]) -> ShippingOrderExtractionRun | None:
|
||||
"""读取占用任一 Intake 的未释放 Run,供并发唯一约束冲突后返回明确业务结果。"""
|
||||
return (
|
||||
@@ -969,6 +1092,12 @@ def create_order_extraction_run(
|
||||
run.phase = 'waiting_layout' if layouts_pending else 'queued'
|
||||
if layouts_pending:
|
||||
record_run_progress(run=run, event_code='layout_parsing_started', commit=False)
|
||||
# PDF 直传路径:快照已有 document_id,发送时即可建 Item(layout_parsing/queued)。
|
||||
if _run_snapshot_document_ids(run):
|
||||
ensure_workflow_items_for_run(
|
||||
run,
|
||||
stage_when_ready='queued',
|
||||
)
|
||||
for intake in intakes:
|
||||
intake.order_extraction_status = 'extracting'
|
||||
intake.order_extraction_error_code = None
|
||||
@@ -2148,6 +2277,74 @@ def sync_order_extraction_run_after_job_recovery(job: Any) -> None:
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
|
||||
error_message=str(job.error_message or '订单抽取后台任务执行超时'),
|
||||
)
|
||||
# [STEP] 同步 WorkflowItem,避免永久卡在 layout_parsing / extracting。
|
||||
sync_workflow_items_after_extraction_job_recovery(run=run, job=job)
|
||||
|
||||
|
||||
def sync_workflow_items_after_extraction_job_recovery(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
job: Any,
|
||||
) -> int:
|
||||
"""
|
||||
订单抽取 Job 超时回收后,将相关 WorkflowItem 从版面/抽取中态迁出。
|
||||
|
||||
核心逻辑:Job 重新排队 → queued;Job 终态失败 → failed;仅处理 early pipeline 状态。
|
||||
|
||||
Args:
|
||||
run: 已同步的领域 Run。
|
||||
job: 回收后的 Job。
|
||||
|
||||
Returns:
|
||||
成功迁移的 Item 数量。
|
||||
"""
|
||||
from app.models.shipping_notice_workflow import ShippingNoticeWorkflowItem
|
||||
from app.services.shipping_notice.workflow_ledger_service import transition_item_status
|
||||
|
||||
job_status = str(getattr(job, 'status', '') or '')
|
||||
if job_status == 'queued':
|
||||
target = 'queued'
|
||||
elif job_status in {'failed', 'dead', 'cancelled'}:
|
||||
target = 'failed'
|
||||
else:
|
||||
return 0
|
||||
stuck = frozenset({'layout_parsing', 'extracting'})
|
||||
document_ids = _run_snapshot_document_ids(run)
|
||||
candidates = (
|
||||
ShippingNoticeWorkflowItem.query
|
||||
.filter(
|
||||
ShippingNoticeWorkflowItem.conversation_id == str(run.conversation_id),
|
||||
ShippingNoticeWorkflowItem.lifecycle_status.in_(tuple(stuck)),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
updated = 0
|
||||
for item in candidates:
|
||||
matches_run = str(item.current_run_no or '') == str(run.run_no)
|
||||
matches_doc = bool(document_ids) and (
|
||||
int(item.root_document_id) in document_ids
|
||||
or int(item.current_document_id) in document_ids
|
||||
)
|
||||
if not matches_run and not matches_doc:
|
||||
continue
|
||||
try:
|
||||
transition_item_status(
|
||||
item=item,
|
||||
lifecycle_status=target,
|
||||
stage=target,
|
||||
actor_type='system',
|
||||
actor_id='job_recovery',
|
||||
expected_from=stuck,
|
||||
reason=f'extraction_job_recovery:{job_status}',
|
||||
)
|
||||
updated += 1
|
||||
except Exception:
|
||||
_LOGGER.exception(
|
||||
'workflow item recovery transition failed item_no=%s run_no=%s',
|
||||
getattr(item, 'item_no', None),
|
||||
run.run_no,
|
||||
)
|
||||
return updated
|
||||
|
||||
|
||||
def sync_order_extraction_run_after_job_failure(job: Any) -> None:
|
||||
|
||||
@@ -304,7 +304,11 @@ def _profile_snapshot_targets_valid(
|
||||
for layout in (table.get('header_layouts') or []) + (table.get('line_layouts') or []):
|
||||
for target in layout.get('field_regions') or []:
|
||||
code = str(target.get('field_code') or '')
|
||||
config = contract.fields_by_code.get(code) or (schema_fields or {}).get(code)
|
||||
scope = str(target.get('scope') or '')
|
||||
config = next((
|
||||
item for item in (schema_fields or {}).values()
|
||||
if str(item.get('scope') or '') == scope and str(item.get('field_code') or '') == code
|
||||
), None)
|
||||
if config is None or str(target.get('field_id') or '') != str(config.get('field_id') or ''):
|
||||
return False
|
||||
targets = target.get('target_fields') if isinstance(target.get('target_fields'), list) else []
|
||||
@@ -312,7 +316,12 @@ def _profile_snapshot_targets_valid(
|
||||
return False
|
||||
for output in targets:
|
||||
output_code = str(output.get('field_code') or '') if isinstance(output, dict) else ''
|
||||
output_config = contract.fields_by_code.get(output_code) or (schema_fields or {}).get(output_code)
|
||||
output_scope = str(output.get('scope') or '') if isinstance(output, dict) else ''
|
||||
output_config = next((
|
||||
item for item in (schema_fields or {}).values()
|
||||
if str(item.get('scope') or '') == output_scope
|
||||
and str(item.get('field_code') or '') == output_code
|
||||
), None)
|
||||
if output_config is None or str(output.get('field_id') or '') != str(output_config.get('field_id') or ''):
|
||||
return False
|
||||
return True
|
||||
@@ -419,6 +428,7 @@ def _coordinate_v2_profile_rows(
|
||||
termination_rules=[item.model_dump() for item in region.termination_rules],
|
||||
exclusion_regions=[item.model_dump() for item in region.exclusion_regions],
|
||||
initial_fields=carry.get('fields'), initial_next_offset=int(carry.get('next_offset') or 0),
|
||||
line_start_field_code=region.line_start_field_code,
|
||||
):
|
||||
values: list[dict[str, Any]] = []
|
||||
issues = list(reconstructed.issues)
|
||||
@@ -530,8 +540,8 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
definition = schema_snapshot.get('definition') if isinstance(schema_snapshot.get('definition'), dict) else {}
|
||||
contract = compile_table_header_contract(definition)
|
||||
schema_fields = {
|
||||
str(item.get('field_code') or ''): item for item in definition.get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True)
|
||||
str(item.get('field_id') or ''): item for item in definition.get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True) and item.get('field_id')
|
||||
}
|
||||
profiles = [
|
||||
item for item in snapshot.get('order_document_profiles') or []
|
||||
|
||||
@@ -3,9 +3,9 @@ services/shipping_notice/order_freeze_service.py
|
||||
|
||||
用途:将已复核的动态订单解析冻结为强类型履约快照。
|
||||
依赖:ShippingOrderExtraction/FieldValue/Observation、ShippingOrderSnapshot、ShippingTask、
|
||||
standard_field_registry(投影列)、统一 AppError。
|
||||
standard_field_registry(投影列)、audit_service、统一 AppError。
|
||||
逻辑:Candidate/Extraction 阶段可继续保留动态证据;本服务通过门禁后一次写入按 field_id 冻结的 Snapshot;
|
||||
冻结摘要含 family_code + schema_version/checksum;库存、导出和上传后续阶段只读取该快照。
|
||||
冻结时固化 derivation_rules 快照与 field_lineage;库存、导出和上传后续阶段只读取该快照。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -29,6 +29,7 @@ from app.models import (
|
||||
ShippingTask,
|
||||
ShippingNoticeDocument,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
# 强类型列只是既有查询/导出投影;56 项标准字段的完整事实始终写在 field_id JSON。
|
||||
# 注意:本常量须保持在固定履约契约 / standard_field_registry 导入之前定义,
|
||||
@@ -124,6 +125,18 @@ def freeze_order_snapshot(
|
||||
order_data_version=actual_version,
|
||||
rule_versions_json={
|
||||
**dict(rule_versions or {}),
|
||||
'derivation_rules_snapshot': list(
|
||||
((extraction.schema_version.definition_json or {}) if extraction.schema_version else {}).get('derivation_rules')
|
||||
or []
|
||||
),
|
||||
'derivation_rules_checksum': (
|
||||
((extraction.normalized_result_json or {}) if isinstance(extraction.normalized_result_json, dict) else {}).get(
|
||||
'derivation_rules_checksum'
|
||||
)
|
||||
or ((extraction.schema_version.definition_json or {}) if extraction.schema_version else {}).get(
|
||||
'derivation_rules_checksum'
|
||||
)
|
||||
),
|
||||
'fulfillment_rule': {
|
||||
'code': policy['rule_code'],
|
||||
'checksum': _fixed_rule_checksum(),
|
||||
@@ -139,7 +152,15 @@ def freeze_order_snapshot(
|
||||
'confirmed_at': customer_match.confirmed_at.isoformat() if customer_match.confirmed_at else None,
|
||||
},
|
||||
},
|
||||
source_manifest_json=_source_manifest(extraction=extraction, policy=policy),
|
||||
source_manifest_json={
|
||||
**_source_manifest(extraction=extraction, policy=policy),
|
||||
'field_lineage': list(
|
||||
((extraction.normalized_result_json or {}) if isinstance(extraction.normalized_result_json, dict) else {}).get(
|
||||
'field_lineage'
|
||||
)
|
||||
or []
|
||||
),
|
||||
},
|
||||
frozen_by_id=actor_id,
|
||||
header_values_json=_field_id_values(header_values, configs),
|
||||
**_project_values(header_values, HEADER_FIELD_PROJECTIONS),
|
||||
@@ -159,6 +180,26 @@ def freeze_order_snapshot(
|
||||
extraction_id=extraction.id,
|
||||
snapshot_id=None,
|
||||
).update({'snapshot_id': snapshot.id}, synchronize_session=False)
|
||||
append_shipping_audit_event(
|
||||
event_type='ORDER_FROZEN',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=str(task.task_no),
|
||||
task_no=task.task_no,
|
||||
actor_type='user' if actor_id else 'system',
|
||||
actor_id=actor_id or 'order_freeze_service',
|
||||
action='freeze_order_snapshot',
|
||||
result='success',
|
||||
metadata={
|
||||
'snapshot_id': snapshot.id,
|
||||
'derivation_rules_checksum': (snapshot.rule_versions_json or {}).get('derivation_rules_checksum'),
|
||||
'schema_version_id': extraction.schema_version_id,
|
||||
},
|
||||
after={
|
||||
'task_no': task.task_no,
|
||||
'schema_version_id': extraction.schema_version_id,
|
||||
'derivation_rules_checksum': (snapshot.rule_versions_json or {}).get('derivation_rules_checksum'),
|
||||
},
|
||||
)
|
||||
db.session.flush()
|
||||
return snapshot
|
||||
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
backend/app/services/shipping_notice/order_review_confirmation_service.py
|
||||
|
||||
用途:按 PDF 确认复核草稿并独立创建发货任务,确认后复用同一 auto_progress 链。
|
||||
依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task、fulfillment_audit、
|
||||
依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task、stp_inventory_freeze、
|
||||
customer_auto_resolution、fulfillment_audit、workflow_ledger_service、
|
||||
progress_workflow.auto_progress。
|
||||
逻辑:确认在单事务内分别锁定 Case 与 Draft(避免 joinedload+FOR UPDATE),
|
||||
冻结不可变 Revision,物化仅供履约的人工 Candidate 与 accepted Extraction;
|
||||
全程不改写机器 Candidate,也不创建 Batch。确认成功后无条件写 Case 级统一审计
|
||||
(不依赖工作项是否绑定),再尝试关闭会话工作项。由 workspace shipping_notice API 调用;
|
||||
API commit 后触发 progress_workflow.auto_progress(禁止平行推进链)。
|
||||
逻辑:确认在单事务内分别锁定 Case 与 Draft,重跑资格门禁,冻结行级库存源候选与
|
||||
可自动确认的客户;物化人工 Candidate 与 accepted Extraction(保留派生 field_lineage);
|
||||
校验 WorkflowItem 当前版本后推进至 building_order(不关闭);API commit 后触发
|
||||
auto_progress(库存源已冻结时跳过 inventory_source_review),止于 manual_upload_pending。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,10 +16,10 @@ from __future__ import annotations
|
||||
import copy
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
from typing import Any, NoReturn
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingNoticeCandidate,
|
||||
@@ -34,7 +34,6 @@ from app.models import (
|
||||
ShippingOrderReviewCaseEvent,
|
||||
ShippingOrderReviewConfirmedRevision,
|
||||
ShippingOrderReviewDraft,
|
||||
ShippingSessionPdfWorkItem,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
@@ -59,6 +58,54 @@ from app.services.shipping_notice.tool_common import generate_task_no, log_task_
|
||||
_CONFIRMABLE_STATUSES = frozenset({'draft', 'ready', 'unreviewed'})
|
||||
|
||||
|
||||
def soft_load_case_for_confirm_reject(*, user_id: int, case_no: str) -> ShippingOrderReviewCase | None:
|
||||
"""
|
||||
无行锁加载确认目标 Case,供幂等键/警告格式等早期门禁写拒绝审计。
|
||||
|
||||
Args:
|
||||
user_id: Case 属主。
|
||||
case_no: 复核 Case 编号。
|
||||
|
||||
Returns:
|
||||
Case 或 None。
|
||||
"""
|
||||
from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit
|
||||
|
||||
return soft_load_review_case_for_audit(user_id=user_id, case_no=case_no)
|
||||
|
||||
|
||||
def reject_confirm_precondition(
|
||||
*,
|
||||
user_id: int,
|
||||
case_no: str,
|
||||
error: AppError,
|
||||
idempotency_key: str = '',
|
||||
) -> NoReturn:
|
||||
"""
|
||||
Case 可定位时写确认拒绝审计后抛错;否则直接抛错。
|
||||
|
||||
核心逻辑:用于锁定 Case 之前的请求边界拒绝(缺幂等键、警告格式非法、body 非对象)。
|
||||
|
||||
Args:
|
||||
user_id: 操作人。
|
||||
case_no: 目标 Case。
|
||||
error: 业务异常。
|
||||
idempotency_key: 已解析的幂等键(可为空)。
|
||||
|
||||
Raises:
|
||||
AppError: 传入的 error。
|
||||
"""
|
||||
case = soft_load_case_for_confirm_reject(user_id=user_id, case_no=case_no)
|
||||
if case is None:
|
||||
raise error
|
||||
_reject_confirmation(
|
||||
case,
|
||||
actor_id=int(user_id),
|
||||
error=error,
|
||||
idempotency_key=str(idempotency_key or ''),
|
||||
)
|
||||
|
||||
|
||||
def _expected_version(value: Any) -> int:
|
||||
"""确认请求必须声明草稿版本,避免旧页面确认一个已变更的订单。"""
|
||||
if isinstance(value, bool):
|
||||
@@ -88,11 +135,13 @@ def _warning_acknowledgements(value: Any) -> list[dict[str, Any]]:
|
||||
]
|
||||
|
||||
|
||||
def _locked_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase:
|
||||
"""锁定 Case/Draft,确保双击或并发浏览器不会创建两张 Task。
|
||||
def _locked_case(*, user_id: int, case_no: str, idempotency_key: str) -> ShippingOrderReviewCase:
|
||||
"""
|
||||
锁定 Case/Draft,确保双击或并发浏览器不会创建两张 Task。
|
||||
|
||||
核心逻辑:先单独 FOR UPDATE Case;再按 current_draft_id 二次锁定 Draft。
|
||||
PostgreSQL 不允许对外连接可空侧使用 FOR UPDATE,故禁止 joinedload + with_for_update。
|
||||
不可确认态写拒绝审计后抛错。
|
||||
"""
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
@@ -107,10 +156,22 @@ def _locked_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase:
|
||||
return case
|
||||
# [STEP 2] 可确认态必须存在 Draft;按非空 FK 单独加锁,避免 LEFT JOIN FOR UPDATE
|
||||
if case.status not in _CONFIRMABLE_STATUSES or case.current_draft_id is None:
|
||||
raise ConflictError('Order review case cannot be confirmed', code='SHIPPING.REVIEW_CONFIRM_NOT_ALLOWED')
|
||||
if case.current_draft_id is not None and case.current_draft is None:
|
||||
case.current_draft = db.session.get(ShippingOrderReviewDraft, int(case.current_draft_id))
|
||||
_reject_confirmation(
|
||||
case,
|
||||
actor_id=int(user_id),
|
||||
error=ConflictError('Order review case cannot be confirmed', code='SHIPPING.REVIEW_CONFIRM_NOT_ALLOWED'),
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
draft = ShippingOrderReviewDraft.query.filter_by(id=int(case.current_draft_id)).with_for_update().first()
|
||||
if draft is None:
|
||||
raise ConflictError('Order review case cannot be confirmed', code='SHIPPING.REVIEW_CONFIRM_NOT_ALLOWED')
|
||||
_reject_confirmation(
|
||||
case,
|
||||
actor_id=int(user_id),
|
||||
error=ConflictError('Order review case cannot be confirmed', code='SHIPPING.REVIEW_CONFIRM_NOT_ALLOWED'),
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
case.current_draft = draft
|
||||
return case
|
||||
|
||||
@@ -136,6 +197,132 @@ def _json_value(value: Any) -> Any:
|
||||
return value
|
||||
|
||||
|
||||
def _source_extraction_lineage(case: ShippingOrderReviewCase) -> tuple[list[dict[str, Any]], str | None]:
|
||||
"""
|
||||
读取机器解析 Extraction / Unit 上的派生血缘与规则校验和。
|
||||
|
||||
核心逻辑:优先 Candidate.order_extraction_id → normalized_result_json;
|
||||
否则回退 Unit.result_json。供确认物化 Extraction 写入冻结可追溯快照。
|
||||
"""
|
||||
rows: list[dict[str, Any]] = []
|
||||
checksum: str | None = None
|
||||
candidate = db.session.get(ShippingNoticeCandidate, case.candidate_id) if case.candidate_id else None
|
||||
extraction_id = getattr(candidate, 'order_extraction_id', None) if candidate is not None else None
|
||||
if extraction_id:
|
||||
extraction = db.session.get(ShippingOrderExtraction, int(extraction_id))
|
||||
normalized = extraction.normalized_result_json if extraction is not None and isinstance(
|
||||
extraction.normalized_result_json, dict,
|
||||
) else {}
|
||||
rows = [item for item in (normalized.get('field_lineage') or []) if isinstance(item, dict)]
|
||||
raw_checksum = normalized.get('derivation_rules_checksum')
|
||||
checksum = str(raw_checksum) if raw_checksum else None
|
||||
if not checksum and extraction is not None and extraction.schema_version is not None:
|
||||
definition = extraction.schema_version.definition_json or {}
|
||||
if isinstance(definition, dict) and definition.get('derivation_rules_checksum'):
|
||||
checksum = str(definition.get('derivation_rules_checksum'))
|
||||
if not rows and case.unit is not None and isinstance(case.unit.result_json, dict):
|
||||
rows = [item for item in (case.unit.result_json.get('field_lineage') or []) if isinstance(item, dict)]
|
||||
if not checksum and case.unit.result_json.get('derivation_rules_checksum'):
|
||||
checksum = str(case.unit.result_json.get('derivation_rules_checksum'))
|
||||
return rows, checksum
|
||||
|
||||
|
||||
def _confirmation_field_lineage(
|
||||
case: ShippingOrderReviewCase,
|
||||
*,
|
||||
summary_lines: list[dict[str, Any]],
|
||||
) -> tuple[list[dict[str, Any]], str | None]:
|
||||
"""
|
||||
将源解析血缘按行位映射到确认后 Extraction 的 review-* line_key。
|
||||
|
||||
核心逻辑:按草稿行顺序对齐;若该行 line_no 已被人工覆盖,则改写为 manual_override 血缘。
|
||||
"""
|
||||
source_rows, checksum = _source_extraction_lineage(case)
|
||||
draft_lines = [
|
||||
item for item in (case.current_draft.lines_json or [])
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
line_no_field_id = None
|
||||
run = case.run
|
||||
definition = (
|
||||
(run.input_snapshot_json or {}).get('schema', {}).get('definition', {})
|
||||
if run is not None and isinstance(run.input_snapshot_json, dict) else {}
|
||||
)
|
||||
for item in definition.get('fields') or []:
|
||||
if (
|
||||
isinstance(item, dict)
|
||||
and str(item.get('field_code') or '') == 'line_no'
|
||||
and str(item.get('scope') or '') == 'line'
|
||||
):
|
||||
line_no_field_id = str(item.get('field_id') or '') or None
|
||||
break
|
||||
|
||||
by_key: dict[str, list[dict[str, Any]]] = {}
|
||||
for item in source_rows:
|
||||
key = str(item.get('line_key') or '').strip()
|
||||
if key:
|
||||
by_key.setdefault(key, []).append(item)
|
||||
|
||||
ordered_keys: list[str] = []
|
||||
for item in source_rows:
|
||||
key = str(item.get('line_key') or '').strip()
|
||||
if key and key not in ordered_keys:
|
||||
ordered_keys.append(key)
|
||||
|
||||
remapped: list[dict[str, Any]] = []
|
||||
for position, draft_line in enumerate(draft_lines):
|
||||
new_key = f'review-{position + 1}'
|
||||
old_key = str(draft_line.get('line_key') or '').strip()
|
||||
source_items = list(by_key.get(old_key) or [])
|
||||
if not source_items and position < len(ordered_keys):
|
||||
source_items = list(by_key.get(ordered_keys[position]) or [])
|
||||
|
||||
values = draft_line.get('values') if isinstance(draft_line.get('values'), dict) else {}
|
||||
override_entry = values.get(line_no_field_id) if line_no_field_id else None
|
||||
line_no_overridden = (
|
||||
isinstance(override_entry, dict)
|
||||
and str(override_entry.get('source') or '') == 'manual_override'
|
||||
)
|
||||
summary_line = summary_lines[position] if position < len(summary_lines) else {}
|
||||
for item in source_items:
|
||||
row = dict(item)
|
||||
row['line_key'] = new_key
|
||||
if str(row.get('field_code') or '') == 'line_no' and line_no_overridden:
|
||||
row['value_source'] = 'manual_override'
|
||||
row['after_value'] = summary_line.get('line_no')
|
||||
row['skip_reason'] = None
|
||||
remapped.append(row)
|
||||
return remapped, checksum
|
||||
|
||||
|
||||
def _build_confirmation_normalized_result(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
summary: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
组装确认后 Extraction.normalized_result_json。
|
||||
|
||||
核心逻辑:保留确认摘要的 header/lines,并附加源解析 field_lineage 与派生规则校验和,
|
||||
供冻结快照写入可追溯项次派生来源。
|
||||
"""
|
||||
header_values = {key: value for key, value in summary.items() if key != 'lines'}
|
||||
lines = [dict(item) for item in (summary.get('lines') or []) if isinstance(item, dict)]
|
||||
lineage, checksum = _confirmation_field_lineage(case, summary_lines=lines)
|
||||
if not checksum and case.current_draft is not None:
|
||||
from app.models import ShippingOrderSchemaVersion
|
||||
version = db.session.get(ShippingOrderSchemaVersion, int(case.current_draft.schema_version_id))
|
||||
definition = (version.definition_json or {}) if version is not None else {}
|
||||
if isinstance(definition, dict) and definition.get('derivation_rules_checksum'):
|
||||
checksum = str(definition.get('derivation_rules_checksum'))
|
||||
return {
|
||||
'header': header_values,
|
||||
'lines': lines,
|
||||
'field_lineage': lineage,
|
||||
'derivation_rules_checksum': checksum,
|
||||
}
|
||||
|
||||
|
||||
def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, summary: dict[str, Any], actor_id: int) -> ShippingOrderExtraction:
|
||||
"""以人工确认草稿建立 accepted Extraction,不伪造机器观察或覆盖机器抽取。"""
|
||||
run = case.run
|
||||
@@ -144,16 +331,16 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su
|
||||
if isinstance(run.input_snapshot_json, dict) else {}
|
||||
)
|
||||
configs = [item for item in definition.get('fields') or [] if isinstance(item, dict) and item.get('enabled', True)]
|
||||
normalized = _build_confirmation_normalized_result(case=case, summary=summary)
|
||||
extraction = ShippingOrderExtraction(
|
||||
run_id=int(run.id), intake_id=int(intake_id), schema_version_id=int(case.current_draft.schema_version_id),
|
||||
input_snapshot_hash=str(run.input_snapshot_hash or ''),
|
||||
input_snapshot_json={'source': 'review_confirmation', 'case_no': case.case_no, 'document_id': int(case.document_id)},
|
||||
status='accepted', raw_llm_output_json=None, normalized_result_json=copy.deepcopy(summary),
|
||||
status='accepted', raw_llm_output_json=None, normalized_result_json=normalized,
|
||||
validation_result_json={'blocked_fields': [], 'source': 'review_confirmation'}, created_by_id=int(actor_id),
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
header = summary.get('lines')
|
||||
header_values = {key: value for key, value in summary.items() if key != 'lines'}
|
||||
for scope, line_id, values in [('header', None, header_values)]:
|
||||
for config in configs:
|
||||
@@ -197,20 +384,40 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su
|
||||
return extraction
|
||||
|
||||
|
||||
def _session_item_no_for_case(case: ShippingOrderReviewCase) -> str | None:
|
||||
def _workflow_refs_for_case(case: ShippingOrderReviewCase) -> dict[str, str | None]:
|
||||
"""
|
||||
按 current_case_id 反查会话工作项编号。
|
||||
|
||||
核心逻辑:确认审计不得因工作项缺失而跳过;仅用于填充关联字段。
|
||||
按 current_case_id 反查 Workflow / WorkflowItem 业务编号。
|
||||
|
||||
Args:
|
||||
case: 当前复核 Case。
|
||||
|
||||
Returns:
|
||||
工作项编号;未绑定时为 None。
|
||||
workflow_id(workflow_no)与 workflow_item_id(item_no);未绑定时为 None。
|
||||
"""
|
||||
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=int(case.id)).first()
|
||||
return str(item.item_no) if item is not None else None
|
||||
from app.services.shipping_notice.workflow_ledger_service import find_item_by_current_case
|
||||
|
||||
item = find_item_by_current_case(case_id=int(case.id))
|
||||
if item is None:
|
||||
return {'workflow_id': None, 'workflow_item_id': None}
|
||||
return {
|
||||
'workflow_id': str(item.workflow_no) if item.workflow_no else None,
|
||||
'workflow_item_id': str(item.item_no) if item.item_no else None,
|
||||
}
|
||||
|
||||
|
||||
def _workflow_item_no_for_case(case: ShippingOrderReviewCase) -> str | None:
|
||||
"""
|
||||
按 current_case_id 反查 WorkflowItem 业务编号。
|
||||
|
||||
核心逻辑:确认审计不得因 Item 缺失而跳过;仅用于填充关联字段。
|
||||
|
||||
Args:
|
||||
case: 当前复核 Case。
|
||||
|
||||
Returns:
|
||||
WorkflowItem 编号;未绑定时为 None。
|
||||
"""
|
||||
return _workflow_refs_for_case(case).get('workflow_item_id')
|
||||
|
||||
|
||||
def _conversation_id_for_case(case: ShippingOrderReviewCase) -> str | None:
|
||||
@@ -229,6 +436,76 @@ def _conversation_id_for_case(case: ShippingOrderReviewCase) -> str | None:
|
||||
return str(run.conversation_id) if run is not None and run.conversation_id else None
|
||||
|
||||
|
||||
def _reject_confirmation(
|
||||
case: ShippingOrderReviewCase,
|
||||
*,
|
||||
actor_id: int,
|
||||
error: AppError,
|
||||
idempotency_key: str,
|
||||
before: dict[str, Any] | None = None,
|
||||
needs_rollback: bool = False,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> NoReturn:
|
||||
"""
|
||||
记录确认建单拒绝审计并独立提交后抛出业务异常。
|
||||
|
||||
核心逻辑:API 遇 AppError 不会 commit。门禁拒绝直接写审计;若已进入 confirming
|
||||
并产生脏写,先 rollback 再按 case_no 重载 Case,仅提交拒绝审计,避免留下
|
||||
confirming 半成品。
|
||||
|
||||
Args:
|
||||
case: 已识别的复核 Case(needs_rollback 时仅取其 case_no/owner)。
|
||||
actor_id: 请求操作人。
|
||||
error: 即将抛出的业务异常(须含 code)。
|
||||
idempotency_key: 本次确认幂等键。
|
||||
before: 拒绝前状态快照;缺省取当前 Case。
|
||||
needs_rollback: True 时丢弃本事务业务脏写后再写审计。
|
||||
metadata: 额外脱敏诊断。
|
||||
|
||||
Raises:
|
||||
AppError: 传入的 error(审计已提交)。
|
||||
"""
|
||||
case_no = str(case.case_no)
|
||||
owner_user_id = int(case.owner_user_id)
|
||||
before_snap = dict(before) if before else None
|
||||
if needs_rollback:
|
||||
db.session.rollback()
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(case_no=case_no, owner_user_id=owner_user_id)
|
||||
.first()
|
||||
)
|
||||
if case is None:
|
||||
raise error
|
||||
if case.current_draft_id and case.current_draft is None:
|
||||
case.current_draft = db.session.get(ShippingOrderReviewDraft, int(case.current_draft_id))
|
||||
code = str(getattr(error, 'code', '') or 'SHIPPING.REVIEW_CONFIRM_REJECTED')
|
||||
snap = {
|
||||
'status': str(case.status or ''),
|
||||
'disposition': case.disposition,
|
||||
'draft_version': int(case.current_draft.draft_version) if case.current_draft is not None else None,
|
||||
}
|
||||
if before_snap is None:
|
||||
before_snap = dict(snap)
|
||||
_record_unified_confirmation_audit(
|
||||
case,
|
||||
actor_id=int(actor_id),
|
||||
before=before_snap,
|
||||
after={**snap, 'error_code': code},
|
||||
task_no=None,
|
||||
idempotency_key=idempotency_key,
|
||||
result='rejected',
|
||||
error_code=code,
|
||||
metadata={
|
||||
'rejection': True,
|
||||
'error_code': code,
|
||||
**(metadata or {}),
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
raise error
|
||||
|
||||
|
||||
def _record_unified_confirmation_audit(
|
||||
case: ShippingOrderReviewCase,
|
||||
*,
|
||||
@@ -237,21 +514,34 @@ def _record_unified_confirmation_audit(
|
||||
after: dict[str, Any],
|
||||
task_no: str | None,
|
||||
idempotency_key: str,
|
||||
result: str = 'success',
|
||||
idempotent_replay: bool = False,
|
||||
error_code: str | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
将确认建单写入统一 ShippingAuditEvent,供审计中心无条件覆盖。
|
||||
|
||||
核心逻辑:与 CaseEvent / 工作项关闭同事务;即使未绑定工作项也必须落库,
|
||||
保证操作人、请求关联与前后快照可追溯。
|
||||
核心逻辑:与 CaseEvent / 工作项关闭同事务;即使未绑定工作项也必须落库;
|
||||
幂等回放路径使用 result=ignored;拒绝路径使用 result=rejected + error_code。
|
||||
|
||||
Args:
|
||||
case: 已置为 confirmed 的 Case。
|
||||
case: 复核 Case。
|
||||
actor_id: 确认操作人用户 ID。
|
||||
before: 确认前状态摘要(白名单字段)。
|
||||
after: 确认后状态摘要(含 task_no)。
|
||||
task_no: 新建任务号。
|
||||
after: 确认后或拒绝时状态摘要。
|
||||
task_no: 新建或回放任务号;拒绝时为 None。
|
||||
idempotency_key: 建单幂等键。
|
||||
result: 审计结果码(success / ignored / rejected)。
|
||||
idempotent_replay: 是否为幂等回放请求。
|
||||
error_code: 拒绝时的业务错误码。
|
||||
metadata: 额外脱敏元数据(与标准 idempotency 字段合并)。
|
||||
"""
|
||||
merged_meta = {
|
||||
'idempotency_key': idempotency_key,
|
||||
'idempotent_replay': bool(idempotent_replay),
|
||||
**(metadata or {}),
|
||||
}
|
||||
record_fulfillment_audit(
|
||||
event_type='review_confirmed',
|
||||
aggregate_type='order_review_case',
|
||||
@@ -263,15 +553,53 @@ def _record_unified_confirmation_audit(
|
||||
owner_user_id=case.owner_user_id,
|
||||
document_id=case.document_id,
|
||||
conversation_id=_conversation_id_for_case(case),
|
||||
session_item_id=_session_item_no_for_case(case),
|
||||
workflow_item_id=_workflow_item_no_for_case(case),
|
||||
task_no=task_no,
|
||||
result=result,
|
||||
error_code=error_code,
|
||||
before=before,
|
||||
after=after,
|
||||
metadata={'idempotency_key': idempotency_key},
|
||||
metadata=merged_meta,
|
||||
source='order_review',
|
||||
)
|
||||
|
||||
|
||||
def _audit_idempotent_confirmation_replay(
|
||||
*,
|
||||
user_id: int,
|
||||
case: ShippingOrderReviewCase,
|
||||
task_no: str | None,
|
||||
idempotency_key: str,
|
||||
) -> None:
|
||||
"""
|
||||
记录确认建单幂等回放请求的统一审计。
|
||||
|
||||
核心逻辑:不改业务状态;before=after 为当前确认态,result=ignored。
|
||||
|
||||
Args:
|
||||
user_id: 本次请求操作人。
|
||||
case: 已确认 Case。
|
||||
task_no: 既有任务号。
|
||||
idempotency_key: 本次请求幂等键。
|
||||
"""
|
||||
snap = {
|
||||
'status': str(case.status or ''),
|
||||
'disposition': case.disposition,
|
||||
'confirmed_task_no': task_no,
|
||||
'draft_version': int(case.current_draft.draft_version) if case.current_draft is not None else None,
|
||||
}
|
||||
_record_unified_confirmation_audit(
|
||||
case,
|
||||
actor_id=int(user_id),
|
||||
before=snap,
|
||||
after=snap,
|
||||
task_no=task_no,
|
||||
idempotency_key=idempotency_key,
|
||||
result='ignored',
|
||||
idempotent_replay=True,
|
||||
)
|
||||
|
||||
|
||||
def _create_review_candidate(*, case: ShippingOrderReviewCase, intake: ShippingNoticeIntake, document: ShippingNoticeDocument, summary: dict[str, Any], extraction: ShippingOrderExtraction, user_id: int) -> ShippingNoticeCandidate:
|
||||
"""物化独立人工 Candidate,复用既有重复、客户和下游 Task 关联契约。"""
|
||||
identity = build_business_fingerprint(summary)
|
||||
@@ -306,10 +634,14 @@ def _create_review_candidate(*, case: ShippingOrderReviewCase, intake: ShippingN
|
||||
|
||||
def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: Any, idempotency_key: str | None, warning_acknowledgements: Any = None) -> dict[str, Any]:
|
||||
"""
|
||||
确认一个 PDF 草稿并建一张无 Batch 的 Task;任何门禁失败都由事务回滚。
|
||||
确认一个 PDF 草稿并建一张无 Batch 的 Task;门禁拒绝写统一审计后抛错。
|
||||
|
||||
核心逻辑:成功路径无条件写 Case 级 `review_confirmed` 统一审计(含操作人与前后快照),
|
||||
再尝试关闭绑定的会话工作项;工作项缺失不得跳过统一审计。
|
||||
再尝试将绑定的会话工作项推进至 building_order 并返回 workflow_id / workflow_item_id;
|
||||
工作项缺失不得跳过统一审计。
|
||||
幂等回放(同键或已确认 Case)同样写审计(result=ignored),追溯重复提交。
|
||||
版本冲突/校验失败/文档不可用/重复订单等拒绝写 result=rejected,并在 raise 前独立 commit。
|
||||
锁定 Case 之前的边界拒绝(缺幂等键、警告格式非法、幂等键跨 Case 占用)在 Case 可定位时同样写拒绝审计。
|
||||
|
||||
Args:
|
||||
user_id: Case 属主用户 ID。
|
||||
@@ -319,55 +651,151 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
warning_acknowledgements: 警告确认列表。
|
||||
|
||||
Returns:
|
||||
含 task_no / case / trigger_auto_progress 的确认结果。
|
||||
含 task_no / case / workflow_id / workflow_item_id / trigger_auto_progress 的确认结果。
|
||||
"""
|
||||
key = normalize_create_idempotency_key(idempotency_key)
|
||||
if not key:
|
||||
raise ValidationError('idempotency_key is required', code='SHIPPING.REVIEW_IDEMPOTENCY_KEY_REQUIRED')
|
||||
expected = _expected_version(expected_draft_version)
|
||||
acknowledgements = _warning_acknowledgements(warning_acknowledgements)
|
||||
reject_confirm_precondition(
|
||||
user_id=int(user_id),
|
||||
case_no=case_no,
|
||||
error=ValidationError('idempotency_key is required', code='SHIPPING.REVIEW_IDEMPOTENCY_KEY_REQUIRED'),
|
||||
idempotency_key='',
|
||||
)
|
||||
try:
|
||||
acknowledgements = _warning_acknowledgements(warning_acknowledgements)
|
||||
except ValidationError as err:
|
||||
reject_confirm_precondition(
|
||||
user_id=int(user_id),
|
||||
case_no=case_no,
|
||||
error=err,
|
||||
idempotency_key=key,
|
||||
)
|
||||
replay = ShippingOrderReviewConfirmedRevision.query.filter_by(idempotency_key=key).first()
|
||||
if replay is not None:
|
||||
case = db.session.get(ShippingOrderReviewCase, int(replay.case_id))
|
||||
if case is None or int(case.owner_user_id) != int(user_id):
|
||||
raise ConflictError('Idempotency key is unavailable', code='SHIPPING.REVIEW_IDEMPOTENCY_KEY_CONFLICT')
|
||||
# 同键仅允许回放原 Case;其他 Case(含同用户)或属主不匹配均拒绝并写审计。
|
||||
if (
|
||||
case is None
|
||||
or int(case.owner_user_id) != int(user_id)
|
||||
or str(case.case_no) != str(case_no)
|
||||
):
|
||||
reject_confirm_precondition(
|
||||
user_id=int(user_id),
|
||||
case_no=case_no,
|
||||
error=ConflictError(
|
||||
'Idempotency key is unavailable',
|
||||
code='SHIPPING.REVIEW_IDEMPOTENCY_KEY_CONFLICT',
|
||||
),
|
||||
idempotency_key=key,
|
||||
)
|
||||
task = db.session.get(ShippingTask, int(replay.task_id))
|
||||
return {'task_no': task.task_no if task else None, 'idempotent_replay': True, 'case': serialize_review_case(case)}
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
task_no = task.task_no if task else None
|
||||
_audit_idempotent_confirmation_replay(
|
||||
user_id=user_id,
|
||||
case=case,
|
||||
task_no=task_no,
|
||||
idempotency_key=key,
|
||||
)
|
||||
db.session.flush()
|
||||
return {
|
||||
'task_no': task_no,
|
||||
'idempotent_replay': True,
|
||||
'case': serialize_review_case(case),
|
||||
**_workflow_refs_for_case(case),
|
||||
}
|
||||
case = _locked_case(user_id=user_id, case_no=case_no, idempotency_key=key)
|
||||
if case.status == 'confirmed' and case.confirmed_task_id:
|
||||
task = db.session.get(ShippingTask, int(case.confirmed_task_id))
|
||||
return {'task_no': task.task_no if task else None, 'idempotent_replay': True, 'case': serialize_review_case(case)}
|
||||
task_no = task.task_no if task else None
|
||||
_audit_idempotent_confirmation_replay(
|
||||
user_id=user_id,
|
||||
case=case,
|
||||
task_no=task_no,
|
||||
idempotency_key=key,
|
||||
)
|
||||
db.session.flush()
|
||||
return {
|
||||
'task_no': task_no,
|
||||
'idempotent_replay': True,
|
||||
'case': serialize_review_case(case),
|
||||
**_workflow_refs_for_case(case),
|
||||
} try:
|
||||
expected = _expected_version(expected_draft_version)
|
||||
except ValidationError as err:
|
||||
_reject_confirmation(case, actor_id=int(user_id), error=err, idempotency_key=key)
|
||||
if int(case.current_draft.draft_version) != expected:
|
||||
raise ConflictError('Review draft version changed', code='SHIPPING.REVIEW_DRAFT_VERSION_MISMATCH')
|
||||
_reject_confirmation(
|
||||
case,
|
||||
actor_id=int(user_id),
|
||||
error=ConflictError('Review draft version changed', code='SHIPPING.REVIEW_DRAFT_VERSION_MISMATCH'),
|
||||
idempotency_key=key,
|
||||
metadata={'expected_draft_version': expected},
|
||||
)
|
||||
summary, validation = build_confirmable_draft_summary(case)
|
||||
if validation.get('status') != 'ready':
|
||||
raise ConflictError('Review draft is not ready', code='SHIPPING.REVIEW_CONFIRM_VALIDATION_FAILED', details={'issues': validation.get('issues') or []})
|
||||
_reject_confirmation(
|
||||
case,
|
||||
actor_id=int(user_id),
|
||||
error=ConflictError(
|
||||
'Review draft is not ready',
|
||||
code='SHIPPING.REVIEW_CONFIRM_VALIDATION_FAILED',
|
||||
details={'issues': validation.get('issues') or []},
|
||||
),
|
||||
idempotency_key=key,
|
||||
metadata={'validation_status': str(validation.get('status') or '')[:32] or None},
|
||||
)
|
||||
document = db.session.get(ShippingNoticeDocument, int(case.document_id))
|
||||
if document is None:
|
||||
raise ConflictError('Review document is unavailable', code='SHIPPING.REVIEW_CONFIRM_DOCUMENT_INVALID')
|
||||
_reject_confirmation(
|
||||
case,
|
||||
actor_id=int(user_id),
|
||||
error=ConflictError('Review document is unavailable', code='SHIPPING.REVIEW_CONFIRM_DOCUMENT_INVALID'),
|
||||
idempotency_key=key,
|
||||
)
|
||||
intake = db.session.get(ShippingNoticeIntake, int(document.intake_id))
|
||||
if intake is None or int(intake.user_id) != int(user_id) or str(document.parse_status or '') != 'parsed':
|
||||
raise ConflictError('Review document is unavailable', code='SHIPPING.REVIEW_CONFIRM_DOCUMENT_INVALID')
|
||||
_reject_confirmation(
|
||||
case,
|
||||
actor_id=int(user_id),
|
||||
error=ConflictError('Review document is unavailable', code='SHIPPING.REVIEW_CONFIRM_DOCUMENT_INVALID'),
|
||||
idempotency_key=key,
|
||||
)
|
||||
asset = db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else None
|
||||
content_hash = str(document.content_hash or (asset.content_hash if asset else '')).strip()
|
||||
if content_hash:
|
||||
acquire_notice_create_locks(int(user_id), [content_hash])
|
||||
assert_no_exact_duplicate_notices(int(user_id), [{
|
||||
'source_content_hash': content_hash,
|
||||
'source_file_name': document.filename,
|
||||
'duplicate_resolution_type': 'normal',
|
||||
}])
|
||||
try:
|
||||
assert_no_exact_duplicate_notices(int(user_id), [{
|
||||
'source_content_hash': content_hash,
|
||||
'source_file_name': document.filename,
|
||||
'duplicate_resolution_type': 'normal',
|
||||
}])
|
||||
except ConflictError as err:
|
||||
_reject_confirmation(case, actor_id=int(user_id), error=err, idempotency_key=key)
|
||||
previous_status = str(case.status or '')
|
||||
previous_disposition = case.disposition
|
||||
before_snap = {'status': previous_status, 'disposition': previous_disposition}
|
||||
case.status = 'confirming'
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import (
|
||||
assert_case_is_current_work_item_version,
|
||||
close_work_item_for_case,
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
advance_workflow_item_after_confirm,
|
||||
assert_case_is_current_workflow_version,
|
||||
)
|
||||
assert_case_is_current_work_item_version(case=case)
|
||||
normalized = normalize_candidate_business_summary(summary)
|
||||
extraction = _materialize_extraction(case=case, intake_id=int(intake.id), summary=normalized, actor_id=int(user_id))
|
||||
candidate = _create_review_candidate(case=case, intake=intake, document=document, summary=normalized, extraction=extraction, user_id=int(user_id))
|
||||
try:
|
||||
assert_case_is_current_workflow_version(case=case)
|
||||
normalized = normalize_candidate_business_summary(summary)
|
||||
extraction = _materialize_extraction(case=case, intake_id=int(intake.id), summary=normalized, actor_id=int(user_id))
|
||||
candidate = _create_review_candidate(
|
||||
case=case, intake=intake, document=document, summary=normalized, extraction=extraction, user_id=int(user_id),
|
||||
)
|
||||
except AppError as err:
|
||||
_reject_confirmation(
|
||||
case,
|
||||
actor_id=int(user_id),
|
||||
error=err,
|
||||
idempotency_key=key,
|
||||
before=before_snap,
|
||||
needs_rollback=True,
|
||||
)
|
||||
shipping_case = resolve_shipping_case_for_new_task(created_by_id=int(user_id))
|
||||
task = ShippingTask(
|
||||
task_no=generate_task_no(), shipping_case_id=int(shipping_case.id), batch_id=None, user_id=int(user_id),
|
||||
@@ -386,8 +814,18 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
candidate.updated_at = datetime.utcnow()
|
||||
# The review Case is the explicit human confirmation for this PDF. Do not
|
||||
# recreate a low-confidence parse checkpoint on the newly materialized Task.
|
||||
# Customer/inventory gates remain enforced by the standard task UI state.
|
||||
apply_task_transition(task, TaskTransition.CONFIRM_PARSE)
|
||||
# [STEP] 冻结建单资格中的行级库存源候选;单源 resolved,多源 candidates_frozen。
|
||||
from app.services.shipping_notice.stp_inventory_freeze import freeze_stp_inventory_candidates_on_task
|
||||
|
||||
freeze_stp_inventory_candidates_on_task(
|
||||
task,
|
||||
line_projections=list(validation.get('line_projections') or []),
|
||||
)
|
||||
# [STEP] 客户可自动确认时跳过 customer_review,与批次建单路径一致。
|
||||
from app.services.shipping_notice.customer_auto_resolution import try_auto_confirm_task_customer
|
||||
|
||||
try_auto_confirm_task_customer(task)
|
||||
revision = ShippingOrderReviewConfirmedRevision(
|
||||
case_id=int(case.id), task_id=int(task.id), draft_version=int(case.current_draft.draft_version),
|
||||
schema_version_id=int(case.current_draft.schema_version_id), header_values_json=copy.deepcopy(case.current_draft.header_values_json or {}),
|
||||
@@ -406,7 +844,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
_record_unified_confirmation_audit(
|
||||
case,
|
||||
actor_id=int(user_id),
|
||||
before={'status': previous_status, 'disposition': previous_disposition},
|
||||
before=before_snap,
|
||||
after={
|
||||
'status': case.status,
|
||||
'disposition': case.disposition,
|
||||
@@ -416,25 +854,25 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
task_no=task.task_no,
|
||||
idempotency_key=key,
|
||||
)
|
||||
close_work_item_for_case(
|
||||
# Phase 3:确认后推进至 building_order 并持续自动进度,直至 manual_upload_pending;不关闭 Item。
|
||||
advance_workflow_item_after_confirm(
|
||||
case=case,
|
||||
closed_reason='confirmed',
|
||||
task_no=task.task_no,
|
||||
actor_type='user',
|
||||
actor_id=user_id,
|
||||
task_no=task.task_no,
|
||||
event_type='review_confirmed',
|
||||
)
|
||||
log_task_event(task, 'task_created_from_review_case', {'case_no': case.case_no, 'confirmed_revision_id': None})
|
||||
db.session.flush()
|
||||
workflow_refs = _workflow_refs_for_case(case)
|
||||
# 调用方须在 commit 后调用 trigger_auto_progress_after_review_confirm。
|
||||
return {
|
||||
'task_no': task.task_no,
|
||||
'idempotent_replay': False,
|
||||
'case': serialize_review_case(case),
|
||||
'trigger_auto_progress': True,
|
||||
**workflow_refs,
|
||||
}
|
||||
|
||||
|
||||
def trigger_auto_progress_after_review_confirm(*, task_no: str | None, idempotent_replay: bool = False) -> dict[str, Any] | None:
|
||||
"""
|
||||
人工复核确认建单并提交事务后,复用与 STP 直通相同的 auto_progress 入口。
|
||||
|
||||
@@ -2,19 +2,21 @@
|
||||
backend/app/services/shipping_notice/order_review_disposition_service.py
|
||||
|
||||
用途:建单前订单复核的 PDF 处置与单文件重识别服务。
|
||||
依赖:Review Case/Draft/Event、冻结 Run/Document、抽取 Run 创建服务、fulfillment_audit。
|
||||
依赖:Review Case/Draft/Event、冻结 Run/Document、抽取 Run 创建服务、fulfillment_audit、
|
||||
workflow_ledger_service。
|
||||
逻辑:处置只改变当前 PDF 的 Case 生命周期;锁定时分别 FOR UPDATE Case 与 Draft,
|
||||
禁止 joinedload+FOR UPDATE。单文件重识别通过新的 Run 保留原始 PDF 与机器结果,
|
||||
成功后才由 Run 终态钩子替代旧 Case。每次关键处置同时写 CaseEvent + 统一 ShippingAuditEvent;
|
||||
质量异常原因码 `other` 时备注必填。由 workspace shipping_notice API 调用。
|
||||
质量异常原因码 `other` 时备注必填。被拒绝操作(无效原因、终态冲突、替代状态不满足、
|
||||
WorkflowItem 已关闭等)在抛错前独立 commit 拒绝审计,避免 API 回滚吞掉留痕。由 workspace shipping_notice API 调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from typing import Any, NoReturn
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
Agent,
|
||||
ShippingNoticeCandidate,
|
||||
@@ -33,6 +35,9 @@ _QUALITY_REASONS = frozenset({
|
||||
'blurred', 'incomplete_pages', 'password_protected', 'corrupted', 'wrong_orientation',
|
||||
'unsupported_layout', 'missing_order_table', 'other',
|
||||
})
|
||||
_NON_ORDER_REASONS = frozenset({'non_order', 'duplicate_file', 'other'})
|
||||
_TERMINAL_DISPOSITION_STATUSES = frozenset({'confirmed', 'non_order', 'superseded', 'reparse_pending'})
|
||||
_REPLACEMENT_ALLOWED_STATUSES = frozenset({'quality_issue', 'draft', 'ready', 'unreviewed'})
|
||||
|
||||
|
||||
def _locked_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase:
|
||||
@@ -73,11 +78,11 @@ def _append_event(case: ShippingOrderReviewCase, *, actor_id: int, event_type: s
|
||||
))
|
||||
|
||||
|
||||
def _session_item_no_for_case(case: ShippingOrderReviewCase) -> str | None:
|
||||
"""按 current_case_id 反查会话工作项编号。"""
|
||||
from app.models import ShippingSessionPdfWorkItem
|
||||
def _workflow_item_no_for_case(case: ShippingOrderReviewCase) -> str | None:
|
||||
"""按 current_case_id 反查 WorkflowItem 业务编号。"""
|
||||
from app.services.shipping_notice.workflow_ledger_service import find_item_by_current_case
|
||||
|
||||
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=int(case.id)).first()
|
||||
item = find_item_by_current_case(case_id=int(case.id))
|
||||
return str(item.item_no) if item is not None else None
|
||||
|
||||
|
||||
@@ -98,11 +103,26 @@ def _record_unified_disposition_audit(
|
||||
reason_code: str | None = None,
|
||||
reason: str | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
result: str = 'success',
|
||||
error_code: str | None = None,
|
||||
run_no: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
将处置写入统一 ShippingAuditEvent,供管理员审计中心覆盖。
|
||||
|
||||
核心逻辑:与 CaseEvent 同事务;附带会话/工作项关联与请求客户端哈希。
|
||||
核心逻辑:与 CaseEvent 同事务;附带会话/WorkflowItem 关联与请求客户端哈希;
|
||||
幂等复用路径使用 result=ignored;拒绝路径使用 result=rejected。
|
||||
|
||||
Args:
|
||||
case: 复核 Case。
|
||||
actor_id: 操作人用户 ID。
|
||||
event_type/action: 稳定事件与动作码。
|
||||
before/after: 白名单状态摘要。
|
||||
reason_code/reason: 原因码与说明。
|
||||
metadata: 脱敏诊断字段。
|
||||
result: 审计结果;幂等复用为 ignored,拒绝为 rejected。
|
||||
error_code: 拒绝时的稳定业务错误码。
|
||||
run_no: 关联抽取 Run 编号。
|
||||
"""
|
||||
record_fulfillment_audit(
|
||||
event_type=event_type,
|
||||
@@ -115,9 +135,12 @@ def _record_unified_disposition_audit(
|
||||
owner_user_id=case.owner_user_id,
|
||||
document_id=case.document_id,
|
||||
conversation_id=_conversation_id_for_case(case),
|
||||
session_item_id=_session_item_no_for_case(case),
|
||||
workflow_item_id=_workflow_item_no_for_case(case),
|
||||
run_no=run_no,
|
||||
reason_code=reason_code,
|
||||
reason=reason,
|
||||
result=result,
|
||||
error_code=error_code,
|
||||
before=before,
|
||||
after=after,
|
||||
metadata=metadata or {},
|
||||
@@ -125,15 +148,264 @@ def _record_unified_disposition_audit(
|
||||
)
|
||||
|
||||
|
||||
def _reject_case_operation(
|
||||
case: ShippingOrderReviewCase,
|
||||
*,
|
||||
actor_id: int,
|
||||
event_type: str,
|
||||
action: str,
|
||||
error: AppError,
|
||||
reason_code: str | None = None,
|
||||
reason: str | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> NoReturn:
|
||||
"""
|
||||
记录 Case 级拒绝审计并独立提交后抛出业务异常。
|
||||
|
||||
核心逻辑:API 在 AppError 时不会 commit;拒绝事实必须在 raise 前落库,
|
||||
否则审计中心无法追溯被拒绝请求的操作人、时间与当时状态。
|
||||
|
||||
Args:
|
||||
case: 已识别的复核 Case。
|
||||
actor_id: 请求操作人。
|
||||
event_type/action: 与拟执行操作对齐的稳定码。
|
||||
error: 即将抛出的业务异常(须含 code)。
|
||||
reason_code/reason: 请求中携带的原因(可为空)。
|
||||
metadata: 额外脱敏诊断。
|
||||
|
||||
Raises:
|
||||
AppError: 传入的 error(审计已提交)。
|
||||
"""
|
||||
snap = {
|
||||
'status': str(case.status or ''),
|
||||
'disposition': case.disposition,
|
||||
'draft_version': int(case.current_draft.draft_version) if case.current_draft is not None else None,
|
||||
}
|
||||
code = str(getattr(error, 'code', '') or 'SHIPPING.REVIEW_OPERATION_REJECTED')
|
||||
_record_unified_disposition_audit(
|
||||
case,
|
||||
actor_id=actor_id,
|
||||
event_type=event_type,
|
||||
action=action,
|
||||
before=snap,
|
||||
after={**snap, 'error_code': code},
|
||||
reason_code=reason_code,
|
||||
reason=reason,
|
||||
result='rejected',
|
||||
error_code=code,
|
||||
metadata={
|
||||
'rejection': True,
|
||||
'error_code': code,
|
||||
**(metadata or {}),
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
raise error
|
||||
|
||||
|
||||
def _reject_reparse_after_dirty_failure(
|
||||
*,
|
||||
case_no: str,
|
||||
owner_user_id: int,
|
||||
actor_id: int,
|
||||
event_type: str,
|
||||
action: str,
|
||||
error: AppError,
|
||||
reason_code: str | None = None,
|
||||
reason: str | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> NoReturn:
|
||||
"""
|
||||
重识别写路径中途失败时:回滚脏写后对可定位 Case 写拒绝审计。
|
||||
|
||||
核心逻辑:`mark_reparse_started` 发现工作项已关闭等冲突时,此前可能已写入
|
||||
reparse_pending / CaseEvent / 成功态审计 / 后继 Run;须先 rollback 再只提交拒绝审计。
|
||||
|
||||
Args:
|
||||
case_no/owner_user_id: 回滚后重载 Case 的定位键。
|
||||
actor_id: 操作人。
|
||||
event_type/action: 拟执行操作码。
|
||||
error: 业务冲突。
|
||||
reason_code/reason/metadata: 可选诊断。
|
||||
|
||||
Raises:
|
||||
AppError: 传入的 error(审计已提交);Case 不可重载时直接抛出。
|
||||
"""
|
||||
db.session.rollback()
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(case_no=str(case_no), owner_user_id=int(owner_user_id))
|
||||
.first()
|
||||
)
|
||||
if case is None:
|
||||
raise error
|
||||
if case.current_draft_id and case.current_draft is None:
|
||||
case.current_draft = db.session.get(ShippingOrderReviewDraft, int(case.current_draft_id))
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=int(actor_id),
|
||||
event_type=event_type,
|
||||
action=action,
|
||||
error=error,
|
||||
reason_code=reason_code,
|
||||
reason=reason,
|
||||
metadata={'dirty_rollback': True, **(metadata or {})},
|
||||
)
|
||||
|
||||
|
||||
def _reject_if_work_item_closed(
|
||||
case: ShippingOrderReviewCase,
|
||||
*,
|
||||
actor_id: int,
|
||||
event_type: str,
|
||||
action: str,
|
||||
reason_code: str | None = None,
|
||||
reason: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
写入处置/重识别前检查 WorkflowItem 是否已关闭;已关闭则写拒绝审计并抛错。
|
||||
|
||||
核心逻辑:按 current_case_id 定位 Item。关闭/取消后仅保留追溯入口,禁止再改 Case 状态。
|
||||
"""
|
||||
from app.services.shipping_notice.workflow_ledger_service import find_item_by_current_case
|
||||
|
||||
item = find_item_by_current_case(case_id=int(case.id))
|
||||
if item is None:
|
||||
return
|
||||
if item.lifecycle_status in {'closed', 'cancelled'}:
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=int(actor_id),
|
||||
event_type=event_type,
|
||||
action=action,
|
||||
error=ConflictError(
|
||||
'Closed workflow item cannot be mutated',
|
||||
code='SHIPPING_NOTICE.WORKFLOW_ITEM_CLOSED',
|
||||
),
|
||||
reason_code=reason_code,
|
||||
reason=reason,
|
||||
metadata={'item_no': item.item_no, 'closed_reason': item.closed_reason},
|
||||
)
|
||||
|
||||
|
||||
def _require_reason(
|
||||
case: ShippingOrderReviewCase,
|
||||
*,
|
||||
actor_id: int,
|
||||
event_type: str,
|
||||
action: str,
|
||||
value: Any,
|
||||
allowed: frozenset[str],
|
||||
code: str,
|
||||
) -> str:
|
||||
"""
|
||||
校验原因码;无效时写拒绝审计并抛错。
|
||||
|
||||
Args:
|
||||
case: 当前 Case。
|
||||
actor_id: 操作人。
|
||||
event_type/action: 拟执行操作码。
|
||||
value: 请求原因。
|
||||
allowed: 允许原因集合。
|
||||
code: 无效时的错误码。
|
||||
|
||||
Returns:
|
||||
规范化原因码。
|
||||
"""
|
||||
normalized = str(value or '').strip().lower()
|
||||
if normalized not in allowed:
|
||||
attempted = str(value or '').strip()[:64] or None
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=actor_id,
|
||||
event_type=event_type,
|
||||
action=action,
|
||||
error=ValidationError('Review disposition reason is invalid', code=code),
|
||||
reason_code=attempted,
|
||||
metadata={'attempted_reason_present': bool(attempted)},
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def _audit_idempotent_reparse_reuse(
|
||||
case: ShippingOrderReviewCase,
|
||||
*,
|
||||
actor_id: int,
|
||||
event_type: str,
|
||||
action: str,
|
||||
successor_run: ShippingOrderExtractionRun,
|
||||
reason_code: str | None = None,
|
||||
reason: str | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
记录重识别/替代重识别幂等复用请求的 Case 级统一审计。
|
||||
|
||||
核心逻辑:不改 Case 状态;before=after,result=ignored,关联后继 Run。
|
||||
|
||||
Args:
|
||||
case: 当前复核 Case。
|
||||
actor_id: 本次请求操作人。
|
||||
event_type/action: 与首次请求对齐的稳定码。
|
||||
successor_run: 被复用的处理中/既有后继 Run。
|
||||
reason_code/reason: 本次提交的原因。
|
||||
metadata: 额外脱敏字段。
|
||||
"""
|
||||
snap = {'status': str(case.status or ''), 'disposition': case.disposition, 'successor_run_no': successor_run.run_no}
|
||||
meta = {
|
||||
'idempotent_reuse': True,
|
||||
'successor_run_no': successor_run.run_no,
|
||||
**(metadata or {}),
|
||||
}
|
||||
_record_unified_disposition_audit(
|
||||
case,
|
||||
actor_id=actor_id,
|
||||
event_type=event_type,
|
||||
action=action,
|
||||
before=snap,
|
||||
after=snap,
|
||||
reason_code=reason_code,
|
||||
reason=reason,
|
||||
metadata=meta,
|
||||
result='ignored',
|
||||
run_no=successor_run.run_no,
|
||||
)
|
||||
|
||||
|
||||
def create_manual_draft(*, user_id: int, case_no: str, comment: str | None = None) -> dict[str, Any]:
|
||||
"""启用无 Candidate PDF 的唯一现有 Draft;不会创建第二个订单或修改机器来源。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
_reject_if_work_item_closed(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_manual_draft_created',
|
||||
action='create_manual_draft',
|
||||
reason=str(comment or '').strip()[:500] or None,
|
||||
)
|
||||
if case.candidate_id is not None:
|
||||
raise ConflictError('Machine order already exists', code='SHIPPING.REVIEW_MANUAL_DRAFT_ALREADY_HAS_CANDIDATE')
|
||||
if case.status in {'confirmed', 'non_order', 'superseded', 'reparse_pending'}:
|
||||
raise ConflictError('Order review case cannot create a manual draft', code='SHIPPING.REVIEW_CASE_NOT_EDITABLE')
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_manual_draft_created',
|
||||
action='create_manual_draft',
|
||||
error=ConflictError('Machine order already exists', code='SHIPPING.REVIEW_MANUAL_DRAFT_ALREADY_HAS_CANDIDATE'),
|
||||
)
|
||||
if case.status in _TERMINAL_DISPOSITION_STATUSES:
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_manual_draft_created',
|
||||
action='create_manual_draft',
|
||||
error=ConflictError('Order review case cannot create a manual draft', code='SHIPPING.REVIEW_CASE_NOT_EDITABLE'),
|
||||
)
|
||||
if case.current_draft is None:
|
||||
raise ConflictError('Review draft is unavailable', code='SHIPPING.REVIEW_DRAFT_NOT_FOUND')
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_manual_draft_created',
|
||||
action='create_manual_draft',
|
||||
error=ConflictError('Review draft is unavailable', code='SHIPPING.REVIEW_DRAFT_NOT_FOUND'),
|
||||
)
|
||||
previous = case.status
|
||||
case.status = 'draft'
|
||||
case.disposition = 'manual_order'
|
||||
@@ -156,9 +428,31 @@ def create_manual_draft(*, user_id: int, case_no: str, comment: str | None = Non
|
||||
def mark_non_order(*, user_id: int, case_no: str, reason: str, comment: str | None = None) -> dict[str, Any]:
|
||||
"""把当前 PDF 标记为非订单;仅影响本 Case,且不产生 Task 或删除机器结果。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
if case.status in {'confirmed', 'non_order', 'superseded', 'reparse_pending'}:
|
||||
raise ConflictError('Order review case cannot be marked non-order', code='SHIPPING.REVIEW_DISPOSITION_NOT_ALLOWED')
|
||||
normalized = _reason(reason, allowed=frozenset({'non_order', 'duplicate_file', 'other'}), code='SHIPPING.REVIEW_NON_ORDER_REASON_INVALID')
|
||||
_reject_if_work_item_closed(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_marked_non_order',
|
||||
action='mark_non_order',
|
||||
reason_code=str(reason or '').strip().lower()[:64] or None,
|
||||
)
|
||||
if case.status in _TERMINAL_DISPOSITION_STATUSES:
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_marked_non_order',
|
||||
action='mark_non_order',
|
||||
error=ConflictError('Order review case cannot be marked non-order', code='SHIPPING.REVIEW_DISPOSITION_NOT_ALLOWED'),
|
||||
reason_code=str(reason or '').strip().lower()[:64] or None,
|
||||
)
|
||||
normalized = _require_reason(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_marked_non_order',
|
||||
action='mark_non_order',
|
||||
value=reason,
|
||||
allowed=_NON_ORDER_REASONS,
|
||||
code='SHIPPING.REVIEW_NON_ORDER_REASON_INVALID',
|
||||
)
|
||||
previous = case.status
|
||||
previous_disposition = case.disposition
|
||||
case.status = 'non_order'
|
||||
@@ -183,8 +477,8 @@ def mark_non_order(*, user_id: int, case_no: str, reason: str, comment: str | No
|
||||
reason_code=normalized,
|
||||
reason=comment_text or normalized,
|
||||
)
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import close_work_item_for_case
|
||||
close_work_item_for_case(
|
||||
from app.services.shipping_notice.workflow_ledger_service import close_workflow_item_for_case
|
||||
close_workflow_item_for_case(
|
||||
case=case,
|
||||
closed_reason='non_order',
|
||||
actor_type='user',
|
||||
@@ -200,7 +494,8 @@ def mark_quality_issue(*, user_id: int, case_no: str, reason: str, comment: str
|
||||
"""
|
||||
标记文件质量异常并保留 PDF、草稿和机器值,供补件或单文件重识别恢复。
|
||||
|
||||
核心逻辑:原因码 `other` 时备注必填,确保统一审计可复盘具体业务理由。
|
||||
核心逻辑:原因码 `other` 时备注必填,确保统一审计可复盘具体业务理由;
|
||||
终态/无效原因/空备注拒绝前写独立拒绝审计。
|
||||
|
||||
Args:
|
||||
user_id: Case 属主用户 ID。
|
||||
@@ -216,14 +511,43 @@ def mark_quality_issue(*, user_id: int, case_no: str, reason: str, comment: str
|
||||
ConflictError: Case 处于不可处置终态。
|
||||
"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
if case.status in {'confirmed', 'non_order', 'superseded', 'reparse_pending'}:
|
||||
raise ConflictError('Order review case cannot be marked quality issue', code='SHIPPING.REVIEW_DISPOSITION_NOT_ALLOWED')
|
||||
normalized = _reason(reason, allowed=_QUALITY_REASONS, code='SHIPPING.REVIEW_QUALITY_REASON_INVALID')
|
||||
_reject_if_work_item_closed(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_marked_quality_issue',
|
||||
action='mark_quality_issue',
|
||||
reason_code=str(reason or '').strip().lower()[:64] or None,
|
||||
)
|
||||
if case.status in _TERMINAL_DISPOSITION_STATUSES:
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_marked_quality_issue',
|
||||
action='mark_quality_issue',
|
||||
error=ConflictError('Order review case cannot be marked quality issue', code='SHIPPING.REVIEW_DISPOSITION_NOT_ALLOWED'),
|
||||
reason_code=str(reason or '').strip().lower()[:64] or None,
|
||||
)
|
||||
normalized = _require_reason(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_marked_quality_issue',
|
||||
action='mark_quality_issue',
|
||||
value=reason,
|
||||
allowed=_QUALITY_REASONS,
|
||||
code='SHIPPING.REVIEW_QUALITY_REASON_INVALID',
|
||||
)
|
||||
comment_text = str(comment or '').strip()[:500] or None
|
||||
if normalized == 'other' and not comment_text:
|
||||
raise ValidationError(
|
||||
'Quality issue comment is required when reason is other',
|
||||
code='SHIPPING.REVIEW_QUALITY_COMMENT_REQUIRED',
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_marked_quality_issue',
|
||||
action='mark_quality_issue',
|
||||
error=ValidationError(
|
||||
'Quality issue comment is required when reason is other',
|
||||
code='SHIPPING.REVIEW_QUALITY_COMMENT_REQUIRED',
|
||||
),
|
||||
reason_code=normalized,
|
||||
)
|
||||
previous = case.status
|
||||
case.status = 'quality_issue'
|
||||
@@ -246,16 +570,53 @@ def mark_quality_issue(*, user_id: int, case_no: str, reason: str, comment: str
|
||||
|
||||
|
||||
def reparse_case_document(*, user_id: int, case_no: str, reason: str, comment: str | None = None) -> tuple[ShippingOrderExtractionRun, bool]:
|
||||
"""仅以当前 Case 的 Document 创建新版 Run;重复点击复用同一后继 Run。"""
|
||||
"""
|
||||
仅以当前 Case 的 Document 创建新版 Run;重复点击复用同一后继 Run。
|
||||
|
||||
核心逻辑:发现处理中后继或 create 返回 reused 时不改业务状态,但仍写 Case 级幂等审计。
|
||||
|
||||
Args:
|
||||
user_id: Case 属主。
|
||||
case_no: 复核 Case 编号。
|
||||
reason: 重识别原因码。
|
||||
comment: 自由说明。
|
||||
|
||||
Returns:
|
||||
(后继 Run, 是否复用既有 Run)。
|
||||
"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
if case.status in {'confirmed', 'non_order', 'superseded'}:
|
||||
raise ConflictError('Order review case cannot be reparsed', code='SHIPPING.REVIEW_REPARSE_NOT_ALLOWED')
|
||||
normalized = _reason(reason, allowed=_REPARSE_REASONS, code='SHIPPING.REVIEW_REPARSE_REASON_INVALID')
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='document_reparse_requested',
|
||||
action='reparse_document',
|
||||
error=ConflictError('Order review case cannot be reparsed', code='SHIPPING.REVIEW_REPARSE_NOT_ALLOWED'),
|
||||
reason_code=str(reason or '').strip().lower()[:64] or None,
|
||||
)
|
||||
normalized = _require_reason(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='document_reparse_requested',
|
||||
action='reparse_document',
|
||||
value=reason,
|
||||
allowed=_REPARSE_REASONS,
|
||||
code='SHIPPING.REVIEW_REPARSE_REASON_INVALID',
|
||||
)
|
||||
comment_text = str(comment or '').strip()[:500] or None
|
||||
source = db.session.get(ShippingOrderExtractionRun, int(case.run_id))
|
||||
user = db.session.get(User, int(user_id))
|
||||
owner_agent = db.session.get(Agent, int(source.owner_agent_id)) if source is not None else None
|
||||
if source is None or user is None or owner_agent is None:
|
||||
raise ConflictError('Review reparse source is unavailable', code='SHIPPING.REVIEW_REPARSE_SOURCE_INVALID')
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='document_reparse_requested',
|
||||
action='reparse_document',
|
||||
error=ConflictError('Review reparse source is unavailable', code='SHIPPING.REVIEW_REPARSE_SOURCE_INVALID'),
|
||||
reason_code=normalized,
|
||||
reason=comment_text,
|
||||
)
|
||||
# 同一个 Document 的处理中后继是幂等赢家;其他 PDF 的重识别不应互相影响。
|
||||
successors = ShippingOrderExtractionRun.query.filter_by(reparse_of_run_id=int(source.id)).order_by(
|
||||
ShippingOrderExtractionRun.created_at.desc(),
|
||||
@@ -264,29 +625,95 @@ def reparse_case_document(*, user_id: int, case_no: str, reason: str, comment: s
|
||||
marker = (successor.input_snapshot_json or {}).get('review_reparse')
|
||||
if isinstance(marker, dict) and int(marker.get('document_id') or 0) == int(case.document_id):
|
||||
if successor.status in {'queued', 'processing'}:
|
||||
_audit_idempotent_reparse_reuse(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='document_reparse_requested',
|
||||
action='reparse_document',
|
||||
successor_run=successor,
|
||||
reason_code=normalized,
|
||||
reason=comment_text,
|
||||
)
|
||||
db.session.flush()
|
||||
return successor, True
|
||||
if case.status == 'reparse_pending':
|
||||
raise ConflictError('Document reparse is pending', code='SHIPPING.REVIEW_REPARSE_PENDING')
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='document_reparse_requested',
|
||||
action='reparse_document',
|
||||
error=ConflictError('Document reparse is pending', code='SHIPPING.REVIEW_REPARSE_PENDING'),
|
||||
reason_code=normalized,
|
||||
reason=comment_text,
|
||||
)
|
||||
_reject_if_work_item_closed(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='document_reparse_requested',
|
||||
action='reparse_document',
|
||||
reason_code=normalized,
|
||||
reason=comment_text,
|
||||
)
|
||||
source_intake = next((item for item in source.intakes if int(item.intake_id) == int(case.unit.intake_id)), None)
|
||||
if source_intake is None:
|
||||
raise ConflictError('Review reparse input is unavailable', code='SHIPPING.REVIEW_REPARSE_SOURCE_INVALID')
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='document_reparse_requested',
|
||||
action='reparse_document',
|
||||
error=ConflictError('Review reparse input is unavailable', code='SHIPPING.REVIEW_REPARSE_SOURCE_INVALID'),
|
||||
reason_code=normalized,
|
||||
reason=comment_text,
|
||||
)
|
||||
from app.models import ShippingNoticeIntake
|
||||
intake = db.session.get(ShippingNoticeIntake, int(source_intake.intake_id))
|
||||
intake_no = str(intake.intake_no if intake is not None else '').strip()
|
||||
if not intake_no:
|
||||
raise ConflictError('Review reparse input is unavailable', code='SHIPPING.REVIEW_REPARSE_SOURCE_INVALID')
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='document_reparse_requested',
|
||||
action='reparse_document',
|
||||
error=ConflictError('Review reparse input is unavailable', code='SHIPPING.REVIEW_REPARSE_SOURCE_INVALID'),
|
||||
reason_code=normalized,
|
||||
reason=comment_text,
|
||||
)
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user, agent_id=int(owner_agent.id), conversation_id=str(source.conversation_id), intake_nos=[intake_no],
|
||||
upload_batch_id=(source.input_snapshot_json or {}).get('upload_batch_id'), reparse_of_run=source,
|
||||
reparse_reason=normalized, reparse_comment=comment, selected_document_id=int(case.document_id), reparse_case_no=case.case_no,
|
||||
)
|
||||
if not reused:
|
||||
previous = case.status
|
||||
case.status = 'reparse_pending'
|
||||
_append_event(case, actor_id=user_id, event_type='document_reparse_started', operation={
|
||||
'previous_status': previous, 'reason': normalized, 'successor_run_no': run.run_no,
|
||||
})
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import mark_reparse_started
|
||||
if reused:
|
||||
_audit_idempotent_reparse_reuse(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='document_reparse_requested',
|
||||
action='reparse_document',
|
||||
successor_run=run,
|
||||
reason_code=normalized,
|
||||
reason=comment_text,
|
||||
)
|
||||
db.session.flush()
|
||||
return run, True
|
||||
previous = case.status
|
||||
case.status = 'reparse_pending'
|
||||
_append_event(case, actor_id=user_id, event_type='document_reparse_started', operation={
|
||||
'previous_status': previous, 'reason': normalized, 'successor_run_no': run.run_no,
|
||||
})
|
||||
_record_unified_disposition_audit(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='document_reparse_requested',
|
||||
action='reparse_document',
|
||||
before={'status': previous},
|
||||
after={'status': case.status, 'successor_run_no': run.run_no},
|
||||
reason_code=normalized,
|
||||
reason=comment_text,
|
||||
metadata={'successor_run_no': run.run_no},
|
||||
run_no=run.run_no,
|
||||
)
|
||||
from app.services.shipping_notice.workflow_ledger_service import mark_reparse_started
|
||||
try:
|
||||
mark_reparse_started(
|
||||
case=case,
|
||||
successor_run=run,
|
||||
@@ -294,25 +721,65 @@ def reparse_case_document(*, user_id: int, case_no: str, reason: str, comment: s
|
||||
comment=comment,
|
||||
actor_id=user_id,
|
||||
)
|
||||
db.session.flush()
|
||||
return run, reused
|
||||
except ConflictError as err:
|
||||
_reject_reparse_after_dirty_failure(
|
||||
case_no=str(case.case_no),
|
||||
owner_user_id=int(case.owner_user_id),
|
||||
actor_id=user_id,
|
||||
event_type='document_reparse_requested',
|
||||
action='reparse_document',
|
||||
error=err,
|
||||
reason_code=normalized,
|
||||
reason=comment_text,
|
||||
metadata={'successor_run_no': run.run_no},
|
||||
)
|
||||
db.session.flush()
|
||||
return run, False
|
||||
|
||||
|
||||
def create_replacement_upload_intake(*, user_id: int, case_no: str, asset_no: str) -> dict[str, Any]:
|
||||
"""为质量异常 PDF 建立新的私有 Intake;新文件永不覆盖原 Document 或旧 Case。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
if case.status not in {'quality_issue', 'draft', 'ready', 'unreviewed'}:
|
||||
raise ConflictError('Order review case cannot upload a replacement', code='SHIPPING.REVIEW_REPLACEMENT_NOT_ALLOWED')
|
||||
if case.status not in _REPLACEMENT_ALLOWED_STATUSES:
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_intake_created',
|
||||
action='create_replacement_intake',
|
||||
error=ConflictError('Order review case cannot upload a replacement', code='SHIPPING.REVIEW_REPLACEMENT_NOT_ALLOWED'),
|
||||
)
|
||||
source = db.session.get(ShippingOrderExtractionRun, int(case.run_id))
|
||||
if source is None:
|
||||
raise ConflictError('Review replacement source is unavailable', code='SHIPPING.REVIEW_REPARSE_SOURCE_INVALID')
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_intake_created',
|
||||
action='create_replacement_intake',
|
||||
error=ConflictError('Review replacement source is unavailable', code='SHIPPING.REVIEW_REPARSE_SOURCE_INVALID'),
|
||||
)
|
||||
from app.services.file_assets.service import get_asset_for_user
|
||||
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
|
||||
|
||||
asset = get_asset_for_user(str(asset_no or '').strip(), int(user_id))
|
||||
try:
|
||||
asset = get_asset_for_user(str(asset_no or '').strip(), int(user_id))
|
||||
except AppError as err:
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_intake_created',
|
||||
action='create_replacement_intake',
|
||||
error=err,
|
||||
metadata={'asset_no': str(asset_no or '').strip()[:64] or None},
|
||||
)
|
||||
extension = str(asset.extension or '').strip().lower()
|
||||
if extension != 'pdf':
|
||||
raise ValidationError('Replacement file must be a PDF', code='SHIPPING.REVIEW_REPLACEMENT_FILE_INVALID')
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_intake_created',
|
||||
action='create_replacement_intake',
|
||||
error=ValidationError('Replacement file must be a PDF', code='SHIPPING.REVIEW_REPLACEMENT_FILE_INVALID'),
|
||||
)
|
||||
intake = create_shipping_notice_intake(
|
||||
user_id=int(user_id), asset_no=str(asset.asset_no), conversation_id=str(source.conversation_id),
|
||||
upload_batch_id=f'review-replacement-{case.case_no.lower()}',
|
||||
@@ -334,60 +801,122 @@ def create_replacement_upload_intake(*, user_id: int, case_no: str, asset_no: st
|
||||
|
||||
|
||||
def create_replacement_document_run(*, user_id: int, case_no: str, intake_no: str) -> tuple[ShippingOrderExtractionRun, bool]:
|
||||
"""在替代 Intake 已解析为唯一 PDF Document 后创建新 Run,并把旧 Case 置为等待替代结果。"""
|
||||
"""
|
||||
在替代 Intake 已解析为唯一 PDF Document 后创建新 Run,并把旧 Case 置为等待替代结果。
|
||||
|
||||
核心逻辑:create 返回 reused 时仍写 Case 级幂等审计;状态/解析不满足时写拒绝审计。
|
||||
"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
if case.status not in {'quality_issue', 'draft', 'ready', 'unreviewed'}:
|
||||
raise ConflictError('Order review case cannot use a replacement', code='SHIPPING.REVIEW_REPLACEMENT_NOT_ALLOWED')
|
||||
if case.status not in _REPLACEMENT_ALLOWED_STATUSES:
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
error=ConflictError('Order review case cannot use a replacement', code='SHIPPING.REVIEW_REPLACEMENT_NOT_ALLOWED'),
|
||||
)
|
||||
source = db.session.get(ShippingOrderExtractionRun, int(case.run_id))
|
||||
user = db.session.get(User, int(user_id))
|
||||
owner_agent = db.session.get(Agent, int(source.owner_agent_id)) if source is not None else None
|
||||
if source is None or user is None or owner_agent is None:
|
||||
raise ConflictError('Review replacement source is unavailable', code='SHIPPING.REVIEW_REPARSE_SOURCE_INVALID')
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
error=ConflictError('Review replacement source is unavailable', code='SHIPPING.REVIEW_REPARSE_SOURCE_INVALID'),
|
||||
)
|
||||
from app.models import ShippingNoticeDocument, ShippingNoticeIntake
|
||||
|
||||
intake = ShippingNoticeIntake.query.filter_by(
|
||||
intake_no=str(intake_no or '').strip().upper(), user_id=int(user_id), purpose='shipping_notice',
|
||||
).with_for_update().first()
|
||||
if intake is None or str(intake.conversation_id or '') != str(source.conversation_id or ''):
|
||||
raise NotFoundError('Replacement intake not found', code='SHIPPING.REVIEW_REPLACEMENT_NOT_FOUND')
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
error=NotFoundError('Replacement intake not found', code='SHIPPING.REVIEW_REPLACEMENT_NOT_FOUND'),
|
||||
metadata={'replacement_intake_no': str(intake_no or '').strip().upper() or None},
|
||||
)
|
||||
if intake.parse_status != 'parsed':
|
||||
raise ConflictError('Replacement PDF is still parsing', code='SHIPPING.REVIEW_REPLACEMENT_PENDING')
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
error=ConflictError('Replacement PDF is still parsing', code='SHIPPING.REVIEW_REPLACEMENT_PENDING'),
|
||||
metadata={'replacement_intake_no': intake.intake_no, 'parse_status': str(intake.parse_status or '')},
|
||||
)
|
||||
documents = ShippingNoticeDocument.query.filter_by(intake_id=int(intake.id)).filter(
|
||||
ShippingNoticeDocument.document_type != 'email_body',
|
||||
).all()
|
||||
pdfs = [item for item in documents if str(item.filename or '').lower().endswith('.pdf')]
|
||||
if len(pdfs) != 1:
|
||||
raise ConflictError('Replacement intake must contain exactly one PDF', code='SHIPPING.REVIEW_REPLACEMENT_DOCUMENT_INVALID')
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
error=ConflictError('Replacement intake must contain exactly one PDF', code='SHIPPING.REVIEW_REPLACEMENT_DOCUMENT_INVALID'),
|
||||
metadata={'replacement_intake_no': intake.intake_no, 'pdf_count': len(pdfs)},
|
||||
)
|
||||
_reject_if_work_item_closed(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
reason_code='document_quality',
|
||||
reason=f'replacement for {case.case_no}',
|
||||
)
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user, agent_id=int(owner_agent.id), conversation_id=str(source.conversation_id), intake_nos=[intake.intake_no],
|
||||
upload_batch_id=intake.upload_batch_id, reparse_of_run=source, reparse_reason='document_quality',
|
||||
reparse_comment=f'replacement for {case.case_no}', selected_document_id=int(pdfs[0].id), reparse_case_no=case.case_no,
|
||||
)
|
||||
if not reused:
|
||||
previous = case.status
|
||||
case.status = 'reparse_pending'
|
||||
_append_event(case, actor_id=user_id, event_type='replacement_reparse_started', operation={
|
||||
'previous_status': previous, 'replacement_intake_no': intake.intake_no,
|
||||
'replacement_document_id': int(pdfs[0].id), 'successor_run_no': run.run_no,
|
||||
})
|
||||
_record_unified_disposition_audit(
|
||||
if reused:
|
||||
_audit_idempotent_reparse_reuse(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
before={'status': previous},
|
||||
after={
|
||||
'status': case.status,
|
||||
'replacement_intake_no': intake.intake_no,
|
||||
'successor_run_no': run.run_no,
|
||||
},
|
||||
successor_run=run,
|
||||
reason_code='document_quality',
|
||||
reason=f'replacement for {case.case_no}',
|
||||
metadata={
|
||||
'replacement_intake_no': intake.intake_no,
|
||||
'replacement_document_id': int(pdfs[0].id),
|
||||
'successor_run_no': run.run_no,
|
||||
},
|
||||
)
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import mark_reparse_started
|
||||
db.session.flush()
|
||||
return run, True
|
||||
previous = case.status
|
||||
case.status = 'reparse_pending'
|
||||
_append_event(case, actor_id=user_id, event_type='replacement_reparse_started', operation={
|
||||
'previous_status': previous, 'replacement_intake_no': intake.intake_no,
|
||||
'replacement_document_id': int(pdfs[0].id), 'successor_run_no': run.run_no,
|
||||
})
|
||||
_record_unified_disposition_audit(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
before={'status': previous},
|
||||
after={
|
||||
'status': case.status,
|
||||
'replacement_intake_no': intake.intake_no,
|
||||
'successor_run_no': run.run_no,
|
||||
},
|
||||
reason_code='document_quality',
|
||||
metadata={
|
||||
'replacement_document_id': int(pdfs[0].id),
|
||||
'successor_run_no': run.run_no,
|
||||
},
|
||||
run_no=run.run_no,
|
||||
)
|
||||
from app.services.shipping_notice.workflow_ledger_service import mark_reparse_started
|
||||
try:
|
||||
mark_reparse_started(
|
||||
case=case,
|
||||
successor_run=run,
|
||||
@@ -396,8 +925,23 @@ def create_replacement_document_run(*, user_id: int, case_no: str, intake_no: st
|
||||
actor_id=user_id,
|
||||
replacement_document_id=int(pdfs[0].id),
|
||||
)
|
||||
db.session.flush()
|
||||
return run, reused
|
||||
except ConflictError as err:
|
||||
_reject_reparse_after_dirty_failure(
|
||||
case_no=str(case.case_no),
|
||||
owner_user_id=int(case.owner_user_id),
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
error=err,
|
||||
reason_code='document_quality',
|
||||
reason=f'replacement for {case.case_no}',
|
||||
metadata={
|
||||
'replacement_intake_no': intake.intake_no,
|
||||
'successor_run_no': run.run_no,
|
||||
},
|
||||
)
|
||||
db.session.flush()
|
||||
return run, False
|
||||
|
||||
|
||||
def finalize_document_reparse(*, run: ShippingOrderExtractionRun, succeeded: bool) -> None:
|
||||
@@ -441,7 +985,7 @@ def finalize_document_reparse(*, run: ShippingOrderExtractionRun, succeeded: boo
|
||||
_append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_failed', operation={
|
||||
'successor_run_no': run.run_no, 'restored_status': previous,
|
||||
})
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import mark_reparse_failed_and_restore
|
||||
from app.services.shipping_notice.workflow_ledger_service import mark_reparse_failed_and_restore
|
||||
mark_reparse_failed_and_restore(
|
||||
source_case=source_case,
|
||||
failed_run=run,
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
services/shipping_notice/order_review_draft_service.py
|
||||
|
||||
用途:建单前订单复核草稿的编辑、校验与统一审计。
|
||||
依赖:Review Case/Draft、Run 冻结 Schema、订单字段规则、fulfillment_audit、
|
||||
session_pdf_work_item_service.assert_case_is_current_work_item_version。
|
||||
逻辑:只修改独立 Draft JSON;每次写入锁定 Case/Draft、校验草稿版本并追加 CaseEvent +
|
||||
ShippingAuditEvent(含 request_id/operation_id 与字段前后值);绝不修改机器 Candidate。
|
||||
依赖:Review Case/Draft、Run 冻结 Schema、订单字段规则、order_build_eligibility_service、
|
||||
fulfillment_audit、workflow_ledger_service.assert_case_is_current_workflow_version。
|
||||
逻辑:只修改独立 Draft JSON;每次写入锁定 Case/Draft、校验草稿版本与 WorkflowItem 可写状态,
|
||||
追加 CaseEvent + ShippingAuditEvent;Item 已关闭/重识别中的冲突经 `_reject_draft_operation`
|
||||
落 rejected 审计;整单校验汇总有效 Reservation、行级库存源候选与自动建单五门禁
|
||||
(五门失败仅 can_auto_create=False,不阻断人工确认 can_build)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,23 +16,148 @@ import copy
|
||||
import uuid
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
from typing import Any, NoReturn
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewCaseEvent, ShippingOrderReviewDraft
|
||||
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
|
||||
from app.services.shipping_notice.order_build_eligibility_service import (
|
||||
apply_manual_inventory_candidates,
|
||||
assess_order_build_eligibility,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
is_valid_line_no_value,
|
||||
normalize_order_field_value,
|
||||
validate_order_field_value,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
_EDITABLE_STATUSES = frozenset({'unreviewed', 'draft', 'ready'})
|
||||
|
||||
|
||||
def _locked_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase:
|
||||
"""按 owner 分别锁定 Case 和当前 Draft,阻止旧浏览器窗口静默覆盖新草稿。"""
|
||||
def soft_load_review_case_for_audit(*, user_id: int, case_no: str) -> ShippingOrderReviewCase | None:
|
||||
"""
|
||||
无行锁加载属主 Case(及 Draft),供路由层/早期门禁写拒绝审计。
|
||||
|
||||
核心逻辑:Case 不存在时返回 None,由调用方直接抛业务错;存在时尽量附带 current_draft
|
||||
以便快照含 draft_version。
|
||||
|
||||
Args:
|
||||
user_id: 操作人 / Case 属主。
|
||||
case_no: 复核 Case 编号。
|
||||
|
||||
Returns:
|
||||
Case 或 None。
|
||||
"""
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(case_no=str(case_no or '').strip().upper(), owner_user_id=int(user_id))
|
||||
.first()
|
||||
)
|
||||
if case is None:
|
||||
return None
|
||||
if case.current_draft_id is not None and case.current_draft is None:
|
||||
case.current_draft = db.session.get(ShippingOrderReviewDraft, int(case.current_draft_id))
|
||||
return case
|
||||
|
||||
|
||||
def reject_invalid_draft_request_payload(*, user_id: int, case_no: str, action: str) -> NoReturn:
|
||||
"""
|
||||
请求体不是 JSON 对象时写拒绝审计(Case 可定位)后抛错。
|
||||
|
||||
核心逻辑:路由层在进入业务服务前拦截非法 body;若 Case 可识别则落 rejected 审计,
|
||||
满足「操作节点可追溯」;Case 不存在时仅抛 VALIDATION.INVALID_PARAM。
|
||||
|
||||
Args:
|
||||
user_id: 请求用户。
|
||||
case_no: 目标 Case 编号。
|
||||
action: 拟执行写操作码。
|
||||
|
||||
Raises:
|
||||
ValidationError: 请求体非法(审计已提交或 Case 不可定位)。
|
||||
"""
|
||||
error = ValidationError('Review draft payload must be an object', code='VALIDATION.INVALID_PARAM')
|
||||
case = soft_load_review_case_for_audit(user_id=user_id, case_no=case_no)
|
||||
if case is None:
|
||||
raise error
|
||||
_reject_draft_operation(
|
||||
case,
|
||||
actor_id=int(user_id),
|
||||
action=action,
|
||||
error=error,
|
||||
metadata={'reason': 'payload_not_object'},
|
||||
)
|
||||
|
||||
|
||||
def _reject_draft_operation(
|
||||
case: ShippingOrderReviewCase,
|
||||
*,
|
||||
actor_id: int,
|
||||
action: str,
|
||||
error: AppError,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> NoReturn:
|
||||
"""
|
||||
记录草稿写路径拒绝审计并独立提交后抛出业务异常。
|
||||
|
||||
核心逻辑:workspace API 遇 AppError 不会 commit;拒绝事实须在 raise 前落库,
|
||||
否则审计中心无法追溯操作人、时间、请求关联与当时草稿状态。
|
||||
|
||||
Args:
|
||||
case: 已识别的复核 Case(含 current_draft)。
|
||||
actor_id: 请求操作人。
|
||||
action: 拟执行操作码(与成功路径 CaseEvent/action 对齐)。
|
||||
error: 即将抛出的业务异常(须含 code)。
|
||||
metadata: 额外脱敏诊断(不含字段正文大对象)。
|
||||
|
||||
Raises:
|
||||
AppError: 传入的 error(审计已提交)。
|
||||
"""
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
code = str(getattr(error, 'code', '') or 'SHIPPING.REVIEW_DRAFT_OPERATION_REJECTED')
|
||||
draft = case.current_draft
|
||||
snap = {
|
||||
'status': str(case.status or ''),
|
||||
'disposition': case.disposition,
|
||||
'draft_version': int(draft.draft_version) if draft is not None else None,
|
||||
'error_code': code,
|
||||
}
|
||||
record_fulfillment_audit(
|
||||
event_type='review_draft_changed',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(case.case_no),
|
||||
action=str(action)[:64],
|
||||
actor_type='user',
|
||||
actor_id=actor_id,
|
||||
review_case_no=str(case.case_no),
|
||||
owner_user_id=case.owner_user_id,
|
||||
document_id=case.document_id,
|
||||
conversation_id=_conversation_id_for_case(case),
|
||||
workflow_item_id=_workflow_item_no_for_case(case),
|
||||
result='rejected',
|
||||
error_code=code,
|
||||
before={'status': snap['status'], 'disposition': snap['disposition'], 'draft_version': snap['draft_version']},
|
||||
after=snap,
|
||||
metadata={
|
||||
'rejection': True,
|
||||
'error_code': code,
|
||||
**(metadata or {}),
|
||||
},
|
||||
source='order_review',
|
||||
)
|
||||
db.session.commit()
|
||||
raise error
|
||||
|
||||
|
||||
def _locked_case(*, user_id: int, case_no: str, action: str) -> ShippingOrderReviewCase:
|
||||
"""
|
||||
按 owner 分别锁定 Case 和当前 Draft;不可编辑时写拒绝审计。
|
||||
|
||||
核心逻辑:两段 FOR UPDATE 避免 joinedload+nullable 侧锁问题;Case 可识别后
|
||||
若状态不在可编辑集合,先落 rejected 审计再抛错。
|
||||
"""
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(case_no=str(case_no or '').strip().upper(), owner_user_id=int(user_id))
|
||||
@@ -46,7 +173,12 @@ def _locked_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase:
|
||||
raise NotFoundError('Order review draft not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
case.current_draft = draft
|
||||
if case.status not in _EDITABLE_STATUSES:
|
||||
raise ConflictError('Order review case is not editable', code='SHIPPING.REVIEW_CASE_NOT_EDITABLE')
|
||||
_reject_draft_operation(
|
||||
case,
|
||||
actor_id=int(user_id),
|
||||
action=action,
|
||||
error=ConflictError('Order review case is not editable', code='SHIPPING.REVIEW_CASE_NOT_EDITABLE'),
|
||||
)
|
||||
return case
|
||||
|
||||
|
||||
@@ -63,10 +195,31 @@ def _expected_version(value: Any) -> int:
|
||||
return version
|
||||
|
||||
|
||||
def _assert_version(case: ShippingOrderReviewCase, expected: Any) -> None:
|
||||
"""在行锁内比较乐观锁版本;冲突由客户端重新加载完整 Case 后处理。"""
|
||||
if int(case.current_draft.draft_version) != _expected_version(expected):
|
||||
raise ConflictError('Review draft version changed', code='SHIPPING.REVIEW_DRAFT_VERSION_MISMATCH')
|
||||
def _assert_version(
|
||||
case: ShippingOrderReviewCase,
|
||||
expected: Any,
|
||||
*,
|
||||
actor_id: int,
|
||||
action: str,
|
||||
) -> None:
|
||||
"""
|
||||
在行锁内比较乐观锁版本;参数无效或冲突时写拒绝审计。
|
||||
|
||||
核心逻辑:先解析 expected_draft_version;失败或与当前 draft_version 不一致均
|
||||
落 rejected 审计后抛错,由客户端重新加载完整 Case。
|
||||
"""
|
||||
try:
|
||||
expected_v = _expected_version(expected)
|
||||
except ValidationError as err:
|
||||
_reject_draft_operation(case, actor_id=actor_id, action=action, error=err)
|
||||
if int(case.current_draft.draft_version) != expected_v:
|
||||
_reject_draft_operation(
|
||||
case,
|
||||
actor_id=actor_id,
|
||||
action=action,
|
||||
error=ConflictError('Review draft version changed', code='SHIPPING.REVIEW_DRAFT_VERSION_MISMATCH'),
|
||||
metadata={'expected_draft_version': expected_v},
|
||||
)
|
||||
|
||||
|
||||
def _schema_fields(case: ShippingOrderReviewCase) -> dict[str, dict[str, Any]]:
|
||||
@@ -81,11 +234,24 @@ def _schema_fields(case: ShippingOrderReviewCase) -> dict[str, dict[str, Any]]:
|
||||
}
|
||||
|
||||
|
||||
def _require_field(case: ShippingOrderReviewCase, field_id: str, scope: str) -> dict[str, Any]:
|
||||
"""确认字段属于冻结 Schema 和目标作用域,前端不能伪造字段或跨 header/line 写入。"""
|
||||
def _require_field(
|
||||
case: ShippingOrderReviewCase,
|
||||
field_id: str,
|
||||
scope: str,
|
||||
*,
|
||||
actor_id: int,
|
||||
action: str,
|
||||
) -> dict[str, Any]:
|
||||
"""确认字段属于冻结 Schema 和目标作用域;无效时写拒绝审计。"""
|
||||
field = _schema_fields(case).get(str(field_id or '').strip())
|
||||
if field is None or str(field.get('scope') or '') != scope:
|
||||
raise ValidationError('Review field is unavailable', code='SHIPPING.REVIEW_FIELD_INVALID')
|
||||
_reject_draft_operation(
|
||||
case,
|
||||
actor_id=actor_id,
|
||||
action=action,
|
||||
error=ValidationError('Review field is unavailable', code='SHIPPING.REVIEW_FIELD_INVALID'),
|
||||
metadata={'field_id': str(field_id or '')[:64] or None, 'scope': scope},
|
||||
)
|
||||
return field
|
||||
|
||||
|
||||
@@ -100,12 +266,25 @@ def _machine_value(machine_fields: list[Any], field_id: str) -> Any:
|
||||
return None
|
||||
|
||||
|
||||
def _find_line(lines: list[dict[str, Any]], line_key: str) -> dict[str, Any]:
|
||||
"""按稳定 line_key 获取草稿行,禁止用可变化的数组下标定位编辑目标。"""
|
||||
def _find_line(
|
||||
case: ShippingOrderReviewCase,
|
||||
lines: list[dict[str, Any]],
|
||||
line_key: str,
|
||||
*,
|
||||
actor_id: int,
|
||||
action: str,
|
||||
) -> dict[str, Any]:
|
||||
"""按稳定 line_key 获取草稿行;不存在时写拒绝审计。"""
|
||||
for item in lines:
|
||||
if isinstance(item, dict) and str(item.get('line_key') or '') == str(line_key or ''):
|
||||
return item
|
||||
raise ValidationError('Review line is unavailable', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
|
||||
_reject_draft_operation(
|
||||
case,
|
||||
actor_id=actor_id,
|
||||
action=action,
|
||||
error=ValidationError('Review line is unavailable', code='SHIPPING.REVIEW_LINE_NOT_FOUND'),
|
||||
metadata={'line_key': str(line_key or '')[:64] or None},
|
||||
)
|
||||
|
||||
|
||||
def _current_value(container: dict[str, Any], field_id: str) -> Any:
|
||||
@@ -117,6 +296,14 @@ def _current_value(container: dict[str, Any], field_id: str) -> Any:
|
||||
return _machine_value(list(container.get('machine_fields') or []), field_id)
|
||||
|
||||
|
||||
LINE_NO_OVERRIDE_REASON_CODES = frozenset({
|
||||
'recognition_error',
|
||||
'customer_line_exception',
|
||||
'business_correction',
|
||||
'other',
|
||||
})
|
||||
|
||||
|
||||
def _set_value(container: dict[str, Any], field: dict[str, Any], value: Any, *, restore_machine: bool) -> dict[str, Any]:
|
||||
"""写入单字段人工值或移除人工覆盖层;类型规范化始终按冻结字段规则执行。"""
|
||||
values = dict(container.get('values') or {})
|
||||
@@ -137,7 +324,12 @@ def _set_value(container: dict[str, Any], field: dict[str, Any], value: Any, *,
|
||||
|
||||
|
||||
def _validation(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
"""全量校验草稿:动态 Schema 与 part/qty/Reservation 硬门禁同时生效,但不建单。"""
|
||||
"""
|
||||
全量校验草稿:动态 Schema、有效 Reservation 与行级库存源候选门禁同时生效,但不建单。
|
||||
|
||||
核心逻辑:投影 field_code 值后调用资格服务;多候选不阻断;结果写入
|
||||
validation_result_json(含 line_projections)供工作台展示。
|
||||
"""
|
||||
draft = case.current_draft
|
||||
fields = _schema_fields(case)
|
||||
issues: list[dict[str, Any]] = []
|
||||
@@ -154,6 +346,7 @@ def _validation(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
elif normalized is not None and not validate_order_field_value(normalized, field):
|
||||
issues.append({'code': 'field_value_invalid', 'field_id': field_id, 'scope': 'header', 'severity': 'blocking'})
|
||||
lines: list[dict[str, Any]] = []
|
||||
line_metas: list[dict[str, Any]] = []
|
||||
for raw_line in draft.lines_json or []:
|
||||
if not isinstance(raw_line, dict):
|
||||
continue
|
||||
@@ -169,15 +362,46 @@ def _validation(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
elif normalized is not None and not validate_order_field_value(normalized, field):
|
||||
issues.append({'code': 'field_value_invalid', 'field_id': field_id, 'line_key': raw_line.get('line_key'), 'severity': 'blocking'})
|
||||
lines.append(line)
|
||||
assessment = assess_candidate_business_summary({**header, 'lines': lines})
|
||||
for item in assessment['blocking_issues']:
|
||||
issues.append({'code': str(item.get('code') or 'invalid_order_line'), 'line_index': item.get('line_index'), 'severity': 'blocking'})
|
||||
for field_code in assessment['missing_process_fields']:
|
||||
issues.append({'code': 'process_field_missing', 'field_code': field_code, 'severity': 'blocking'})
|
||||
reservations = [str(item.get('reservation_id') or '').strip() for item in lines if item.get('reservation_id')]
|
||||
if len(reservations) != len(set(reservations)):
|
||||
issues.append({'code': 'reservation_duplicated_in_order', 'severity': 'blocking'})
|
||||
return {'status': 'ready' if not issues and assessment['can_auto_progress'] else 'needs_review', 'issues': issues}
|
||||
line_metas.append(raw_line)
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNoticeCandidate, ShippingOrderExtractionRun, ShippingOrderExtractionUnit
|
||||
|
||||
candidate = db.session.get(ShippingNoticeCandidate, int(case.candidate_id)) if case.candidate_id else None
|
||||
unit = case.unit
|
||||
if unit is None and case.unit_id:
|
||||
unit = db.session.get(ShippingOrderExtractionUnit, int(case.unit_id))
|
||||
run = case.run
|
||||
if run is None and case.run_id:
|
||||
run = db.session.get(ShippingOrderExtractionRun, int(case.run_id))
|
||||
eligibility = assess_order_build_eligibility(
|
||||
fields=fields,
|
||||
header_by_code=header,
|
||||
lines=lines,
|
||||
line_metas=line_metas,
|
||||
customer_resolved=True,
|
||||
candidate=candidate,
|
||||
unit=unit,
|
||||
run=run,
|
||||
)
|
||||
# [STEP 1] Schema 字段问题与资格问题合并;资格 issues 已含 Reservation / 库存候选。
|
||||
for item in eligibility.get('issues') or []:
|
||||
if isinstance(item, dict):
|
||||
issues.append(dict(item))
|
||||
# 人工确认只看 blocking;五门禁 severity=auto_create_blocking 不阻断 can_build。
|
||||
can_build = bool(eligibility.get('can_build')) and not any(
|
||||
str(item.get('severity') or '') == 'blocking' for item in issues
|
||||
)
|
||||
return {
|
||||
'status': 'ready' if can_build else 'needs_review',
|
||||
'can_build': can_build,
|
||||
'can_auto_create': bool(eligibility.get('can_auto_create')) and can_build,
|
||||
'gates': dict(eligibility.get('gates') or {}),
|
||||
'failed_gates': list(eligibility.get('failed_gates') or []),
|
||||
'issues': issues,
|
||||
'line_projections': list(eligibility.get('line_projections') or []),
|
||||
'enabled_inventory_source_codes': list(eligibility.get('enabled_inventory_source_codes') or []),
|
||||
}
|
||||
|
||||
|
||||
def build_confirmable_draft_summary(case: ShippingOrderReviewCase) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
@@ -222,11 +446,11 @@ def _audit_scalar(value: Any, *, limit: int = 200) -> Any:
|
||||
return text
|
||||
|
||||
|
||||
def _session_item_no_for_case(case: ShippingOrderReviewCase) -> str | None:
|
||||
"""按 current_case_id 反查会话工作项编号。"""
|
||||
from app.models import ShippingSessionPdfWorkItem
|
||||
def _workflow_item_no_for_case(case: ShippingOrderReviewCase) -> str | None:
|
||||
"""按 current_case_id 反查 WorkflowItem 业务编号。"""
|
||||
from app.services.shipping_notice.workflow_ledger_service import find_item_by_current_case
|
||||
|
||||
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=int(case.id)).first()
|
||||
item = find_item_by_current_case(case_id=int(case.id))
|
||||
return str(item.item_no) if item is not None else None
|
||||
|
||||
|
||||
@@ -245,13 +469,23 @@ def _record_change(
|
||||
"""
|
||||
保存草稿变更并写入统一审计。
|
||||
|
||||
核心逻辑:仅显式校验时跑整单门禁;审计附带 request_id/operation_id、字段前后值与工作项关联。
|
||||
核心逻辑:先校验 WorkflowItem 仍可写(未关闭、未在重识别);冲突经 `_reject_draft_operation`
|
||||
落 rejected 审计后再抛错。仅显式校验时跑整单门禁;成功审计附带字段前后值与 WorkflowItem 关联。
|
||||
"""
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import (
|
||||
assert_case_is_current_work_item_version,
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
assert_case_is_current_workflow_version,
|
||||
)
|
||||
assert_case_is_current_work_item_version(case=case)
|
||||
try:
|
||||
assert_case_is_current_workflow_version(case=case)
|
||||
except ConflictError as err:
|
||||
_reject_draft_operation(
|
||||
case,
|
||||
actor_id=int(actor_id),
|
||||
action=str(event_type)[:64],
|
||||
error=err,
|
||||
metadata={'work_item_gate': True},
|
||||
)
|
||||
draft = case.current_draft
|
||||
before_version = int(draft.draft_version)
|
||||
previous_status = str(case.status or 'draft')
|
||||
@@ -312,7 +546,7 @@ def _record_change(
|
||||
owner_user_id=case.owner_user_id,
|
||||
document_id=case.document_id,
|
||||
conversation_id=_conversation_id_for_case(case),
|
||||
session_item_id=_session_item_no_for_case(case),
|
||||
workflow_item_id=_workflow_item_no_for_case(case),
|
||||
before=before_snapshot,
|
||||
after=after_snapshot,
|
||||
metadata={'case_event_type': event_type},
|
||||
@@ -324,9 +558,10 @@ def _record_change(
|
||||
|
||||
def patch_header_field(*, user_id: int, case_no: str, field_id: str, value: Any, expected_draft_version: Any, restore_machine: bool = False) -> dict[str, Any]:
|
||||
"""编辑或恢复单个订单头字段;仅修改该字段,不会清理其他问题或人工值。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
_assert_version(case, expected_draft_version)
|
||||
field = _require_field(case, field_id, 'header')
|
||||
action = 'header_field_changed'
|
||||
case = _locked_case(user_id=user_id, case_no=case_no, action=action)
|
||||
_assert_version(case, expected_draft_version, actor_id=user_id, action=action)
|
||||
field = _require_field(case, field_id, 'header', actor_id=user_id, action=action)
|
||||
header = dict(case.current_draft.header_values_json or {})
|
||||
previous_value = _current_value(header, field_id)
|
||||
change = _set_value(header, field, value, restore_machine=restore_machine)
|
||||
@@ -334,25 +569,155 @@ def patch_header_field(*, user_id: int, case_no: str, field_id: str, value: Any,
|
||||
return _record_change(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='header_field_changed',
|
||||
event_type=action,
|
||||
operation={'field_id': field_id, 'previous_value': previous_value, **change},
|
||||
)
|
||||
|
||||
|
||||
def patch_line_field(*, user_id: int, case_no: str, line_key: str, field_id: str, value: Any, expected_draft_version: Any, restore_machine: bool = False) -> dict[str, Any]:
|
||||
"""编辑或恢复一条明细字段;行由不可变 line_key 定位并受同一草稿版本锁保护。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
_assert_version(case, expected_draft_version)
|
||||
field = _require_field(case, field_id, 'line')
|
||||
def patch_line_field(
|
||||
*,
|
||||
user_id: int,
|
||||
case_no: str,
|
||||
line_key: str,
|
||||
field_id: str,
|
||||
value: Any,
|
||||
expected_draft_version: Any,
|
||||
restore_machine: bool = False,
|
||||
override_reason_code: str | None = None,
|
||||
override_reason_text: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
编辑或恢复一条明细字段;行由不可变 line_key 定位并受同一草稿版本锁保护。
|
||||
|
||||
核心逻辑:一般字段沿用 manual 覆盖;内部项次 line_no 覆盖须原因分类并锁定;
|
||||
恢复时清除 override,回退到草稿 machine_fields 中的识别/派生投影(不重新跑派生引擎),
|
||||
并写 LINE_NO_RESTORED。
|
||||
"""
|
||||
action = 'line_field_changed'
|
||||
case = _locked_case(user_id=user_id, case_no=case_no, action=action)
|
||||
_assert_version(case, expected_draft_version, actor_id=user_id, action=action)
|
||||
field = _require_field(case, field_id, 'line', actor_id=user_id, action=action)
|
||||
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
|
||||
target = _find_line(lines, line_key)
|
||||
target = _find_line(case, lines, line_key, actor_id=user_id, action=action)
|
||||
previous_value = _current_value(target, field_id)
|
||||
field_code = str(field.get('field_code') or '')
|
||||
|
||||
if field_code == 'line_no' and restore_machine:
|
||||
prior_entry = (target.get('values') or {}).get(field_id) if isinstance(target.get('values'), dict) else None
|
||||
prior_source = str((prior_entry or {}).get('source') or 'manual_override')
|
||||
change = _set_value(target, field, value, restore_machine=True)
|
||||
# 恢复后的展示值来自 machine_fields:初始化草稿时已含识别/派生投影,非二次派生。
|
||||
restored_source = 'machine_or_derived_projection'
|
||||
case.current_draft.lines_json = lines
|
||||
result = _record_change(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type=action,
|
||||
operation={
|
||||
'line_key': line_key,
|
||||
'field_id': field_id,
|
||||
'field_code': field_code,
|
||||
'previous_value': previous_value,
|
||||
'restored_source': restored_source,
|
||||
'prior_value_source': prior_source,
|
||||
**change,
|
||||
},
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type='LINE_NO_RESTORED',
|
||||
aggregate_type='shipping_order_review_case',
|
||||
aggregate_id=str(case.case_no),
|
||||
actor_type='user',
|
||||
actor_id=user_id,
|
||||
review_case_no=str(case.case_no),
|
||||
action='restore_line_no',
|
||||
result='success',
|
||||
metadata={
|
||||
'line_key': line_key,
|
||||
'field_code': 'line_no',
|
||||
'restored_source': restored_source,
|
||||
'prior_value_source': prior_source,
|
||||
},
|
||||
before={'previous_value': previous_value, 'value_source': prior_source},
|
||||
after={'new_value': change.get('value'), 'value_source': restored_source},
|
||||
)
|
||||
return result
|
||||
|
||||
if field_code == 'line_no' and not restore_machine:
|
||||
reason_code = str(override_reason_code or '').strip()
|
||||
reason_text = str(override_reason_text or '').strip()
|
||||
if reason_code not in LINE_NO_OVERRIDE_REASON_CODES:
|
||||
raise ValidationError(
|
||||
'line_no override requires a valid reason code',
|
||||
code='SHIPPING.REVIEW_LINE_NO_OVERRIDE_REASON_REQUIRED',
|
||||
)
|
||||
if reason_code == 'other' and not reason_text:
|
||||
raise ValidationError(
|
||||
'line_no override reason text is required for other',
|
||||
code='SHIPPING.REVIEW_LINE_NO_OVERRIDE_TEXT_REQUIRED',
|
||||
)
|
||||
if not is_valid_line_no_value(value):
|
||||
raise ValidationError(
|
||||
'line_no must be 1-6 digits',
|
||||
code='SHIPPING.REVIEW_LINE_NO_FORMAT_INVALID',
|
||||
)
|
||||
change = _set_value(target, field, value, restore_machine=False)
|
||||
values = dict(target.get('values') or {})
|
||||
values[str(field['field_id'])] = {
|
||||
'value': change['value'],
|
||||
'source': 'manual_override',
|
||||
'locked': True,
|
||||
'override_reason_code': reason_code,
|
||||
'override_reason_text': reason_text or None,
|
||||
}
|
||||
target['values'] = values
|
||||
change = {
|
||||
**change,
|
||||
'source': 'manual_override',
|
||||
'override_reason_code': reason_code,
|
||||
'override_reason_text': reason_text or None,
|
||||
'locked': True,
|
||||
}
|
||||
case.current_draft.lines_json = lines
|
||||
result = _record_change(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type=action,
|
||||
operation={
|
||||
'line_key': line_key,
|
||||
'field_id': field_id,
|
||||
'field_code': field_code,
|
||||
'previous_value': previous_value,
|
||||
**change,
|
||||
},
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type='LINE_NO_OVERRIDDEN',
|
||||
aggregate_type='shipping_order_review_case',
|
||||
aggregate_id=str(case.case_no),
|
||||
actor_type='user',
|
||||
actor_id=user_id,
|
||||
review_case_no=str(case.case_no),
|
||||
action='override_line_no',
|
||||
result='success',
|
||||
reason_code=reason_code,
|
||||
reason=reason_text or None,
|
||||
metadata={
|
||||
'line_key': line_key,
|
||||
'field_code': 'line_no',
|
||||
'override_reason_code': reason_code,
|
||||
},
|
||||
before={'previous_value': previous_value, 'value_source': 'prior'},
|
||||
after={'new_value': change['value'], 'value_source': 'manual_override'},
|
||||
)
|
||||
return result
|
||||
|
||||
change = _set_value(target, field, value, restore_machine=restore_machine)
|
||||
case.current_draft.lines_json = lines
|
||||
return _record_change(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='line_field_changed',
|
||||
event_type=action,
|
||||
operation={
|
||||
'line_key': line_key,
|
||||
'field_id': field_id,
|
||||
@@ -364,39 +729,107 @@ def patch_line_field(*, user_id: int, case_no: str, line_key: str, field_id: str
|
||||
|
||||
def add_line(*, user_id: int, case_no: str, expected_draft_version: Any) -> dict[str, Any]:
|
||||
"""新增空人工明细行;空行立即进入校验问题,不能绕过后续建单门禁。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
_assert_version(case, expected_draft_version)
|
||||
action = 'line_added'
|
||||
case = _locked_case(user_id=user_id, case_no=case_no, action=action)
|
||||
_assert_version(case, expected_draft_version, actor_id=user_id, action=action)
|
||||
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
|
||||
line_key = f'manual-{uuid.uuid4().hex[:16]}'
|
||||
lines.append({'line_key': line_key, 'machine_fields': [], 'values': {}})
|
||||
case.current_draft.lines_json = lines
|
||||
return _record_change(case, actor_id=user_id, event_type='line_added', operation={'line_key': line_key})
|
||||
return _record_change(case, actor_id=user_id, event_type=action, operation={'line_key': line_key})
|
||||
|
||||
|
||||
def copy_line(*, user_id: int, case_no: str, line_key: str, expected_draft_version: Any) -> dict[str, Any]:
|
||||
"""复制明细为新 line_key;复制后的 Reservation 重复会由全量校验显式阻断。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
_assert_version(case, expected_draft_version)
|
||||
action = 'line_copied'
|
||||
case = _locked_case(user_id=user_id, case_no=case_no, action=action)
|
||||
_assert_version(case, expected_draft_version, actor_id=user_id, action=action)
|
||||
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
|
||||
copied = copy.deepcopy(_find_line(lines, line_key))
|
||||
copied = copy.deepcopy(_find_line(case, lines, line_key, actor_id=user_id, action=action))
|
||||
copied['line_key'] = f'manual-{uuid.uuid4().hex[:16]}'
|
||||
lines.append(copied)
|
||||
case.current_draft.lines_json = lines
|
||||
return _record_change(case, actor_id=user_id, event_type='line_copied', operation={'source_line_key': line_key, 'line_key': copied['line_key']})
|
||||
return _record_change(case, actor_id=user_id, event_type=action, operation={'source_line_key': line_key, 'line_key': copied['line_key']})
|
||||
|
||||
|
||||
def delete_line(*, user_id: int, case_no: str, line_key: str, expected_draft_version: Any) -> dict[str, Any]:
|
||||
"""删除单条草稿行并写审计;删除最后有效行会保留为阻断校验结果。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
_assert_version(case, expected_draft_version)
|
||||
action = 'line_deleted'
|
||||
case = _locked_case(user_id=user_id, case_no=case_no, action=action)
|
||||
_assert_version(case, expected_draft_version, actor_id=user_id, action=action)
|
||||
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
|
||||
_find_line(lines, line_key)
|
||||
_find_line(case, lines, line_key, actor_id=user_id, action=action)
|
||||
case.current_draft.lines_json = [item for item in lines if str(item.get('line_key') or '') != str(line_key)]
|
||||
return _record_change(case, actor_id=user_id, event_type='line_deleted', operation={'line_key': line_key})
|
||||
return _record_change(case, actor_id=user_id, event_type=action, operation={'line_key': line_key})
|
||||
|
||||
|
||||
def validate_draft(*, user_id: int, case_no: str, expected_draft_version: Any) -> dict[str, Any]:
|
||||
"""显式执行全量草稿校验;只更新验证结果和事件,不创建 Candidate 或 ShippingTask。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
_assert_version(case, expected_draft_version)
|
||||
return _record_change(case, actor_id=user_id, event_type='draft_validated', operation={}, validate=True)
|
||||
action = 'draft_validated'
|
||||
case = _locked_case(user_id=user_id, case_no=case_no, action=action)
|
||||
_assert_version(case, expected_draft_version, actor_id=user_id, action=action)
|
||||
return _record_change(case, actor_id=user_id, event_type=action, operation={}, validate=True)
|
||||
|
||||
|
||||
def set_line_inventory_candidates(
|
||||
*,
|
||||
user_id: int,
|
||||
case_no: str,
|
||||
line_key: str,
|
||||
source_codes: list[str],
|
||||
reason: str,
|
||||
expected_draft_version: Any,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
人工为明细选择 1..N 个已启用库存源候选(强制填写原因)。
|
||||
|
||||
核心逻辑:写入行级 inventory_routing 覆盖层并跑全量校验;不修改机器 Candidate。
|
||||
|
||||
Args:
|
||||
user_id: 操作人。
|
||||
case_no: 复核 Case 编号。
|
||||
line_key: 稳定行键。
|
||||
source_codes: 候选库存源编码。
|
||||
reason: 人工选择原因。
|
||||
expected_draft_version: 乐观锁版本。
|
||||
|
||||
Returns:
|
||||
序列化后的 Case 详情。
|
||||
"""
|
||||
action = 'line_inventory_candidates_selected'
|
||||
case = _locked_case(user_id=user_id, case_no=case_no, action=action)
|
||||
_assert_version(case, expected_draft_version, actor_id=user_id, action=action)
|
||||
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
|
||||
target = _find_line(case, lines, line_key, actor_id=user_id, action=action)
|
||||
try:
|
||||
overlay = apply_manual_inventory_candidates(
|
||||
line_meta=target,
|
||||
source_codes=list(source_codes or []),
|
||||
reason=reason,
|
||||
)
|
||||
except ValueError as exc:
|
||||
code = str(exc)
|
||||
_reject_draft_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
action=action,
|
||||
error=ValidationError(
|
||||
'Manual inventory source selection is invalid',
|
||||
code='SHIPPING.REVIEW_INVENTORY_CANDIDATES_INVALID',
|
||||
details={'reason': code},
|
||||
),
|
||||
metadata={'line_key': str(line_key)[:64], 'reason': code},
|
||||
)
|
||||
case.current_draft.lines_json = lines
|
||||
return _record_change(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type=action,
|
||||
operation={
|
||||
'line_key': line_key,
|
||||
'candidate_inventory_source_codes': list(overlay.get('candidate_inventory_source_codes') or []),
|
||||
'manual_reason': str(overlay.get('manual_reason') or '')[:200],
|
||||
'new_value': list(overlay.get('candidate_inventory_source_codes') or []),
|
||||
},
|
||||
validate=True,
|
||||
)
|
||||
@@ -1,9 +1,13 @@
|
||||
"""
|
||||
建单前订单复核的用户态只读投影。
|
||||
|
||||
依赖:Review Case/Draft、冻结 Run Schema、冻结文档快照和机器 Candidate 摘要。
|
||||
逻辑:只返回工作台展示所需的字段定义、机器/人工草稿值、问题与动作;不返回
|
||||
全文、对象存储定位、模型原始响应、Prompt 或其他内部执行载荷。
|
||||
依赖:Review Case/Draft、冻结 Run Schema、冻结文档快照、机器 Candidate 摘要、
|
||||
Extraction.normalized_result_json.field_lineage(派生血缘)、
|
||||
workflow_ledger_service.find_item_by_current_case。
|
||||
逻辑:只返回工作台展示所需的字段定义、机器/人工草稿值、问题、建单资格与行级库存候选;
|
||||
为每行/表头投影 field_meta(value_source / locked / override_reason);
|
||||
WorkflowItem 已关闭时 available_actions 仅保留 view;
|
||||
不返回全文、对象存储定位、模型原始响应、Prompt 或其他内部执行载荷。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,7 +15,12 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNoticeCandidate, ShippingOrderExtractionRun, ShippingOrderReviewCase
|
||||
from app.models import (
|
||||
ShippingNoticeCandidate,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderReviewCase,
|
||||
)
|
||||
|
||||
|
||||
def _safe_filename(value: Any) -> str | None:
|
||||
@@ -41,6 +50,107 @@ def _schema_fields(run: ShippingOrderExtractionRun) -> list[dict[str, Any]]:
|
||||
return fields
|
||||
|
||||
|
||||
def _field_lineage_index(case: ShippingOrderReviewCase) -> dict[tuple[str, str], dict[str, Any]]:
|
||||
"""
|
||||
从关联 Extraction 或 Unit 结果索引派生血缘,键为 (line_key, field_code)。
|
||||
|
||||
核心逻辑:优先 Candidate.order_extraction_id → normalized_result_json.field_lineage;
|
||||
否则回退 Unit.result_json.field_lineage。仅保留脱敏后的来源元数据。
|
||||
"""
|
||||
rows: list[Any] = []
|
||||
candidate = db.session.get(ShippingNoticeCandidate, case.candidate_id) if case.candidate_id else None
|
||||
extraction_id = getattr(candidate, 'order_extraction_id', None) if candidate is not None else None
|
||||
if extraction_id:
|
||||
extraction = db.session.get(ShippingOrderExtraction, int(extraction_id))
|
||||
normalized = extraction.normalized_result_json if extraction is not None and isinstance(
|
||||
extraction.normalized_result_json, dict,
|
||||
) else {}
|
||||
rows = list(normalized.get('field_lineage') or [])
|
||||
if not rows and case.unit is not None and isinstance(case.unit.result_json, dict):
|
||||
rows = list(case.unit.result_json.get('field_lineage') or [])
|
||||
index: dict[tuple[str, str], dict[str, Any]] = {}
|
||||
for item in rows:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
line_key = str(item.get('line_key') or '').strip()
|
||||
field_code = str(item.get('field_code') or '').strip()
|
||||
if not field_code:
|
||||
continue
|
||||
index[(line_key, field_code)] = {
|
||||
'value_source': str(item.get('value_source') or 'derived'),
|
||||
'rule_id': item.get('rule_id'),
|
||||
'skip_reason': item.get('skip_reason'),
|
||||
'source_field_code': item.get('source_field_code'),
|
||||
}
|
||||
return index
|
||||
|
||||
|
||||
def _resolve_field_meta(
|
||||
*,
|
||||
container: dict[str, Any],
|
||||
field_id: str,
|
||||
field_code: str,
|
||||
lineage_index: dict[tuple[str, str], dict[str, Any]],
|
||||
line_key: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
合并草稿 values 与派生血缘,投影字段值来源元数据。
|
||||
|
||||
优先级:manual_override / manual(含 locked、覆盖原因)→ derived/skipped 血缘 → machine。
|
||||
"""
|
||||
values = container.get('values') if isinstance(container.get('values'), dict) else {}
|
||||
entry = values.get(field_id) if isinstance(values.get(field_id), dict) else None
|
||||
if entry is not None and 'value' in entry:
|
||||
source = str(entry.get('source') or 'manual').strip() or 'manual'
|
||||
meta: dict[str, Any] = {
|
||||
'value_source': source if source in {'manual', 'manual_override'} else 'manual',
|
||||
'locked': bool(entry.get('locked')),
|
||||
}
|
||||
if entry.get('override_reason_code'):
|
||||
meta['override_reason_code'] = str(entry.get('override_reason_code'))
|
||||
if entry.get('override_reason_text'):
|
||||
meta['override_reason_text'] = str(entry.get('override_reason_text'))
|
||||
return meta
|
||||
lineage = lineage_index.get((str(line_key or ''), field_code))
|
||||
if lineage is not None:
|
||||
return {
|
||||
'value_source': str(lineage.get('value_source') or 'derived'),
|
||||
'locked': False,
|
||||
'derivation': {
|
||||
'rule_id': lineage.get('rule_id'),
|
||||
'skip_reason': lineage.get('skip_reason'),
|
||||
'source_field_code': lineage.get('source_field_code'),
|
||||
},
|
||||
}
|
||||
return {'value_source': 'machine', 'locked': False}
|
||||
|
||||
|
||||
def _project_draft_container(
|
||||
container: dict[str, Any] | None,
|
||||
*,
|
||||
scope_fields: list[dict[str, Any]],
|
||||
lineage_index: dict[tuple[str, str], dict[str, Any]],
|
||||
line_key: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""在保留原草稿结构基础上附加 field_meta,供复核 UI 展示来源徽章。"""
|
||||
payload = dict(container or {})
|
||||
field_meta: dict[str, Any] = {}
|
||||
for field in scope_fields:
|
||||
field_id = str(field.get('field_id') or '')
|
||||
field_code = str(field.get('field_code') or '')
|
||||
if not field_id:
|
||||
continue
|
||||
field_meta[field_id] = _resolve_field_meta(
|
||||
container=payload,
|
||||
field_id=field_id,
|
||||
field_code=field_code,
|
||||
lineage_index=lineage_index,
|
||||
line_key=line_key,
|
||||
)
|
||||
payload['field_meta'] = field_meta
|
||||
return payload
|
||||
|
||||
|
||||
def _document_filename(run: ShippingOrderExtractionRun, document_id: int) -> str | None:
|
||||
"""仅从 Run 冻结快照获取文件展示名,避免回读可变资产。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
@@ -54,7 +164,12 @@ def _document_filename(run: ShippingOrderExtractionRun, document_id: int) -> str
|
||||
|
||||
|
||||
def _allowed_actions(case: ShippingOrderReviewCase) -> list[str]:
|
||||
"""由后端 Case 状态决定可用动作,前端不可自行推导确认资格。"""
|
||||
"""由后端 Case 状态与 WorkflowItem 生命周期决定可用动作,前端不可自行推导确认资格。"""
|
||||
from app.services.shipping_notice.workflow_ledger_service import find_item_by_current_case
|
||||
|
||||
item = find_item_by_current_case(case_id=int(case.id))
|
||||
if item is not None and str(item.lifecycle_status or '') in {'closed', 'cancelled'}:
|
||||
return ['view']
|
||||
if case.status in {'confirmed', 'non_order', 'superseded'}:
|
||||
return ['view']
|
||||
if case.status == 'reparse_pending':
|
||||
@@ -76,6 +191,43 @@ def serialize_review_case(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
run = case.run
|
||||
draft = case.current_draft
|
||||
candidate = db.session.get(ShippingNoticeCandidate, case.candidate_id) if case.candidate_id else None
|
||||
schema_fields = _schema_fields(run)
|
||||
header_fields = [item for item in schema_fields if item.get('scope') == 'header']
|
||||
line_fields = [item for item in schema_fields if item.get('scope') == 'line']
|
||||
lineage_index = _field_lineage_index(case) if draft is not None else {}
|
||||
projected_draft = None
|
||||
if draft is not None:
|
||||
raw_lines = list(draft.lines_json or [])
|
||||
projected_draft = {
|
||||
'draft_version': int(draft.draft_version),
|
||||
'header_values': _project_draft_container(
|
||||
dict(draft.header_values_json or {}),
|
||||
scope_fields=header_fields,
|
||||
lineage_index=lineage_index,
|
||||
),
|
||||
'lines': [
|
||||
_project_draft_container(
|
||||
dict(line) if isinstance(line, dict) else {},
|
||||
scope_fields=line_fields,
|
||||
lineage_index=lineage_index,
|
||||
line_key=str((line or {}).get('line_key') or '') if isinstance(line, dict) else None,
|
||||
)
|
||||
for line in raw_lines
|
||||
],
|
||||
'issues': list(draft.issue_summary_json or []),
|
||||
'validation': dict(draft.validation_result_json or {}),
|
||||
'build_eligibility': {
|
||||
'can_build': bool((draft.validation_result_json or {}).get('can_build')),
|
||||
'can_auto_create': bool((draft.validation_result_json or {}).get('can_auto_create')),
|
||||
'status': str((draft.validation_result_json or {}).get('status') or 'needs_review'),
|
||||
'gates': dict((draft.validation_result_json or {}).get('gates') or {}),
|
||||
'failed_gates': list((draft.validation_result_json or {}).get('failed_gates') or []),
|
||||
'line_projections': list((draft.validation_result_json or {}).get('line_projections') or []),
|
||||
'enabled_inventory_source_codes': list(
|
||||
(draft.validation_result_json or {}).get('enabled_inventory_source_codes') or []
|
||||
),
|
||||
},
|
||||
}
|
||||
return {
|
||||
'case_no': case.case_no,
|
||||
'run_no': run.run_no,
|
||||
@@ -88,14 +240,8 @@ def serialize_review_case(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
'validation_status': candidate.validation_status,
|
||||
'po_number': candidate.po_number,
|
||||
} if candidate is not None else None,
|
||||
'schema': {'schema_version_id': int(run.schema_version_id), 'fields': _schema_fields(run)},
|
||||
'draft': {
|
||||
'draft_version': int(draft.draft_version),
|
||||
'header_values': dict(draft.header_values_json or {}),
|
||||
'lines': list(draft.lines_json or []),
|
||||
'issues': list(draft.issue_summary_json or []),
|
||||
'validation': dict(draft.validation_result_json or {}),
|
||||
} if draft is not None else None,
|
||||
'schema': {'schema_version_id': int(run.schema_version_id), 'fields': schema_fields},
|
||||
'draft': projected_draft,
|
||||
'available_actions': _allowed_actions(case),
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
建单前订单复核 Case 的初始化与只读加载服务。
|
||||
|
||||
依赖:冻结 Run/Unit、机器 Candidate、Review Case/Draft 模型和冻结 Schema 快照。
|
||||
依赖:冻结 Run/Unit、机器 Candidate、Review Case/Draft 模型、冻结 Schema 快照、
|
||||
workflow_ledger_service.bind_cases_for_run。
|
||||
逻辑:每个 PDF Unit 幂等创建一个 Case;只有该 PDF 恰有一个本 Run Candidate
|
||||
时才把它作为只读机器来源。Draft 从 Unit 的冻结结果初始化,绝不回写 Candidate。
|
||||
时才把它作为只读机器来源。Draft 从 Unit 的冻结结果初始化,绝不回写 Candidate;
|
||||
Case 初始化后绑定/创建对应 WorkflowItem。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -197,8 +199,8 @@ def ensure_run_review_cases(*, run: ShippingOrderExtractionRun) -> list[Shipping
|
||||
))
|
||||
cases.append(case)
|
||||
db.session.flush()
|
||||
# [STEP] 会话 PDF 工作项绑定:同会话多 PDF 各一条;重识别复用并切换当前版本。
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import bind_cases_for_run
|
||||
# [STEP] WorkflowItem 绑定:同会话多 PDF 各一条;重识别复用并切换当前版本。
|
||||
from app.services.shipping_notice.workflow_ledger_service import bind_cases_for_run
|
||||
bind_cases_for_run(run=run, cases=cases)
|
||||
return cases
|
||||
|
||||
|
||||
@@ -186,10 +186,13 @@ def remap_profile_field_codes(
|
||||
continue
|
||||
old_code = str(field.get('field_code') or '')
|
||||
field['field_code'] = target_field.get('field_code')
|
||||
field['scope'] = target_field.get('scope')
|
||||
code_map[old_code] = str(target_field.get('field_code') or '')
|
||||
for output in field.get('target_fields') or []:
|
||||
if isinstance(output, dict) and output.get('field_id') in target:
|
||||
output['field_code'] = target[str(output['field_id'])].get('field_code')
|
||||
target_output = target[str(output['field_id'])]
|
||||
output['field_code'] = target_output.get('field_code')
|
||||
output['scope'] = target_output.get('scope')
|
||||
for key in ('required_fields', 'allowed_empty_fields'):
|
||||
values = layout.get(key)
|
||||
if isinstance(values, list):
|
||||
@@ -200,4 +203,5 @@ def remap_profile_field_codes(
|
||||
target_field = target.get(str(field.get('field_id') or ''))
|
||||
if target_field:
|
||||
field['field_code'] = target_field.get('field_code')
|
||||
field['scope'] = target_field.get('scope')
|
||||
return result
|
||||
@@ -0,0 +1,105 @@
|
||||
"""
|
||||
services/shipping_notice/order_schema/derivation_engine.py
|
||||
|
||||
用途:执行 Schema 级字段派生规则(首期 copy_if_empty),供模拟与运行时共用。
|
||||
依赖:field_rules(规则归一化与 line_no 格式)、统一 ValidationError。
|
||||
逻辑:仅处理启用中的 line→line 规则;目标非空/来源空/格式非法时记录跳过原因;
|
||||
不写库;调用方负责持久化与审计。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
derivation_rules_checksum,
|
||||
is_valid_line_no_value,
|
||||
normalize_derivation_rules,
|
||||
)
|
||||
|
||||
|
||||
def apply_derivation_rules_to_lines(
|
||||
lines: list[dict[str, Any]],
|
||||
rules: list[dict[str, Any]] | None,
|
||||
*,
|
||||
locked_targets: set[tuple[int, str]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
对明细行集合执行派生规则,返回派生后行与逐行结果摘要。
|
||||
|
||||
核心逻辑:仅启用规则生效;copy_if_empty 仅在目标为空时复制来源;
|
||||
目标已锁定(人工覆盖)时跳过;来源缺失或目标格式非法时跳过。
|
||||
|
||||
Args:
|
||||
lines: 明细字段字典列表(按行可变副本由本函数新建)。
|
||||
rules: Schema definition_json.derivation_rules 或草稿规则。
|
||||
locked_targets: 可选 ``{(line_index, field_code)}`` 人工锁定集合。
|
||||
|
||||
Returns:
|
||||
``{lines, results, rules_checksum, derived_count, skipped_count}``;
|
||||
``results`` 每项含 line_index、rule_id、status(derived|skipped)、skip_reason、
|
||||
source/target 前后值。
|
||||
"""
|
||||
normalized = normalize_derivation_rules(rules, adopted_line_field_codes=None)
|
||||
checksum = derivation_rules_checksum(normalized)
|
||||
enabled = [rule for rule in normalized if rule.get('enabled')]
|
||||
output_lines = [dict(line) for line in lines]
|
||||
results: list[dict[str, Any]] = []
|
||||
locks = locked_targets or set()
|
||||
|
||||
for line_index, line in enumerate(output_lines):
|
||||
for rule in enabled:
|
||||
source_code = str(rule['source_field_code'])
|
||||
target_code = str(rule['target_field_code'])
|
||||
rule_id = str(rule['rule_id'])
|
||||
before_target = line.get(target_code)
|
||||
before_source = line.get(source_code)
|
||||
entry: dict[str, Any] = {
|
||||
'line_index': line_index,
|
||||
'rule_id': rule_id,
|
||||
'source_field_code': source_code,
|
||||
'target_field_code': target_code,
|
||||
'strategy': rule['strategy'],
|
||||
'before_source': before_source,
|
||||
'before_target': before_target,
|
||||
'after_target': before_target,
|
||||
'status': 'skipped',
|
||||
'skip_reason': None,
|
||||
}
|
||||
if (line_index, target_code) in locks:
|
||||
entry['skip_reason'] = 'manual_override_locked'
|
||||
results.append(entry)
|
||||
continue
|
||||
if before_target not in (None, ''):
|
||||
entry['skip_reason'] = 'target_not_empty'
|
||||
results.append(entry)
|
||||
continue
|
||||
if before_source in (None, ''):
|
||||
entry['skip_reason'] = 'source_empty'
|
||||
results.append(entry)
|
||||
continue
|
||||
source_text = str(before_source).strip()
|
||||
if target_code == 'line_no' and not is_valid_line_no_value(source_text):
|
||||
entry['skip_reason'] = 'source_format_invalid'
|
||||
results.append(entry)
|
||||
continue
|
||||
if rule['strategy'] != 'copy_if_empty':
|
||||
entry['skip_reason'] = 'unsupported_strategy'
|
||||
results.append(entry)
|
||||
continue
|
||||
line[target_code] = source_text
|
||||
entry['after_target'] = source_text
|
||||
entry['status'] = 'derived'
|
||||
entry['skip_reason'] = None
|
||||
results.append(entry)
|
||||
|
||||
derived_count = sum(1 for item in results if item['status'] == 'derived')
|
||||
skipped_count = sum(1 for item in results if item['status'] == 'skipped')
|
||||
return {
|
||||
'lines': output_lines,
|
||||
'results': results,
|
||||
'rules': normalized,
|
||||
'rules_checksum': checksum,
|
||||
'derived_count': derived_count,
|
||||
'skipped_count': skipped_count,
|
||||
}
|
||||
@@ -1,13 +1,18 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_schema/field_rules.py
|
||||
|
||||
用途:执行冻结订单 Schema 的通用字段归一化与 validator,供 Dify Observation 和确定性表格共用。
|
||||
用途:执行冻结订单 Schema 的通用字段归一化、validator,以及 Schema 级字段派生规则契约校验。
|
||||
依赖:标准库 Decimal/date、reservation_id 安全校验、统一 ValidationError。
|
||||
逻辑:运行时传入完整字段配置;本模块不查询数据库,也不允许配置绕过 Reservation ID 安全规则。
|
||||
逻辑:运行时传入完整字段配置;本模块不查询数据库,也不允许配置绕过 Reservation ID 安全规则;
|
||||
Header/Line Reservation 均可选,有效值由行优先回退头计算;
|
||||
derivation_rules 仅允许 line→line、首期策略 copy_if_empty、目标仅 line_no。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
@@ -15,6 +20,186 @@ from typing import Any
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
# Phase 0/1 派生规则契约常量。
|
||||
DERIVATION_STRATEGIES = frozenset({'copy_if_empty'})
|
||||
DERIVATION_ALLOWED_TARGETS = frozenset({'line_no'})
|
||||
DERIVATION_LINE_NO_PATTERN = re.compile(r'^\d{1,6}$')
|
||||
DEFAULT_DERIVATION_RULE_ID = 'R-LINE-NO-FROM-CUSTOMER-PO'
|
||||
|
||||
|
||||
def compute_effective_reservation_id(
|
||||
*,
|
||||
line_reservation_id: Any = None,
|
||||
header_reservation_id: Any = None,
|
||||
) -> str | None:
|
||||
"""
|
||||
计算明细有效 Reservation。
|
||||
|
||||
核心逻辑:行级覆盖订单头;二者均可空。空值或非法格式一律视为缺失,
|
||||
不在字段层强制必填(建单门禁另由资格服务裁决)。
|
||||
|
||||
Args:
|
||||
line_reservation_id: 明细 reservation_id 原始或已规范化值。
|
||||
header_reservation_id: 订单头 reservation_id 原始或已规范化值。
|
||||
|
||||
Returns:
|
||||
通过安全校验的 Reservation 字符串;否则 None。
|
||||
"""
|
||||
return (
|
||||
validated_reservation_id(line_reservation_id)
|
||||
or validated_reservation_id(header_reservation_id)
|
||||
or None
|
||||
)
|
||||
|
||||
|
||||
def default_derivation_rules() -> list[dict[str, Any]]:
|
||||
"""
|
||||
返回新草稿默认派生规则(关闭状态)。
|
||||
|
||||
核心逻辑:预置 customer_po_line_no → line_no 的 copy_if_empty 规则,enabled=False,
|
||||
避免未评审规则自动改写内部项次。
|
||||
|
||||
Returns:
|
||||
可写入 definition_json.derivation_rules 的规则列表。
|
||||
"""
|
||||
return [{
|
||||
'rule_id': DEFAULT_DERIVATION_RULE_ID,
|
||||
'enabled': False,
|
||||
'source_field_code': 'customer_po_line_no',
|
||||
'target_field_code': 'line_no',
|
||||
'strategy': 'copy_if_empty',
|
||||
'scope': 'line',
|
||||
}]
|
||||
|
||||
|
||||
def derivation_rules_checksum(rules: list[dict[str, Any]]) -> str:
|
||||
"""
|
||||
计算派生规则稳定校验和,供发布冻结与审计引用。
|
||||
|
||||
Args:
|
||||
rules: 已归一化的派生规则列表。
|
||||
|
||||
Returns:
|
||||
SHA-256 hex 摘要。
|
||||
"""
|
||||
payload = json.dumps(rules, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
|
||||
return hashlib.sha256(payload.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def normalize_derivation_rules(
|
||||
value: Any,
|
||||
*,
|
||||
adopted_line_field_codes: set[str] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
归一化并校验 Schema definition_json.derivation_rules。
|
||||
|
||||
核心逻辑:仅允许 line→line;首期策略仅 copy_if_empty;目标仅 line_no;
|
||||
禁止自引用;同一启用目标只允许一条规则;来源/目标须属于已采用明细字段(若提供)。
|
||||
|
||||
Args:
|
||||
value: 原始 derivation_rules(None 时返回默认关闭预置)。
|
||||
adopted_line_field_codes: 当前草稿已采用的明细 field_code 集合;None 表示跳过采用检查。
|
||||
|
||||
Returns:
|
||||
归一化后的规则列表。
|
||||
|
||||
Raises:
|
||||
ValidationError: 结构、策略、循环或竞争冲突。
|
||||
"""
|
||||
if value is None:
|
||||
return default_derivation_rules()
|
||||
if not isinstance(value, list):
|
||||
raise ValidationError(
|
||||
'derivation_rules must be a list',
|
||||
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
|
||||
)
|
||||
normalized: list[dict[str, Any]] = []
|
||||
enabled_targets: set[str] = set()
|
||||
for index, raw in enumerate(value):
|
||||
if not isinstance(raw, dict):
|
||||
raise ValidationError(
|
||||
'derivation rule must be an object',
|
||||
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
|
||||
details={'index': index},
|
||||
)
|
||||
rule_id = str(raw.get('rule_id') or '').strip() or f'R-DERIVE-{index + 1}'
|
||||
enabled = raw.get('enabled', False)
|
||||
if not isinstance(enabled, bool):
|
||||
raise ValidationError(
|
||||
'derivation rule enabled must be boolean',
|
||||
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
|
||||
details={'rule_id': rule_id},
|
||||
)
|
||||
source = str(raw.get('source_field_code') or '').strip()
|
||||
target = str(raw.get('target_field_code') or '').strip()
|
||||
strategy = str(raw.get('strategy') or '').strip()
|
||||
scope = str(raw.get('scope') or 'line').strip()
|
||||
if scope != 'line':
|
||||
raise ValidationError(
|
||||
'derivation rules only allow line scope',
|
||||
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
|
||||
details={'rule_id': rule_id},
|
||||
)
|
||||
if strategy not in DERIVATION_STRATEGIES:
|
||||
raise ValidationError(
|
||||
'unsupported derivation strategy',
|
||||
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
|
||||
details={'rule_id': rule_id, 'strategy': strategy},
|
||||
)
|
||||
if target not in DERIVATION_ALLOWED_TARGETS:
|
||||
raise ValidationError(
|
||||
'derivation target is not allowed in this phase',
|
||||
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
|
||||
details={'rule_id': rule_id, 'target_field_code': target},
|
||||
)
|
||||
if not source or source == target:
|
||||
raise ValidationError(
|
||||
'derivation source/target must differ and be non-empty',
|
||||
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
|
||||
details={'rule_id': rule_id},
|
||||
)
|
||||
if adopted_line_field_codes is not None:
|
||||
missing = {code for code in (source, target) if code not in adopted_line_field_codes}
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
'derivation fields must be adopted line fields',
|
||||
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
|
||||
details={'rule_id': rule_id, 'missing_field_codes': sorted(missing)},
|
||||
)
|
||||
if enabled and target in enabled_targets:
|
||||
raise ValidationError(
|
||||
'only one enabled derivation rule is allowed per target',
|
||||
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
|
||||
details={'target_field_code': target},
|
||||
)
|
||||
if enabled:
|
||||
enabled_targets.add(target)
|
||||
normalized.append({
|
||||
'rule_id': rule_id,
|
||||
'enabled': enabled,
|
||||
'source_field_code': source,
|
||||
'target_field_code': target,
|
||||
'strategy': strategy,
|
||||
'scope': scope,
|
||||
})
|
||||
return normalized
|
||||
|
||||
|
||||
def is_valid_line_no_value(value: Any) -> bool:
|
||||
"""
|
||||
校验内部项次格式:1–6 位数字,保留前导零。
|
||||
|
||||
Args:
|
||||
value: 候选内部项次。
|
||||
|
||||
Returns:
|
||||
是否符合契约。
|
||||
"""
|
||||
if value in (None, ''):
|
||||
return False
|
||||
return bool(DERIVATION_LINE_NO_PATTERN.fullmatch(str(value).strip()))
|
||||
|
||||
|
||||
def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any:
|
||||
"""按冻结字段类型解析候选值,同时保留原始文本大小写。
|
||||
@@ -64,8 +249,15 @@ def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any:
|
||||
|
||||
|
||||
def validate_order_field_value(value: Any, config: dict[str, Any]) -> bool:
|
||||
"""执行冻结字段 validator;Reservation ID 永远叠加后端安全校验。"""
|
||||
if str(config.get('field_code') or '') == 'reservation_id' and not validated_reservation_id(value):
|
||||
"""执行冻结字段 validator;Reservation ID 永远叠加后端安全校验。
|
||||
|
||||
Header/Line `reservation_id` 允许缺省(None/空串视为通过字段层校验);
|
||||
一旦给出非空值,则必须通过安全格式校验。
|
||||
"""
|
||||
field_code = str(config.get('field_code') or '')
|
||||
if field_code == 'reservation_id' and value not in (None, '') and not validated_reservation_id(value):
|
||||
return False
|
||||
if field_code == 'line_no' and value not in (None, '') and not is_valid_line_no_value(value):
|
||||
return False
|
||||
for key in config.get('validator_keys') or []:
|
||||
if key == 'non_empty' and value in (None, ''):
|
||||
@@ -74,7 +266,7 @@ def validate_order_field_value(value: Any, config: dict[str, Any]) -> bool:
|
||||
return False
|
||||
if key == 'non_negative_decimal' and Decimal(str(value)) < 0:
|
||||
return False
|
||||
if key == 'reservation_id' and not validated_reservation_id(value):
|
||||
if key == 'reservation_id' and value not in (None, '') and not validated_reservation_id(value):
|
||||
return False
|
||||
if key == 'atomic_part_number' and '/' in str(value):
|
||||
return False
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
backend/app/services/shipping_notice/order_schema/runtime.py
|
||||
|
||||
用途:编译已发布订单 Schema,并裁决 Dify 返回的动态字段 Observation。
|
||||
依赖:订单 Schema 动态模型、standard_field_registry、ShippingNoticeDocument、registry、订单客户匹配服务。
|
||||
逻辑:提交时先验证原文证据和字段规则,再以已裁决订单头匹配 Bill-to/Ship-to 客户主数据并输出业务投影;
|
||||
依赖:订单 Schema 动态模型、standard_field_registry、ShippingNoticeDocument、registry、
|
||||
derivation_engine、audit_service、订单客户匹配服务。
|
||||
逻辑:提交时先验证原文证据和字段规则并投影;再执行 Schema 派生并落库 FieldValue;
|
||||
必填门禁仅在派生后按最终投影判定;
|
||||
published_version 固定读取唯一 Schema STANDARD_SHIPPING_NOTICE(兼容历史 SHIPPING_ORDER)。
|
||||
"""
|
||||
|
||||
@@ -11,6 +13,7 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
import uuid
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
@@ -35,9 +38,12 @@ from app.services.shipping_notice.context_fields.runtime import (
|
||||
)
|
||||
from app.services.shipping_notice.order_customer_matching import refresh_order_customer_matches
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
compute_effective_reservation_id,
|
||||
normalize_order_field_value,
|
||||
validate_order_field_value,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.derivation_engine import apply_derivation_rules_to_lines
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
from app.services.shipping_notice.standard_field_registry import DEFAULT_SCHEMA_FAMILY_CODE
|
||||
|
||||
@@ -487,7 +493,7 @@ def _associated_backend_rows(raw_fields: list[Any], configs: dict[str, dict[str,
|
||||
rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""仅用同 Document 的强身份字段关联 layout 行,禁止 Qty 等常见值导致跨文档串行。"""
|
||||
strong_codes = {
|
||||
'part_number', 'customer_part_number', 'reservation_id', 'line_no', 'customer_po_number',
|
||||
'part_number', 'customer_part_number', 'reservation_id', 'customer_po_line_no', 'customer_po_number',
|
||||
}
|
||||
signatures: list[tuple[str, Any, int]] = []
|
||||
for raw in raw_fields:
|
||||
@@ -541,6 +547,164 @@ def _backend_candidates(config: dict[str, Any], *, rows: list[dict[str, Any]]) -
|
||||
return result
|
||||
|
||||
|
||||
def _persist_derived_line_field(
|
||||
*,
|
||||
extraction: ShippingOrderExtraction,
|
||||
line: ShippingOrderLine,
|
||||
config: dict[str, Any],
|
||||
value: Any,
|
||||
rule_id: str,
|
||||
rules_checksum: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将派生成功的明细字段写入 Decision + FieldValue,供冻结/导出读取。
|
||||
|
||||
核心逻辑:更新既有 missing/blocked Decision 为 accepted(reason=derived);
|
||||
若尚无 FieldValue 则新建。不新增 Observation(派生非原文证据)。
|
||||
|
||||
Args:
|
||||
extraction: 当前 Extraction。
|
||||
line: 目标明细行。
|
||||
config: Schema 字段配置(含 field_id/value_type)。
|
||||
value: 派生后的业务值。
|
||||
rule_id: 派生规则 ID。
|
||||
rules_checksum: 规则校验和。
|
||||
|
||||
Returns:
|
||||
决策摘要,便于并入 decisions 列表。
|
||||
"""
|
||||
field_id = str(config['field_id'])
|
||||
decision = ShippingOrderFieldDecision.query.filter_by(
|
||||
extraction_id=int(extraction.id),
|
||||
line_id=int(line.id),
|
||||
field_id=field_id,
|
||||
).one_or_none()
|
||||
payload = _json_value(value)
|
||||
if decision is None:
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=int(extraction.id),
|
||||
line_id=int(line.id),
|
||||
field_id=field_id,
|
||||
decision_status='accepted',
|
||||
selected_observation_id=None,
|
||||
supporting_observation_ids_json=[],
|
||||
resolved_value_json=payload,
|
||||
reason_code='derived',
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
else:
|
||||
decision.decision_status = 'accepted'
|
||||
decision.resolved_value_json = payload
|
||||
decision.reason_code = 'derived'
|
||||
db.session.flush()
|
||||
|
||||
existing_value = ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=int(extraction.id),
|
||||
line_id=int(line.id),
|
||||
field_id=field_id,
|
||||
).one_or_none()
|
||||
value_type = str(config.get('value_type') or 'string')
|
||||
columns = {
|
||||
'value_text': str(value) if value_type in {'string', 'enum'} else None,
|
||||
'value_decimal': value if value_type == 'decimal' else None,
|
||||
'value_integer': value if value_type == 'integer' else None,
|
||||
'value_date': value if value_type == 'date' else None,
|
||||
'value_boolean': value if value_type == 'boolean' else None,
|
||||
'value_json': payload,
|
||||
}
|
||||
if existing_value is None:
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=int(extraction.id),
|
||||
line_id=int(line.id),
|
||||
field_id=field_id,
|
||||
decision_id=int(decision.id),
|
||||
**columns,
|
||||
))
|
||||
else:
|
||||
existing_value.decision_id = int(decision.id)
|
||||
for key, column_value in columns.items():
|
||||
setattr(existing_value, key, column_value)
|
||||
db.session.flush()
|
||||
return {
|
||||
'id': int(decision.id),
|
||||
'field_id': field_id,
|
||||
'field_code': config.get('field_code'),
|
||||
'line_id': int(line.id),
|
||||
'status': 'accepted',
|
||||
'value': payload,
|
||||
'reason_code': 'derived',
|
||||
'rule_id': rule_id,
|
||||
'derivation_rules_checksum': rules_checksum,
|
||||
'observation_ids': [],
|
||||
'confidence': 1.0,
|
||||
}
|
||||
|
||||
|
||||
def _config_by_line_field_code(all_configs: dict[str, dict[str, Any]], field_code: str) -> dict[str, Any] | None:
|
||||
"""按明细 field_code 查找 Schema 配置。"""
|
||||
for config in all_configs.values():
|
||||
if config.get('scope') == 'line' and str(config.get('field_code') or '') == field_code:
|
||||
return config
|
||||
return None
|
||||
|
||||
|
||||
def _derivation_evidence_refs(
|
||||
*,
|
||||
extraction_id: int,
|
||||
line_id: int | None,
|
||||
source_field_code: str | None,
|
||||
all_configs: dict[str, dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
为派生审计构造来源字段证据引用(不含正文/quote)。
|
||||
|
||||
核心逻辑:按 source_field_code 定位同行 Decision → selected Observation,
|
||||
仅输出 observation_id / document_id / evidence_ref / 元数据中的页码坐标标识。
|
||||
"""
|
||||
if not source_field_code:
|
||||
return []
|
||||
field_id = next(
|
||||
(
|
||||
str(config['field_id'])
|
||||
for config in all_configs.values()
|
||||
if str(config.get('field_code') or '') == source_field_code and config.get('scope') == 'line'
|
||||
),
|
||||
None,
|
||||
)
|
||||
refs: list[dict[str, Any]] = [{
|
||||
'kind': 'derived_source_field',
|
||||
'field_code': source_field_code,
|
||||
'field_id': field_id,
|
||||
'line_id': line_id,
|
||||
'extraction_id': extraction_id,
|
||||
}]
|
||||
if not field_id:
|
||||
return refs
|
||||
decision = ShippingOrderFieldDecision.query.filter_by(
|
||||
extraction_id=extraction_id, line_id=line_id, field_id=field_id,
|
||||
).one_or_none()
|
||||
if decision is None or not decision.selected_observation_id:
|
||||
return refs
|
||||
observation = db.session.get(ShippingOrderFieldObservation, int(decision.selected_observation_id))
|
||||
if observation is None:
|
||||
return refs
|
||||
meta = observation.evidence_metadata_json if isinstance(observation.evidence_metadata_json, dict) else {}
|
||||
refs.append({
|
||||
'kind': 'field_observation',
|
||||
'observation_id': int(observation.id),
|
||||
'decision_id': int(decision.id),
|
||||
'source_document_id': int(observation.source_document_id) if observation.source_document_id else None,
|
||||
'source_type': observation.source_type,
|
||||
'extractor': observation.extractor,
|
||||
'evidence_ref': observation.evidence_ref,
|
||||
'page_no': meta.get('page_no') or meta.get('page'),
|
||||
'cell_id': meta.get('cell_id'),
|
||||
'table_id': meta.get('table_id'),
|
||||
})
|
||||
return refs
|
||||
|
||||
|
||||
def persist_dynamic_order(
|
||||
*,
|
||||
raw_order: dict[str, Any],
|
||||
@@ -620,7 +784,11 @@ def persist_dynamic_order(
|
||||
for position, raw_line in enumerate(raw_order.get('lines') or []):
|
||||
if not isinstance(raw_line, dict):
|
||||
raise ValidationError('Dynamic order line must be an object', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT')
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=position)
|
||||
line = ShippingOrderLine(
|
||||
extraction_id=extraction.id,
|
||||
position=position,
|
||||
line_key=str(uuid.uuid4()),
|
||||
)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
projection: dict[str, Any] = {}
|
||||
@@ -649,10 +817,14 @@ def persist_dynamic_order(
|
||||
decisions.append(decision)
|
||||
if value is not None:
|
||||
projection[str(config['field_code'])] = _json_value(value)
|
||||
if status not in {'accepted', 'corroborated'}:
|
||||
# 必填且值为空留给派生后统一门禁;此处只拦已提交但未通过裁决的质量问题。
|
||||
if status not in {'accepted', 'corroborated'} and not (
|
||||
config.get('required') and value is None
|
||||
):
|
||||
blocked.append(str(config['field_code']))
|
||||
|
||||
# [STEP 2] 未提交字段也必须形成 missing Decision,保证每个 Schema 字段都有可审计结果。
|
||||
# 必填缺失不在此处写入 blocked,避免派生补齐后仍残留阻断。
|
||||
for config in configs.values():
|
||||
field_id = str(config['field_id'])
|
||||
if config.get('scope') != scope or (line_id, field_id) in seen:
|
||||
@@ -667,10 +839,76 @@ def persist_dynamic_order(
|
||||
decisions.append(decision)
|
||||
if value is not None:
|
||||
projection[str(config['field_code'])] = _json_value(value)
|
||||
if config.get('required') and status not in {'accepted', 'corroborated'}:
|
||||
blocked.append(str(config['field_code']))
|
||||
|
||||
# [STEP 3] Required 按 Header/每一 Line 检查,缺值和冲突都阻断自动建单。
|
||||
# [STEP 3] Schema 派生规则:仅补齐空目标;成功后落库 FieldValue,供冻结/Excel 读取。
|
||||
derivation_outcome = apply_derivation_rules_to_lines(
|
||||
line_projections,
|
||||
(version.definition_json or {}).get('derivation_rules'),
|
||||
)
|
||||
line_projections = derivation_outcome['lines']
|
||||
field_lineage: list[dict[str, Any]] = []
|
||||
for item in derivation_outcome['results']:
|
||||
line_index = int(item['line_index'])
|
||||
line_obj = extraction.lines[line_index] if line_index < len(extraction.lines) else None
|
||||
lineage_row = {
|
||||
'line_key': line_obj.line_key if line_obj is not None else None,
|
||||
'field_code': item['target_field_code'],
|
||||
'value_source': 'derived' if item['status'] == 'derived' else 'skipped',
|
||||
'rule_id': item['rule_id'],
|
||||
'rule_checksum': derivation_outcome['rules_checksum'],
|
||||
'skip_reason': item.get('skip_reason'),
|
||||
'before_value': item.get('before_target'),
|
||||
'after_value': item.get('after_target'),
|
||||
'source_field_code': item.get('source_field_code'),
|
||||
'source_value': item.get('before_source'),
|
||||
}
|
||||
field_lineage.append(lineage_row)
|
||||
if item['status'] == 'derived' and line_obj is not None:
|
||||
target_config = _config_by_line_field_code(all_configs, str(item['target_field_code']))
|
||||
if target_config is not None and item.get('after_target') not in (None, ''):
|
||||
decisions.append(_persist_derived_line_field(
|
||||
extraction=extraction,
|
||||
line=line_obj,
|
||||
config=target_config,
|
||||
value=item.get('after_target'),
|
||||
rule_id=str(item['rule_id']),
|
||||
rules_checksum=str(derivation_outcome['rules_checksum']),
|
||||
))
|
||||
event_type = 'FIELD_DERIVED' if item['status'] == 'derived' else 'FIELD_DERIVATION_SKIPPED'
|
||||
evidence_refs = _derivation_evidence_refs(
|
||||
extraction_id=int(extraction.id),
|
||||
line_id=int(line_obj.id) if line_obj is not None else None,
|
||||
source_field_code=str(item.get('source_field_code') or '') or None,
|
||||
all_configs=all_configs,
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type=event_type,
|
||||
aggregate_type='shipping_order_extraction',
|
||||
aggregate_id=str(extraction.id),
|
||||
intake_no=getattr(intake, 'intake_no', None),
|
||||
actor_type='system',
|
||||
actor_id='derivation_engine',
|
||||
action='derive_line_field',
|
||||
result='success' if item['status'] == 'derived' else 'ignored',
|
||||
reason_code=item.get('skip_reason'),
|
||||
evidence_refs=evidence_refs or None,
|
||||
metadata={
|
||||
'rule_id': item['rule_id'],
|
||||
'derivation_rules_checksum': derivation_outcome['rules_checksum'],
|
||||
'field_code': item['target_field_code'],
|
||||
'line_key': lineage_row['line_key'],
|
||||
'source_field_code': item.get('source_field_code'),
|
||||
'skip_reason': item.get('skip_reason'),
|
||||
'schema_version_id': version.id,
|
||||
},
|
||||
before={'previous_value': item.get('before_target'), 'value_source': 'machine'},
|
||||
after={
|
||||
'new_value': item.get('after_target'),
|
||||
'value_source': 'derived' if item['status'] == 'derived' else 'skipped',
|
||||
},
|
||||
)
|
||||
|
||||
# [STEP 4] Required 仅在派生之后按最终投影检查,避免派生刚补齐的必填项仍被误拦。
|
||||
for config in all_configs.values():
|
||||
if not config.get('required'):
|
||||
continue
|
||||
@@ -679,7 +917,23 @@ def persist_dynamic_order(
|
||||
blocked.append(code)
|
||||
if config['scope'] == 'line' and (not line_projections or any(code not in line for line in line_projections)):
|
||||
blocked.append(code)
|
||||
extraction.normalized_result_json = {'header': header, 'lines': line_projections}
|
||||
|
||||
# 行级辅助投影:仅输出 line_key 与有效 Reservation;line_no 为可识别/可派生内部项次。
|
||||
system_line_projections: list[dict[str, Any]] = []
|
||||
for line, projection in zip(extraction.lines, line_projections):
|
||||
system_line_projections.append({
|
||||
'line_key': line.line_key,
|
||||
'effective_reservation_id': compute_effective_reservation_id(
|
||||
line_reservation_id=projection.get('reservation_id'),
|
||||
header_reservation_id=header.get('reservation_id'),
|
||||
),
|
||||
})
|
||||
extraction.normalized_result_json = {
|
||||
'header': header,
|
||||
'lines': line_projections,
|
||||
'field_lineage': field_lineage,
|
||||
'derivation_rules_checksum': derivation_outcome['rules_checksum'],
|
||||
}
|
||||
extraction.validation_result_json = {
|
||||
'blocked_fields': sorted(set(blocked)),
|
||||
'deterministic_table_issues': table_issues,
|
||||
@@ -692,6 +946,9 @@ def persist_dynamic_order(
|
||||
'extraction': extraction,
|
||||
'header': header,
|
||||
'lines': line_projections,
|
||||
'system_line_projections': system_line_projections,
|
||||
'field_lineage': field_lineage,
|
||||
'derivation_rules_checksum': derivation_outcome['rules_checksum'],
|
||||
'blocked_fields': sorted(set(blocked)),
|
||||
'observations': observations,
|
||||
'decisions': decisions,
|
||||
|
||||
@@ -2,10 +2,9 @@
|
||||
backend/app/services/shipping_notice/order_schema/service.py
|
||||
|
||||
用途:管理唯一发货订单 Schema 的版本采用/发布与追加式配置审计;字段资产生命周期委托 field_asset_service。
|
||||
依赖:db、订单 Schema 模型、standard_field_registry、field_asset_service、registry、统一 AppError。
|
||||
逻辑:草稿与发布版本统一读写 definition_json(含 auto_creation_policy);乐观锁阻止覆盖;
|
||||
依赖:db、订单 Schema 模型、standard_field_registry、field_asset_service、field_rules、registry、统一 AppError。
|
||||
逻辑:草稿与发布版本统一读写 definition_json(含 auto_creation_policy 与 derivation_rules);乐观锁阻止覆盖;
|
||||
发布冻结快照并追加审计事件。固定 Schema 编码 STANDARD_SHIPPING_NOTICE;不开放多族治理。
|
||||
自动建单策略随版本发布生效;容器列仅作发布后的兼容缓存。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -69,6 +68,13 @@ from app.services.shipping_notice.order_schema.registry import (
|
||||
from app.services.shipping_notice.order_schema.compatibility import compare_profile_schema
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
from app.services.shipping_notice.order_schema.diff import compare_definitions
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
default_derivation_rules,
|
||||
derivation_rules_checksum,
|
||||
normalize_derivation_rules,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.derivation_engine import apply_derivation_rules_to_lines
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
SCHEMA_CODE = DEFAULT_SCHEMA_FAMILY_CODE
|
||||
FIELD_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,63}$')
|
||||
@@ -877,24 +883,45 @@ def save_field(
|
||||
data: dict[str, Any], *, actor_id: int | None, field_id: str | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""兼容旧 API:扩展创建/更新委托 field_asset_service;标准字段只读返回。"""
|
||||
"""兼容旧 API:扩展创建/更新委托 field_asset_service;标准/上下文字段只读返回。"""
|
||||
from app.services.shipping_notice import field_asset_service as assets
|
||||
|
||||
ensure_standard_assets_seeded(actor_id=actor_id)
|
||||
assets.ensure_context_assets_seeded(actor_id=actor_id)
|
||||
if field_id:
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
if field is None:
|
||||
raise NotFoundError('Shipping order field not found', code='SHIPPING.ORDER_FIELD_NOT_FOUND')
|
||||
if field.asset_kind == 'system_standard':
|
||||
if field.asset_kind == 'system_standard' or field.collection_mode == 'deterministic_context':
|
||||
return _field_payload(field)
|
||||
return assets.update_extension(field_id, data, actor_id=actor_id, request_id=request_id)
|
||||
code = str(data.get('field_code') or '').strip().lower()
|
||||
if is_standard_field_code(code):
|
||||
existing = ShippingOrderField.query.filter_by(field_code=code).one_or_none()
|
||||
scope = str(data.get('scope') or '').strip().lower()
|
||||
existing = ShippingOrderField.query.filter_by(field_code=code, scope=scope).one_or_none()
|
||||
if existing is not None:
|
||||
return _field_payload(existing)
|
||||
raise ValidationError('Cannot create system standard fields via API', code='SHIPPING.FIELD_ASSET_STANDARD_READONLY')
|
||||
return assets.create_extension(data, actor_id=actor_id, request_id=request_id)
|
||||
# 上下文字段由种子保证存在;禁止走 create_extension(FORBIDDEN_CONTEXT_CODES)。
|
||||
if code in assets.FORBIDDEN_CONTEXT_CODES or code.startswith('mail_') or code.startswith('sender_'):
|
||||
existing = ShippingOrderField.query.filter_by(field_code=code, scope='header').one_or_none()
|
||||
requested_scope = str(data.get('scope') or 'header').strip().lower() or 'header'
|
||||
if existing is not None and existing.collection_mode == 'deterministic_context':
|
||||
if requested_scope != 'header':
|
||||
raise ValidationError(
|
||||
'Context fields must be header-scoped deterministic assets',
|
||||
code='SHIPPING.ORDER_FIELD_INVALID',
|
||||
)
|
||||
return _field_payload(existing)
|
||||
raise ValidationError(
|
||||
'Context/mail identifiers cannot be registered as order field assets',
|
||||
code='SHIPPING.FIELD_ASSET_CONTEXT_FORBIDDEN',
|
||||
)
|
||||
# Legacy schema API callers may omit display_name; asset service still requires one.
|
||||
payload = dict(data)
|
||||
if not str(payload.get('display_name') or payload.get('display_name_default') or '').strip():
|
||||
payload['display_name'] = code
|
||||
return assets.create_extension(payload, actor_id=actor_id, request_id=request_id)
|
||||
|
||||
|
||||
def reorder_fields(data: dict[str, Any], *, actor_id: int | None, request_id: str | None = None) -> dict[str, Any]:
|
||||
@@ -919,6 +946,7 @@ def retire_field(
|
||||
actor_id: int | None = None,
|
||||
request_id: str | None = None,
|
||||
reason: str | None = None,
|
||||
confirm_impact: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""退役扩展字段资产;系统标准字段禁止退役。"""
|
||||
from app.services.shipping_notice import field_asset_service as assets
|
||||
@@ -928,6 +956,7 @@ def retire_field(
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
reason=reason or 'retired via schema legacy API',
|
||||
confirm_impact=confirm_impact,
|
||||
)
|
||||
|
||||
|
||||
@@ -974,6 +1003,12 @@ def create_draft(
|
||||
definition if source else None,
|
||||
fallback=schema.auto_creation_policy_json,
|
||||
)
|
||||
# [STEP] 派生规则:复制来源时归一化;全新草稿预置关闭状态的默认规则。
|
||||
definition['derivation_rules'] = normalize_derivation_rules(
|
||||
definition.get('derivation_rules') if source else None,
|
||||
adopted_line_field_codes=None,
|
||||
)
|
||||
definition['derivation_rules_checksum'] = derivation_rules_checksum(definition['derivation_rules'])
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id,
|
||||
version=next_version,
|
||||
@@ -1185,11 +1220,28 @@ def save_draft(
|
||||
auto_creation_policy = _resolve_auto_creation_policy_for_definition(
|
||||
before, fallback=version.schema.auto_creation_policy_json,
|
||||
)
|
||||
adopted_line_codes = {
|
||||
str(item.get('field_code'))
|
||||
for item in normalized_fields
|
||||
if isinstance(item, dict) and item.get('enabled', True) and item.get('scope') == 'line'
|
||||
}
|
||||
# 保存时未传 derivation_rules 则保留草稿既有规则;缺省时回退关闭预置。
|
||||
raw_derivation_rules = data['derivation_rules'] if 'derivation_rules' in data else before.get('derivation_rules')
|
||||
derivation_rules = normalize_derivation_rules(
|
||||
raw_derivation_rules if raw_derivation_rules is not None else default_derivation_rules(),
|
||||
adopted_line_field_codes=adopted_line_codes if any(
|
||||
rule.get('enabled') for rule in (
|
||||
raw_derivation_rules if isinstance(raw_derivation_rules, list) else default_derivation_rules()
|
||||
)
|
||||
) else None,
|
||||
)
|
||||
after = {
|
||||
'schema_code': version.schema.schema_code,
|
||||
'version': version.version,
|
||||
'fields': normalized_fields,
|
||||
'auto_creation_policy': auto_creation_policy,
|
||||
'derivation_rules': derivation_rules,
|
||||
'derivation_rules_checksum': derivation_rules_checksum(derivation_rules),
|
||||
}
|
||||
compile_table_header_contract(after)
|
||||
version.definition_json = after
|
||||
@@ -1255,6 +1307,22 @@ def publish(
|
||||
enabled_configs = _enabled_fields(definition)
|
||||
if not enabled_configs:
|
||||
raise ValidationError('Schema version requires at least one field', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
# [STEP] 发布前再次归一化派生规则;启用中的规则要求来源/目标已采用。
|
||||
adopted_line_codes = {
|
||||
str(item.get('field_code'))
|
||||
for item in enabled_configs
|
||||
if item.get('scope') == 'line' and item.get('field_code')
|
||||
}
|
||||
derivation_rules = normalize_derivation_rules(
|
||||
definition.get('derivation_rules'),
|
||||
adopted_line_field_codes=adopted_line_codes if any(
|
||||
isinstance(rule, dict) and rule.get('enabled')
|
||||
for rule in (definition.get('derivation_rules') or [])
|
||||
) else None,
|
||||
)
|
||||
definition['derivation_rules'] = derivation_rules
|
||||
definition['derivation_rules_checksum'] = derivation_rules_checksum(derivation_rules)
|
||||
version.definition_json = definition
|
||||
included_field_ids = {str(config.get('field_id')) for config in enabled_configs}
|
||||
previous = ShippingOrderSchemaVersion.query.filter_by(schema_id=version.schema_id, status='published').first()
|
||||
previous_ids = {
|
||||
@@ -1366,3 +1434,180 @@ def get_published_contract() -> dict[str, Any]:
|
||||
'checksum': version.checksum,
|
||||
'fields': _enabled_fields(_definition(version)),
|
||||
}
|
||||
|
||||
|
||||
def simulate_derivation(
|
||||
version_id: int,
|
||||
data: dict[str, Any],
|
||||
*,
|
||||
actor_id: int | None,
|
||||
request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
对草稿或已发布 Schema 版本的派生规则做只读样本模拟。
|
||||
|
||||
核心逻辑:优先使用请求体 derivation_rules,否则读版本 definition;
|
||||
lines 可直接提交,或通过 sample_ref=`extraction:<id>` 从历史 Extraction 加载明细投影;
|
||||
模拟前仅对历史 Extraction 样本剔除规则目标字段,避免已派生结果恒跳过;
|
||||
手工 JSON 保留目标字段以真实评估 copy_if_empty;
|
||||
写入 DERIVATION_SIMULATED 审计(不 commit),不改订单。
|
||||
|
||||
Args:
|
||||
version_id: Schema 版本 ID。
|
||||
data: 含 lines 或 sample_ref(extraction:<id>)、可选 derivation_rules。
|
||||
actor_id: 管理员 ID。
|
||||
request_id: 请求追踪 ID。
|
||||
|
||||
Returns:
|
||||
模拟结果摘要与逐行结果。
|
||||
|
||||
Raises:
|
||||
ValidationError: lines / sample_ref 非法。
|
||||
NotFoundError: 版本或 Extraction 不存在。
|
||||
"""
|
||||
from app.models import ShippingOrderExtraction
|
||||
|
||||
_, version = _resolve_schema_for_version(version_id)
|
||||
sample_ref = str(data.get('sample_ref') or '').strip() or None
|
||||
raw_lines = data.get('lines')
|
||||
sample_source: dict[str, Any] | None = None
|
||||
|
||||
# [STEP] 支持可追溯样本:extraction:<id> → normalized_result_json.lines
|
||||
# 历史样本可能已含派生后的目标字段;模拟前剔除规则目标,避免 copy_if_empty 恒跳过。
|
||||
if sample_ref and sample_ref.startswith('extraction:'):
|
||||
try:
|
||||
extraction_id = int(sample_ref.split(':', 1)[1])
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'sample_ref extraction id is invalid',
|
||||
code='SHIPPING.ORDER_SCHEMA_DERIVATION_SAMPLE_INVALID',
|
||||
) from exc
|
||||
extraction = db.session.get(ShippingOrderExtraction, extraction_id)
|
||||
if extraction is None:
|
||||
raise NotFoundError(
|
||||
'Derivation sample extraction not found',
|
||||
code='SHIPPING.ORDER_SCHEMA_DERIVATION_SAMPLE_NOT_FOUND',
|
||||
)
|
||||
normalized = extraction.normalized_result_json if isinstance(extraction.normalized_result_json, dict) else {}
|
||||
loaded = list(normalized.get('lines') or [])
|
||||
if not loaded or any(not isinstance(item, dict) for item in loaded):
|
||||
raise ValidationError(
|
||||
'extraction sample has no usable line projections',
|
||||
code='SHIPPING.ORDER_SCHEMA_DERIVATION_SAMPLE_EMPTY',
|
||||
)
|
||||
raw_lines = loaded
|
||||
sample_source = {
|
||||
'kind': 'extraction',
|
||||
'extraction_id': int(extraction.id),
|
||||
'schema_version_id': int(extraction.schema_version_id),
|
||||
'intake_id': int(extraction.intake_id),
|
||||
'status': extraction.status,
|
||||
'targets_stripped_for_simulate': True,
|
||||
}
|
||||
|
||||
if not isinstance(raw_lines, list) or any(not isinstance(item, dict) for item in raw_lines):
|
||||
raise ValidationError(
|
||||
'lines must be a list of objects (or provide sample_ref=extraction:<id>)',
|
||||
code='SHIPPING.ORDER_SCHEMA_DERIVATION_SIMULATE_INVALID',
|
||||
)
|
||||
definition = _definition(version)
|
||||
rules = data.get('derivation_rules') if 'derivation_rules' in data else definition.get('derivation_rules')
|
||||
normalized_rules = normalize_derivation_rules(rules if isinstance(rules, list) else None)
|
||||
# 仅历史 Extraction 样本剔除目标字段;手工 JSON 保留原值以真实评估 copy_if_empty。
|
||||
strip_targets = bool(sample_source and sample_source.get('targets_stripped_for_simulate'))
|
||||
if strip_targets:
|
||||
target_codes = {
|
||||
str(rule.get('target_field_code') or '')
|
||||
for rule in normalized_rules
|
||||
if rule.get('target_field_code')
|
||||
}
|
||||
simulate_lines = []
|
||||
for line in raw_lines:
|
||||
cleaned = dict(line)
|
||||
for code in target_codes:
|
||||
cleaned.pop(code, None)
|
||||
simulate_lines.append(cleaned)
|
||||
else:
|
||||
simulate_lines = [dict(line) for line in raw_lines]
|
||||
outcome = apply_derivation_rules_to_lines(simulate_lines, normalized_rules)
|
||||
append_shipping_audit_event(
|
||||
event_type='DERIVATION_SIMULATED',
|
||||
aggregate_type='shipping_order_schema_version',
|
||||
aggregate_id=str(version.id),
|
||||
actor_type='admin',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
action='simulate_derivation',
|
||||
result='success',
|
||||
metadata={
|
||||
'schema_version': version.version,
|
||||
'schema_version_status': version.status,
|
||||
'derivation_rules_checksum': outcome['rules_checksum'],
|
||||
'derived_count': outcome['derived_count'],
|
||||
'skipped_count': outcome['skipped_count'],
|
||||
'sample_ref': sample_ref,
|
||||
'sample_source': sample_source,
|
||||
'line_count': len(raw_lines),
|
||||
},
|
||||
after={
|
||||
'derivation_rules_checksum': outcome['rules_checksum'],
|
||||
'derived_count': outcome['derived_count'],
|
||||
'skipped_count': outcome['skipped_count'],
|
||||
'sample_ref': sample_ref,
|
||||
},
|
||||
)
|
||||
# 不在此 commit:由路由层统一提交,便于与样本读取等审计同事务。
|
||||
return {
|
||||
'schema_version_id': version.id,
|
||||
'schema_version': version.version,
|
||||
'schema_version_status': version.status,
|
||||
'rules_checksum': outcome['rules_checksum'],
|
||||
'rules': outcome['rules'],
|
||||
'derived_count': outcome['derived_count'],
|
||||
'skipped_count': outcome['skipped_count'],
|
||||
'results': outcome['results'],
|
||||
'lines_after': outcome['lines'],
|
||||
'sample_ref': sample_ref,
|
||||
'sample_source': sample_source,
|
||||
'mutates_orders': False,
|
||||
}
|
||||
|
||||
|
||||
def list_derivation_simulate_samples(*, limit: int = 20) -> dict[str, Any]:
|
||||
"""
|
||||
列出可供派生规则模拟的历史 Extraction 样本(脱敏摘要)。
|
||||
|
||||
核心逻辑:取最近含 normalized lines 的 Extraction;sample_ref 形如 extraction:<id>。
|
||||
|
||||
Args:
|
||||
limit: 返回条数上限(1–50)。
|
||||
|
||||
Returns:
|
||||
{ items: [{ sample_ref, extraction_id, line_count, status, created_at, schema_version_id }] }
|
||||
"""
|
||||
from app.models import ShippingOrderExtraction
|
||||
|
||||
capped = max(1, min(int(limit or 20), 50))
|
||||
rows = (
|
||||
ShippingOrderExtraction.query
|
||||
.order_by(ShippingOrderExtraction.id.desc())
|
||||
.limit(capped * 3)
|
||||
.all()
|
||||
)
|
||||
items: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
normalized = row.normalized_result_json if isinstance(row.normalized_result_json, dict) else {}
|
||||
lines = normalized.get('lines') if isinstance(normalized.get('lines'), list) else []
|
||||
if not lines:
|
||||
continue
|
||||
items.append({
|
||||
'sample_ref': f'extraction:{int(row.id)}',
|
||||
'extraction_id': int(row.id),
|
||||
'line_count': len(lines),
|
||||
'status': row.status,
|
||||
'schema_version_id': int(row.schema_version_id),
|
||||
'created_at': row.created_at.isoformat() if row.created_at else None,
|
||||
})
|
||||
if len(items) >= capped:
|
||||
break
|
||||
return {'items': items}
|
||||
@@ -0,0 +1,174 @@
|
||||
"""
|
||||
services/shipping_notice/order_stp_auto_create_service.py
|
||||
|
||||
用途:对未人工改脏且五门禁全绿的复核 Case 执行幂等 STP 自动建单。
|
||||
依赖:order_review_confirmation_service、draft 资格校验(含 can_auto_create)、fulfillment_audit。
|
||||
逻辑:由抽取单元提交 / Run 收尾在 ensure_run_review_cases 之后调用;
|
||||
有人工字段覆盖、资格未 ready 或五门禁失败则跳过(仅 Review Case);
|
||||
每单成功后独立 commit 并触发 auto_progress;成功/失败审计均 strict。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingOrderExtractionRun, ShippingOrderReviewCase
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.order_review_confirmation_service import (
|
||||
confirm_review_case,
|
||||
trigger_auto_progress_after_review_confirm,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_draft_service import _validation
|
||||
|
||||
|
||||
def _draft_has_manual_edits(case: ShippingOrderReviewCase) -> bool:
|
||||
"""
|
||||
判断草稿是否含人工覆盖值。
|
||||
|
||||
核心逻辑:header/line values 中任一 source=manual 即视为需显式确认。
|
||||
"""
|
||||
draft = case.current_draft
|
||||
if draft is None:
|
||||
return True
|
||||
header = draft.header_values_json if isinstance(draft.header_values_json, dict) else {}
|
||||
values = header.get('values') if isinstance(header.get('values'), dict) else {}
|
||||
for item in values.values():
|
||||
if isinstance(item, dict) and str(item.get('source') or '') == 'manual':
|
||||
return True
|
||||
for raw_line in draft.lines_json or []:
|
||||
if not isinstance(raw_line, dict):
|
||||
continue
|
||||
line_values = raw_line.get('values') if isinstance(raw_line.get('values'), dict) else {}
|
||||
for item in line_values.values():
|
||||
if isinstance(item, dict) and str(item.get('source') or '') == 'manual':
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def maybe_stp_auto_create_for_run(*, run: ShippingOrderExtractionRun) -> list[dict[str, Any]]:
|
||||
"""
|
||||
尝试对 Run 下未确认 Case 自动建单。
|
||||
|
||||
核心逻辑:资格 ready 且无人工改脏 → confirm_review_case;成功后 commit 并
|
||||
触发与人工确认相同的 auto_progress。失败不阻断同 Run 其他 Case。
|
||||
|
||||
Args:
|
||||
run: 已 ensure_run_review_cases 的抽取 Run。
|
||||
|
||||
Returns:
|
||||
每个尝试过的 Case 摘要列表。
|
||||
"""
|
||||
results: list[dict[str, Any]] = []
|
||||
case_ids = [
|
||||
int(row.id)
|
||||
for row in (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(run_id=int(run.id))
|
||||
.order_by(ShippingOrderReviewCase.id.asc())
|
||||
.with_entities(ShippingOrderReviewCase.id)
|
||||
.all()
|
||||
)
|
||||
]
|
||||
for case_id in case_ids:
|
||||
case = db.session.get(ShippingOrderReviewCase, case_id)
|
||||
if case is None:
|
||||
continue
|
||||
if case.confirmed_task_id or case.status in {
|
||||
'confirmed', 'confirming', 'non_order', 'superseded', 'quality_issue', 'reparse_pending',
|
||||
}:
|
||||
continue
|
||||
if case.current_draft is None:
|
||||
continue
|
||||
owner_id = int(case.owner_user_id)
|
||||
draft_version = int(case.current_draft.draft_version)
|
||||
validation = _validation(case)
|
||||
case.current_draft.validation_result_json = validation
|
||||
case.current_draft.issue_summary_json = list(validation.get('issues') or [])
|
||||
# [STEP] 五门禁 + 无人工改脏才自动建单;否则仅 Review Case。
|
||||
if (
|
||||
validation.get('status') == 'ready'
|
||||
and bool(validation.get('can_auto_create'))
|
||||
and not _draft_has_manual_edits(case)
|
||||
):
|
||||
case.status = 'ready'
|
||||
db.session.flush()
|
||||
else:
|
||||
if case.status in {'unreviewed', 'draft', 'ready'}:
|
||||
case.status = 'draft'
|
||||
results.append({
|
||||
'case_no': case.case_no,
|
||||
'status': 'skipped_needs_review',
|
||||
'can_build': bool(validation.get('can_build')),
|
||||
'can_auto_create': bool(validation.get('can_auto_create')),
|
||||
'failed_gates': list(validation.get('failed_gates') or []),
|
||||
})
|
||||
db.session.flush()
|
||||
continue
|
||||
|
||||
idempotency_key = f'stp-auto:{run.run_no}:doc-{int(case.document_id)}:v{draft_version}'
|
||||
try:
|
||||
created = confirm_review_case(
|
||||
user_id=owner_id,
|
||||
case_no=str(case.case_no),
|
||||
expected_draft_version=draft_version,
|
||||
idempotency_key=idempotency_key,
|
||||
warning_acknowledgements=[],
|
||||
)
|
||||
record_fulfillment_audit(
|
||||
event_type='stp_auto_create',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(case.case_no),
|
||||
action='stp_auto_create',
|
||||
actor_type='system',
|
||||
actor_id=None,
|
||||
review_case_no=str(case.case_no),
|
||||
owner_user_id=owner_id,
|
||||
document_id=case.document_id,
|
||||
task_no=created.get('task_no'),
|
||||
metadata={
|
||||
'idempotent_replay': bool(created.get('idempotent_replay')),
|
||||
'run_no': str(run.run_no),
|
||||
},
|
||||
source='stp_auto_create',
|
||||
strict=True,
|
||||
)
|
||||
db.session.commit()
|
||||
progress = trigger_auto_progress_after_review_confirm(
|
||||
task_no=created.get('task_no'),
|
||||
idempotent_replay=bool(created.get('idempotent_replay')),
|
||||
)
|
||||
results.append({
|
||||
'case_no': case.case_no,
|
||||
'status': 'auto_created' if not created.get('idempotent_replay') else 'idempotent_replay',
|
||||
'task_no': created.get('task_no'),
|
||||
'auto_progress_status': (progress or {}).get('status') if isinstance(progress, dict) else None,
|
||||
})
|
||||
except AppError as exc:
|
||||
# confirm 拒绝路径可能已独立 commit;此处仅记录摘要,审计失败必须抛出。
|
||||
results.append({
|
||||
'case_no': case.case_no,
|
||||
'status': 'auto_create_failed',
|
||||
'error_code': getattr(exc, 'code', None),
|
||||
})
|
||||
record_fulfillment_audit(
|
||||
event_type='stp_auto_create_failed',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(case.case_no),
|
||||
action='stp_auto_create_failed',
|
||||
actor_type='system',
|
||||
actor_id=None,
|
||||
result='rejected',
|
||||
error_code=str(getattr(exc, 'code', '') or '') or None,
|
||||
metadata={'run_no': str(run.run_no)},
|
||||
source='stp_auto_create',
|
||||
strict=True,
|
||||
)
|
||||
# 失败节点审计必须持久化;commit 失败回滚后上抛,禁止静默丢审计后继续下一单。
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
return results
|
||||
@@ -1,11 +1,12 @@
|
||||
"""
|
||||
services/shipping_notice/progress_audit_contract.py
|
||||
|
||||
用途:冻结货代发货通知进度审计与「会话 PDF 工作项」领域契约词典。
|
||||
依赖:无外部 IO;被 progress / audit / session work item / projection / OpenAPI 与测试引用。
|
||||
逻辑:状态、用户可见阶段、健康提示、取消语义、会话工作项生命周期、审计事件字典、
|
||||
快照白名单与敏感键黑名单的唯一代码源;UI 与 Worker 行为变更在后续阶段实现,
|
||||
本模块只冻结名称与规则,禁止运行时猜测。
|
||||
用途:冻结货代发货通知进度审计与 Workflow(批次/PDF 项)领域契约词典。
|
||||
依赖:无外部 IO;被 progress / audit / workflow / projection / OpenAPI 与测试引用。
|
||||
逻辑:状态、用户可见阶段、健康提示、取消语义、Workflow Item 生命周期(含终态/
|
||||
待人工上传登记集合)、审计事件字典、快照白名单与敏感键黑名单的唯一代码源;
|
||||
UI 与 Worker 行为变更在后续阶段实现,本模块只冻结名称与规则,禁止运行时猜测。
|
||||
SESSION_* 别名保留供过渡期测试引用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,10 +19,47 @@ PROGRESS_MAPPING_VERSION: Final[str] = 'shipping-order-progress-v3'
|
||||
# 审计默认保留期(天);默认三年,可由环境变量覆盖(阶段 4 留存 Job 读取)。
|
||||
AUDIT_RETENTION_DAYS: Final[int] = 365 * 3
|
||||
|
||||
# 会话未关闭 PDF 工作项上限;超出由阶段 1 写路径拒绝,前端不得自行截断真相。
|
||||
MAX_OPEN_SESSION_WORK_ITEMS: Final[int] = 50
|
||||
# Workflow 未关闭 Item 上限;超出由写路径拒绝,前端不得自行截断真相。
|
||||
MAX_OPEN_WORKFLOW_ITEMS: Final[int] = 50
|
||||
# 过渡期别名:历史会话 PDF 工作项上限与 Workflow Item 上限对齐。
|
||||
MAX_OPEN_SESSION_WORK_ITEMS: Final[int] = MAX_OPEN_WORKFLOW_ITEMS
|
||||
|
||||
# 会话 PDF 工作项生命周期(真相源);closed 以外均为未关闭。
|
||||
# Workflow Item 生命周期(与 shipping_notice_workflow_items 模型 CHECK 对齐)。
|
||||
WORKFLOW_ITEM_LIFECYCLE_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'queued',
|
||||
'layout_parsing',
|
||||
'extracting',
|
||||
'pending_review',
|
||||
'building_order',
|
||||
'inventory_matching',
|
||||
'generating_excel',
|
||||
'manual_upload_pending',
|
||||
'reparse_failed',
|
||||
'cancelled',
|
||||
'failed',
|
||||
'closed',
|
||||
})
|
||||
|
||||
# 真正终态:登记成功关闭或取消后,父 Workflow 才可收敛 completed。
|
||||
WORKFLOW_ITEM_TERMINAL_LIFECYCLE_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'closed',
|
||||
'cancelled',
|
||||
})
|
||||
|
||||
# 待人工上传登记:非完成,仍计开放项。
|
||||
WORKFLOW_ITEM_WAITING_MANUAL_UPLOAD_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'manual_upload_pending',
|
||||
})
|
||||
|
||||
WORKFLOW_ITEM_CLOSED_REASONS: Final[frozenset[str]] = frozenset({
|
||||
'confirmed',
|
||||
'non_order',
|
||||
'user_cancelled',
|
||||
'admin_terminated',
|
||||
'failed',
|
||||
})
|
||||
|
||||
# 过渡期别名:旧会话工作项生命周期集合映射到 Workflow 子集(保持测试兼容)。
|
||||
SESSION_WORK_ITEM_LIFECYCLE_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'pending_review',
|
||||
'extracting',
|
||||
@@ -36,8 +74,12 @@ SESSION_WORK_ITEM_CLOSED_REASONS: Final[frozenset[str]] = frozenset({
|
||||
'admin_terminated',
|
||||
})
|
||||
|
||||
# 会话工作项 / 版本切换 / 人工复核 / 监管相关审计事件字典(阶段 1+ 落库)。
|
||||
SESSION_WORK_ITEM_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
# Workflow / 版本切换 / 人工复核 / 监管相关审计事件字典(含历史 session_* 字符串兼容)。
|
||||
WORKFLOW_ITEM_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'workflow_created',
|
||||
'workflow_item_created',
|
||||
'workflow_item_cancelled',
|
||||
'workflow_stage_changed',
|
||||
'session_work_item_created',
|
||||
'document_extraction_started',
|
||||
'document_reparse_requested',
|
||||
@@ -57,6 +99,40 @@ SESSION_WORK_ITEM_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'audit_access',
|
||||
'shipping_resource_accessed',
|
||||
})
|
||||
# 过渡期别名。
|
||||
SESSION_WORK_ITEM_AUDIT_EVENT_TYPES: Final[frozenset[str]] = WORKFLOW_ITEM_AUDIT_EVENT_TYPES
|
||||
|
||||
# 字段派生 / 人工覆盖 / 规则模拟 / Excel 导出等项次相关审计事件词典(语义分组)。
|
||||
# 自 2026-07-30 起:货代统一审计账本全部事件永久保留;本集合仅作事件分类引用。
|
||||
LINE_DERIVATION_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'FIELD_DERIVED',
|
||||
'FIELD_DERIVATION_SKIPPED',
|
||||
'LINE_NO_OVERRIDDEN',
|
||||
'LINE_NO_RESTORED',
|
||||
'DERIVATION_SIMULATED',
|
||||
'DERIVATION_RULES_CHANGED',
|
||||
'ORDER_FROZEN',
|
||||
'EXPORT_GENERATED',
|
||||
'AUDIT_QUERY_EXPORTED',
|
||||
})
|
||||
|
||||
|
||||
def is_permanent_audit_event_type(event_type: str) -> bool:
|
||||
"""
|
||||
判断审计事件是否永久保留(不得写入 retention_expires_at)。
|
||||
|
||||
核心逻辑:货代全业务节点统一永久保留;保留参数仅兼容旧调用方,清理 Job
|
||||
仅删除历史已写入到期时间且已过期的遗留行。
|
||||
|
||||
Args:
|
||||
event_type: 审计事件类型码(保留形参供调用方与测试兼容)。
|
||||
|
||||
Returns:
|
||||
恒为 True。
|
||||
"""
|
||||
del event_type
|
||||
return True
|
||||
|
||||
|
||||
# Run 业务状态(真相源);cancellation_requested 不是 Run.status,而是取消请求元数据投影。
|
||||
RUN_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
@@ -191,7 +267,7 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
|
||||
'policy_checksum',
|
||||
'queue_position',
|
||||
'selection_batch',
|
||||
# 会话 PDF 工作项 / 版本指针(禁止字段正文与附件 URL)。
|
||||
# Workflow / 版本指针(禁止字段正文与附件 URL)。
|
||||
'lifecycle_status',
|
||||
'closed_reason',
|
||||
'lock_version',
|
||||
@@ -204,6 +280,10 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
|
||||
'current_document_id',
|
||||
'session_item_no',
|
||||
'item_no',
|
||||
'workflow_no',
|
||||
'workflow_item_no',
|
||||
'current_stage',
|
||||
'version_status',
|
||||
'owner_user_id',
|
||||
'conversation_id',
|
||||
'reparse_failure_stage',
|
||||
@@ -225,6 +305,16 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
|
||||
'task_no',
|
||||
'replacement_intake_no',
|
||||
'successor_run_no',
|
||||
# 字段派生 / 覆盖 / 导出血缘(脱敏摘要,禁止邮件/PDF 正文)。
|
||||
'rule_id',
|
||||
'rule_checksum',
|
||||
'derivation_rules_checksum',
|
||||
'skip_reason',
|
||||
'override_reason_code',
|
||||
'export_sequence',
|
||||
'export_artifact_no',
|
||||
'template_version',
|
||||
'field_code',
|
||||
})
|
||||
|
||||
# 四语言 i18n key 清单(阶段 2 补齐文案;此处仅冻结路径,禁止前端硬编码)。
|
||||
|
||||
@@ -4,7 +4,7 @@ services/shipping_notice/progress_workflow.py
|
||||
用途:承接发货通知任务的自动推进流程,包括解析确认检查、正式库存准备与履约侧串联。
|
||||
依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、
|
||||
state_machine(CheckpointKind)、tool_response。
|
||||
逻辑:由 task_workflow / 复核确认 / Unit 直通落库对外转调本文件;按 checkpoint_kind 早停或继续;
|
||||
逻辑:由 task_workflow / 复核确认 / STP 直通落库对外转调本文件;按 checkpoint_kind 早停或继续;
|
||||
STP:must_human / wait_manual_upload 无副作用早停;货代 RPA 上传不在自动链内;
|
||||
系统触发时事件 actor_id=None 且 detail.source=system。
|
||||
"""
|
||||
@@ -44,7 +44,8 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
亦由 STP 直通建单、人工复核确认后系统入口复用(同一函数,禁止平行链路)。
|
||||
|
||||
核心逻辑:先按 checkpoint_kind 早停(must_human / wait_manual_upload / complete);
|
||||
再检查解析门禁与客户/库存源,保证正式库存就绪后委托 fulfillment(止于待人工上传,不触发 RPA 上传)。
|
||||
Excel 后 WAIT_MANUAL_UPLOAD 幂等对齐 manual_upload_pending 并禁止 upload_to_freight;
|
||||
再检查解析门禁与客户/库存源,保证正式库存就绪后委托 fulfillment(止于人工上传登记,不触发 RPA)。
|
||||
Args:
|
||||
payload: 必须能定位任务;可额外携带 lang/locale/language、auto-chain 控制参数,
|
||||
以及 source(system|workspace_api|tool_api|review_confirmation 等)。
|
||||
@@ -75,19 +76,8 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
steps: list[str] = []
|
||||
|
||||
# [STEP 0] STP 检查点早停:必须人工或待人工上传时不产生新副作用。
|
||||
# [STEP 0] STP 检查点早停:必须人工、待人工上传登记或已完成时不产生新副作用。
|
||||
ui_early = resolve_task_ui_state(task)
|
||||
if ui_early.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD:
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message="发货 Excel 已生成,请在任务处理工作台完成人工上传凭据。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui_early.human_options,
|
||||
checkpoint=ui_early.checkpoint,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
)
|
||||
if ui_early.checkpoint_kind == CheckpointKind.MUST_HUMAN:
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
@@ -105,6 +95,31 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
message="任务已结束,无需自动推进。",
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
if ui_early.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD:
|
||||
# 幂等对齐 WorkflowItem 为 manual_upload_pending;自动链禁止 upload_to_freight。
|
||||
try:
|
||||
from app.services.shipping_notice.workflow_ledger_service import sync_workflow_item_stage_for_task
|
||||
sync_workflow_item_stage_for_task(
|
||||
task_no=str(task.task_no),
|
||||
lifecycle_status='manual_upload_pending',
|
||||
event_code='manual_upload_pending',
|
||||
actor_type='system',
|
||||
actor_id=None,
|
||||
payload={'task_no': task.task_no, 'source': source},
|
||||
)
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message="Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui_early.human_options,
|
||||
checkpoint=ui_early.checkpoint,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
)
|
||||
|
||||
# [STEP 1] 先判断解析结果是否允许进入自动链路。
|
||||
# 解析待确认或低置信度时必须立即停下,避免在错误数据上继续做库存/出货操作。
|
||||
@@ -194,7 +209,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
else:
|
||||
steps.append("载入库存")
|
||||
|
||||
# [STEP 3] 库存就绪后进入履约侧自动推进(止于待人工上传)。
|
||||
# [STEP 3] 库存就绪后进入履约侧自动推进(止于 Excel 就绪)。
|
||||
fulfillment_result = fulfillment_workflow.run_auto_progress_fulfillment_steps(task, payload, steps)
|
||||
if fulfillment_result is not None:
|
||||
return fulfillment_result
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/query_service.py
|
||||
|
||||
用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。
|
||||
依赖:models.ShippingBatch、ShippingCase、ShippingNoticeCandidate、ShippingTask、ShippingTaskEvent、
|
||||
ShippingOrderReviewCase、ShippingOrderExtractionRun、state_machine、动态订单字段编辑器。
|
||||
ShippingReservation、ShippingOrderReviewCase、ShippingOrderExtractionRun、state_machine、动态订单字段编辑器。
|
||||
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
|
||||
tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉;
|
||||
SUMMARY 经 _enrich_task_center_fields 附带 todo_category / can_handle / ui_state / recent_event;
|
||||
@@ -11,7 +11,7 @@ services/shipping_notice/query_service.py
|
||||
客户关键字 SQL 同时过滤 Review Case(文件名/Case 号/PO)与 Task(客户快照/来源文件名);
|
||||
待办 todo_category 下推为与状态机同序的 SQL CASE;list 用 UNION ALL + COUNT/OFFSET/LIMIT,
|
||||
仅水合当前页(禁止 500 截断冒充总数);
|
||||
DETAIL 另投影 parse_validation / process_field_gate / source_candidate 供持久只读展示;
|
||||
DETAIL 另投影 parse_validation / process_field_gate / source_candidate 与履约时间线(Reservation/Artifact);
|
||||
订单行仅从任务锁定 Extraction 的 FieldValue 投影,未抽取任务返回空行集。
|
||||
"""
|
||||
|
||||
@@ -22,7 +22,7 @@ from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import asc, case, desc, exists, func, literal, select, union_all
|
||||
from sqlalchemy import String, asc, case, cast, desc, exists, func, literal, select, union_all
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
@@ -38,6 +38,7 @@ from app.models import (
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingReservation,
|
||||
ShippingTask,
|
||||
ShippingTaskEvent,
|
||||
ShippingUploadAttempt,
|
||||
@@ -833,8 +834,10 @@ def task_todo_category(task: ShippingTask) -> str:
|
||||
"""
|
||||
由 checkpoint_kind + 复核检查点推导待办分类(服务端唯一口径)。
|
||||
|
||||
核心逻辑:complete→done;wait_manual_upload→manual_upload;
|
||||
must_human 且属复核入口→review,其余 must_human→exception;auto_continue→in_progress。
|
||||
核心逻辑:wait_manual_upload→manual_upload(含 Excel 导出后待登记);
|
||||
complete→done;must_human 且属复核入口→review,其余 must_human→exception;
|
||||
auto_continue→in_progress。
|
||||
筛选 manual_upload 时 SQL 侧亦覆盖 waiting_upload / 有导出文件的任务。
|
||||
|
||||
Returns:
|
||||
review | exception | manual_upload | in_progress | done
|
||||
@@ -845,10 +848,10 @@ def task_todo_category(task: ShippingTask) -> str:
|
||||
|
||||
def _todo_category_from_ui(checkpoint: str | None, kind: CheckpointKind) -> str:
|
||||
"""将 checkpoint_kind(及复核入口集合)映射为 todo_category。"""
|
||||
if kind == CheckpointKind.COMPLETE:
|
||||
return "done"
|
||||
if kind == CheckpointKind.WAIT_MANUAL_UPLOAD:
|
||||
return "manual_upload"
|
||||
if kind == CheckpointKind.COMPLETE:
|
||||
return "done"
|
||||
if kind == CheckpointKind.MUST_HUMAN:
|
||||
if str(checkpoint or "") in _REVIEW_TODO_CHECKPOINTS:
|
||||
return "review"
|
||||
@@ -982,7 +985,8 @@ def _enrich_task_center_fields(
|
||||
为 SUMMARY/DETAIL 投影补充任务中心字段(就地写入并返回 data)。
|
||||
|
||||
核心逻辑:todo_category / created_by 始终写入;viewer 给定时写入 can_handle;
|
||||
recent_event / artifact_summary / ui_state 懒加载同源状态,避免任务中心再推导。
|
||||
recent_event / artifact_summary / ui_state 懒加载同源状态,避免任务中心再推导;
|
||||
DETAIL 另附 workflow_item(含 Workflow Event)供时间线与最后活动展示。
|
||||
|
||||
Args:
|
||||
task: 源任务。
|
||||
@@ -1008,6 +1012,25 @@ def _enrich_task_center_fields(
|
||||
return data
|
||||
|
||||
|
||||
def _attach_workflow_item_projection(task: ShippingTask, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
为任务详情附带绑定的 WorkflowItem 投影(含可见 Workflow Event)。
|
||||
|
||||
核心逻辑:按 current_task_no 定位 Item;未绑定时 workflow_item=None,不阻断详情。
|
||||
"""
|
||||
try:
|
||||
from app.services.shipping_notice.workflow_ledger_service import find_item_by_current_task_no
|
||||
from app.services.shipping_notice.workflow_progress_projection import serialize_workflow_item
|
||||
|
||||
item = find_item_by_current_task_no(task_no=str(task.task_no or ''))
|
||||
data['workflow_item'] = (
|
||||
serialize_workflow_item(item, include_events=True) if item is not None else None
|
||||
)
|
||||
except Exception:
|
||||
data['workflow_item'] = None
|
||||
return data
|
||||
|
||||
|
||||
def serialize_task_summary(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
@@ -1035,7 +1058,7 @@ def serialize_task_detail(
|
||||
is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
工作台任务详情用的 DETAIL 投影(含 lines、events 与任务中心 enrich)。
|
||||
工作台任务详情用的 DETAIL 投影(含 lines、events、WorkflowItem 与任务中心 enrich)。
|
||||
|
||||
Args:
|
||||
task: 源任务。
|
||||
@@ -1043,9 +1066,10 @@ def serialize_task_detail(
|
||||
is_admin: 是否管理员视图。
|
||||
"""
|
||||
data = serialize_task(task, TaskProjection.DETAIL)
|
||||
return _enrich_task_center_fields(
|
||||
_enrich_task_center_fields(
|
||||
task, data, viewer_user_id=viewer_user_id, is_admin=is_admin,
|
||||
)
|
||||
return _attach_workflow_item_projection(task, data)
|
||||
|
||||
|
||||
def get_batch_for_user(batch_no: str, user_id: int) -> ShippingBatch | None:
|
||||
@@ -1368,15 +1392,22 @@ def _todo_category_sql_filter(allowed: frozenset[str]):
|
||||
核心逻辑:与 task_todo_category 对齐的保守 OR;精确分类由 _task_todo_category_sql_expr 完成。
|
||||
"""
|
||||
clauses = []
|
||||
if "done" in allowed:
|
||||
clauses.append(ShippingTask.process_status.in_(("uploaded", "closed", "rejected")))
|
||||
if "manual_upload" in allowed:
|
||||
# wait_manual_upload:waiting_upload / 已有导出文件且未 uploaded。
|
||||
clauses.append(
|
||||
db.or_(
|
||||
ShippingTask.process_status.in_(("waiting_upload", "upload_failed")),
|
||||
ShippingTask.export_file_path.isnot(None),
|
||||
db.and_(
|
||||
ShippingTask.export_file_path.isnot(None),
|
||||
ShippingTask.process_status.notin_(("uploaded", "closed", "rejected")),
|
||||
),
|
||||
)
|
||||
)
|
||||
if "done" in allowed:
|
||||
# 已上传/关闭/驳回终态(不含待人工上传登记)。
|
||||
clauses.append(
|
||||
ShippingTask.process_status.in_(("uploaded", "closed", "rejected"))
|
||||
)
|
||||
if "review" in allowed:
|
||||
clauses.append(
|
||||
db.or_(
|
||||
@@ -1419,8 +1450,14 @@ def _task_has_dynamic_order_lines_sql():
|
||||
|
||||
|
||||
def _sql_json_falsy(column):
|
||||
"""JSON 列在 Python 中视为假值的 SQL 近似(None / [] / {})。"""
|
||||
return db.or_(column.is_(None), column == [], column == {})
|
||||
"""
|
||||
JSON 列在 Python 中视为假值的 SQL 近似(None / [] / {})。
|
||||
|
||||
核心逻辑:Postgres `json` 无等号运算符(`json = json` 会 UndefinedFunction);
|
||||
转为 text 再与紧凑字面量比较,兼容 SQLite 测试库。
|
||||
"""
|
||||
as_text = cast(column, String)
|
||||
return db.or_(column.is_(None), as_text == '[]', as_text == '{}')
|
||||
|
||||
|
||||
def _sql_str_blank(column):
|
||||
@@ -1511,15 +1548,11 @@ def _task_todo_category_sql_expr():
|
||||
),
|
||||
literal("exception"),
|
||||
),
|
||||
(reason == PH_UPLOAD_RESULT_UNKNOWN, literal("exception")),
|
||||
(reason == PH_UPLOAD_RESULT_UNKNOWN, literal("manual_upload")),
|
||||
(reason == PH_RPA_PENDING, literal("exception")),
|
||||
(
|
||||
db.or_(
|
||||
reason == PH_UPLOAD_RPA_PENDING,
|
||||
ShippingTask.process_status == "waiting_upload",
|
||||
),
|
||||
literal("exception"),
|
||||
),
|
||||
(reason == PH_UPLOAD_RPA_PENDING, literal("exception")),
|
||||
# Excel 后待人工上传登记。
|
||||
(ShippingTask.process_status == "waiting_upload", literal("manual_upload")),
|
||||
else_=literal("in_progress"),
|
||||
)
|
||||
|
||||
@@ -1601,8 +1634,17 @@ def _todo_tasks_base_query(
|
||||
)
|
||||
)
|
||||
elif normalized_bucket == "done":
|
||||
# Excel 就绪(matched+export / waiting_upload)与历史上传完成均归 done。
|
||||
q = q.filter(
|
||||
ShippingTask.process_status.in_(("uploaded", "closed", "rejected"))
|
||||
db.or_(
|
||||
ShippingTask.process_status.in_(
|
||||
("uploaded", "closed", "rejected", "waiting_upload")
|
||||
),
|
||||
db.and_(
|
||||
ShippingTask.process_status == "matched",
|
||||
ShippingTask.export_file_path.isnot(None),
|
||||
),
|
||||
)
|
||||
)
|
||||
return q.filter(_task_todo_category_sql_expr().in_(tuple(sorted(allowed))))
|
||||
|
||||
@@ -1790,7 +1832,17 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]:
|
||||
processing = active.filter(category_expr == "in_progress").count()
|
||||
done = (
|
||||
_visible_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||||
.filter(ShippingTask.process_status.in_(("uploaded", "closed", "rejected")))
|
||||
.filter(
|
||||
db.or_(
|
||||
ShippingTask.process_status.in_(
|
||||
("uploaded", "closed", "rejected", "waiting_upload")
|
||||
),
|
||||
db.and_(
|
||||
ShippingTask.process_status == "matched",
|
||||
ShippingTask.export_file_path.isnot(None),
|
||||
),
|
||||
)
|
||||
)
|
||||
.filter(category_expr == "done")
|
||||
.count()
|
||||
)
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
services/shipping_notice/queue_service.py
|
||||
|
||||
用途:货代发货后台任务队列适配层。
|
||||
依赖:app.jobs.queue、jobs.types、batch_orchestrator、intake_parse_workflow。
|
||||
依赖:app.jobs.queue、jobs.types、batch_orchestrator、intake_parse_workflow、
|
||||
order_extraction_run_service / document_layout.lifecycle(超时回收同步领域与 Workflow)。
|
||||
逻辑:发货通知写入通用 jobs;worker 领取 RUN/PARSE;超时回收时 PARSE Job
|
||||
经 sync_intake_after_parse_job_recovery 同步 Intake,避免永久 parsing。
|
||||
经 sync_intake_after_parse_job_recovery 同步 Intake,避免永久 parsing;
|
||||
订单抽取/版面回收同步 WorkflowItem,避免永久 layout_parsing/extracting。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
@@ -1,441 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/session_pdf_work_item_projection.py
|
||||
|
||||
用途:会话 PDF 工作台聚合读模型投影(未关闭/已关闭分组、版本摘要、统计)。
|
||||
依赖:ShippingSessionPdfWorkItem、ShippingNoticeDocument、ShippingOrderReviewCase、
|
||||
ShippingOrderExtractionRun、FileAsset。
|
||||
逻辑:由 workspace/admin API 调用;版本历史严格限定会话 + 重识别谱系;
|
||||
管理员投影额外返回 terminate/revoke 动作。前端不得按最新 Run 自行拼装列表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingNoticeDocument,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingSessionPdfWorkItem,
|
||||
)
|
||||
from app.services.shipping_notice.progress_audit_contract import MAX_OPEN_SESSION_WORK_ITEMS
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
"""UTC datetime → ISO8601 Z。"""
|
||||
if value is None:
|
||||
return None
|
||||
return value.isoformat() + ('Z' if value.tzinfo is None else '')
|
||||
|
||||
|
||||
def _document_filename(document_id: int | None) -> str | None:
|
||||
"""读取 Document 文件名;缺失时返回 None。"""
|
||||
if not document_id:
|
||||
return None
|
||||
document = ShippingNoticeDocument.query.get(int(document_id))
|
||||
if document is None:
|
||||
return None
|
||||
name = str(document.filename or '').strip()
|
||||
if name:
|
||||
return name
|
||||
if document.asset_id:
|
||||
asset = FileAsset.query.get(int(document.asset_id))
|
||||
if asset is not None:
|
||||
return str(asset.original_filename or asset.filename or '').strip() or None
|
||||
return None
|
||||
|
||||
|
||||
def _collect_lineage_run_ids(item: ShippingSessionPdfWorkItem) -> set[int]:
|
||||
"""
|
||||
收集工作项真实版本谱系的 Run ID。
|
||||
|
||||
核心逻辑:从 current_run 向上沿 reparse_of_run_id 追溯祖先(并收集替换文档);
|
||||
再向下收集同会话且 review_reparse 文档落在谱系文档集内的后继 Run。
|
||||
"""
|
||||
docs = {int(item.root_document_id), int(item.current_document_id)}
|
||||
run_ids: set[int] = set()
|
||||
|
||||
# [STEP 1] 向上追溯祖先链,并收集路径上的替换文档 ID。
|
||||
cursor = int(item.current_run_id) if item.current_run_id else None
|
||||
seen: set[int] = set()
|
||||
while cursor and cursor not in seen:
|
||||
seen.add(cursor)
|
||||
run_ids.add(cursor)
|
||||
run = ShippingOrderExtractionRun.query.get(cursor)
|
||||
if run is None:
|
||||
break
|
||||
marker = (run.input_snapshot_json or {}).get('review_reparse')
|
||||
if isinstance(marker, dict):
|
||||
marker_doc = int(marker.get('document_id') or 0)
|
||||
if marker_doc:
|
||||
docs.add(marker_doc)
|
||||
cursor = int(run.reparse_of_run_id) if run.reparse_of_run_id else None
|
||||
|
||||
# [STEP 2] 向下扩展后继;仅纳入同会话且文档属于本工作项谱系的重识别分支。
|
||||
frontier = list(run_ids)
|
||||
while frontier:
|
||||
parent_id = frontier.pop()
|
||||
children = ShippingOrderExtractionRun.query.filter_by(reparse_of_run_id=int(parent_id)).all()
|
||||
for child in children:
|
||||
child_id = int(child.id)
|
||||
if child_id in run_ids:
|
||||
continue
|
||||
if str(child.conversation_id or '') != str(item.conversation_id or ''):
|
||||
continue
|
||||
marker = (child.input_snapshot_json or {}).get('review_reparse')
|
||||
if isinstance(marker, dict):
|
||||
marker_doc = int(marker.get('document_id') or 0)
|
||||
if marker_doc and marker_doc not in docs:
|
||||
continue
|
||||
if marker_doc:
|
||||
docs.add(marker_doc)
|
||||
run_ids.add(child_id)
|
||||
frontier.append(child_id)
|
||||
|
||||
return run_ids
|
||||
|
||||
|
||||
def _collect_lineage_document_ids(
|
||||
item: ShippingSessionPdfWorkItem,
|
||||
lineage_run_ids: set[int],
|
||||
) -> set[int]:
|
||||
"""
|
||||
收集工作项版本谱系涉及的全部 Document ID(含多次替换的中间版本)。
|
||||
|
||||
核心逻辑:根/当前 + 谱系 Run 的 review_reparse.document_id;
|
||||
不把同 Run 其他 PDF 的 Case.document_id 一并纳入,避免兄弟文件污染。
|
||||
"""
|
||||
docs = {int(item.root_document_id), int(item.current_document_id)}
|
||||
if not lineage_run_ids:
|
||||
return docs
|
||||
runs = ShippingOrderExtractionRun.query.filter(
|
||||
ShippingOrderExtractionRun.id.in_(lineage_run_ids),
|
||||
).all()
|
||||
for run in runs:
|
||||
marker = (run.input_snapshot_json or {}).get('review_reparse')
|
||||
if isinstance(marker, dict):
|
||||
marker_doc = int(marker.get('document_id') or 0)
|
||||
if marker_doc:
|
||||
docs.add(marker_doc)
|
||||
return docs
|
||||
|
||||
|
||||
def _assign_version_numbers(
|
||||
cases: list[ShippingOrderReviewCase],
|
||||
*,
|
||||
item: ShippingSessionPdfWorkItem,
|
||||
) -> dict[int, int]:
|
||||
"""
|
||||
按创建时间升序分配真实版本号,并与工作项 current_version_no 对齐。
|
||||
|
||||
核心逻辑:当前 Case 固定为 item.current_version_no;更早 Case 依次递减,
|
||||
禁止按「查询结果下标」倒推导致中间版本丢失后错配。
|
||||
"""
|
||||
if not cases:
|
||||
return {}
|
||||
ordered = sorted(
|
||||
cases,
|
||||
key=lambda case: (case.created_at or datetime.min, int(case.id)),
|
||||
)
|
||||
current_case_id = int(item.current_case_id) if item.current_case_id else None
|
||||
current_version = int(item.current_version_no or 1)
|
||||
current_idx = next(
|
||||
(index for index, case in enumerate(ordered) if int(case.id) == current_case_id),
|
||||
None,
|
||||
)
|
||||
if current_idx is None:
|
||||
return {int(case.id): index + 1 for index, case in enumerate(ordered)}
|
||||
# current_idx 对应 current_version;其前序为更小版本号。
|
||||
base = current_version - current_idx
|
||||
return {
|
||||
int(case.id): max(1, base + index)
|
||||
for index, case in enumerate(ordered)
|
||||
}
|
||||
|
||||
|
||||
def _available_actions(item: ShippingSessionPdfWorkItem, *, for_admin: bool = False) -> list[str]:
|
||||
"""
|
||||
按生命周期投影可用动作;前端不得本地发明。
|
||||
|
||||
Args:
|
||||
item: 工作项。
|
||||
for_admin: True 时附加监管台 terminate/revoke 动作。
|
||||
"""
|
||||
status = str(item.lifecycle_status or '')
|
||||
if status == 'closed':
|
||||
actions = ['view_version_history']
|
||||
if for_admin and item.closed_reason == 'confirmed':
|
||||
actions.append('admin_revoke_confirmation')
|
||||
return actions
|
||||
if status == 'extracting':
|
||||
actions = ['refresh_status', 'view_version_history']
|
||||
if for_admin:
|
||||
actions.append('admin_terminate')
|
||||
return actions
|
||||
actions = [
|
||||
'enter_manual_review',
|
||||
'view_version_history',
|
||||
'request_reparse',
|
||||
'mark_non_order',
|
||||
'cancel',
|
||||
]
|
||||
if status == 'reparse_failed':
|
||||
actions = [
|
||||
'enter_manual_review',
|
||||
'view_version_history',
|
||||
'request_reparse',
|
||||
'cancel',
|
||||
]
|
||||
if status == 'pending_review':
|
||||
# 质量异常/替换入口由复核页完整流程承载;面板提供重识别与关闭。
|
||||
actions.append('replace_file')
|
||||
if for_admin:
|
||||
actions.append('admin_terminate')
|
||||
return actions
|
||||
|
||||
|
||||
def serialize_session_work_item(
|
||||
item: ShippingSessionPdfWorkItem,
|
||||
*,
|
||||
for_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
序列化单条会话 PDF 工作项摘要。
|
||||
|
||||
Args:
|
||||
item: ORM 工作项。
|
||||
for_admin: 监管台场景附加管理员动作。
|
||||
|
||||
Returns:
|
||||
前端工作台行模型。
|
||||
"""
|
||||
superseded = bool(item.current_version_no and int(item.current_version_no) > 1)
|
||||
return {
|
||||
'item_no': item.item_no,
|
||||
'conversation_id': item.conversation_id,
|
||||
'owner_user_id': int(item.owner_user_id),
|
||||
'root_document_id': int(item.root_document_id),
|
||||
'current_document_id': int(item.current_document_id),
|
||||
'current_document_filename': _document_filename(item.current_document_id),
|
||||
'current_run_id': int(item.current_run_id) if item.current_run_id else None,
|
||||
'current_run_no': item.current_run_no,
|
||||
'current_case_id': int(item.current_case_id) if item.current_case_id else None,
|
||||
'current_case_no': item.current_case_no,
|
||||
'current_version_no': int(item.current_version_no or 1),
|
||||
'lifecycle_status': item.lifecycle_status,
|
||||
'closed_reason': item.closed_reason,
|
||||
'closed_at': _iso(item.closed_at),
|
||||
'lock_version': int(item.lock_version or 1),
|
||||
'version_replaced': superseded,
|
||||
'available_actions': _available_actions(item, for_admin=for_admin),
|
||||
'created_at': _iso(item.created_at),
|
||||
'updated_at': _iso(item.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def list_session_work_item_versions(*, item: ShippingSessionPdfWorkItem) -> list[dict[str, Any]]:
|
||||
"""
|
||||
只读版本时间线:严格限定本会话 + 工作项重识别/替换谱系。
|
||||
|
||||
核心逻辑:纳入谱系全部 Document(含中间替换版本)的 Case;版本号按创建时间对齐
|
||||
current_version_no,禁止按结果下标倒推;禁止同属主其他会话的同 PDF Case 混入。
|
||||
"""
|
||||
lineage_run_ids = _collect_lineage_run_ids(item)
|
||||
if item.current_case_id is None and not lineage_run_ids:
|
||||
return []
|
||||
|
||||
lineage_docs = _collect_lineage_document_ids(item, lineage_run_ids)
|
||||
query = (
|
||||
ShippingOrderReviewCase.query
|
||||
.join(
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionRun.id == ShippingOrderReviewCase.run_id,
|
||||
)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.owner_user_id == int(item.owner_user_id),
|
||||
ShippingOrderExtractionRun.conversation_id == str(item.conversation_id),
|
||||
ShippingOrderReviewCase.document_id.in_(lineage_docs),
|
||||
)
|
||||
)
|
||||
if lineage_run_ids:
|
||||
query = query.filter(ShippingOrderReviewCase.run_id.in_(lineage_run_ids))
|
||||
elif item.current_case_id:
|
||||
query = query.filter(ShippingOrderReviewCase.id == int(item.current_case_id))
|
||||
else:
|
||||
return []
|
||||
|
||||
cases = query.order_by(
|
||||
ShippingOrderReviewCase.created_at.desc(),
|
||||
ShippingOrderReviewCase.id.desc(),
|
||||
).all()
|
||||
# 首轮多 PDF Run:无 review_reparse 时只保留根文档;后继 Run 只保留 marker 目标文档。
|
||||
if lineage_run_ids:
|
||||
run_marker_docs: dict[int, int] = {}
|
||||
for run in ShippingOrderExtractionRun.query.filter(
|
||||
ShippingOrderExtractionRun.id.in_(lineage_run_ids),
|
||||
).all():
|
||||
marker = (run.input_snapshot_json or {}).get('review_reparse')
|
||||
if isinstance(marker, dict) and int(marker.get('document_id') or 0):
|
||||
run_marker_docs[int(run.id)] = int(marker['document_id'])
|
||||
root_doc = int(item.root_document_id)
|
||||
cases = [
|
||||
case for case in cases
|
||||
if (
|
||||
int(case.document_id) == run_marker_docs[int(case.run_id)]
|
||||
if int(case.run_id) in run_marker_docs
|
||||
else int(case.document_id) == root_doc
|
||||
)
|
||||
]
|
||||
|
||||
run_ids = {int(case.run_id) for case in cases if case.run_id}
|
||||
run_no_by_id: dict[int, str | None] = {}
|
||||
if run_ids:
|
||||
for run in ShippingOrderExtractionRun.query.filter(
|
||||
ShippingOrderExtractionRun.id.in_(run_ids),
|
||||
).all():
|
||||
run_no_by_id[int(run.id)] = run.run_no
|
||||
|
||||
version_by_case_id = _assign_version_numbers(cases, item=item)
|
||||
rows: list[dict[str, Any]] = []
|
||||
for case in cases:
|
||||
is_current = bool(item.current_case_id and int(case.id) == int(item.current_case_id))
|
||||
version_no = version_by_case_id.get(int(case.id), 1)
|
||||
rows.append({
|
||||
'case_no': case.case_no,
|
||||
'case_status': case.status,
|
||||
'run_id': int(case.run_id),
|
||||
'run_no': run_no_by_id.get(int(case.run_id)),
|
||||
'document_id': int(case.document_id),
|
||||
'document_filename': _document_filename(case.document_id),
|
||||
'is_current': is_current,
|
||||
'is_readonly': not is_current or item.lifecycle_status == 'closed',
|
||||
'version_label': f'V{version_no}',
|
||||
'created_at': _iso(case.created_at),
|
||||
'confirmed_at': _iso(case.confirmed_at),
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def project_session_workbench(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str,
|
||||
include_closed: bool = True,
|
||||
open_only: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
投影会话工作台:未关闭项、已关闭项与统计。
|
||||
|
||||
Args:
|
||||
user_id: 属主。
|
||||
conversation_id: 会话 ID。
|
||||
include_closed: 是否包含已关闭分组。
|
||||
open_only: True 时仅返回未关闭项(忽略 include_closed)。
|
||||
|
||||
Returns:
|
||||
ShippingSessionWorkItemSummary 形状的读模型。
|
||||
"""
|
||||
conversation = str(conversation_id or '').strip()
|
||||
query = ShippingSessionPdfWorkItem.query.filter_by(
|
||||
owner_user_id=int(user_id),
|
||||
conversation_id=conversation,
|
||||
).order_by(
|
||||
ShippingSessionPdfWorkItem.updated_at.desc(),
|
||||
ShippingSessionPdfWorkItem.id.desc(),
|
||||
)
|
||||
items = query.all()
|
||||
open_items = [item for item in items if item.lifecycle_status != 'closed']
|
||||
closed_items = [item for item in items if item.lifecycle_status == 'closed']
|
||||
truncated = False
|
||||
if len(open_items) > MAX_OPEN_SESSION_WORK_ITEMS:
|
||||
open_items = open_items[:MAX_OPEN_SESSION_WORK_ITEMS]
|
||||
truncated = True
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
'conversation_id': conversation,
|
||||
'open_count': len([item for item in items if item.lifecycle_status != 'closed']),
|
||||
'closed_count': len(closed_items),
|
||||
'pending_review_count': len([
|
||||
item for item in open_items
|
||||
if item.lifecycle_status in {'pending_review', 'reparse_failed'}
|
||||
]),
|
||||
'extracting_count': len([item for item in open_items if item.lifecycle_status == 'extracting']),
|
||||
'open_items': [serialize_session_work_item(item) for item in open_items],
|
||||
'max_open_items': MAX_OPEN_SESSION_WORK_ITEMS,
|
||||
'truncated': truncated,
|
||||
}
|
||||
if open_only:
|
||||
payload['closed_items'] = []
|
||||
payload['closed_collapsed'] = True
|
||||
return payload
|
||||
if include_closed:
|
||||
payload['closed_items'] = [serialize_session_work_item(item) for item in closed_items]
|
||||
payload['closed_collapsed'] = True
|
||||
else:
|
||||
payload['closed_items'] = []
|
||||
payload['closed_collapsed'] = True
|
||||
return payload
|
||||
|
||||
|
||||
def project_admin_supervision_page(
|
||||
*,
|
||||
lifecycle_status: str | None = None,
|
||||
owner_user_id: int | None = None,
|
||||
conversation_id: str | None = None,
|
||||
q: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
管理员监管台分页投影(含 admin_terminate / admin_revoke_confirmation 动作)。
|
||||
|
||||
Args:
|
||||
lifecycle_status: 可选生命周期过滤。
|
||||
owner_user_id: 可选属主。
|
||||
conversation_id: 可选会话。
|
||||
q: 可选 item_no / case_no / filename 模糊。
|
||||
page/page_size: 分页。
|
||||
|
||||
Returns:
|
||||
items + pagination。
|
||||
"""
|
||||
query = ShippingSessionPdfWorkItem.query
|
||||
if lifecycle_status:
|
||||
query = query.filter(
|
||||
ShippingSessionPdfWorkItem.lifecycle_status == str(lifecycle_status)[:32],
|
||||
)
|
||||
if owner_user_id is not None:
|
||||
query = query.filter(ShippingSessionPdfWorkItem.owner_user_id == int(owner_user_id))
|
||||
if conversation_id:
|
||||
query = query.filter(
|
||||
ShippingSessionPdfWorkItem.conversation_id == str(conversation_id)[:100],
|
||||
)
|
||||
text = str(q or '').strip()
|
||||
if text:
|
||||
like = f'%{text[:64]}%'
|
||||
query = query.filter(
|
||||
ShippingSessionPdfWorkItem.item_no.ilike(like)
|
||||
| ShippingSessionPdfWorkItem.current_case_no.ilike(like)
|
||||
| ShippingSessionPdfWorkItem.current_run_no.ilike(like)
|
||||
| ShippingSessionPdfWorkItem.conversation_id.ilike(like)
|
||||
)
|
||||
total = query.count()
|
||||
page = max(1, int(page or 1))
|
||||
page_size = min(100, max(1, int(page_size or 20)))
|
||||
rows = (
|
||||
query.order_by(
|
||||
ShippingSessionPdfWorkItem.updated_at.desc(),
|
||||
ShippingSessionPdfWorkItem.id.desc(),
|
||||
)
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
'items': [serialize_session_work_item(item, for_admin=True) for item in rows],
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'total': int(total),
|
||||
}
|
||||
@@ -1,949 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/session_pdf_work_item_service.py
|
||||
|
||||
用途:会话 PDF 工作项领域写服务(创建、版本切换、失败回退、关闭、撤销确认)。
|
||||
依赖:ShippingSessionPdfWorkItem、ShippingOrderReviewCase、ShippingTask、audit_service、契约词典。
|
||||
逻辑:由抽取 Run/复核处置/确认服务与 workspace/admin API 调用;所有写操作在同一事务内
|
||||
使用 FOR UPDATE + lock_version,并与审计同事务追加。禁止前端自行推导当前版本指针。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingSessionPdfWorkItem,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
MAX_OPEN_SESSION_WORK_ITEMS,
|
||||
SESSION_WORK_ITEM_CLOSED_REASONS,
|
||||
SESSION_WORK_ITEM_LIFECYCLE_STATUSES,
|
||||
)
|
||||
from app.services.shipping_notice.task_disposition_service import void_task
|
||||
|
||||
# 确认后可撤销窗口(小时)。
|
||||
CONFIRM_REVOKE_WINDOW_HOURS = 24
|
||||
|
||||
# 已进入库存匹配或更后履约阶段的 process_status;禁止直接撤销确认。
|
||||
_INVENTORY_MATCHED_OR_LATER = frozenset({
|
||||
'matched',
|
||||
'waiting_upload',
|
||||
'upload_failed',
|
||||
'uploaded',
|
||||
'closed',
|
||||
'completed',
|
||||
})
|
||||
|
||||
|
||||
def generate_session_work_item_no() -> str:
|
||||
"""生成会话 PDF 工作项稳定业务编号。"""
|
||||
return f"SPWI-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:10].upper()}"
|
||||
|
||||
|
||||
def _snapshot(item: ShippingSessionPdfWorkItem) -> dict[str, Any]:
|
||||
"""投影工作项审计白名单快照。"""
|
||||
return {
|
||||
'item_no': item.item_no,
|
||||
'session_item_no': item.item_no,
|
||||
'conversation_id': item.conversation_id,
|
||||
'owner_user_id': item.owner_user_id,
|
||||
'root_document_id': item.root_document_id,
|
||||
'current_document_id': item.current_document_id,
|
||||
'current_run_no': item.current_run_no,
|
||||
'current_case_no': item.current_case_no,
|
||||
'current_version_no': int(item.current_version_no or 1),
|
||||
'lifecycle_status': item.lifecycle_status,
|
||||
'closed_reason': item.closed_reason,
|
||||
'lock_version': int(item.lock_version or 1),
|
||||
}
|
||||
|
||||
|
||||
def _audit(
|
||||
*,
|
||||
event_type: str,
|
||||
item: ShippingSessionPdfWorkItem,
|
||||
actor_type: str,
|
||||
actor_id: str | int | None,
|
||||
before: dict[str, Any] | None,
|
||||
after: dict[str, Any] | None,
|
||||
action: str | None = None,
|
||||
reason: str | None = None,
|
||||
reason_code: str | None = None,
|
||||
result: str = 'success',
|
||||
error_code: str | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
source: str | None = None,
|
||||
actor_role: str | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
task_no: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
在当前事务追加会话工作项审计事件。
|
||||
|
||||
核心逻辑:缺省时从 Flask 请求补齐 request_id / operation_id 与客户端 IP/UA(哈希入库)。
|
||||
"""
|
||||
from app.services.shipping_notice.fulfillment_audit import resolve_request_audit_context
|
||||
|
||||
ctx = resolve_request_audit_context()
|
||||
resolved_request_id = request_id or ctx.get('request_id')
|
||||
append_shipping_audit_event(
|
||||
event_type=event_type,
|
||||
aggregate_type='session_pdf_work_item',
|
||||
aggregate_id=item.item_no,
|
||||
session_item_id=item.item_no,
|
||||
owner_user_id=item.owner_user_id,
|
||||
conversation_id=item.conversation_id,
|
||||
document_id=item.current_document_id,
|
||||
run_no=item.current_run_no,
|
||||
review_case_no=item.current_case_no,
|
||||
task_no=task_no,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
actor_role=actor_role,
|
||||
request_id=resolved_request_id,
|
||||
operation_id=operation_id or resolved_request_id,
|
||||
client_ip=ctx.get('client_ip'),
|
||||
user_agent=ctx.get('user_agent'),
|
||||
source=source or 'shipping_notice',
|
||||
result=result,
|
||||
error_code=error_code,
|
||||
action=action,
|
||||
reason=reason,
|
||||
reason_code=reason_code,
|
||||
before=before,
|
||||
after=after,
|
||||
metadata=metadata or {},
|
||||
)
|
||||
|
||||
|
||||
def _bump_lock(item: ShippingSessionPdfWorkItem, *, expected_lock_version: int | None = None) -> None:
|
||||
"""乐观锁递增;版本不匹配时拒绝写。"""
|
||||
if expected_lock_version is not None and int(item.lock_version or 0) != int(expected_lock_version):
|
||||
raise ConflictError(
|
||||
'Session PDF work item was updated concurrently',
|
||||
code='SHIPPING_NOTICE.SESSION_WORK_ITEM_VERSION_CONFLICT',
|
||||
)
|
||||
item.lock_version = int(item.lock_version or 1) + 1
|
||||
item.updated_at = datetime.utcnow()
|
||||
|
||||
|
||||
def _count_open_items(*, conversation_id: str) -> int:
|
||||
"""统计会话未关闭工作项数量。"""
|
||||
return (
|
||||
ShippingSessionPdfWorkItem.query
|
||||
.filter(
|
||||
ShippingSessionPdfWorkItem.conversation_id == str(conversation_id),
|
||||
ShippingSessionPdfWorkItem.lifecycle_status != 'closed',
|
||||
)
|
||||
.count()
|
||||
)
|
||||
|
||||
|
||||
def get_work_item_for_user(*, user_id: int, item_no: str, for_update: bool = False) -> ShippingSessionPdfWorkItem:
|
||||
"""
|
||||
按属主加载工作项。
|
||||
|
||||
Args:
|
||||
user_id: 属主用户 ID。
|
||||
item_no: 工作项业务编号。
|
||||
for_update: True 时行锁。
|
||||
|
||||
Returns:
|
||||
ShippingSessionPdfWorkItem。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 不存在或不属于该用户。
|
||||
"""
|
||||
query = ShippingSessionPdfWorkItem.query.filter_by(
|
||||
item_no=str(item_no or '').strip().upper(),
|
||||
owner_user_id=int(user_id),
|
||||
)
|
||||
if for_update:
|
||||
query = query.with_for_update()
|
||||
item = query.first()
|
||||
if item is None:
|
||||
raise NotFoundError('Session PDF work item not found', code='SHIPPING_NOTICE.SESSION_WORK_ITEM_NOT_FOUND')
|
||||
return item
|
||||
|
||||
|
||||
def get_work_item_by_no(*, item_no: str, for_update: bool = False) -> ShippingSessionPdfWorkItem:
|
||||
"""管理员按编号加载工作项(跨用户)。"""
|
||||
query = ShippingSessionPdfWorkItem.query.filter_by(item_no=str(item_no or '').strip().upper())
|
||||
if for_update:
|
||||
query = query.with_for_update()
|
||||
item = query.first()
|
||||
if item is None:
|
||||
raise NotFoundError('Session PDF work item not found', code='SHIPPING_NOTICE.SESSION_WORK_ITEM_NOT_FOUND')
|
||||
return item
|
||||
|
||||
|
||||
def find_open_work_item_by_root(
|
||||
*,
|
||||
conversation_id: str,
|
||||
root_document_id: int,
|
||||
for_update: bool = False,
|
||||
) -> ShippingSessionPdfWorkItem | None:
|
||||
"""按会话 + 同源 Document 查找工作项(含已关闭,供幂等复用)。"""
|
||||
query = ShippingSessionPdfWorkItem.query.filter_by(
|
||||
conversation_id=str(conversation_id),
|
||||
root_document_id=int(root_document_id),
|
||||
)
|
||||
if for_update:
|
||||
query = query.with_for_update()
|
||||
return query.first()
|
||||
|
||||
|
||||
def ensure_work_item_for_document(
|
||||
*,
|
||||
conversation_id: str,
|
||||
owner_user_id: int,
|
||||
document_id: int,
|
||||
root_document_id: int | None = None,
|
||||
run: ShippingOrderExtractionRun | None = None,
|
||||
case: ShippingOrderReviewCase | None = None,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> ShippingSessionPdfWorkItem:
|
||||
"""
|
||||
为会话内 PDF 幂等绑定/创建工作项。
|
||||
|
||||
核心逻辑:同源 root_document_id 复用;新建时检查未关闭上限 50;绑定当前 Run/Case 指针。
|
||||
|
||||
Args:
|
||||
conversation_id: 聊天会话 ID。
|
||||
owner_user_id: 属主。
|
||||
document_id: 当前 Document。
|
||||
root_document_id: 同源根 Document;默认等于 document_id。
|
||||
run/case: 可选当前版本指针。
|
||||
actor_*: 审计操作者。
|
||||
|
||||
Returns:
|
||||
已存在或新建的工作项。
|
||||
"""
|
||||
root_id = int(root_document_id or document_id)
|
||||
existing = find_open_work_item_by_root(
|
||||
conversation_id=conversation_id,
|
||||
root_document_id=root_id,
|
||||
for_update=True,
|
||||
)
|
||||
if existing is not None:
|
||||
before = _snapshot(existing)
|
||||
changed = False
|
||||
if run is not None and (
|
||||
existing.current_run_id != int(run.id)
|
||||
or existing.current_run_no != str(run.run_no)
|
||||
):
|
||||
existing.current_run_id = int(run.id)
|
||||
existing.current_run_no = str(run.run_no)
|
||||
changed = True
|
||||
if case is not None and (
|
||||
existing.current_case_id != int(case.id)
|
||||
or existing.current_case_no != str(case.case_no)
|
||||
):
|
||||
existing.current_case_id = int(case.id)
|
||||
existing.current_case_no = str(case.case_no)
|
||||
if existing.lifecycle_status in {'extracting', 'reparse_failed'}:
|
||||
existing.lifecycle_status = 'pending_review'
|
||||
changed = True
|
||||
if int(existing.current_document_id) != int(document_id):
|
||||
existing.current_document_id = int(document_id)
|
||||
changed = True
|
||||
if existing.lifecycle_status == 'closed':
|
||||
# 已关闭项不因旁路绑定自动重开;由显式恢复/撤销路径处理。
|
||||
return existing
|
||||
if changed:
|
||||
_bump_lock(existing)
|
||||
db.session.flush()
|
||||
_audit(
|
||||
event_type='document_extraction_started',
|
||||
item=existing,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id or owner_user_id,
|
||||
before=before,
|
||||
after=_snapshot(existing),
|
||||
action='bind_current_version',
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
source='order_extraction',
|
||||
)
|
||||
return existing
|
||||
|
||||
if _count_open_items(conversation_id=conversation_id) >= MAX_OPEN_SESSION_WORK_ITEMS:
|
||||
raise ConflictError(
|
||||
'Session open PDF work item limit exceeded',
|
||||
code='SHIPPING_NOTICE.SESSION_WORK_ITEM_LIMIT_EXCEEDED',
|
||||
details={'limit': MAX_OPEN_SESSION_WORK_ITEMS},
|
||||
)
|
||||
|
||||
item = ShippingSessionPdfWorkItem(
|
||||
item_no=generate_session_work_item_no(),
|
||||
conversation_id=str(conversation_id),
|
||||
owner_user_id=int(owner_user_id),
|
||||
root_document_id=root_id,
|
||||
current_document_id=int(document_id),
|
||||
current_run_id=int(run.id) if run is not None else None,
|
||||
current_run_no=str(run.run_no) if run is not None else None,
|
||||
current_case_id=int(case.id) if case is not None else None,
|
||||
current_case_no=str(case.case_no) if case is not None else None,
|
||||
current_version_no=1,
|
||||
lifecycle_status='pending_review' if case is not None else 'extracting',
|
||||
lock_version=1,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(item)
|
||||
db.session.flush()
|
||||
_audit(
|
||||
event_type='session_work_item_created',
|
||||
item=item,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id or owner_user_id,
|
||||
before=None,
|
||||
after=_snapshot(item),
|
||||
action='create',
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
source='order_extraction',
|
||||
metadata={'root_document_id': root_id},
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
def bind_cases_for_run(*, run: ShippingOrderExtractionRun, cases: list[ShippingOrderReviewCase]) -> list[ShippingSessionPdfWorkItem]:
|
||||
"""
|
||||
Run 初始化 Case 后,为每个 PDF Case 绑定/创建会话工作项。
|
||||
|
||||
核心逻辑:重识别后继 Run 优先按 source_case 的 root 复用工作项并切换指针;
|
||||
普通创建按 document_id 作为 root。
|
||||
"""
|
||||
items: list[ShippingSessionPdfWorkItem] = []
|
||||
marker = (run.input_snapshot_json or {}).get('review_reparse') if isinstance(run.input_snapshot_json, dict) else None
|
||||
source_case_no = ''
|
||||
source_root_id: int | None = None
|
||||
if isinstance(marker, dict):
|
||||
source_case_no = str(marker.get('source_case_no') or '').strip().upper()
|
||||
if source_case_no:
|
||||
source_case = ShippingOrderReviewCase.query.filter_by(case_no=source_case_no).first()
|
||||
if source_case is not None:
|
||||
existing = ShippingSessionPdfWorkItem.query.filter_by(
|
||||
conversation_id=str(run.conversation_id),
|
||||
current_case_id=int(source_case.id),
|
||||
).first()
|
||||
if existing is None:
|
||||
existing = find_open_work_item_by_root(
|
||||
conversation_id=str(run.conversation_id),
|
||||
root_document_id=int(source_case.document_id),
|
||||
)
|
||||
if existing is not None:
|
||||
source_root_id = int(existing.root_document_id)
|
||||
|
||||
for case in cases:
|
||||
root_id = source_root_id if (
|
||||
source_root_id is not None
|
||||
and isinstance(marker, dict)
|
||||
and int(marker.get('document_id') or 0) == int(case.document_id)
|
||||
) else int(case.document_id)
|
||||
# 若能通过同源找到已有项,优先切换版本而非新建。
|
||||
existing = find_open_work_item_by_root(
|
||||
conversation_id=str(run.conversation_id),
|
||||
root_document_id=root_id,
|
||||
for_update=True,
|
||||
)
|
||||
if existing is not None and run.reparse_of_run_id:
|
||||
items.append(
|
||||
mark_reparse_succeeded(
|
||||
item=existing,
|
||||
run=run,
|
||||
case=case,
|
||||
actor_type='system',
|
||||
actor_id=run.user_id,
|
||||
)
|
||||
)
|
||||
continue
|
||||
items.append(
|
||||
ensure_work_item_for_document(
|
||||
conversation_id=str(run.conversation_id),
|
||||
owner_user_id=int(run.user_id),
|
||||
document_id=int(case.document_id),
|
||||
root_document_id=root_id,
|
||||
run=run,
|
||||
case=case,
|
||||
actor_type='system',
|
||||
actor_id=run.user_id,
|
||||
)
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def mark_reparse_started(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
successor_run: ShippingOrderExtractionRun,
|
||||
reason: str,
|
||||
comment: str | None = None,
|
||||
actor_id: int,
|
||||
replacement_document_id: int | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> ShippingSessionPdfWorkItem | None:
|
||||
"""
|
||||
单 PDF 重识别开始:锁定旧入口语义,工作项进入 extracting。
|
||||
|
||||
核心逻辑:按当前 Case 定位工作项;写入前后快照与 reparse 审计;不创建新工作项。
|
||||
"""
|
||||
item = (
|
||||
ShippingSessionPdfWorkItem.query
|
||||
.filter_by(current_case_id=int(case.id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if item is None:
|
||||
item = find_open_work_item_by_root(
|
||||
conversation_id=str(successor_run.conversation_id),
|
||||
root_document_id=int(case.document_id),
|
||||
for_update=True,
|
||||
)
|
||||
if item is None:
|
||||
return None
|
||||
if item.lifecycle_status == 'closed':
|
||||
raise ConflictError(
|
||||
'Closed session work item cannot be reparsed',
|
||||
code='SHIPPING_NOTICE.SESSION_WORK_ITEM_CLOSED',
|
||||
)
|
||||
before = _snapshot(item)
|
||||
item.lifecycle_status = 'extracting'
|
||||
if replacement_document_id is not None:
|
||||
item.current_document_id = int(replacement_document_id)
|
||||
# 重识别进行中仍保留旧 Case 指针,供失败回退;成功后再切换。
|
||||
_bump_lock(item)
|
||||
db.session.flush()
|
||||
_audit(
|
||||
event_type='document_reparse_requested',
|
||||
item=item,
|
||||
actor_type='user',
|
||||
actor_id=actor_id,
|
||||
before=before,
|
||||
after={
|
||||
**_snapshot(item),
|
||||
'previous_run_no': before.get('current_run_no'),
|
||||
'previous_case_no': before.get('current_case_no'),
|
||||
},
|
||||
action='reparse_started',
|
||||
reason=comment,
|
||||
reason_code=reason,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
metadata={'successor_run_no': successor_run.run_no},
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
def mark_reparse_succeeded(
|
||||
*,
|
||||
item: ShippingSessionPdfWorkItem,
|
||||
run: ShippingOrderExtractionRun,
|
||||
case: ShippingOrderReviewCase,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
) -> ShippingSessionPdfWorkItem:
|
||||
"""重识别成功:切换当前版本指针,旧 Case 由处置服务标记 superseded。"""
|
||||
before = _snapshot(item)
|
||||
item.current_run_id = int(run.id)
|
||||
item.current_run_no = str(run.run_no)
|
||||
item.current_case_id = int(case.id)
|
||||
item.current_case_no = str(case.case_no)
|
||||
item.current_document_id = int(case.document_id)
|
||||
item.current_version_no = int(item.current_version_no or 1) + 1
|
||||
item.lifecycle_status = 'pending_review'
|
||||
item.closed_reason = None
|
||||
item.closed_at = None
|
||||
_bump_lock(item)
|
||||
db.session.flush()
|
||||
_audit(
|
||||
event_type='document_version_replaced',
|
||||
item=item,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id or item.owner_user_id,
|
||||
before=before,
|
||||
after={
|
||||
**_snapshot(item),
|
||||
'previous_run_no': before.get('current_run_no'),
|
||||
'previous_case_no': before.get('current_case_no'),
|
||||
},
|
||||
action='version_replaced',
|
||||
source='order_extraction_worker',
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
def mark_reparse_failed_and_restore(
|
||||
*,
|
||||
source_case: ShippingOrderReviewCase,
|
||||
failed_run: ShippingOrderExtractionRun,
|
||||
failure_stage: str | None = None,
|
||||
) -> ShippingSessionPdfWorkItem | None:
|
||||
"""
|
||||
重识别失败:恢复旧 Case 为当前可操作入口,并写恢复审计。
|
||||
|
||||
核心逻辑:工作项 current_* 仍指向旧 Case(开始时未切换);仅把生命周期改为 reparse_failed。
|
||||
"""
|
||||
item = (
|
||||
ShippingSessionPdfWorkItem.query
|
||||
.filter_by(current_case_id=int(source_case.id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if item is None:
|
||||
item = find_open_work_item_by_root(
|
||||
conversation_id=str(failed_run.conversation_id),
|
||||
root_document_id=int(source_case.document_id),
|
||||
for_update=True,
|
||||
)
|
||||
if item is None:
|
||||
return None
|
||||
before = _snapshot(item)
|
||||
item.lifecycle_status = 'reparse_failed'
|
||||
# 确保指针仍指向可恢复的旧 Case。
|
||||
item.current_case_id = int(source_case.id)
|
||||
item.current_case_no = str(source_case.case_no)
|
||||
item.current_run_id = int(source_case.run_id)
|
||||
source_run = db.session.get(ShippingOrderExtractionRun, int(source_case.run_id))
|
||||
if source_run is not None:
|
||||
item.current_run_no = str(source_run.run_no)
|
||||
item.current_document_id = int(source_case.document_id)
|
||||
_bump_lock(item)
|
||||
db.session.flush()
|
||||
after = {
|
||||
**_snapshot(item),
|
||||
'reparse_failure_stage': failure_stage or failed_run.status,
|
||||
'restore_target_case_no': source_case.case_no,
|
||||
'previous_run_no': failed_run.run_no,
|
||||
}
|
||||
_audit(
|
||||
event_type='document_reparse_failed',
|
||||
item=item,
|
||||
actor_type='system',
|
||||
actor_id=failed_run.user_id,
|
||||
before=before,
|
||||
after=after,
|
||||
action='reparse_failed',
|
||||
result='failure',
|
||||
error_code=str(getattr(failed_run, 'error_code', None) or 'reparse_failed'),
|
||||
source='order_extraction_worker',
|
||||
metadata={'failed_run_no': failed_run.run_no},
|
||||
)
|
||||
_audit(
|
||||
event_type='document_previous_version_restored',
|
||||
item=item,
|
||||
actor_type='system',
|
||||
actor_id=failed_run.user_id,
|
||||
before=before,
|
||||
after=after,
|
||||
action='restore_previous_version',
|
||||
source='order_extraction_worker',
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
def close_work_item(
|
||||
*,
|
||||
item: ShippingSessionPdfWorkItem,
|
||||
closed_reason: str,
|
||||
actor_type: str,
|
||||
actor_id: str | int | None,
|
||||
reason: str | None = None,
|
||||
expected_lock_version: int | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
actor_role: str | None = None,
|
||||
task_no: str | None = None,
|
||||
event_type: str | None = None,
|
||||
) -> ShippingSessionPdfWorkItem:
|
||||
"""关闭工作项(确认建单 / 非订单 / 用户取消 / 管理员终止)。"""
|
||||
normalized = str(closed_reason or '').strip().lower()
|
||||
if normalized not in SESSION_WORK_ITEM_CLOSED_REASONS:
|
||||
raise ValidationError(
|
||||
'Invalid session work item closed reason',
|
||||
code='SHIPPING_NOTICE.SESSION_WORK_ITEM_CLOSE_REASON_INVALID',
|
||||
)
|
||||
if item.lifecycle_status == 'closed':
|
||||
return item
|
||||
before = _snapshot(item)
|
||||
item.lifecycle_status = 'closed'
|
||||
item.closed_reason = normalized
|
||||
item.closed_at = datetime.utcnow()
|
||||
_bump_lock(item, expected_lock_version=expected_lock_version)
|
||||
db.session.flush()
|
||||
resolved_event = event_type or {
|
||||
'confirmed': 'review_confirmed',
|
||||
'non_order': 'review_marked_non_order',
|
||||
'user_cancelled': 'session_work_item_cancelled',
|
||||
'admin_terminated': 'session_work_item_cancelled',
|
||||
}.get(normalized, 'session_work_item_cancelled')
|
||||
_audit(
|
||||
event_type=resolved_event,
|
||||
item=item,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
actor_role=actor_role,
|
||||
before=before,
|
||||
after=_snapshot(item),
|
||||
action='close',
|
||||
reason=reason,
|
||||
reason_code=normalized,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
task_no=task_no,
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
def close_work_item_for_case(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
closed_reason: str,
|
||||
actor_type: str,
|
||||
actor_id: str | int | None,
|
||||
reason: str | None = None,
|
||||
task_no: str | None = None,
|
||||
event_type: str | None = None,
|
||||
) -> ShippingSessionPdfWorkItem | None:
|
||||
"""按 Case 定位并关闭工作项;找不到时静默跳过(兼容尚未绑定的历史数据)。"""
|
||||
item = (
|
||||
ShippingSessionPdfWorkItem.query
|
||||
.filter_by(current_case_id=int(case.id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if item is None:
|
||||
return None
|
||||
return close_work_item(
|
||||
item=item,
|
||||
closed_reason=closed_reason,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
reason=reason,
|
||||
task_no=task_no,
|
||||
event_type=event_type,
|
||||
)
|
||||
|
||||
|
||||
def reopen_work_item_pending_review(
|
||||
*,
|
||||
item: ShippingSessionPdfWorkItem,
|
||||
case: ShippingOrderReviewCase,
|
||||
actor_type: str,
|
||||
actor_id: str | int | None,
|
||||
reason: str | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> ShippingSessionPdfWorkItem:
|
||||
"""撤销确认后恢复工作项为待确认。"""
|
||||
before = _snapshot(item)
|
||||
item.lifecycle_status = 'pending_review'
|
||||
item.closed_reason = None
|
||||
item.closed_at = None
|
||||
item.current_case_id = int(case.id)
|
||||
item.current_case_no = str(case.case_no)
|
||||
item.current_document_id = int(case.document_id)
|
||||
_bump_lock(item)
|
||||
db.session.flush()
|
||||
_audit(
|
||||
event_type='review_confirmation_revoked',
|
||||
item=item,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
before=before,
|
||||
after=_snapshot(item),
|
||||
action='revoke_confirmation',
|
||||
reason=reason,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
source='admin_api',
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
def task_has_entered_inventory_match(task: ShippingTask) -> bool:
|
||||
"""判断任务是否已进入库存匹配或更后履约阶段。"""
|
||||
return str(task.process_status or '').strip().lower() in _INVENTORY_MATCHED_OR_LATER
|
||||
|
||||
|
||||
def revoke_review_confirmation(
|
||||
*,
|
||||
admin_user_id: int,
|
||||
item_no: str,
|
||||
reason: str,
|
||||
confirm_token: str | None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
管理员在 24 小时内撤销确认:未库存匹配则作废任务并恢复工作项;已匹配则拒绝并记受控异常。
|
||||
|
||||
Args:
|
||||
admin_user_id: 实际操作管理员。
|
||||
item_no: 工作项编号。
|
||||
reason: 必填撤销理由。
|
||||
confirm_token: 二次确认令牌;必须为 ``CONFIRM_REVOKE``。
|
||||
request_id/operation_id: 请求关联。
|
||||
|
||||
Returns:
|
||||
含 status / item_no / task_no / blocked 等摘要。
|
||||
|
||||
Raises:
|
||||
ValidationError/ConflictError/ForbiddenError: 理由、窗口、状态或库存匹配阻断。
|
||||
"""
|
||||
reason_text = str(reason or '').strip()
|
||||
if not reason_text:
|
||||
raise ValidationError(
|
||||
'Admin revoke reason is required',
|
||||
code='SHIPPING_NOTICE.ADMIN_REASON_REQUIRED',
|
||||
)
|
||||
if str(confirm_token or '').strip() != 'CONFIRM_REVOKE':
|
||||
raise ValidationError(
|
||||
'Admin revoke requires secondary confirmation',
|
||||
code='SHIPPING_NOTICE.ADMIN_CONFIRM_REQUIRED',
|
||||
)
|
||||
|
||||
item = get_work_item_by_no(item_no=item_no, for_update=True)
|
||||
if item.lifecycle_status != 'closed' or item.closed_reason != 'confirmed':
|
||||
raise ConflictError(
|
||||
'Only confirmed work items can be revoked',
|
||||
code='SHIPPING_NOTICE.REVOKE_NOT_CONFIRMED',
|
||||
)
|
||||
if item.current_case_id is None:
|
||||
raise ConflictError('Confirmed case pointer missing', code='SHIPPING_NOTICE.REVOKE_CASE_MISSING')
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(id=int(item.current_case_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if case is None or case.status != 'confirmed' or not case.confirmed_task_id:
|
||||
raise ConflictError('Confirmed case is unavailable', code='SHIPPING_NOTICE.REVOKE_CASE_INVALID')
|
||||
if case.confirmed_at is None or (
|
||||
datetime.utcnow() - case.confirmed_at > timedelta(hours=CONFIRM_REVOKE_WINDOW_HOURS)
|
||||
):
|
||||
raise ConflictError(
|
||||
'Confirmation revoke window exceeded',
|
||||
code='SHIPPING_NOTICE.REVOKE_WINDOW_EXPIRED',
|
||||
details={'window_hours': CONFIRM_REVOKE_WINDOW_HOURS},
|
||||
)
|
||||
task = (
|
||||
ShippingTask.query
|
||||
.filter_by(id=int(case.confirmed_task_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if task is None:
|
||||
raise ConflictError('Confirmed task missing', code='SHIPPING_NOTICE.REVOKE_TASK_MISSING')
|
||||
|
||||
before = _snapshot(item)
|
||||
if task_has_entered_inventory_match(task):
|
||||
_audit(
|
||||
event_type='review_confirmation_revoked',
|
||||
item=item,
|
||||
actor_type='admin',
|
||||
actor_id=admin_user_id,
|
||||
actor_role='admin',
|
||||
before=before,
|
||||
after={
|
||||
**before,
|
||||
'revocation_blocked': True,
|
||||
'inventory_matched': True,
|
||||
},
|
||||
action='revoke_blocked_inventory_matched',
|
||||
reason=reason_text,
|
||||
result='rejected',
|
||||
error_code='SHIPPING_NOTICE.REVOKE_INVENTORY_MATCHED',
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
task_no=task.task_no,
|
||||
metadata={'controlled_exception': True},
|
||||
)
|
||||
raise ConflictError(
|
||||
'Cannot revoke confirmation after inventory match; controlled exception recorded',
|
||||
code='SHIPPING_NOTICE.REVOKE_INVENTORY_MATCHED',
|
||||
details={'task_no': task.task_no, 'process_status': task.process_status},
|
||||
)
|
||||
|
||||
# 作废下游任务并恢复 Case/工作项。
|
||||
void_task(
|
||||
task,
|
||||
actor_id=int(admin_user_id),
|
||||
reason=reason_text,
|
||||
request_id=request_id,
|
||||
)
|
||||
case.status = 'ready'
|
||||
case.confirmed_task_id = None
|
||||
case.confirmed_at = None
|
||||
case.disposition = None
|
||||
reopen_work_item_pending_review(
|
||||
item=item,
|
||||
case=case,
|
||||
actor_type='admin',
|
||||
actor_id=admin_user_id,
|
||||
reason=reason_text,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
)
|
||||
_audit(
|
||||
event_type='admin_impersonated_review_action',
|
||||
item=item,
|
||||
actor_type='admin',
|
||||
actor_id=admin_user_id,
|
||||
actor_role='admin',
|
||||
before=before,
|
||||
after=_snapshot(item),
|
||||
action='revoke_confirmation',
|
||||
reason=reason_text,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
task_no=task.task_no,
|
||||
metadata={'admin_action': 'revoke_confirmation', 'owner_user_id': item.owner_user_id},
|
||||
)
|
||||
db.session.flush()
|
||||
return {
|
||||
'item_no': item.item_no,
|
||||
'case_no': case.case_no,
|
||||
'task_no': task.task_no,
|
||||
'lifecycle_status': item.lifecycle_status,
|
||||
'revoked': True,
|
||||
}
|
||||
|
||||
|
||||
def terminate_work_item_as_admin(
|
||||
*,
|
||||
admin_user_id: int,
|
||||
item_no: str,
|
||||
reason: str,
|
||||
confirm_token: str | None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> ShippingSessionPdfWorkItem:
|
||||
"""
|
||||
管理员终止未关闭工作项;必须理由 + 二次确认。
|
||||
|
||||
核心逻辑:已关闭时不改状态,但仍记录本次终止请求的审计(result=ignored,metadata 标记幂等),
|
||||
覆盖重复管理操作尝试,避免仅有首次状态变化可追溯。
|
||||
|
||||
Args:
|
||||
admin_user_id: 管理员用户 ID。
|
||||
item_no: 工作项编号。
|
||||
reason: 终止理由(必填)。
|
||||
confirm_token: 须为 `CONFIRM_TERMINATE`。
|
||||
request_id / operation_id: 可选请求关联;缺省由请求上下文补齐。
|
||||
|
||||
Returns:
|
||||
终止后或已关闭的工作项。
|
||||
"""
|
||||
reason_text = str(reason or '').strip()
|
||||
if not reason_text:
|
||||
raise ValidationError('Admin terminate reason is required', code='SHIPPING_NOTICE.ADMIN_REASON_REQUIRED')
|
||||
if str(confirm_token or '').strip() != 'CONFIRM_TERMINATE':
|
||||
raise ValidationError('Admin terminate requires secondary confirmation', code='SHIPPING_NOTICE.ADMIN_CONFIRM_REQUIRED')
|
||||
item = get_work_item_by_no(item_no=item_no, for_update=True)
|
||||
if item.lifecycle_status == 'closed':
|
||||
snap = _snapshot(item)
|
||||
_audit(
|
||||
event_type='admin_impersonated_review_action',
|
||||
item=item,
|
||||
actor_type='admin',
|
||||
actor_id=admin_user_id,
|
||||
actor_role='admin',
|
||||
before=snap,
|
||||
after=snap,
|
||||
action='terminate',
|
||||
reason=reason_text,
|
||||
result='ignored',
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
metadata={
|
||||
'admin_action': 'terminate',
|
||||
'owner_user_id': item.owner_user_id,
|
||||
'idempotent': True,
|
||||
'already_closed': True,
|
||||
'closed_reason': item.closed_reason,
|
||||
},
|
||||
)
|
||||
return item
|
||||
before = _snapshot(item)
|
||||
close_work_item(
|
||||
item=item,
|
||||
closed_reason='admin_terminated',
|
||||
actor_type='admin',
|
||||
actor_id=admin_user_id,
|
||||
actor_role='admin',
|
||||
reason=reason_text,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
event_type='session_work_item_cancelled',
|
||||
)
|
||||
_audit(
|
||||
event_type='admin_impersonated_review_action',
|
||||
item=item,
|
||||
actor_type='admin',
|
||||
actor_id=admin_user_id,
|
||||
actor_role='admin',
|
||||
before=before,
|
||||
after=_snapshot(item),
|
||||
action='terminate',
|
||||
reason=reason_text,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
metadata={'admin_action': 'terminate', 'owner_user_id': item.owner_user_id},
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
def assert_case_is_current_work_item_version(*, case: ShippingOrderReviewCase) -> None:
|
||||
"""
|
||||
确认写路径仅允许当前有效 Case。
|
||||
|
||||
核心逻辑:若工作项存在且 current_case_id 不是本 Case,拒绝确认/编辑。
|
||||
"""
|
||||
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=int(case.id)).first()
|
||||
if item is not None:
|
||||
if item.lifecycle_status == 'closed':
|
||||
raise ConflictError('Session work item is closed', code='SHIPPING_NOTICE.SESSION_WORK_ITEM_CLOSED')
|
||||
if item.lifecycle_status == 'extracting':
|
||||
raise ConflictError('Document reparse is in progress', code='SHIPPING_NOTICE.SESSION_WORK_ITEM_EXTRACTING')
|
||||
return
|
||||
|
||||
conversation_id = ''
|
||||
if case.run is not None:
|
||||
conversation_id = str(case.run.conversation_id or '')
|
||||
if not conversation_id:
|
||||
run = db.session.get(ShippingOrderExtractionRun, int(case.run_id))
|
||||
conversation_id = str(run.conversation_id or '') if run is not None else ''
|
||||
if not conversation_id:
|
||||
return
|
||||
sibling = find_open_work_item_by_root(
|
||||
conversation_id=conversation_id,
|
||||
root_document_id=int(case.document_id),
|
||||
)
|
||||
if sibling is not None and sibling.current_case_id and int(sibling.current_case_id) != int(case.id):
|
||||
raise ConflictError(
|
||||
'Review case has been superseded by a newer version',
|
||||
code='SHIPPING_NOTICE.SESSION_WORK_ITEM_SUPERSEDED',
|
||||
details={
|
||||
'current_case_no': sibling.current_case_no,
|
||||
'item_no': sibling.item_no,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# 供测试引用的冻结集合。
|
||||
SESSION_WORK_ITEM_LIFECYCLES = SESSION_WORK_ITEM_LIFECYCLE_STATUSES
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/standard_field_registry.py
|
||||
|
||||
用途:注册货代订单系统标准字段目录(锁定 57 项)及 Snapshot 核心投影元数据。
|
||||
用途:注册货代订单系统标准字段目录(锁定 58 项)及 Snapshot 核心投影元数据。
|
||||
依赖:shipping_order_snapshot ORM 列、order_freeze_service 投影表。
|
||||
逻辑:字段资产种子与治理校验只读本注册表;扩展字段不得占用标准 field_code;
|
||||
typed 项必须能投影到 Snapshot 物理列。启动/测试可调用 assert_registry_consistent。
|
||||
@@ -34,7 +34,6 @@ DEFAULT_V1_ADOPTION_CODES: tuple[str, ...] = (
|
||||
'ship_to_customer',
|
||||
'ship_to_address',
|
||||
'currency',
|
||||
'line_no',
|
||||
'part_number',
|
||||
'customer_part_number',
|
||||
'required_date',
|
||||
@@ -95,7 +94,8 @@ def _spec(
|
||||
)
|
||||
|
||||
|
||||
# [STEP 1] 锁定的 57 项标准目录(与历史 STANDARD_ORDER_FIELD_SPECS 编码/范围/类型一致)。
|
||||
# [STEP 1] 锁定的 58 项标准目录。Reservation 可同时位于订单头和订单行,
|
||||
# 由行级值覆盖订单头值;所有标准字段均可按 Schema 配置抽取规则。
|
||||
_STANDARD_FIELD_SPECS: tuple[StandardFieldSpec, ...] = (
|
||||
_spec('customer_po_number', 'header', 'string', '客户 PO 号', '客户下达的采购订单标识;不得填写内部 ERP 单号'),
|
||||
_spec('order_date', 'header', 'date', '订单日期', '客户订单或发货通知上的订单日期'),
|
||||
@@ -120,12 +120,20 @@ _STANDARD_FIELD_SPECS: tuple[StandardFieldSpec, ...] = (
|
||||
_spec('direct_ship_required', 'header', 'boolean', '是否直发', '是否要求直发'),
|
||||
_spec('urgent_order', 'header', 'boolean', '是否紧急', '是否紧急订单'),
|
||||
_spec('order_remark', 'header', 'string', '订单备注', '订单头备注'),
|
||||
_spec('line_no', 'line', 'string', '项次', '订单明细行号'),
|
||||
_spec('reservation_id', 'line', 'string', '预约单号', '库存占用/预约单标识', fulfillment_role='reservation_identity'),
|
||||
_spec('reservation_id', 'header', 'string', '预约单号', '可选的订单级库存占用/预约单标识;明细可覆盖'),
|
||||
_spec(
|
||||
'line_no', 'line', 'string', '内部项次',
|
||||
'内部业务项次;可识别、可由 Schema 派生规则补齐、冻结前可人工覆盖;'
|
||||
'仅接受 1–6 位数字并保留前导零;与 Excel 导出行序号 export_sequence 无关',
|
||||
),
|
||||
_spec('reservation_id', 'line', 'string', '预约单号', '可选的行级库存占用/预约单标识;优先于订单头', fulfillment_role='reservation_identity'),
|
||||
_spec('part_number', 'line', 'string', '内部料号', '公司内部主料号,用于库存匹配', fulfillment_role='part_number'),
|
||||
_spec('product_revision', 'line', 'string', '产品版本', '产品料号版本/revision'),
|
||||
_spec('customer_part_number', 'line', 'string', '客户料号', '客户侧物料编码'),
|
||||
_spec('customer_po_line_no', 'line', 'string', '客户 PO 行号', '客户采购订单行号'),
|
||||
_spec(
|
||||
'customer_po_line_no', 'line', 'string', '客户 PO 行号',
|
||||
'客户采购订单原始 Item No./LN/Line#;必须按字符串保留前导零;识别/复核后永久保留原始事实',
|
||||
),
|
||||
_spec('product_feature', 'line', 'string', '产品特征', '产品特征或规格摘要'),
|
||||
_spec('qty', 'line', 'decimal', '数量', '本行需求数量,须大于 0', fulfillment_role='quantity'),
|
||||
_spec('uom', 'line', 'string', '单位', '数量计量单位'),
|
||||
@@ -156,29 +164,34 @@ _STANDARD_FIELD_SPECS: tuple[StandardFieldSpec, ...] = (
|
||||
_spec('line_remark', 'line', 'string', '行备注', '明细备注'),
|
||||
)
|
||||
|
||||
STANDARD_FIELD_SPECS: dict[str, StandardFieldSpec] = {
|
||||
item.field_code: item for item in _STANDARD_FIELD_SPECS
|
||||
STANDARD_FIELD_SPECS: dict[tuple[str, str], StandardFieldSpec] = {
|
||||
(item.scope, item.field_code): item for item in _STANDARD_FIELD_SPECS
|
||||
}
|
||||
|
||||
# 兼容旧服务中 (scope, value_type) 二元组查询。
|
||||
STANDARD_ORDER_FIELD_SPECS: dict[str, tuple[str, str]] = {
|
||||
code: (spec.scope, spec.value_type) for code, spec in STANDARD_FIELD_SPECS.items()
|
||||
spec.field_code: (spec.scope, spec.value_type) for spec in _STANDARD_FIELD_SPECS
|
||||
}
|
||||
|
||||
|
||||
def standard_field_codes() -> frozenset[str]:
|
||||
"""返回全部标准 field_code 集合。"""
|
||||
return frozenset(STANDARD_FIELD_SPECS)
|
||||
return frozenset(spec.field_code for spec in _STANDARD_FIELD_SPECS)
|
||||
|
||||
|
||||
def is_standard_field_code(field_code: str) -> bool:
|
||||
"""判断编码是否属于锁定的系统标准目录。"""
|
||||
return str(field_code or '').strip().lower() in STANDARD_FIELD_SPECS
|
||||
def is_standard_field_code(field_code: str, *, scope: str | None = None) -> bool:
|
||||
"""判断编码(及可选 scope)是否属于锁定的系统标准目录。"""
|
||||
code = str(field_code or '').strip().lower()
|
||||
return ((scope, code) in STANDARD_FIELD_SPECS) if scope else code in standard_field_codes()
|
||||
|
||||
|
||||
def get_standard_field(field_code: str) -> StandardFieldSpec | None:
|
||||
"""按编码读取标准字段注册项。"""
|
||||
return STANDARD_FIELD_SPECS.get(str(field_code or '').strip().lower())
|
||||
def get_standard_field(field_code: str, *, scope: str | None = None) -> StandardFieldSpec | None:
|
||||
"""按编码和 scope 读取标准字段注册项;省略 scope 时仅返回唯一匹配项。"""
|
||||
code = str(field_code or '').strip().lower()
|
||||
if scope:
|
||||
return STANDARD_FIELD_SPECS.get((scope, code))
|
||||
matches = [spec for spec in _STANDARD_FIELD_SPECS if spec.field_code == code]
|
||||
return matches[0] if len(matches) == 1 else None
|
||||
|
||||
|
||||
def assert_registry_consistent() -> None:
|
||||
@@ -186,14 +199,14 @@ def assert_registry_consistent() -> None:
|
||||
校验注册表内部一致性及与 Snapshot ORM / 冻结投影的对齐。
|
||||
|
||||
Raises:
|
||||
AssertionError: 数量不为 57、typed 列缺失、或投影键不在标准目录中。
|
||||
AssertionError: 数量不为 58、typed 列缺失、或投影键不在标准目录中。
|
||||
"""
|
||||
# [STEP 1] 锁定数量与唯一性
|
||||
assert len(STANDARD_FIELD_SPECS) == 57, f'expected 57 standard fields, got {len(STANDARD_FIELD_SPECS)}'
|
||||
assert len(_STANDARD_FIELD_SPECS) == 57
|
||||
assert len(STANDARD_FIELD_SPECS) == 58, f'expected 58 standard fields, got {len(STANDARD_FIELD_SPECS)}'
|
||||
assert len(_STANDARD_FIELD_SPECS) == 58
|
||||
header_count = sum(1 for item in _STANDARD_FIELD_SPECS if item.scope == 'header')
|
||||
line_count = sum(1 for item in _STANDARD_FIELD_SPECS if item.scope == 'line')
|
||||
assert header_count == 23 and line_count == 34
|
||||
assert header_count == 24 and line_count == 34
|
||||
|
||||
# [STEP 2] typed 投影列必须存在于 Snapshot ORM
|
||||
header_columns = {column.key for column in ShippingOrderSnapshot.__table__.columns}
|
||||
@@ -209,12 +222,12 @@ def assert_registry_consistent() -> None:
|
||||
|
||||
# [STEP 3] 冻结投影表的每个键都必须是标准字段
|
||||
for code in HEADER_FIELD_PROJECTIONS:
|
||||
assert code in STANDARD_FIELD_SPECS and STANDARD_FIELD_SPECS[code].scope == 'header'
|
||||
assert ('header', code) in STANDARD_FIELD_SPECS
|
||||
for code in LINE_FIELD_PROJECTIONS:
|
||||
assert code in STANDARD_FIELD_SPECS and STANDARD_FIELD_SPECS[code].scope == 'line'
|
||||
assert ('line', code) in STANDARD_FIELD_SPECS
|
||||
|
||||
# [STEP 4] 建议采用集与履约核心均落在标准目录
|
||||
for code in DEFAULT_V1_ADOPTION_CODES:
|
||||
assert code in STANDARD_FIELD_SPECS
|
||||
assert is_standard_field_code(code)
|
||||
for code in FULFILLMENT_CORE_FIELD_CODES:
|
||||
assert code in STANDARD_FIELD_SPECS and STANDARD_FIELD_SPECS[code].scope == 'line'
|
||||
assert ('line', code) in STANDARD_FIELD_SPECS
|
||||
@@ -10,6 +10,7 @@ services/shipping_notice/state_machine.py
|
||||
扩展说明(开发者):
|
||||
- checkpoint id 即 API `checkpoint` / Dify `flow_ckpt`
|
||||
- checkpoint_kind 区分 auto_continue / must_human / wait_manual_upload / complete
|
||||
(导出 CP_EXPORT_* → wait_manual_upload:Excel 后待人工上传登记)
|
||||
- 动作按钮 id 定义于 ACTION_SPECS;DB 写入统一走 TaskTransition
|
||||
- GET /tools/checkpoint-catalog 供文档/CI,不接入 Dify 画布
|
||||
"""
|
||||
@@ -81,7 +82,10 @@ def _task_has_dynamic_order_lines(task: ShippingTask) -> bool:
|
||||
|
||||
|
||||
class CheckpointKind(StrEnum):
|
||||
"""STP 检查点分类:自动可继续 / 必须人工 / 待人工上传 / 完成。"""
|
||||
"""STP 检查点分类:自动可继续 / 必须人工 / 待人工上传登记 / 完成。
|
||||
|
||||
CP_EXPORT_READY/GENERATED 映射为 WAIT_MANUAL_UPLOAD(Excel 后须登记凭据,非终态)。
|
||||
"""
|
||||
|
||||
AUTO_CONTINUE = "auto_continue"
|
||||
MUST_HUMAN = "must_human"
|
||||
@@ -143,8 +147,9 @@ CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
|
||||
CP_RSV_REQ: ("replace_notice_file", "reparse", "reject"),
|
||||
RS_SHORTAGE_REVIEW: ("retry_rpa", "rematch", "reject"),
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("replace_notice_file", "reparse", "reject"),
|
||||
CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"),
|
||||
CP_WAITING_UPLOAD: ("refresh", "retry_upload", "download_excel", "mark_manual_uploaded"),
|
||||
# 上传失败仅允许下载;待上传/结果未知允许下载 + 人工凭据登记(禁 RPA retry_upload)。
|
||||
CP_UPLOAD_FAILED: ("download_excel",),
|
||||
CP_WAITING_UPLOAD: ("refresh", "download_excel", "mark_manual_uploaded"),
|
||||
CP_UPLOAD_RESULT_UNKNOWN: ("refresh", "download_excel", "mark_manual_uploaded"),
|
||||
CP_READY_MATCH: ("match_inventory",),
|
||||
CP_READY_EXPORT: ("generate_excel",),
|
||||
@@ -167,8 +172,8 @@ CHECKPOINT_KIND_REGISTRY: dict[str, CheckpointKind] = {
|
||||
RS_SHORTAGE_REVIEW: CheckpointKind.MUST_HUMAN,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED: CheckpointKind.MUST_HUMAN,
|
||||
CP_UPLOAD_FAILED: CheckpointKind.MUST_HUMAN,
|
||||
CP_WAITING_UPLOAD: CheckpointKind.MUST_HUMAN,
|
||||
CP_UPLOAD_RESULT_UNKNOWN: CheckpointKind.MUST_HUMAN,
|
||||
CP_WAITING_UPLOAD: CheckpointKind.WAIT_MANUAL_UPLOAD,
|
||||
CP_UPLOAD_RESULT_UNKNOWN: CheckpointKind.WAIT_MANUAL_UPLOAD,
|
||||
CP_READY_MATCH: CheckpointKind.AUTO_CONTINUE,
|
||||
CP_READY_EXPORT: CheckpointKind.AUTO_CONTINUE,
|
||||
CP_EXPORT_READY: CheckpointKind.WAIT_MANUAL_UPLOAD,
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
"""
|
||||
services/shipping_notice/stp_inventory_freeze.py
|
||||
|
||||
用途:建单时将资格服务的行级库存源候选冻结到 Task,供后续库存准备消费。
|
||||
依赖:inventory_source_gate、inventory_source_repository、inventory_source_rules、tool_common。
|
||||
逻辑:由 confirm_review_case / STP 自动建单调用;单候选直接 resolved;
|
||||
多候选写入 candidates_frozen(视为可进入库存准备,不再强制 inventory_source_review);
|
||||
冻结结果写入 ShippingTaskEvent(candidates_frozen / inventory_source_resolved_at_build)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
get_database_inventory_source,
|
||||
inventory_sources_runtime_version,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
InventorySourceAdjudication,
|
||||
_candidate,
|
||||
compute_routing_fingerprint,
|
||||
extract_routing_context,
|
||||
)
|
||||
|
||||
|
||||
def collect_frozen_candidate_codes(line_projections: list[dict[str, Any]] | None) -> list[str]:
|
||||
"""
|
||||
从资格投影汇总去重后的候选库存源编码(保序)。
|
||||
|
||||
Args:
|
||||
line_projections: validation.line_projections。
|
||||
|
||||
Returns:
|
||||
大写 source_code 列表。
|
||||
"""
|
||||
codes: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for item in line_projections or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
for raw in item.get('candidate_inventory_source_codes') or []:
|
||||
code = str(raw or '').strip().upper()
|
||||
if not code or code in seen:
|
||||
continue
|
||||
seen.add(code)
|
||||
codes.append(code)
|
||||
return codes
|
||||
|
||||
|
||||
def freeze_stp_inventory_candidates_on_task(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
line_projections: list[dict[str, Any]] | None,
|
||||
) -> InventorySourceAdjudication:
|
||||
"""
|
||||
将建单前候选冻结到任务字段与 step_payload。
|
||||
|
||||
核心逻辑:
|
||||
- 恰好 1 个有效启用候选 → status=resolved(任务级摘要);
|
||||
- 多个有效候选 → status=candidates_frozen,允许进入库存准备;
|
||||
- 零有效候选 → unresolved(调用方本不应在 can_build 后走到此处)。
|
||||
|
||||
Args:
|
||||
task: 已 flush 的 ShippingTask。
|
||||
line_projections: 确认校验产出的行级候选投影。
|
||||
|
||||
Returns:
|
||||
写入后的裁决对象。
|
||||
"""
|
||||
context = extract_routing_context(task)
|
||||
fingerprint = compute_routing_fingerprint(context)
|
||||
config_version = inventory_sources_runtime_version()
|
||||
codes = collect_frozen_candidate_codes(line_projections)
|
||||
sources = [item for code in codes if (item := get_database_inventory_source(code))]
|
||||
valid_codes = [str(item['source_code']).upper() for item in sources]
|
||||
candidates = [_candidate(item) for item in sources]
|
||||
evidence = [{
|
||||
'freeze': 'stp_build',
|
||||
'line_projections': [
|
||||
{
|
||||
'line_key': item.get('line_key'),
|
||||
'line_index': item.get('line_index'),
|
||||
'candidate_inventory_source_codes': list(item.get('candidate_inventory_source_codes') or []),
|
||||
'selection_mode': item.get('selection_mode'),
|
||||
'routing_status': item.get('routing_status'),
|
||||
'matched_rule_ids': list(item.get('matched_rule_ids') or []),
|
||||
}
|
||||
for item in (line_projections or [])
|
||||
if isinstance(item, dict)
|
||||
],
|
||||
}]
|
||||
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload['line_inventory_candidates'] = {
|
||||
'source_codes': valid_codes,
|
||||
'lines': evidence[0]['line_projections'],
|
||||
'frozen_at': 'build',
|
||||
}
|
||||
task.step_payload_json = payload
|
||||
|
||||
if len(valid_codes) == 1 and sources:
|
||||
adjudication = InventorySourceAdjudication(
|
||||
status='resolved',
|
||||
method='stp_build_freeze',
|
||||
source_code=valid_codes[0],
|
||||
connector_type=str(sources[0].get('connector_type') or '') or None,
|
||||
warehouse_id=(
|
||||
str(sources[0].get('fixed_warehouse_id') or '').upper() or None
|
||||
if str(sources[0].get('warehouse_resolution_mode') or '').lower() == 'fixed'
|
||||
else None
|
||||
),
|
||||
config_version=config_version,
|
||||
routing_fingerprint=fingerprint,
|
||||
candidates=candidates,
|
||||
evidence=evidence,
|
||||
reason='single_candidate_at_build',
|
||||
)
|
||||
elif valid_codes:
|
||||
adjudication = InventorySourceAdjudication(
|
||||
status='candidates_frozen',
|
||||
method='stp_build_freeze',
|
||||
source_code=None,
|
||||
connector_type=None,
|
||||
warehouse_id=None,
|
||||
config_version=config_version,
|
||||
routing_fingerprint=fingerprint,
|
||||
candidates=candidates,
|
||||
evidence=evidence,
|
||||
reason='multi_candidate_at_build',
|
||||
)
|
||||
else:
|
||||
adjudication = InventorySourceAdjudication(
|
||||
status='unresolved',
|
||||
method='stp_build_freeze',
|
||||
config_version=config_version,
|
||||
routing_fingerprint=fingerprint,
|
||||
candidates=[],
|
||||
evidence=evidence,
|
||||
reason='no_valid_candidates_at_build',
|
||||
)
|
||||
|
||||
apply_inventory_source_adjudication(task, adjudication)
|
||||
# 多候选时 apply 会清空 task.inventory_source_code;保留 line_inventory_candidates。
|
||||
if adjudication.status == 'candidates_frozen':
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload['line_inventory_candidates'] = {
|
||||
'source_codes': valid_codes,
|
||||
'lines': evidence[0]['line_projections'],
|
||||
'frozen_at': 'build',
|
||||
}
|
||||
resolution = dict(payload.get('inventory_source_resolution') or {})
|
||||
resolution['status'] = 'candidates_frozen'
|
||||
resolution['candidates'] = candidates
|
||||
resolution['reason'] = adjudication.reason
|
||||
payload['inventory_source_resolution'] = resolution
|
||||
task.step_payload_json = payload
|
||||
task.inventory_source_status = 'candidates_frozen'
|
||||
task.inventory_source_method = 'stp_build_freeze'
|
||||
task.inventory_source_config_version = config_version
|
||||
task.inventory_routing_fingerprint = fingerprint
|
||||
|
||||
# [STEP] 仅对真实 ORM 任务写审计事件(单测 SimpleNamespace 跳过)。
|
||||
if isinstance(task, ShippingTask):
|
||||
from app.services.shipping_notice.tool_common import log_task_event
|
||||
|
||||
if adjudication.status == 'candidates_frozen':
|
||||
log_task_event(
|
||||
task,
|
||||
'candidates_frozen',
|
||||
{
|
||||
'source_codes': valid_codes,
|
||||
'reason': adjudication.reason,
|
||||
'method': adjudication.method,
|
||||
},
|
||||
source='system',
|
||||
)
|
||||
elif adjudication.status == 'resolved':
|
||||
log_task_event(
|
||||
task,
|
||||
'inventory_source_resolved_at_build',
|
||||
{
|
||||
'source_code': adjudication.source_code,
|
||||
'reason': adjudication.reason,
|
||||
'method': adjudication.method,
|
||||
},
|
||||
source='system',
|
||||
)
|
||||
return adjudication
|
||||
|
||||
|
||||
def task_frozen_inventory_source_codes(task: ShippingTask) -> list[str]:
|
||||
"""
|
||||
读取任务上冻结的候选库存源(单源任务则回退 inventory_source_code)。
|
||||
|
||||
Args:
|
||||
task: 发货任务。
|
||||
|
||||
Returns:
|
||||
大写 source_code 列表。
|
||||
"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
frozen = payload.get('line_inventory_candidates') if isinstance(payload.get('line_inventory_candidates'), dict) else {}
|
||||
codes = [
|
||||
str(code or '').strip().upper()
|
||||
for code in (frozen.get('source_codes') or [])
|
||||
if str(code or '').strip()
|
||||
]
|
||||
if codes:
|
||||
return list(dict.fromkeys(codes))
|
||||
single = str(task.inventory_source_code or '').strip().upper()
|
||||
return [single] if single else []
|
||||
@@ -0,0 +1,475 @@
|
||||
"""
|
||||
services/shipping_notice/stp_line_inventory_match.py
|
||||
|
||||
用途:STP 阶段 4 跨冻结候选库存源按有效 Reservation + Part Number 匹配并落实行级裁决。
|
||||
依赖:stp_inventory_freeze、reservation_id、inventory_snapshot_store、inventory_source_repository、
|
||||
inventory_source_rules、ShippingOrderSnapshot。
|
||||
逻辑:ensure_inventory 合并候选快照行;match 仅在冻结候选集内检索;多文件命中为冲突;
|
||||
唯一命中且数量充足则冻结 resolved 源与行证据;多源可履约行暂停 Excel(step_payload 标记);
|
||||
人工指定源后 forced_match_source_code 过滤库存行再匹配;结果写入 step_payload / line_results_json。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingOrderSnapshot, ShippingTask
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
get_database_inventory_source,
|
||||
inventory_sources_runtime_version,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
compute_routing_fingerprint,
|
||||
extract_routing_context,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.field_rules import compute_effective_reservation_id
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
|
||||
|
||||
def _norm_part(value: Any) -> str:
|
||||
"""料号匹配键:去空白并大写。"""
|
||||
return str(value or '').strip().upper()
|
||||
|
||||
|
||||
def _qty(value: Any) -> Decimal:
|
||||
"""解析数量;非法视为 0。"""
|
||||
try:
|
||||
return Decimal(str(value or '0').replace(',', '').strip() or '0')
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
return Decimal('0')
|
||||
|
||||
|
||||
def _inventory_row_key(row: dict[str, Any]) -> tuple[str, str] | None:
|
||||
"""
|
||||
从库存行提取 Reservation + Part Number 键。
|
||||
|
||||
核心逻辑:优先标准键名,兼容常见别名;不做数值归一化 Reservation。
|
||||
"""
|
||||
reservation = validated_reservation_id(
|
||||
row.get('reservation_id') or row.get('Reservation ID') or row.get('reservation')
|
||||
)
|
||||
part = _norm_part(row.get('part_number') or row.get('Part Number') or row.get('mpn') or row.get('sku'))
|
||||
if not reservation or not part:
|
||||
return None
|
||||
return reservation, part
|
||||
|
||||
|
||||
def _inventory_row_qty(row: dict[str, Any]) -> Decimal:
|
||||
"""读取库存可用量。"""
|
||||
for key in ('qty', 'quantity', 'available_qty', 'Qty', 'Quantity', 'on_hand'):
|
||||
if key in row and row.get(key) not in (None, ''):
|
||||
return _qty(row.get(key))
|
||||
return Decimal('0')
|
||||
|
||||
|
||||
def snapshot_header_reservation_id(snapshot: ShippingOrderSnapshot | None) -> str | None:
|
||||
"""
|
||||
从冻结 Snapshot 读取 Header 级 reservation_id。
|
||||
|
||||
核心逻辑:Snapshot 无强类型头 Reservation 列;按 Schema field_code=reservation_id
|
||||
且 scope=header 的 field_id 取 header_values_json;兼容 draft 风格的 code 键。
|
||||
|
||||
Args:
|
||||
snapshot: 冻结订单快照;None 时返回 None。
|
||||
|
||||
Returns:
|
||||
校验后的 Reservation 字符串,或 None。
|
||||
"""
|
||||
if snapshot is None:
|
||||
return None
|
||||
header_values = dict(snapshot.header_values_json or {})
|
||||
schema_version = getattr(snapshot, 'schema_version', None)
|
||||
fields = []
|
||||
if schema_version is not None:
|
||||
fields = list((schema_version.definition_json or {}).get('fields') or [])
|
||||
for field in fields:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
if str(field.get('field_code') or '') != 'reservation_id':
|
||||
continue
|
||||
if str(field.get('scope') or 'header').lower() != 'header':
|
||||
continue
|
||||
field_id = str(field.get('field_id') or '').strip()
|
||||
if field_id and field_id in header_values:
|
||||
return validated_reservation_id(header_values.get(field_id))
|
||||
return validated_reservation_id(header_values.get('reservation_id'))
|
||||
|
||||
|
||||
def prepare_candidate_inventory_lines(task: ShippingTask) -> dict[str, Any]:
|
||||
"""
|
||||
为任务准备全部冻结候选源的有效库存行(打上 __source_code 标签)。
|
||||
|
||||
核心逻辑:只查询冻结候选;任一候选无 ready 快照则记录 missing;全部缺失则不可匹配。
|
||||
|
||||
Args:
|
||||
task: 已冻结候选的发货任务。
|
||||
|
||||
Returns:
|
||||
status / lines / missing_source_codes / loaded_source_codes / evidence。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
|
||||
from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot
|
||||
|
||||
codes = task_frozen_inventory_source_codes(task)
|
||||
if not codes:
|
||||
single = str(task.inventory_source_code or '').strip().upper()
|
||||
codes = [single] if single else []
|
||||
|
||||
merged: list[dict[str, Any]] = []
|
||||
missing: list[str] = []
|
||||
loaded: list[str] = []
|
||||
evidence: list[dict[str, Any]] = []
|
||||
|
||||
for code in codes:
|
||||
source = get_database_inventory_source(code)
|
||||
if source is None:
|
||||
missing.append(code)
|
||||
evidence.append({'source_code': code, 'status': 'source_disabled'})
|
||||
continue
|
||||
warehouse_id = (
|
||||
str(source.get('fixed_warehouse_id') or '').strip().upper() or None
|
||||
if str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed'
|
||||
else None
|
||||
)
|
||||
snapshot = find_latest_ready_snapshot(code, warehouse_id)
|
||||
if snapshot is None:
|
||||
missing.append(code)
|
||||
evidence.append({'source_code': code, 'status': 'snapshot_missing'})
|
||||
continue
|
||||
lines = [row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)]
|
||||
if not lines:
|
||||
try:
|
||||
lines, _meta = parse_inventory_snapshot_file(snapshot)
|
||||
except (OSError, ValueError):
|
||||
lines = []
|
||||
if not lines:
|
||||
missing.append(code)
|
||||
evidence.append({
|
||||
'source_code': code,
|
||||
'status': 'snapshot_empty',
|
||||
'inventory_file_no': snapshot.inventory_file_no,
|
||||
})
|
||||
continue
|
||||
for row in lines:
|
||||
tagged = dict(row)
|
||||
tagged['__source_code'] = code
|
||||
tagged['__inventory_file_no'] = snapshot.inventory_file_no
|
||||
merged.append(tagged)
|
||||
loaded.append(code)
|
||||
evidence.append({
|
||||
'source_code': code,
|
||||
'status': 'loaded',
|
||||
'inventory_file_no': snapshot.inventory_file_no,
|
||||
'line_count': len(lines),
|
||||
})
|
||||
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload['candidate_inventory_prep'] = {
|
||||
'loaded_source_codes': loaded,
|
||||
'missing_source_codes': missing,
|
||||
'evidence': evidence,
|
||||
}
|
||||
task.step_payload_json = payload
|
||||
|
||||
if not merged:
|
||||
return {
|
||||
'status': 'missing_files',
|
||||
'lines': [],
|
||||
'missing_source_codes': missing,
|
||||
'loaded_source_codes': loaded,
|
||||
'evidence': evidence,
|
||||
}
|
||||
if missing:
|
||||
return {
|
||||
'status': 'partial_missing',
|
||||
'lines': merged,
|
||||
'missing_source_codes': missing,
|
||||
'loaded_source_codes': loaded,
|
||||
'evidence': evidence,
|
||||
}
|
||||
return {
|
||||
'status': 'ready',
|
||||
'lines': merged,
|
||||
'missing_source_codes': [],
|
||||
'loaded_source_codes': loaded,
|
||||
'evidence': evidence,
|
||||
}
|
||||
|
||||
|
||||
def match_order_lines_across_candidates(
|
||||
*,
|
||||
order_lines: list[dict[str, Any]],
|
||||
inventory_lines: list[dict[str, Any]],
|
||||
header_reservation_id: Any = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
跨候选库存行按有效 Reservation + Part Number 匹配。
|
||||
|
||||
Args:
|
||||
order_lines: 含 part_number / reservation_id / quantity(或 qty)的订单行。
|
||||
inventory_lines: 已打 ``__source_code`` 的库存行。
|
||||
header_reservation_id: 头级 Reservation,用于行级回退。
|
||||
|
||||
Returns:
|
||||
match_status、line_results、shortage_json、resolutions。
|
||||
"""
|
||||
# [STEP 1] 按 (reservation, part, source) 聚合可用量与样例行。
|
||||
buckets: dict[tuple[str, str, str], dict[str, Any]] = {}
|
||||
for row in inventory_lines:
|
||||
key = _inventory_row_key(row)
|
||||
if key is None:
|
||||
continue
|
||||
source = str(row.get('__source_code') or '').strip().upper()
|
||||
if not source:
|
||||
continue
|
||||
bucket_key = (key[0], key[1], source)
|
||||
bucket = buckets.get(bucket_key)
|
||||
if bucket is None:
|
||||
bucket = {'available_qty': Decimal('0'), 'sample_row': row, 'source_code': source}
|
||||
buckets[bucket_key] = bucket
|
||||
bucket['available_qty'] += _inventory_row_qty(row)
|
||||
|
||||
line_results: list[dict[str, Any]] = []
|
||||
shortages: list[dict[str, Any]] = []
|
||||
resolutions: list[dict[str, Any]] = []
|
||||
has_ok = False
|
||||
has_block = False
|
||||
|
||||
for index, line in enumerate(order_lines):
|
||||
part = _norm_part(line.get('part_number') or line.get('__display_part_number'))
|
||||
effective = compute_effective_reservation_id(
|
||||
line_reservation_id=line.get('reservation_id') or line.get('__display_reservation_id'),
|
||||
header_reservation_id=header_reservation_id,
|
||||
)
|
||||
required = _qty(line.get('quantity') if line.get('quantity') is not None else line.get('__required_qty', line.get('qty')))
|
||||
source_hits = [
|
||||
buckets[key]
|
||||
for key in buckets
|
||||
if key[0] == (effective or '') and key[1] == part
|
||||
] if effective and part else []
|
||||
|
||||
if not effective or not part:
|
||||
disposition = 'not_found'
|
||||
result = {
|
||||
'line_index': index,
|
||||
'part_number': part or None,
|
||||
'reservation_id': effective,
|
||||
'required_qty': float(required),
|
||||
'available_qty': 0.0,
|
||||
'shortage_qty': float(required),
|
||||
'line_status': 'shortage',
|
||||
'disposition': disposition,
|
||||
'resolved_inventory_source_code': None,
|
||||
}
|
||||
has_block = True
|
||||
elif len(source_hits) > 1:
|
||||
disposition = 'multi_file_conflict'
|
||||
result = {
|
||||
'line_index': index,
|
||||
'part_number': part,
|
||||
'reservation_id': effective,
|
||||
'required_qty': float(required),
|
||||
'available_qty': float(sum(item['available_qty'] for item in source_hits)),
|
||||
'shortage_qty': 0.0,
|
||||
'line_status': 'conflict',
|
||||
'disposition': disposition,
|
||||
'candidate_hit_source_codes': [item['source_code'] for item in source_hits],
|
||||
'resolved_inventory_source_code': None,
|
||||
}
|
||||
has_block = True
|
||||
elif not source_hits:
|
||||
disposition = 'not_found'
|
||||
result = {
|
||||
'line_index': index,
|
||||
'part_number': part,
|
||||
'reservation_id': effective,
|
||||
'required_qty': float(required),
|
||||
'available_qty': 0.0,
|
||||
'shortage_qty': float(required),
|
||||
'line_status': 'shortage',
|
||||
'disposition': disposition,
|
||||
'resolved_inventory_source_code': None,
|
||||
}
|
||||
has_block = True
|
||||
else:
|
||||
hit = source_hits[0]
|
||||
available = hit['available_qty']
|
||||
if available >= required and required > 0:
|
||||
disposition = 'ok'
|
||||
sample = hit['sample_row']
|
||||
result = {
|
||||
'line_index': index,
|
||||
'part_number': part,
|
||||
'reservation_id': effective,
|
||||
'required_qty': float(required),
|
||||
'available_qty': float(available),
|
||||
'shortage_qty': 0.0,
|
||||
'line_status': 'ok',
|
||||
'disposition': disposition,
|
||||
'resolved_inventory_source_code': hit['source_code'],
|
||||
'inventory_file_no': sample.get('__inventory_file_no'),
|
||||
'inventory_row_ref': {
|
||||
'reservation_id': effective,
|
||||
'part_number': part,
|
||||
'source_code': hit['source_code'],
|
||||
},
|
||||
}
|
||||
has_ok = True
|
||||
else:
|
||||
disposition = 'shortage'
|
||||
result = {
|
||||
'line_index': index,
|
||||
'part_number': part,
|
||||
'reservation_id': effective,
|
||||
'required_qty': float(required),
|
||||
'available_qty': float(available),
|
||||
'shortage_qty': float(max(required - available, Decimal('0'))),
|
||||
'line_status': 'partial' if available > 0 else 'shortage',
|
||||
'disposition': disposition,
|
||||
'resolved_inventory_source_code': hit['source_code'],
|
||||
}
|
||||
has_block = True
|
||||
|
||||
line_results.append(result)
|
||||
resolutions.append({
|
||||
'line_index': index,
|
||||
'line_key': line.get('line_key'),
|
||||
'disposition': result['disposition'],
|
||||
'effective_reservation_id': effective,
|
||||
'part_number': part or None,
|
||||
'resolved_inventory_source_code': result.get('resolved_inventory_source_code'),
|
||||
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
|
||||
'inventory_file_no': result.get('inventory_file_no'),
|
||||
'inventory_row_ref': result.get('inventory_row_ref'),
|
||||
})
|
||||
if float(result.get('shortage_qty') or 0) > 0 or result.get('disposition') in {
|
||||
'not_found', 'multi_file_conflict', 'shortage',
|
||||
}:
|
||||
shortages.append(result)
|
||||
|
||||
if not order_lines:
|
||||
match_status = 'unfulfillable'
|
||||
elif has_block:
|
||||
match_status = 'unfulfillable' if not has_ok else 'partial'
|
||||
else:
|
||||
match_status = 'fulfillable'
|
||||
|
||||
return {
|
||||
'match_status': match_status,
|
||||
'line_results': line_results,
|
||||
'shortage_json': {'lines': shortages},
|
||||
'resolutions': resolutions,
|
||||
}
|
||||
|
||||
|
||||
def apply_line_inventory_resolutions(task: ShippingTask, match_payload: dict[str, Any]) -> None:
|
||||
"""
|
||||
将跨候选匹配结果写入任务并投影汇总库存源。
|
||||
|
||||
核心逻辑:全部 ok 时投影 inventory_source_code(多源取首个作 Excel 模板绑定,
|
||||
行级 resolved 仍保留在 line_inventory_resolutions);不再因多源成功命中阻断制单。
|
||||
"""
|
||||
resolutions = list(match_payload.get('resolutions') or [])
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload['line_inventory_resolutions'] = resolutions
|
||||
# 历史阻断标记:全成功多源场景不再阻断,清理以免误伤自动链。
|
||||
payload.pop('multi_source_excel_block', None)
|
||||
task.step_payload_json = payload
|
||||
task.match_status = str(match_payload.get('match_status') or '')
|
||||
task.line_results_json = list(match_payload.get('line_results') or [])
|
||||
task.shortage_json = dict(match_payload.get('shortage_json') or {})
|
||||
|
||||
ok_sources = sorted({
|
||||
str(item.get('resolved_inventory_source_code') or '').strip().upper()
|
||||
for item in resolutions
|
||||
if item.get('disposition') == 'ok' and item.get('resolved_inventory_source_code')
|
||||
})
|
||||
if match_payload.get('match_status') == 'fulfillable' and ok_sources:
|
||||
primary = ok_sources[0]
|
||||
source = get_database_inventory_source(primary)
|
||||
if source is not None:
|
||||
task.inventory_source_code = primary
|
||||
task.inventory_connector_type = str(source.get('connector_type') or '') or None
|
||||
if str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed':
|
||||
task.inventory_warehouse_id = str(source.get('fixed_warehouse_id') or '').upper() or None
|
||||
task.inventory_source_status = 'resolved'
|
||||
task.inventory_source_method = (
|
||||
'stp_line_match' if len(ok_sources) == 1 else 'stp_line_match_multi'
|
||||
)
|
||||
task.inventory_source_config_version = inventory_sources_runtime_version()
|
||||
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
|
||||
if len(ok_sources) > 1:
|
||||
payload['resolved_ok_source_codes'] = ok_sources
|
||||
payload['excel_binding_source_code'] = primary
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def multi_source_recovery_source_codes(task: ShippingTask) -> list[str]:
|
||||
"""
|
||||
多文件冲突时可人工指定的库存源编码列表。
|
||||
|
||||
核心逻辑:仅汇总 multi_file_conflict 行的 candidate_hit_source_codes;
|
||||
全成功多源制单场景不再需要人工恢复。
|
||||
"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
codes: list[str] = []
|
||||
# 兼容历史 multi_source_excel_block 任务。
|
||||
if bool(payload.get('multi_source_excel_block')):
|
||||
for code in payload.get('resolved_ok_source_codes') or []:
|
||||
normalized = str(code or '').strip().upper()
|
||||
if normalized and normalized not in codes:
|
||||
codes.append(normalized)
|
||||
if codes:
|
||||
return codes
|
||||
resolutions = payload.get('line_inventory_resolutions')
|
||||
for collection in (
|
||||
resolutions,
|
||||
payload.get('match_line_results'),
|
||||
(payload.get('shortage_json') or {}).get('lines') if isinstance(payload.get('shortage_json'), dict) else None,
|
||||
):
|
||||
if not isinstance(collection, list):
|
||||
continue
|
||||
for item in collection:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if str(item.get('disposition') or '') != 'multi_file_conflict':
|
||||
continue
|
||||
for code in item.get('candidate_hit_source_codes') or []:
|
||||
normalized = str(code or '').strip().upper()
|
||||
if normalized and normalized not in codes:
|
||||
codes.append(normalized)
|
||||
return codes
|
||||
|
||||
|
||||
def needs_multi_source_manual_recovery(task: ShippingTask) -> bool:
|
||||
"""是否处于多文件冲突等需人工指定库存源才能继续的匹配阻断态。"""
|
||||
return bool(multi_source_recovery_source_codes(task))
|
||||
|
||||
|
||||
def apply_forced_match_source_filter(
|
||||
inventory_lines: list[dict[str, Any]],
|
||||
*,
|
||||
task: ShippingTask,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
人工指定库存源后,匹配仅使用该源的库存行,消除多源/多文件冲突。
|
||||
|
||||
Args:
|
||||
inventory_lines: 原始库存行(可含 __source_code)。
|
||||
task: 当前任务。
|
||||
|
||||
Returns:
|
||||
过滤后的库存行;无强制源时原样返回。
|
||||
"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
forced = str(payload.get('forced_match_source_code') or task.inventory_source_code or '').strip().upper()
|
||||
if not forced:
|
||||
return inventory_lines
|
||||
if not any(isinstance(row, dict) and row.get('__source_code') for row in inventory_lines):
|
||||
return inventory_lines
|
||||
return [
|
||||
row for row in inventory_lines
|
||||
if isinstance(row, dict) and str(row.get('__source_code') or '').strip().upper() == forced
|
||||
]
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
services/shipping_notice/stp_progress_contract.py
|
||||
|
||||
用途:冻结 STP 履约主链进度/审计事件名与 summary.stp_facts 键,供 UI 与审计双写对齐。
|
||||
依赖:无运行时依赖(纯常量契约)。
|
||||
逻辑:与 order-extraction 的 progress_audit_contract 分离;ui_state / log_task_event /
|
||||
工作台时间线 i18n 共同消费本契约,禁止前端自行发明事件码。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# STP 履约任务事件(ShippingTaskEvent.event_type);前缀匹配亦用于审计双写。
|
||||
STP_TASK_EVENT_TYPES: frozenset[str] = frozenset({
|
||||
'candidates_frozen',
|
||||
'inventory_source_resolved_at_build',
|
||||
'matched_stp_candidates',
|
||||
'matched_multi_source_excel_block',
|
||||
'matched_multi_file_conflict',
|
||||
'matched_shortage',
|
||||
'inventory_candidate_files_missing',
|
||||
'inventory_candidate_files_partial',
|
||||
'stp_auto_create',
|
||||
'stp_auto_create_failed',
|
||||
})
|
||||
|
||||
# log_task_event → ShippingAuditEvent 双写前缀(与库存/导出前缀并列)。
|
||||
STP_AUDIT_DUAL_WRITE_PREFIXES: tuple[str, ...] = (
|
||||
'matched_stp',
|
||||
'matched_multi',
|
||||
'inventory_candidate_',
|
||||
'candidates_frozen',
|
||||
'inventory_source_resolved_at_build',
|
||||
'stp_',
|
||||
)
|
||||
|
||||
# ui_state.summary.stp_facts 允许键(白名单;前端只读这些键)。
|
||||
STP_FACTS_ALLOWED_KEYS: frozenset[str] = frozenset({
|
||||
'inventory_source_status',
|
||||
'inventory_source_code',
|
||||
'inventory_source_method',
|
||||
'frozen_candidate_codes',
|
||||
'resolution_counts',
|
||||
'line_resolutions',
|
||||
'multi_source_excel_block',
|
||||
'resolved_ok_source_codes',
|
||||
'recovery_source_codes',
|
||||
'match_status',
|
||||
})
|
||||
@@ -2,9 +2,9 @@
|
||||
services/shipping_notice/tool_common.py
|
||||
|
||||
用途:发货通知 Tool 链共享配置、payload 合并、消息拼接与任务事件写入(无阶段业务编排)。
|
||||
依赖:constants、models.ShippingTaskEvent、fulfillment_audit(库存/RPA/导出双写,strict)。
|
||||
依赖:constants、models.ShippingTaskEvent、fulfillment_audit、stp_progress_contract。
|
||||
逻辑:task_workflow / inventory_workflow / fulfillment_workflow 共用;log_task_event 对
|
||||
inventory_rpa_/inventory_source_/export_ 前缀事件同步投影到 ShippingAuditEvent,失败阻断业务。
|
||||
inventory_rpa_/inventory_source_/export_/STP 事件同步投影到 ShippingAuditEvent,失败阻断业务。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -293,8 +293,15 @@ def log_task_event(
|
||||
before_json=before,
|
||||
after_json=after,
|
||||
))
|
||||
# 库存/RPA/导出关键节点双写统一审计;失败必须阻断,保证审计中心可检索。
|
||||
if str(event_type or '').startswith(('inventory_rpa_', 'inventory_source_', 'export_')):
|
||||
# 库存/RPA/导出/STP 关键节点双写统一审计;失败必须阻断,保证审计中心可检索。
|
||||
from app.services.shipping_notice.stp_progress_contract import STP_AUDIT_DUAL_WRITE_PREFIXES
|
||||
|
||||
event_name = str(event_type or '')
|
||||
dual_write = event_name.startswith(('inventory_rpa_', 'inventory_source_', 'export_')) or any(
|
||||
event_name.startswith(prefix) or event_name == prefix
|
||||
for prefix in STP_AUDIT_DUAL_WRITE_PREFIXES
|
||||
)
|
||||
if dual_write:
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
safe_before = None
|
||||
@@ -315,6 +322,27 @@ def log_task_event(
|
||||
attempt_count = int((detail or {}).get('attempts') or (detail or {}).get('attempt_no') or 0) or None
|
||||
if attempt_count is not None:
|
||||
meta['attempt_count'] = attempt_count
|
||||
# 将关键操作内容(匹配结论、候选源、原因码等)写入 metadata,供审计中心检索。
|
||||
detail_obj = detail if isinstance(detail, dict) else {}
|
||||
for key in (
|
||||
'match_status',
|
||||
'resolved_ok_source_codes',
|
||||
'source_code',
|
||||
'connector_type',
|
||||
'warehouse_id',
|
||||
'reason_code',
|
||||
'error_code',
|
||||
'verification_id',
|
||||
'disposition',
|
||||
'confirmed_by',
|
||||
):
|
||||
if key not in detail_obj:
|
||||
continue
|
||||
value = detail_obj[key]
|
||||
if isinstance(value, (str, int, float, bool)) or value is None:
|
||||
meta[key] = value
|
||||
elif isinstance(value, list) and all(isinstance(item, (str, int, float, bool)) or item is None for item in value):
|
||||
meta[key] = value[:32]
|
||||
record_fulfillment_audit(
|
||||
event_type=f'task_{event_type}'[:64],
|
||||
aggregate_type='shipping_task',
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
services/shipping_notice/ui_state.py
|
||||
|
||||
用途:发货通知任务/批次 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。
|
||||
依赖:models.ShippingTask/ShippingBatch、state_machine、query_service、constants。
|
||||
依赖:models.ShippingTask/ShippingBatch、state_machine、query_service、constants、stp_progress_contract。
|
||||
逻辑:从 ShippingTask DB 字段经状态机解析 checkpoint/checkpoint_kind/action_buttons,
|
||||
再补充七步流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口);
|
||||
再补充七步流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、stp_facts);
|
||||
批次 UI 仅作会话上传集合摘要,不作为履约写操作面。
|
||||
"""
|
||||
|
||||
@@ -123,9 +123,9 @@ _PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = {
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("notice_text_extraction_failed", "通知文本解析失败"),
|
||||
CP_UPLOAD_FAILED: ("upload_failed", "货代上传失败"),
|
||||
CP_UPLOAD_RESULT_UNKNOWN: ("upload_result_unknown", "货代上传结果未知"),
|
||||
CP_WAITING_UPLOAD: ("waiting_upload", "等待货代上传结果"),
|
||||
CP_EXPORT_READY: ("wait_manual_upload", "Excel 已生成,待人工上传并提交凭据"),
|
||||
CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,待人工上传并提交凭据"),
|
||||
CP_WAITING_UPLOAD: ("waiting_upload", "待人工上传登记"),
|
||||
CP_EXPORT_READY: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"),
|
||||
CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"),
|
||||
}
|
||||
|
||||
|
||||
@@ -206,13 +206,41 @@ def build_shipping_workflow_steps(task: ShippingTask, checkpoint: str | None) ->
|
||||
|
||||
|
||||
def _action_buttons_for_task(task: ShippingTask) -> list[dict[str, str]]:
|
||||
"""从状态机解析当前任务可用动作按钮,库存源确认场景补充 source_code。"""
|
||||
"""
|
||||
从状态机解析当前任务可用动作按钮;多源匹配阻断时前置「人工指定库存源」。
|
||||
|
||||
核心逻辑:库存源确认场景补充 source_code;shortage + multi_source/multi_file 冲突时
|
||||
注入 confirm_inventory_source,使工作台可打开候选选择对话框。
|
||||
"""
|
||||
from app.services.shipping_notice.state_machine import ACTION_SPECS
|
||||
from app.services.shipping_notice.stp_line_inventory_match import (
|
||||
multi_source_recovery_source_codes,
|
||||
needs_multi_source_manual_recovery,
|
||||
)
|
||||
|
||||
ui = resolve_task_ui_state(task)
|
||||
if ui.checkpoint == CP_INVENTORY_SOURCE_REVIEW:
|
||||
return inventory_source_action_buttons(task)
|
||||
if ui.checkpoint == RS_SHORTAGE_REVIEW and needs_multi_source_manual_recovery(task):
|
||||
codes = multi_source_recovery_source_codes(task)
|
||||
confirm_spec = dict(ACTION_SPECS.get('confirm_inventory_source') or {})
|
||||
confirm_btn: dict[str, str] = {
|
||||
'id': 'confirm_inventory_source',
|
||||
'label': str(confirm_spec.get('label') or '人工指定库存源'),
|
||||
'message': '请选择单一库存源后继续匹配',
|
||||
'variant': str(confirm_spec.get('variant') or 'primary'),
|
||||
}
|
||||
if len(codes) == 1:
|
||||
confirm_btn['source_code'] = codes[0]
|
||||
confirm_btn['label'] = f"指定库存源:{codes[0]}"
|
||||
confirm_btn['message'] = f"使用库存源 {codes[0]} 重新匹配"
|
||||
else:
|
||||
confirm_btn['label'] = '人工指定库存源'
|
||||
# 保留重试/重匹配/驳回,但把指定源放在首位作为主恢复入口。
|
||||
rest = [btn for btn in (ui.action_buttons or []) if str(btn.get('id') or '') != 'confirm_inventory_source']
|
||||
return [confirm_btn, *rest]
|
||||
return ui.action_buttons
|
||||
|
||||
|
||||
_PARSE_STAGE_CHECKPOINTS = {
|
||||
CP_PARSE_REVIEW,
|
||||
CP_RSV_REQ,
|
||||
@@ -319,6 +347,9 @@ def _entry_surface_for(checkpoint: str | None, kind: CheckpointKind) -> str:
|
||||
Returns:
|
||||
review_workbench | task_workbench | none
|
||||
"""
|
||||
# Excel 就绪虽为 wait_manual_upload,仍进任务工作台以便下载与登记凭据。
|
||||
if str(checkpoint or "") in {CP_EXPORT_READY, CP_EXPORT_GENERATED}:
|
||||
return "task_workbench"
|
||||
if kind == CheckpointKind.COMPLETE:
|
||||
return "none"
|
||||
if str(checkpoint or "") in _REVIEW_ENTRY_CHECKPOINTS:
|
||||
@@ -346,6 +377,77 @@ def _current_todo_label(checkpoint: str | None, action_buttons: list[dict[str, s
|
||||
return label or None
|
||||
|
||||
|
||||
def _build_stp_facts(task: ShippingTask) -> dict[str, Any] | None:
|
||||
"""
|
||||
投影 STP 履约事实供 Chat/工作台/待办同源消费。
|
||||
|
||||
核心逻辑:只读 task + step_payload;无 STP 痕迹时返回 None,避免普通任务噪声。
|
||||
|
||||
Args:
|
||||
task: 发货任务。
|
||||
|
||||
Returns:
|
||||
stp_facts 字典或 None。
|
||||
"""
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
from app.services.shipping_notice.stp_line_inventory_match import multi_source_recovery_source_codes
|
||||
from app.services.shipping_notice.stp_progress_contract import STP_FACTS_ALLOWED_KEYS
|
||||
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
status = str(task.inventory_source_status or '').strip()
|
||||
method = str(task.inventory_source_method or '').strip()
|
||||
candidates = payload.get('line_inventory_candidates') if isinstance(payload.get('line_inventory_candidates'), dict) else {}
|
||||
resolutions_raw = payload.get('line_inventory_resolutions')
|
||||
resolutions = [item for item in resolutions_raw if isinstance(item, dict)] if isinstance(resolutions_raw, list) else []
|
||||
multi_block = bool(payload.get('multi_source_excel_block'))
|
||||
frozen_codes = list(candidates.get('source_codes') or []) or task_frozen_inventory_source_codes(task)
|
||||
has_stp = (
|
||||
status in {'candidates_frozen', 'resolved'}
|
||||
or method.startswith('stp')
|
||||
or bool(frozen_codes)
|
||||
or bool(resolutions)
|
||||
or multi_block
|
||||
or bool(payload.get('line_inventory_candidates'))
|
||||
)
|
||||
if not has_stp:
|
||||
return None
|
||||
|
||||
counts: dict[str, int] = {}
|
||||
compact_resolutions: list[dict[str, Any]] = []
|
||||
for item in resolutions:
|
||||
disposition = str(item.get('disposition') or 'unknown')
|
||||
counts[disposition] = counts.get(disposition, 0) + 1
|
||||
compact_resolutions.append({
|
||||
'line_index': item.get('line_index'),
|
||||
'line_key': item.get('line_key'),
|
||||
'disposition': disposition,
|
||||
'effective_reservation_id': item.get('effective_reservation_id'),
|
||||
'part_number': item.get('part_number'),
|
||||
'resolved_inventory_source_code': item.get('resolved_inventory_source_code'),
|
||||
'inventory_file_no': item.get('inventory_file_no'),
|
||||
'inventory_row_ref': item.get('inventory_row_ref'),
|
||||
})
|
||||
|
||||
recovery_codes = multi_source_recovery_source_codes(task)
|
||||
facts = {
|
||||
'inventory_source_status': status or None,
|
||||
'inventory_source_code': str(task.inventory_source_code or '').strip().upper() or None,
|
||||
'inventory_source_method': method or None,
|
||||
'frozen_candidate_codes': [str(code).strip().upper() for code in frozen_codes if str(code or '').strip()],
|
||||
'resolution_counts': counts,
|
||||
'line_resolutions': compact_resolutions,
|
||||
'multi_source_excel_block': multi_block,
|
||||
'resolved_ok_source_codes': [
|
||||
str(code).strip().upper()
|
||||
for code in (payload.get('resolved_ok_source_codes') or [])
|
||||
if str(code or '').strip()
|
||||
],
|
||||
'recovery_source_codes': recovery_codes,
|
||||
'match_status': str(task.match_status or '').strip() or None,
|
||||
}
|
||||
return {key: facts[key] for key in STP_FACTS_ALLOWED_KEYS if key in facts}
|
||||
|
||||
|
||||
def _build_task_summary(
|
||||
task: ShippingTask,
|
||||
checkpoint: str | None,
|
||||
@@ -357,7 +459,7 @@ def _build_task_summary(
|
||||
输出可解释任务摘要,供通知卡、人工复核与任务工作台同源消费。
|
||||
|
||||
核心逻辑:保留 title/message/issues;补充 stage、checkpoint_kind、current_todo、
|
||||
pause_reason、next_auto_step、event_at、entry_surface、allowed_actions。
|
||||
pause_reason、next_auto_step、event_at、entry_surface、allowed_actions、stp_facts。
|
||||
"""
|
||||
title = user_facing_task_stage(task)
|
||||
message_by_checkpoint: dict[str, str] = {
|
||||
@@ -371,10 +473,10 @@ def _build_task_summary(
|
||||
RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。",
|
||||
CP_READY_MATCH: "库存已就绪,系统将自动执行匹配。",
|
||||
CP_READY_EXPORT: "库存匹配已满足发货条件,系统将自动生成发货文件。",
|
||||
CP_EXPORT_READY: "发货文件已生成,请下载并在货代系统上传后提交截图/PDF 凭据。",
|
||||
CP_EXPORT_GENERATED: "发货文件已生成,请下载并在货代系统上传后提交截图/PDF 凭据。",
|
||||
CP_WAITING_UPLOAD: "系统正在等待货代上传结果。",
|
||||
CP_UPLOAD_FAILED: "货代上传失败,需要重试或手工确认。",
|
||||
CP_EXPORT_READY: "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。",
|
||||
CP_EXPORT_GENERATED: "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。",
|
||||
CP_WAITING_UPLOAD: "待人工上传登记:请下载 Excel,在货代平台上传后于本系统登记凭据。",
|
||||
CP_UPLOAD_FAILED: "货代上传失败,请下载 Excel 后人工处理。",
|
||||
CP_REJECTED: "任务已驳回,无需继续处理。",
|
||||
CP_UPLOADED: "任务已完成上传。",
|
||||
CP_COMPLETED: "任务已关闭。",
|
||||
@@ -383,21 +485,46 @@ def _build_task_summary(
|
||||
pause = _PAUSE_REASON_BY_CHECKPOINT.get(str(checkpoint or ""))
|
||||
pause_reason_code = pause[0] if pause else (task.pending_human_reason or None)
|
||||
pause_reason = pause[1] if pause else (task.error_message or task.upload_error_message or None)
|
||||
if checkpoint_kind == CheckpointKind.AUTO_CONTINUE:
|
||||
message = message_by_checkpoint.get(str(checkpoint or ""), title)
|
||||
stp_facts = _build_stp_facts(task)
|
||||
current_todo_override: str | None = None
|
||||
|
||||
# [STEP] STP 多源 Excel 阻断:覆盖通用 shortage 文案,并提示可指定库存源。
|
||||
if stp_facts and stp_facts.get('multi_source_excel_block'):
|
||||
pause_reason_code = 'multi_source_excel_block'
|
||||
pause_reason = '订单行命中多个不同库存源,首期无法生成单一发货 Excel,请拆单或人工指定库存源后继续'
|
||||
message = pause_reason
|
||||
title = '多库存源冲突,待人工处理'
|
||||
issue_text = pause_reason
|
||||
if issue_text not in issues:
|
||||
issues = [*issues, issue_text]
|
||||
current_todo_override = '请拆单或人工指定库存源后继续'
|
||||
elif stp_facts and str(stp_facts.get('inventory_source_status') or '') == 'candidates_frozen' and checkpoint_kind == CheckpointKind.AUTO_CONTINUE:
|
||||
message = '多候选库存源已冻结,系统正在准备库存并跨文件匹配。'
|
||||
|
||||
if checkpoint_kind == CheckpointKind.AUTO_CONTINUE and not (stp_facts and stp_facts.get('multi_source_excel_block')):
|
||||
pause_reason = None
|
||||
pause_reason_code = None
|
||||
allowed_actions = [str(btn.get("id")) for btn in action_buttons if btn.get("id")]
|
||||
event_at = None
|
||||
if task.updated_at is not None:
|
||||
event_at = task.updated_at.isoformat()
|
||||
return {
|
||||
summary: dict[str, Any] = {
|
||||
"title": title,
|
||||
"message": message_by_checkpoint.get(str(checkpoint or ""), title),
|
||||
"message": message,
|
||||
"error_message": task.error_message or task.upload_error_message,
|
||||
"issues": issues,
|
||||
"stage": title,
|
||||
"checkpoint_kind": str(checkpoint_kind),
|
||||
"current_todo": _current_todo_label(checkpoint, action_buttons),
|
||||
"current_todo": (
|
||||
current_todo_override
|
||||
if current_todo_override is not None
|
||||
else (
|
||||
pause_reason
|
||||
if stp_facts and stp_facts.get('multi_source_excel_block')
|
||||
else _current_todo_label(checkpoint, action_buttons)
|
||||
)
|
||||
),
|
||||
"pause_reason": pause_reason,
|
||||
"pause_reason_code": pause_reason_code,
|
||||
"next_auto_step": (
|
||||
@@ -409,6 +536,9 @@ def _build_task_summary(
|
||||
"entry_surface": _entry_surface_for(checkpoint, checkpoint_kind),
|
||||
"allowed_actions": allowed_actions,
|
||||
}
|
||||
if stp_facts is not None:
|
||||
summary['stp_facts'] = stp_facts
|
||||
return summary
|
||||
|
||||
|
||||
def build_task_ui_state(task: ShippingTask) -> dict[str, Any]:
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/user_facing_status.py
|
||||
|
||||
用途:将任务 DB / 状态机内部码转为面向用户的中文阶段描述,并过滤 Tool 响应中的内部字段。
|
||||
依赖:models.ShippingTask、constants、state_machine.resolve_task_ui_state。
|
||||
逻辑:get_task_status 与 tool_response 序列化时调用,防止 Agent 向用户暴露 snake_case 状态码。
|
||||
逻辑:get_task_status 与 tool_response 序列化时调用;STP 多源阻断优先于通用 shortage 文案。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -50,8 +50,8 @@ _CHECKPOINT_LABELS: dict[str, str] = {
|
||||
"shortage_review": "库存不足,无法发货",
|
||||
CP_READY_MATCH: "待匹配库存",
|
||||
CP_READY_EXPORT: "待生成发货 Excel",
|
||||
CP_EXPORT_READY: "发货 Excel 已生成",
|
||||
CP_WAITING_UPLOAD: "待上传货代系统",
|
||||
CP_EXPORT_READY: "待人工上传登记",
|
||||
CP_WAITING_UPLOAD: "待人工上传登记",
|
||||
CP_UPLOAD_FAILED: "货代上传失败,待处理",
|
||||
CP_REJECTED: "任务已驳回",
|
||||
CP_UPLOADED: "已完成上传",
|
||||
@@ -65,7 +65,7 @@ _PROCESS_STATUS_LABELS: dict[str, str] = {
|
||||
"waiting_inventory": "待获取库存",
|
||||
"inventory_ready": "库存已就绪",
|
||||
"matched": "库存已匹配",
|
||||
"waiting_upload": "待上传货代系统",
|
||||
"waiting_upload": "待人工上传登记",
|
||||
"upload_failed": "货代上传失败",
|
||||
"uploaded": "已完成上传",
|
||||
"rejected": "已驳回",
|
||||
@@ -87,8 +87,12 @@ def user_facing_task_stage(task: ShippingTask) -> str:
|
||||
Short Chinese label for chat / get_task_status — no snake_case codes.
|
||||
|
||||
核心逻辑:优先返回更具体的 pending_human_reason 标签,避免 `rpa_pending`
|
||||
这类细粒度状态被通用 checkpoint(如“待上传或获取库存”)覆盖。
|
||||
这类细粒度状态被通用 checkpoint(如“待上传或获取库存”)覆盖;
|
||||
STP 多源 Excel 阻断覆盖通用 shortage 文案。
|
||||
"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
if payload.get('multi_source_excel_block'):
|
||||
return '多库存源冲突,待人工处理'
|
||||
reason = str(task.pending_human_reason or "").strip()
|
||||
if reason in _PENDING_REASON_LABELS:
|
||||
return _PENDING_REASON_LABELS[reason]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,304 @@
|
||||
"""
|
||||
services/shipping_notice/workflow_progress_projection.py
|
||||
|
||||
用途:将 Workflow / WorkflowItem / WorkflowEvent 投影为工作台只读 DTO(计数、阶段、摘要)。
|
||||
依赖:ShippingNoticeWorkflow* 模型、ShippingNoticeDocument、workflow_ledger_service、
|
||||
progress_audit_contract。
|
||||
逻辑:由 workspace/shipping_notice 工作流读接口调用;解决「Run 已建但 Item=0」——
|
||||
Item 在版面阶段即存在;会话投影返回全部 open Workflow(非仅第一条);
|
||||
counts.waiting_manual_upload 单独统计,不得并入 completed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ShippingNoticeDocument
|
||||
from app.models.shipping_notice_workflow import (
|
||||
ShippingNoticeWorkflow,
|
||||
ShippingNoticeWorkflowEvent,
|
||||
ShippingNoticeWorkflowItem,
|
||||
)
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
get_workflow_item_for_user,
|
||||
list_open_workflows_for_conversation,
|
||||
)
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
"""UTC ISO8601;空值保持 None。"""
|
||||
return value.isoformat() + 'Z' if value is not None else None
|
||||
|
||||
|
||||
def _document_filename(document_id: int | None) -> str | None:
|
||||
"""
|
||||
按 Document 主键解析展示用文件名。
|
||||
|
||||
Args:
|
||||
document_id: ShippingNoticeDocument.id。
|
||||
|
||||
Returns:
|
||||
filename 或 None。
|
||||
"""
|
||||
if document_id is None:
|
||||
return None
|
||||
document = db.session.get(ShippingNoticeDocument, int(document_id))
|
||||
if document is None:
|
||||
return None
|
||||
name = str(getattr(document, 'filename', None) or '').strip()
|
||||
return name or None
|
||||
|
||||
|
||||
def _item_counts(items: list[ShippingNoticeWorkflowItem]) -> dict[str, int]:
|
||||
"""
|
||||
汇总 Workflow 内 Item 用户态计数。
|
||||
|
||||
核心逻辑:processing 聚合 layout_parsing/extracting 及后续履约中态;
|
||||
waiting_manual_upload 仅 manual_upload_pending(非完成);
|
||||
completed 仅 closed/cancelled。
|
||||
"""
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
WORKFLOW_ITEM_TERMINAL_LIFECYCLE_STATUSES,
|
||||
WORKFLOW_ITEM_WAITING_MANUAL_UPLOAD_STATUSES,
|
||||
)
|
||||
|
||||
processing_statuses = frozenset({
|
||||
'queued',
|
||||
'layout_parsing',
|
||||
'extracting',
|
||||
'building_order',
|
||||
'inventory_matching',
|
||||
'generating_excel',
|
||||
'reparse_failed',
|
||||
})
|
||||
counts = Counter()
|
||||
for item in items:
|
||||
status = str(item.lifecycle_status or '').strip()
|
||||
if status in processing_statuses:
|
||||
counts['processing'] += 1
|
||||
elif status == 'pending_review':
|
||||
counts['pending_review'] += 1
|
||||
elif status == 'failed':
|
||||
counts['failed'] += 1
|
||||
elif status in WORKFLOW_ITEM_WAITING_MANUAL_UPLOAD_STATUSES:
|
||||
counts['waiting_manual_upload'] += 1
|
||||
elif status in WORKFLOW_ITEM_TERMINAL_LIFECYCLE_STATUSES:
|
||||
counts['completed'] += 1
|
||||
else:
|
||||
counts['processing'] += 1
|
||||
return {
|
||||
'total': len(items),
|
||||
'processing': int(counts['processing']),
|
||||
'pending_review': int(counts['pending_review']),
|
||||
'waiting_manual_upload': int(counts['waiting_manual_upload']),
|
||||
'failed': int(counts['failed']),
|
||||
'completed': int(counts['completed']),
|
||||
}
|
||||
|
||||
|
||||
def serialize_workflow_event(event: ShippingNoticeWorkflowEvent) -> dict[str, Any]:
|
||||
"""
|
||||
序列化单条用户可见 WorkflowEvent。
|
||||
|
||||
核心逻辑:返回 actor_type + actor_id,供任务处理台时间线追溯人工确认/取消/登记等操作人。
|
||||
|
||||
Args:
|
||||
event: WorkflowEvent ORM。
|
||||
|
||||
Returns:
|
||||
脱敏事件字典(含 actor_id;不含密钥类字段)。
|
||||
"""
|
||||
actor_id = str(event.actor_id or '').strip() or None
|
||||
return {
|
||||
'seq_no': int(event.seq_no or 0),
|
||||
'event_code': str(event.event_code or ''),
|
||||
'stage_code': str(event.stage_code or '') or None,
|
||||
'message_code': str(event.message_code or '') or None,
|
||||
'item_no': str(event.item_no or '') or None,
|
||||
'version_no': int(event.version_no) if event.version_no is not None else None,
|
||||
'actor_type': str(event.actor_type or ''),
|
||||
'actor_id': actor_id,
|
||||
'reason': str(event.reason or '') or None,
|
||||
'payload': dict(event.payload_json) if isinstance(event.payload_json, dict) else None,
|
||||
'occurred_at': _iso(event.occurred_at),
|
||||
}
|
||||
|
||||
|
||||
def serialize_workflow_item(
|
||||
item: ShippingNoticeWorkflowItem,
|
||||
*,
|
||||
include_events: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
序列化 WorkflowItem 用户态投影。
|
||||
|
||||
核心逻辑:附带当前/根 Document 文件名,供工作台列表直接展示 PDF 名。
|
||||
|
||||
Args:
|
||||
item: WorkflowItem ORM。
|
||||
include_events: True 时附带该 Item 的可见事件(按 seq 升序)。
|
||||
|
||||
Returns:
|
||||
Item DTO(含 current_document_filename / root_document_filename)。
|
||||
"""
|
||||
payload: dict[str, Any] = {
|
||||
'item_no': str(item.item_no),
|
||||
'workflow_no': str(item.workflow_no),
|
||||
'conversation_id': str(item.conversation_id),
|
||||
'root_document_id': int(item.root_document_id),
|
||||
'root_document_filename': _document_filename(item.root_document_id),
|
||||
'current_document_id': int(item.current_document_id),
|
||||
'current_document_filename': _document_filename(item.current_document_id),
|
||||
'current_version_no': int(item.current_version_no or 1),
|
||||
'current_run_no': str(item.current_run_no or '') or None,
|
||||
'current_case_no': str(item.current_case_no or '') or None,
|
||||
'current_task_no': str(item.current_task_no or '') or None,
|
||||
'lifecycle_status': str(item.lifecycle_status or ''),
|
||||
'current_stage': str(item.current_stage or ''),
|
||||
'closed_reason': str(item.closed_reason or '') or None,
|
||||
'lock_version': int(item.lock_version or 1),
|
||||
'last_activity_at': _iso(item.last_activity_at),
|
||||
'closed_at': _iso(item.closed_at),
|
||||
'created_at': _iso(item.created_at),
|
||||
'updated_at': _iso(item.updated_at),
|
||||
}
|
||||
if include_events:
|
||||
events = (
|
||||
ShippingNoticeWorkflowEvent.query
|
||||
.filter_by(workflow_item_id=int(item.id))
|
||||
.order_by(ShippingNoticeWorkflowEvent.seq_no.asc())
|
||||
.all()
|
||||
)
|
||||
payload['events'] = [serialize_workflow_event(row) for row in events]
|
||||
return payload
|
||||
|
||||
|
||||
def serialize_workflow(
|
||||
workflow: ShippingNoticeWorkflow,
|
||||
*,
|
||||
user_id: int | None = None,
|
||||
include_items: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
序列化 Workflow 及 Item 计数摘要。
|
||||
|
||||
Args:
|
||||
workflow: Workflow ORM。
|
||||
user_id: 可选属主校验;传入时仅统计该用户可见 Items(同会话属主一致)。
|
||||
include_items: True 时附带 items 摘要列表。
|
||||
|
||||
Returns:
|
||||
Workflow DTO(含 counts / current_stage / last_activity_at)。
|
||||
"""
|
||||
query = ShippingNoticeWorkflowItem.query.filter_by(workflow_id=int(workflow.id))
|
||||
if user_id is not None:
|
||||
query = query.filter_by(owner_user_id=int(user_id))
|
||||
items = query.order_by(
|
||||
ShippingNoticeWorkflowItem.updated_at.desc(),
|
||||
ShippingNoticeWorkflowItem.id.desc(),
|
||||
).all()
|
||||
payload: dict[str, Any] = {
|
||||
'workflow_no': str(workflow.workflow_no),
|
||||
'conversation_id': str(workflow.conversation_id),
|
||||
'status': str(workflow.status or ''),
|
||||
'current_stage': str(workflow.current_stage or ''),
|
||||
'closed_reason': str(workflow.closed_reason or '') or None,
|
||||
'lock_version': int(workflow.lock_version or 1),
|
||||
'counts': _item_counts(items),
|
||||
'last_activity_at': _iso(workflow.last_activity_at),
|
||||
'closed_at': _iso(workflow.closed_at),
|
||||
'created_at': _iso(workflow.created_at),
|
||||
'updated_at': _iso(workflow.updated_at),
|
||||
}
|
||||
if include_items:
|
||||
payload['items'] = [serialize_workflow_item(item) for item in items]
|
||||
return payload
|
||||
|
||||
|
||||
def get_workflow_for_user(*, user_id: int, workflow_no: str) -> ShippingNoticeWorkflow:
|
||||
"""
|
||||
按属主加载 Workflow。
|
||||
|
||||
Args:
|
||||
user_id: 属主用户。
|
||||
workflow_no: Workflow 业务编号。
|
||||
|
||||
Returns:
|
||||
ShippingNoticeWorkflow。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 不存在或不属于该用户。
|
||||
"""
|
||||
normalized = str(workflow_no or '').strip().upper()
|
||||
workflow = ShippingNoticeWorkflow.query.filter_by(
|
||||
workflow_no=normalized,
|
||||
owner_user_id=int(user_id),
|
||||
).first()
|
||||
if workflow is None:
|
||||
raise NotFoundError('Workflow not found', code='SHIPPING_NOTICE.WORKFLOW_NOT_FOUND')
|
||||
return workflow
|
||||
|
||||
|
||||
def project_conversation_workflows(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
投影会话内全部开放 Workflow 与 Items(版面阶段 Item 已存在)。
|
||||
|
||||
核心逻辑:按 conversation_id + owner 列出所有 open Workflow(updated_at 降序);
|
||||
同会话可并存多个未关闭上传批次,禁止只返回第一条。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户。
|
||||
conversation_id: 聊天会话 ID。
|
||||
|
||||
Returns:
|
||||
``{'conversation_id', 'workflows': [...]}``。
|
||||
|
||||
Raises:
|
||||
ValidationError: conversation_id 为空。
|
||||
"""
|
||||
normalized = str(conversation_id or '').strip()
|
||||
if not normalized:
|
||||
raise ValidationError(
|
||||
'conversation_id is required',
|
||||
code='SHIPPING_NOTICE.WORKFLOW_CONVERSATION_REQUIRED',
|
||||
)
|
||||
open_workflows = list_open_workflows_for_conversation(
|
||||
conversation_id=normalized,
|
||||
owner_user_id=int(user_id),
|
||||
)
|
||||
return {
|
||||
'conversation_id': normalized,
|
||||
'workflows': [
|
||||
serialize_workflow(row, user_id=int(user_id), include_items=True)
|
||||
for row in open_workflows
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def get_workflow_item_dto_for_user(
|
||||
*,
|
||||
user_id: int,
|
||||
item_no: str,
|
||||
include_events: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
属主可见 WorkflowItem 详情;内部复用 ledger 加载。
|
||||
|
||||
Args:
|
||||
user_id: 属主。
|
||||
item_no: Item 编号。
|
||||
include_events: 是否包含事件时间线。
|
||||
|
||||
Returns:
|
||||
Item DTO。
|
||||
"""
|
||||
item = get_workflow_item_for_user(user_id=int(user_id), item_no=str(item_no))
|
||||
return serialize_workflow_item(item, include_events=include_events)
|
||||
@@ -0,0 +1,92 @@
|
||||
"""
|
||||
migrations/versions/4e7a1c9b2d3f_align_shipping_order_line_contract.py
|
||||
|
||||
用途:允许 Header/Line 同名 Reservation 字段资产,并补齐订单级 Reservation 标准资产。
|
||||
依赖:shipping_order_fields、字段资产注册表。
|
||||
逻辑:唯一键由 field_code 收敛为 (field_code, scope),使行级值可安全覆盖订单头值;
|
||||
仅补齐字段目录,不改历史 Schema 版本或履约数据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '4e7a1c9b2d3f'
|
||||
down_revision = '3d6e8f0a1b2c'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""替换字段资产唯一键,并幂等补齐 Header reservation_id。"""
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
constraints = {item.get('name') for item in inspector.get_unique_constraints('shipping_order_fields')}
|
||||
if 'uq_shipping_order_fields_field_code' in constraints:
|
||||
with op.batch_alter_table('shipping_order_fields') as batch:
|
||||
batch.drop_constraint('uq_shipping_order_fields_field_code', type_='unique')
|
||||
inspector = sa.inspect(bind)
|
||||
constraints = {item.get('name') for item in inspector.get_unique_constraints('shipping_order_fields')}
|
||||
if 'uq_shipping_order_fields_code_scope' not in constraints:
|
||||
with op.batch_alter_table('shipping_order_fields') as batch:
|
||||
batch.create_unique_constraint('uq_shipping_order_fields_code_scope', ['field_code', 'scope'])
|
||||
|
||||
exists = bind.execute(sa.text(
|
||||
"SELECT 1 FROM shipping_order_fields WHERE field_code = 'reservation_id' AND scope = 'header'"
|
||||
)).scalar()
|
||||
if not exists:
|
||||
now = datetime.utcnow()
|
||||
bind.execute(sa.text(
|
||||
"""INSERT INTO shipping_order_fields
|
||||
(id, field_code, scope, value_type, field_category, collection_mode, asset_kind,
|
||||
storage_mode, storage_column, semantic_description, display_name_default,
|
||||
fulfillment_role, display_sequence, status, published_once, created_at, updated_at)
|
||||
VALUES (:id, 'reservation_id', 'header', 'string', 'order_header', 'llm_extraction',
|
||||
'system_standard', 'json_only', NULL, :semantic, :display_name, NULL,
|
||||
:sequence, 'active', false, :now, :now)"""
|
||||
), {
|
||||
'id': str(uuid.uuid4()),
|
||||
'semantic': '可选的订单级库存占用/预约单标识;明细可覆盖',
|
||||
'display_name': '预约单号',
|
||||
'sequence': 24, 'now': now,
|
||||
})
|
||||
bind.execute(sa.text(
|
||||
"""UPDATE shipping_order_fields
|
||||
SET display_name_default = :display_name, semantic_description = :semantic, updated_at = :now
|
||||
WHERE field_code = 'line_no' AND scope = 'line'"""
|
||||
), {
|
||||
'display_name': '内部项次',
|
||||
'semantic': (
|
||||
'内部业务项次;可识别、可由 Schema 派生规则补齐、冻结前可人工覆盖;'
|
||||
'仅接受 1–6 位数字并保留前导零;与 Excel 导出行序号 export_sequence 无关'
|
||||
),
|
||||
'now': datetime.utcnow(),
|
||||
})
|
||||
bind.execute(sa.text(
|
||||
"""UPDATE shipping_order_fields
|
||||
SET semantic_description = :semantic, updated_at = :now
|
||||
WHERE field_code = 'customer_po_line_no' AND scope = 'line'"""
|
||||
), {
|
||||
'semantic': '客户采购订单原始 Item No./LN/Line#;必须按字符串保留前导零;识别/复核后永久保留原始事实',
|
||||
'now': datetime.utcnow(),
|
||||
})
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""仅在未采用 Header Reservation 时允许恢复旧的单编码唯一键。"""
|
||||
bind = op.get_bind()
|
||||
definition_column = 'definition_json::text' if bind.dialect.name == 'postgresql' else 'definition_json'
|
||||
used = bind.execute(sa.text(
|
||||
f"SELECT 1 FROM shipping_order_schema_versions WHERE {definition_column} LIKE '%\"reservation_id\"%' LIMIT 1"
|
||||
)).scalar()
|
||||
if used:
|
||||
raise RuntimeError('Cannot downgrade while reservation_id is present in Schema history')
|
||||
bind.execute(sa.text("DELETE FROM shipping_order_fields WHERE field_code = 'reservation_id' AND scope = 'header'"))
|
||||
with op.batch_alter_table('shipping_order_fields') as batch:
|
||||
batch.drop_constraint('uq_shipping_order_fields_code_scope', type_='unique')
|
||||
batch.create_unique_constraint('uq_shipping_order_fields_field_code', ['field_code'])
|
||||
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
migrations/versions/5f8b2d4e6a1c_restore_shipping_context_field_assets.py
|
||||
|
||||
用途:恢复邮件确定性上下文字段资产约束与种子(sender_email / sender_domain)。
|
||||
依赖:shipping_order_fields、字段资产治理迁移 1b2c3d4e5f6a / 4e7a1c9b2d3f。
|
||||
逻辑:放宽 field_category / collection_mode CHECK;幂等插入两条 general_context 资产。
|
||||
create_extension 仍禁止同名编码,仅种子与 ensure_context_assets_seeded 可写入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '5f8b2d4e6a1c'
|
||||
down_revision = '4e7a1c9b2d3f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""放宽字段分类/采集模式约束,并幂等补齐上下文字段资产。"""
|
||||
bind = op.get_bind()
|
||||
dialect = bind.dialect.name
|
||||
# SQLite 测试库多由 metadata.create_all 建表,约束以 ORM 模型为准;此处只对 PG 放宽 CHECK。
|
||||
if dialect != 'sqlite':
|
||||
op.execute(sa.text('ALTER TABLE shipping_order_fields DROP CONSTRAINT IF EXISTS ck_shipping_order_fields_category'))
|
||||
op.execute(sa.text('ALTER TABLE shipping_order_fields DROP CONSTRAINT IF EXISTS ck_shipping_order_fields_collection_mode'))
|
||||
op.execute(sa.text(
|
||||
"ALTER TABLE shipping_order_fields ADD CONSTRAINT ck_shipping_order_fields_category "
|
||||
"CHECK (field_category IN ('general_context', 'order_header', 'order_line'))"
|
||||
))
|
||||
op.execute(sa.text(
|
||||
"ALTER TABLE shipping_order_fields ADD CONSTRAINT ck_shipping_order_fields_collection_mode "
|
||||
"CHECK (collection_mode IN ('deterministic_context', 'llm_extraction'))"
|
||||
))
|
||||
|
||||
now = datetime.utcnow()
|
||||
for code, display_name, semantic in (
|
||||
(
|
||||
'sender_email',
|
||||
'发件人邮箱',
|
||||
'从原始 EML From 确定性采集的发件人邮箱;不可经扩展资产 API 创建。',
|
||||
),
|
||||
(
|
||||
'sender_domain',
|
||||
'发件人域名',
|
||||
'从原始 EML From 确定性采集的发件人域名;不可经扩展资产 API 创建。',
|
||||
),
|
||||
):
|
||||
exists = bind.execute(sa.text(
|
||||
"SELECT 1 FROM shipping_order_fields WHERE field_code = :code AND scope = 'header'"
|
||||
), {'code': code}).first()
|
||||
if exists:
|
||||
bind.execute(sa.text(
|
||||
"UPDATE shipping_order_fields SET "
|
||||
"field_category = 'general_context', collection_mode = 'deterministic_context', "
|
||||
"storage_mode = 'json_only', storage_column = NULL, status = 'active', "
|
||||
"display_name_default = COALESCE(NULLIF(display_name_default, ''), :display_name), "
|
||||
"semantic_description = COALESCE(NULLIF(semantic_description, ''), :semantic), "
|
||||
"updated_at = :now "
|
||||
"WHERE field_code = :code AND scope = 'header'"
|
||||
), {
|
||||
'code': code,
|
||||
'display_name': display_name,
|
||||
'semantic': semantic,
|
||||
'now': now,
|
||||
})
|
||||
continue
|
||||
bind.execute(sa.text(
|
||||
"INSERT INTO shipping_order_fields ("
|
||||
"id, field_code, scope, value_type, field_category, collection_mode, "
|
||||
"asset_kind, storage_mode, storage_column, semantic_description, display_name_default, "
|
||||
"fulfillment_role, display_sequence, status, published_once, created_at, updated_at"
|
||||
") VALUES ("
|
||||
":id, :code, 'header', 'string', 'general_context', 'deterministic_context', "
|
||||
"'extension', 'json_only', NULL, :semantic, :display_name, "
|
||||
"NULL, 0, 'active', false, :now, :now)"
|
||||
), {
|
||||
'id': str(uuid.uuid4()),
|
||||
'code': code,
|
||||
'semantic': semantic,
|
||||
'display_name': display_name,
|
||||
'now': now,
|
||||
})
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除上下文字段资产并收紧约束(回滚仅用于开发环境)。"""
|
||||
bind = op.get_bind()
|
||||
dialect = bind.dialect.name
|
||||
bind.execute(sa.text(
|
||||
"DELETE FROM shipping_order_fields WHERE field_code IN ('sender_email', 'sender_domain') "
|
||||
"AND field_category = 'general_context'"
|
||||
))
|
||||
if dialect == 'sqlite':
|
||||
return
|
||||
op.execute(sa.text('ALTER TABLE shipping_order_fields DROP CONSTRAINT IF EXISTS ck_shipping_order_fields_category'))
|
||||
op.execute(sa.text('ALTER TABLE shipping_order_fields DROP CONSTRAINT IF EXISTS ck_shipping_order_fields_collection_mode'))
|
||||
op.execute(sa.text(
|
||||
"ALTER TABLE shipping_order_fields ADD CONSTRAINT ck_shipping_order_fields_category "
|
||||
"CHECK (field_category IN ('order_header', 'order_line'))"
|
||||
))
|
||||
op.execute(sa.text(
|
||||
"ALTER TABLE shipping_order_fields ADD CONSTRAINT ck_shipping_order_fields_collection_mode "
|
||||
"CHECK (collection_mode IN ('llm_extraction'))"
|
||||
))
|
||||
@@ -0,0 +1,33 @@
|
||||
"""
|
||||
migrations/versions/6a9c3e5f7b2d_make_shipping_audit_events_permanent.py
|
||||
|
||||
用途:将货代统一审计账本改为全量永久保留。
|
||||
依赖:shipping_audit_events.retention_expires_at。
|
||||
逻辑:把既有行的 retention_expires_at 置空;清理 Job 仅删除仍带到期时间的遗留行(本迁移后应为 0)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '6a9c3e5f7b2d'
|
||||
down_revision = '5f8b2d4e6a1c'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""清空全部审计到期时间,使既有与新增事件均永久保留。"""
|
||||
op.execute(sa.text('UPDATE shipping_audit_events SET retention_expires_at = NULL'))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""
|
||||
回滚不恢复历史到期时间(信息已丢弃)。
|
||||
|
||||
新写入若再次启用默认三年策略,由应用层 default_retention_expires_at 决定;
|
||||
本函数仅作空操作,避免伪造错误的到期时间。
|
||||
"""
|
||||
return
|
||||
@@ -0,0 +1,77 @@
|
||||
"""
|
||||
migrations/versions/7b0d4f6a8c3e_expand_shipping_inventory_source_checks.py
|
||||
|
||||
用途:扩展 shipping_tasks 库存源 status/method 检查约束,对齐 STP 建单冻结与行级匹配写入值。
|
||||
依赖:ck_shipping_tasks_inventory_source_status / ck_shipping_tasks_inventory_source_method(d6e7f8a9b0c1)。
|
||||
逻辑:删除旧 CHECK 后重建,纳入 candidates_frozen 与 stp_* / snapshot_match 等方法;否则确认建单 flush 会 500。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = '7b0d4f6a8c3e'
|
||||
down_revision = '6a9c3e5f7b2d'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
# 与 STP/库存门禁当前写入值对齐;保留历史 gate 枚举以免存量行无法回写。
|
||||
_STATUS_VALUES = (
|
||||
'resolved',
|
||||
'user_confirmed',
|
||||
'ambiguous',
|
||||
'unresolved',
|
||||
'invalid',
|
||||
'conflicted',
|
||||
'candidates_frozen',
|
||||
)
|
||||
_METHOD_VALUES = (
|
||||
'rule_exact',
|
||||
'rule_combined',
|
||||
'rule',
|
||||
'user_confirmed',
|
||||
'legacy_migrated',
|
||||
'manual',
|
||||
'manual_multi_source_resolve',
|
||||
'snapshot_match',
|
||||
'stp_build_freeze',
|
||||
'stp_line_match',
|
||||
'stp_line_match_multi',
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""重建 status/method CHECK,允许 STP 冻结与行级匹配枚举。"""
|
||||
op.drop_constraint('ck_shipping_tasks_inventory_source_status', 'shipping_tasks', type_='check')
|
||||
op.drop_constraint('ck_shipping_tasks_inventory_source_method', 'shipping_tasks', type_='check')
|
||||
status_list = ', '.join(f"'{item}'" for item in _STATUS_VALUES)
|
||||
method_list = ', '.join(f"'{item}'" for item in _METHOD_VALUES)
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_tasks_inventory_source_status',
|
||||
'shipping_tasks',
|
||||
f'inventory_source_status IS NULL OR inventory_source_status IN ({status_list})',
|
||||
)
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_tasks_inventory_source_method',
|
||||
'shipping_tasks',
|
||||
f'inventory_source_method IS NULL OR inventory_source_method IN ({method_list})',
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""恢复 d6e7f8a9b0c1 时期的窄枚举;若已有 STP 新值行,回滚会失败。"""
|
||||
op.drop_constraint('ck_shipping_tasks_inventory_source_status', 'shipping_tasks', type_='check')
|
||||
op.drop_constraint('ck_shipping_tasks_inventory_source_method', 'shipping_tasks', type_='check')
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_tasks_inventory_source_status',
|
||||
'shipping_tasks',
|
||||
"inventory_source_status IS NULL OR inventory_source_status IN "
|
||||
"('resolved', 'user_confirmed', 'ambiguous', 'unresolved', 'invalid', 'conflicted')",
|
||||
)
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_tasks_inventory_source_method',
|
||||
'shipping_tasks',
|
||||
"inventory_source_method IS NULL OR inventory_source_method IN "
|
||||
"('rule_exact', 'rule_combined', 'user_confirmed', 'legacy_migrated', 'manual')",
|
||||
)
|
||||
@@ -0,0 +1,132 @@
|
||||
"""
|
||||
migrations/versions/8c1e5a7b9d0f_shipping_audit_workflow_hash_chain.py
|
||||
|
||||
用途:将 shipping_audit_events 从 session_item 软引用迁移为 Workflow 软引用并增加哈希链字段。
|
||||
依赖:shipping_audit_events(3d6e8f0a1b2c / 2b4c6d8e0f1a 等既有列)。
|
||||
逻辑:删除 session_item_id 及其索引;新增 workflow_* / version_no / actor_display /
|
||||
diff_json / previous_event_hash / event_hash / sensitivity_level 与对应索引。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '8c1e5a7b9d0f'
|
||||
down_revision = '7b0d4f6a8c3e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _columns(inspector: sa.Inspector, table_name: str) -> set[str]:
|
||||
return {column['name'] for column in inspector.get_columns(table_name)}
|
||||
|
||||
|
||||
def _indexes(inspector: sa.Inspector, table_name: str) -> set[str]:
|
||||
return {index['name'] for index in inspector.get_indexes(table_name)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""追加 Workflow 软引用与哈希链列;移除 session_item_id。"""
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
if 'shipping_audit_events' not in set(inspector.get_table_names()):
|
||||
return
|
||||
|
||||
cols = _columns(inspector, 'shipping_audit_events')
|
||||
indexes = _indexes(inspector, 'shipping_audit_events')
|
||||
|
||||
if 'ix_shipping_audit_events_session_item_created' in indexes:
|
||||
op.drop_index(
|
||||
'ix_shipping_audit_events_session_item_created',
|
||||
table_name='shipping_audit_events',
|
||||
)
|
||||
|
||||
if 'session_item_id' in cols:
|
||||
op.drop_column('shipping_audit_events', 'session_item_id')
|
||||
|
||||
add_specs: list[tuple[str, sa.Column]] = [
|
||||
('workflow_id', sa.Column('workflow_id', sa.String(length=64), nullable=True)),
|
||||
('workflow_item_id', sa.Column('workflow_item_id', sa.String(length=64), nullable=True)),
|
||||
(
|
||||
'workflow_item_version_id',
|
||||
sa.Column('workflow_item_version_id', sa.String(length=64), nullable=True),
|
||||
),
|
||||
('version_no', sa.Column('version_no', sa.Integer(), nullable=True)),
|
||||
('actor_display', sa.Column('actor_display', sa.String(length=128), nullable=True)),
|
||||
('diff_json', sa.Column('diff_json', sa.JSON(), nullable=True)),
|
||||
('previous_event_hash', sa.Column('previous_event_hash', sa.String(length=64), nullable=True)),
|
||||
('event_hash', sa.Column('event_hash', sa.String(length=64), nullable=True)),
|
||||
('sensitivity_level', sa.Column('sensitivity_level', sa.String(length=16), nullable=True)),
|
||||
]
|
||||
cols = _columns(sa.inspect(bind), 'shipping_audit_events')
|
||||
for name, column in add_specs:
|
||||
if name not in cols:
|
||||
op.add_column('shipping_audit_events', column)
|
||||
|
||||
indexes = _indexes(sa.inspect(bind), 'shipping_audit_events')
|
||||
if 'ix_shipping_audit_events_workflow_created' not in indexes:
|
||||
op.create_index(
|
||||
'ix_shipping_audit_events_workflow_created',
|
||||
'shipping_audit_events',
|
||||
['workflow_id', 'created_at'],
|
||||
)
|
||||
if 'ix_shipping_audit_events_workflow_item_created' not in indexes:
|
||||
op.create_index(
|
||||
'ix_shipping_audit_events_workflow_item_created',
|
||||
'shipping_audit_events',
|
||||
['workflow_item_id', 'created_at'],
|
||||
)
|
||||
if 'ix_shipping_audit_events_event_hash' not in indexes:
|
||||
op.create_index(
|
||||
'ix_shipping_audit_events_event_hash',
|
||||
'shipping_audit_events',
|
||||
['event_hash'],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回滚哈希链与 Workflow 列,恢复 session_item_id。"""
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
if 'shipping_audit_events' not in set(inspector.get_table_names()):
|
||||
return
|
||||
|
||||
indexes = _indexes(inspector, 'shipping_audit_events')
|
||||
for index_name in (
|
||||
'ix_shipping_audit_events_event_hash',
|
||||
'ix_shipping_audit_events_workflow_item_created',
|
||||
'ix_shipping_audit_events_workflow_created',
|
||||
):
|
||||
if index_name in indexes:
|
||||
op.drop_index(index_name, table_name='shipping_audit_events')
|
||||
|
||||
cols = _columns(sa.inspect(bind), 'shipping_audit_events')
|
||||
for column_name in (
|
||||
'sensitivity_level',
|
||||
'event_hash',
|
||||
'previous_event_hash',
|
||||
'diff_json',
|
||||
'actor_display',
|
||||
'version_no',
|
||||
'workflow_item_version_id',
|
||||
'workflow_item_id',
|
||||
'workflow_id',
|
||||
):
|
||||
if column_name in cols:
|
||||
op.drop_column('shipping_audit_events', column_name)
|
||||
|
||||
cols = _columns(sa.inspect(bind), 'shipping_audit_events')
|
||||
if 'session_item_id' not in cols:
|
||||
op.add_column(
|
||||
'shipping_audit_events',
|
||||
sa.Column('session_item_id', sa.String(length=64), nullable=True),
|
||||
)
|
||||
indexes = _indexes(sa.inspect(bind), 'shipping_audit_events')
|
||||
if 'ix_shipping_audit_events_session_item_created' not in indexes:
|
||||
op.create_index(
|
||||
'ix_shipping_audit_events_session_item_created',
|
||||
'shipping_audit_events',
|
||||
['session_item_id', 'created_at'],
|
||||
)
|
||||
+391
@@ -0,0 +1,391 @@
|
||||
"""
|
||||
migrations/versions/9d2f4a6b8c0e_replace_session_work_items_with_workflows.py
|
||||
|
||||
用途:创建 Workflow / Item / Version / Event 四表,并删除旧会话工作项表(不做历史数据迁移)。
|
||||
依赖:users、agents、shipping_notice_documents、shipping_order_extraction_runs、
|
||||
shipping_order_review_cases、shipping_tasks;审计列迁移 8c1e5a7b9d0f。
|
||||
逻辑:若缺则创建 Workflow 四表 → DROP shipping_session_pdf_work_items(若存在,不迁数据);
|
||||
downgrade 仅删除 Workflow 四表(不重建旧会话工作项表)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '9d2f4a6b8c0e'
|
||||
down_revision = '8c1e5a7b9d0f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _tables(inspector: sa.Inspector) -> set[str]:
|
||||
return set(inspector.get_table_names())
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建 Workflow 四表(若缺),并直接删除旧会话工作项表(不迁移历史数据)。"""
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
tables = _tables(inspector)
|
||||
|
||||
if 'shipping_notice_workflows' not in tables:
|
||||
op.create_table(
|
||||
'shipping_notice_workflows',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('workflow_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('conversation_id', sa.String(length=100), nullable=False),
|
||||
sa.Column('owner_user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('owner_agent_id', sa.Integer(), nullable=True),
|
||||
sa.Column('status', sa.String(length=32), nullable=False, server_default='open'),
|
||||
sa.Column('current_stage', sa.String(length=64), nullable=False, server_default='queued'),
|
||||
sa.Column('last_activity_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('closed_reason', sa.String(length=64), nullable=True),
|
||||
sa.Column('closed_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('lock_version', sa.Integer(), nullable=False, server_default='1'),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.CheckConstraint(
|
||||
"status IN ('open', 'completed', 'cancelled', 'failed')",
|
||||
name='ck_shipping_notice_workflows_status',
|
||||
),
|
||||
sa.CheckConstraint('lock_version >= 1', name='ck_shipping_notice_workflows_lock_version'),
|
||||
sa.ForeignKeyConstraint(['owner_user_id'], ['users.id']),
|
||||
sa.ForeignKeyConstraint(['owner_agent_id'], ['agents.id']),
|
||||
sa.UniqueConstraint('workflow_no', name='uq_shipping_notice_workflows_no'),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflows_conversation_id',
|
||||
'shipping_notice_workflows',
|
||||
['conversation_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflows_owner_user_id',
|
||||
'shipping_notice_workflows',
|
||||
['owner_user_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflows_owner_agent_id',
|
||||
'shipping_notice_workflows',
|
||||
['owner_agent_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflows_conversation_status',
|
||||
'shipping_notice_workflows',
|
||||
['conversation_id', 'status', 'updated_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflows_owner_status',
|
||||
'shipping_notice_workflows',
|
||||
['owner_user_id', 'status', 'updated_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflows_open_conversation',
|
||||
'shipping_notice_workflows',
|
||||
['conversation_id', 'updated_at'],
|
||||
postgresql_where=sa.text("status = 'open'"),
|
||||
sqlite_where=sa.text("status = 'open'"),
|
||||
)
|
||||
|
||||
tables = _tables(sa.inspect(bind))
|
||||
if 'shipping_notice_workflow_items' not in tables:
|
||||
op.create_table(
|
||||
'shipping_notice_workflow_items',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('item_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('workflow_id', sa.Integer(), nullable=False),
|
||||
sa.Column('workflow_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('conversation_id', sa.String(length=100), nullable=False),
|
||||
sa.Column('owner_user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('root_document_id', sa.Integer(), nullable=False),
|
||||
sa.Column('current_document_id', sa.Integer(), nullable=False),
|
||||
sa.Column('current_version_id', sa.Integer(), nullable=True),
|
||||
sa.Column('current_version_no', sa.Integer(), nullable=False, server_default='1'),
|
||||
sa.Column('current_run_id', sa.Integer(), nullable=True),
|
||||
sa.Column('current_run_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('current_case_id', sa.Integer(), nullable=True),
|
||||
sa.Column('current_case_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('current_task_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('lifecycle_status', sa.String(length=32), nullable=False, server_default='queued'),
|
||||
sa.Column('current_stage', sa.String(length=64), nullable=False, server_default='queued'),
|
||||
sa.Column('closed_reason', sa.String(length=32), nullable=True),
|
||||
sa.Column('closed_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('last_activity_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('lock_version', sa.Integer(), nullable=False, server_default='1'),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.CheckConstraint(
|
||||
"lifecycle_status IN ("
|
||||
"'queued', 'layout_parsing', 'extracting', 'pending_review', "
|
||||
"'building_order', 'inventory_matching', 'generating_excel', "
|
||||
"'excel_ready', 'reparse_failed', 'cancelled', 'failed', 'closed'"
|
||||
")",
|
||||
name='ck_shipping_notice_workflow_items_lifecycle',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"closed_reason IS NULL OR closed_reason IN ("
|
||||
"'confirmed', 'non_order', 'user_cancelled', 'admin_terminated', 'failed'"
|
||||
")",
|
||||
name='ck_shipping_notice_workflow_items_closed_reason',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
'lock_version >= 1',
|
||||
name='ck_shipping_notice_workflow_items_lock_version',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
'current_version_no >= 1',
|
||||
name='ck_shipping_notice_workflow_items_version_no',
|
||||
),
|
||||
sa.ForeignKeyConstraint(['workflow_id'], ['shipping_notice_workflows.id']),
|
||||
sa.ForeignKeyConstraint(['owner_user_id'], ['users.id']),
|
||||
sa.ForeignKeyConstraint(['root_document_id'], ['shipping_notice_documents.id']),
|
||||
sa.ForeignKeyConstraint(['current_document_id'], ['shipping_notice_documents.id']),
|
||||
sa.ForeignKeyConstraint(['current_run_id'], ['shipping_order_extraction_runs.id']),
|
||||
sa.ForeignKeyConstraint(['current_case_id'], ['shipping_order_review_cases.id']),
|
||||
sa.UniqueConstraint('item_no', name='uq_shipping_notice_workflow_items_no'),
|
||||
sa.UniqueConstraint(
|
||||
'workflow_id',
|
||||
'root_document_id',
|
||||
name='uq_shipping_notice_workflow_items_workflow_root_doc',
|
||||
),
|
||||
sa.UniqueConstraint(
|
||||
'current_case_id',
|
||||
name='uq_shipping_notice_workflow_items_current_case',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_workflow_id',
|
||||
'shipping_notice_workflow_items',
|
||||
['workflow_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_workflow_no',
|
||||
'shipping_notice_workflow_items',
|
||||
['workflow_no'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_conversation_id',
|
||||
'shipping_notice_workflow_items',
|
||||
['conversation_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_owner_user_id',
|
||||
'shipping_notice_workflow_items',
|
||||
['owner_user_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_root_document_id',
|
||||
'shipping_notice_workflow_items',
|
||||
['root_document_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_current_document_id',
|
||||
'shipping_notice_workflow_items',
|
||||
['current_document_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_current_version_id',
|
||||
'shipping_notice_workflow_items',
|
||||
['current_version_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_current_run_id',
|
||||
'shipping_notice_workflow_items',
|
||||
['current_run_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_workflow_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
['workflow_id', 'lifecycle_status', 'updated_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_conversation_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
['conversation_id', 'lifecycle_status', 'updated_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_owner_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
['owner_user_id', 'lifecycle_status', 'updated_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
'shipping_notice_workflow_items',
|
||||
['conversation_id', 'updated_at'],
|
||||
postgresql_where=sa.text(
|
||||
"lifecycle_status NOT IN ('closed', 'cancelled', 'excel_ready')"
|
||||
),
|
||||
sqlite_where=sa.text(
|
||||
"lifecycle_status NOT IN ('closed', 'cancelled', 'excel_ready')"
|
||||
),
|
||||
)
|
||||
|
||||
tables = _tables(sa.inspect(bind))
|
||||
if 'shipping_notice_workflow_item_versions' not in tables:
|
||||
op.create_table(
|
||||
'shipping_notice_workflow_item_versions',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('workflow_item_id', sa.Integer(), nullable=False),
|
||||
sa.Column('item_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('workflow_id', sa.Integer(), nullable=False),
|
||||
sa.Column('workflow_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('version_no', sa.Integer(), nullable=False, server_default='1'),
|
||||
sa.Column('document_id', sa.Integer(), nullable=False),
|
||||
sa.Column('run_id', sa.Integer(), nullable=True),
|
||||
sa.Column('run_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('case_id', sa.Integer(), nullable=True),
|
||||
sa.Column('case_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('task_id', sa.Integer(), nullable=True),
|
||||
sa.Column('task_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('excel_artifact_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('status', sa.String(length=32), nullable=False, server_default='active'),
|
||||
sa.Column('is_current', sa.Boolean(), nullable=False, server_default=sa.text('true')),
|
||||
sa.Column('is_readonly', sa.Boolean(), nullable=False, server_default=sa.text('false')),
|
||||
sa.Column('superseded_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.CheckConstraint(
|
||||
'version_no >= 1',
|
||||
name='ck_shipping_notice_workflow_item_versions_no',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"status IN ('active', 'superseded', 'failed', 'cancelled')",
|
||||
name='ck_shipping_notice_workflow_item_versions_status',
|
||||
),
|
||||
sa.ForeignKeyConstraint(['workflow_item_id'], ['shipping_notice_workflow_items.id']),
|
||||
sa.ForeignKeyConstraint(['workflow_id'], ['shipping_notice_workflows.id']),
|
||||
sa.ForeignKeyConstraint(['document_id'], ['shipping_notice_documents.id']),
|
||||
sa.ForeignKeyConstraint(['run_id'], ['shipping_order_extraction_runs.id']),
|
||||
sa.ForeignKeyConstraint(['case_id'], ['shipping_order_review_cases.id']),
|
||||
sa.ForeignKeyConstraint(['task_id'], ['shipping_tasks.id']),
|
||||
sa.UniqueConstraint(
|
||||
'workflow_item_id',
|
||||
'version_no',
|
||||
name='uq_shipping_notice_workflow_item_versions_item_no',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_item_versions_workflow_item_id',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
['workflow_item_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_item_versions_item_no',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
['item_no'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_item_versions_workflow_id',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
['workflow_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_item_versions_workflow_no',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
['workflow_no'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_item_versions_document_id',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
['document_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_item_versions_item_created',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
['workflow_item_id', 'created_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_item_versions_run',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
['run_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_item_versions_case',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
['case_id'],
|
||||
)
|
||||
|
||||
tables = _tables(sa.inspect(bind))
|
||||
if 'shipping_notice_workflow_events' not in tables:
|
||||
op.create_table(
|
||||
'shipping_notice_workflow_events',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('workflow_id', sa.Integer(), nullable=False),
|
||||
sa.Column('workflow_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('workflow_item_id', sa.Integer(), nullable=True),
|
||||
sa.Column('item_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('workflow_item_version_id', sa.Integer(), nullable=True),
|
||||
sa.Column('version_no', sa.Integer(), nullable=True),
|
||||
sa.Column('seq_no', sa.Integer(), nullable=False),
|
||||
sa.Column('event_code', sa.String(length=64), nullable=False),
|
||||
sa.Column('stage_code', sa.String(length=64), nullable=True),
|
||||
sa.Column('message_code', sa.String(length=128), nullable=True),
|
||||
sa.Column('actor_type', sa.String(length=16), nullable=False, server_default='system'),
|
||||
sa.Column('actor_id', sa.String(length=128), nullable=True),
|
||||
sa.Column('payload_json', sa.JSON(), nullable=True),
|
||||
sa.Column('reason', sa.Text(), nullable=True),
|
||||
sa.Column('occurred_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['workflow_id'], ['shipping_notice_workflows.id']),
|
||||
sa.ForeignKeyConstraint(['workflow_item_id'], ['shipping_notice_workflow_items.id']),
|
||||
sa.ForeignKeyConstraint(
|
||||
['workflow_item_version_id'],
|
||||
['shipping_notice_workflow_item_versions.id'],
|
||||
),
|
||||
sa.UniqueConstraint(
|
||||
'workflow_id',
|
||||
'seq_no',
|
||||
name='uq_shipping_notice_workflow_events_seq',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_events_workflow_id',
|
||||
'shipping_notice_workflow_events',
|
||||
['workflow_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_events_workflow_no',
|
||||
'shipping_notice_workflow_events',
|
||||
['workflow_no'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_events_workflow_item_id',
|
||||
'shipping_notice_workflow_events',
|
||||
['workflow_item_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_events_item_no',
|
||||
'shipping_notice_workflow_events',
|
||||
['item_no'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_events_workflow_occurred',
|
||||
'shipping_notice_workflow_events',
|
||||
['workflow_id', 'occurred_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_events_item_occurred',
|
||||
'shipping_notice_workflow_events',
|
||||
['workflow_item_id', 'occurred_at'],
|
||||
)
|
||||
|
||||
# [STEP] 丢弃旧会话工作项表;不迁移历史行到 Workflow。
|
||||
tables = _tables(sa.inspect(bind))
|
||||
if 'shipping_session_pdf_work_items' in tables:
|
||||
op.drop_table('shipping_session_pdf_work_items')
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""仅删除 Workflow 四表;不重建旧会话工作项表。"""
|
||||
bind = op.get_bind()
|
||||
tables = _tables(sa.inspect(bind))
|
||||
|
||||
for table_name in (
|
||||
'shipping_notice_workflow_events',
|
||||
'shipping_notice_workflow_item_versions',
|
||||
'shipping_notice_workflow_items',
|
||||
'shipping_notice_workflows',
|
||||
):
|
||||
if table_name in tables:
|
||||
op.drop_table(table_name)
|
||||
@@ -0,0 +1,97 @@
|
||||
"""
|
||||
migrations/versions/a0e1f2b3c4d5_shipping_audit_append_only_triggers.py
|
||||
|
||||
用途:为 shipping_audit_events 增加 PostgreSQL 层 append-only 触发器。
|
||||
依赖:shipping_audit_events(迁移 9d2f4a6b8c0e 之后);保留期清理依赖 GUC hxops.shipping_audit_purge。
|
||||
逻辑:UPDATE 一律拒绝;DELETE 仅当同事务已 set_config('hxops.shipping_audit_purge','1')
|
||||
且 retention_expires_at IS NOT NULL AND retention_expires_at < now() 时允许;
|
||||
SQLite / 非 PostgreSQL 方言 no-op(单元测试靠 ORM before_update/before_delete 守卫)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'a0e1f2b3c4d5'
|
||||
down_revision = '9d2f4a6b8c0e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""
|
||||
在 PostgreSQL 上创建 append-only 触发器函数并挂到 shipping_audit_events。
|
||||
|
||||
SQLite 与其它方言跳过:测试库通常 create_all,无触发器亦可依赖 ORM 守卫。
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name != 'postgresql':
|
||||
return
|
||||
|
||||
op.execute(
|
||||
"""
|
||||
CREATE OR REPLACE FUNCTION hxops_shipping_audit_reject_update()
|
||||
RETURNS trigger
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'shipping_audit_events is append-only: UPDATE forbidden'
|
||||
USING ERRCODE = 'integrity_constraint_violation';
|
||||
END;
|
||||
$$;
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"""
|
||||
CREATE OR REPLACE FUNCTION hxops_shipping_audit_guard_delete()
|
||||
RETURNS trigger
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
BEGIN
|
||||
IF current_setting('hxops.shipping_audit_purge', true) IS DISTINCT FROM '1' THEN
|
||||
RAISE EXCEPTION 'shipping_audit_events is append-only: DELETE forbidden'
|
||||
USING ERRCODE = 'integrity_constraint_violation';
|
||||
END IF;
|
||||
IF OLD.retention_expires_at IS NULL OR OLD.retention_expires_at >= now() THEN
|
||||
RAISE EXCEPTION
|
||||
'shipping_audit_events purge only allows expired rows with retention_expires_at'
|
||||
USING ERRCODE = 'integrity_constraint_violation';
|
||||
END IF;
|
||||
RETURN OLD;
|
||||
END;
|
||||
$$;
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"""
|
||||
DROP TRIGGER IF EXISTS trg_shipping_audit_events_no_update
|
||||
ON shipping_audit_events;
|
||||
CREATE TRIGGER trg_shipping_audit_events_no_update
|
||||
BEFORE UPDATE ON shipping_audit_events
|
||||
FOR EACH ROW
|
||||
EXECUTE PROCEDURE hxops_shipping_audit_reject_update();
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"""
|
||||
DROP TRIGGER IF EXISTS trg_shipping_audit_events_guard_delete
|
||||
ON shipping_audit_events;
|
||||
CREATE TRIGGER trg_shipping_audit_events_guard_delete
|
||||
BEFORE DELETE ON shipping_audit_events
|
||||
FOR EACH ROW
|
||||
EXECUTE PROCEDURE hxops_shipping_audit_guard_delete();
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除 PostgreSQL append-only 触发器与函数;其它方言 no-op。"""
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name != 'postgresql':
|
||||
return
|
||||
|
||||
op.execute('DROP TRIGGER IF EXISTS trg_shipping_audit_events_guard_delete ON shipping_audit_events;')
|
||||
op.execute('DROP TRIGGER IF EXISTS trg_shipping_audit_events_no_update ON shipping_audit_events;')
|
||||
op.execute('DROP FUNCTION IF EXISTS hxops_shipping_audit_guard_delete();')
|
||||
op.execute('DROP FUNCTION IF EXISTS hxops_shipping_audit_reject_update();')
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
"""
|
||||
migrations/versions/b1c2d3e4f5a7_rename_manual_upload_pending_to_excel_ready.py
|
||||
|
||||
用途:将 WorkflowItem 终态 manual_upload_pending 收敛为 excel_ready(Excel 就绪即流程终点)。
|
||||
依赖:shipping_notice_workflow_items(迁移 9d2f4a6b8c0e / a0e1f2b3c4d5 之后)。
|
||||
逻辑:UPDATE 存量行 → 重建 lifecycle CHECK 与 open_conversation 部分索引;
|
||||
revision 使用 b1c2d3e4f5a7(b1c2d3e4f5a6 已被历史迁移占用)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'b1c2d3e4f5a7'
|
||||
down_revision = 'a0e1f2b3c4d5'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_LIFECYCLE_NEW = (
|
||||
"lifecycle_status IN ("
|
||||
"'queued', 'layout_parsing', 'extracting', 'pending_review', "
|
||||
"'building_order', 'inventory_matching', 'generating_excel', "
|
||||
"'excel_ready', 'reparse_failed', 'cancelled', 'failed', 'closed'"
|
||||
")"
|
||||
)
|
||||
_LIFECYCLE_OLD = (
|
||||
"lifecycle_status IN ("
|
||||
"'queued', 'layout_parsing', 'extracting', 'pending_review', "
|
||||
"'building_order', 'inventory_matching', 'generating_excel', "
|
||||
"'manual_upload_pending', 'reparse_failed', 'cancelled', 'failed', 'closed'"
|
||||
")"
|
||||
)
|
||||
_OPEN_WHERE_NEW = "lifecycle_status NOT IN ('closed', 'cancelled', 'excel_ready')"
|
||||
_OPEN_WHERE_OLD = "lifecycle_status NOT IN ('closed', 'cancelled', 'manual_upload_pending')"
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""
|
||||
将 manual_upload_pending 重命名为 excel_ready,并更新 CHECK / 部分索引。
|
||||
|
||||
PostgreSQL:先改数据,再 drop/create constraint 与索引。
|
||||
SQLite:batch_alter_table recreate 重建约束;索引 drop/create。
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
dialect = bind.dialect.name
|
||||
tables = set(sa.inspect(bind).get_table_names())
|
||||
if 'shipping_notice_workflow_items' not in tables:
|
||||
return
|
||||
|
||||
op.execute(
|
||||
sa.text(
|
||||
"UPDATE shipping_notice_workflow_items "
|
||||
"SET lifecycle_status = 'excel_ready', current_stage = 'excel_ready' "
|
||||
"WHERE lifecycle_status = 'manual_upload_pending'"
|
||||
)
|
||||
)
|
||||
|
||||
# [STEP 1] 重建 open_conversation 部分索引(WHERE 子句含终态名)。
|
||||
try:
|
||||
op.drop_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
table_name='shipping_notice_workflow_items',
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if dialect == 'postgresql':
|
||||
op.drop_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
type_='check',
|
||||
)
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
_LIFECYCLE_NEW,
|
||||
)
|
||||
else:
|
||||
with op.batch_alter_table('shipping_notice_workflow_items', recreate='always') as batch:
|
||||
batch.drop_constraint('ck_shipping_notice_workflow_items_lifecycle', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
_LIFECYCLE_NEW,
|
||||
)
|
||||
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
'shipping_notice_workflow_items',
|
||||
['conversation_id', 'updated_at'],
|
||||
postgresql_where=sa.text(_OPEN_WHERE_NEW),
|
||||
sqlite_where=sa.text(_OPEN_WHERE_NEW),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回退 excel_ready → manual_upload_pending,并恢复旧 CHECK / 索引。"""
|
||||
bind = op.get_bind()
|
||||
dialect = bind.dialect.name
|
||||
tables = set(sa.inspect(bind).get_table_names())
|
||||
if 'shipping_notice_workflow_items' not in tables:
|
||||
return
|
||||
|
||||
op.execute(
|
||||
sa.text(
|
||||
"UPDATE shipping_notice_workflow_items "
|
||||
"SET lifecycle_status = 'manual_upload_pending', "
|
||||
"current_stage = 'manual_upload_pending' "
|
||||
"WHERE lifecycle_status = 'excel_ready'"
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
op.drop_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
table_name='shipping_notice_workflow_items',
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if dialect == 'postgresql':
|
||||
op.drop_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
type_='check',
|
||||
)
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
_LIFECYCLE_OLD,
|
||||
)
|
||||
else:
|
||||
with op.batch_alter_table('shipping_notice_workflow_items', recreate='always') as batch:
|
||||
batch.drop_constraint('ck_shipping_notice_workflow_items_lifecycle', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
_LIFECYCLE_OLD,
|
||||
)
|
||||
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
'shipping_notice_workflow_items',
|
||||
['conversation_id', 'updated_at'],
|
||||
postgresql_where=sa.text(_OPEN_WHERE_OLD),
|
||||
sqlite_where=sa.text(_OPEN_WHERE_OLD),
|
||||
)
|
||||
@@ -0,0 +1,148 @@
|
||||
"""
|
||||
migrations/versions/d4e5f6a7b8c0_restore_manual_upload_pending_lifecycle.py
|
||||
|
||||
用途:恢复 WorkflowItem 唯一生命周期 manual_upload_pending(Excel 后待人工上传登记);
|
||||
清除存量 excel_ready,CHECK 不再接受该废弃状态。
|
||||
依赖:shipping_notice_workflow_items(b1c2d3e4f5a7 之后)。
|
||||
逻辑:UPDATE 存量 → 重建 lifecycle CHECK(无 excel_ready);
|
||||
open_conversation 部分索引仅排除 closed/cancelled。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'd4e5f6a7b8c0'
|
||||
down_revision = 'b1c2d3e4f5a7'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_LIFECYCLE_NEW = (
|
||||
"lifecycle_status IN ("
|
||||
"'queued', 'layout_parsing', 'extracting', 'pending_review', "
|
||||
"'building_order', 'inventory_matching', 'generating_excel', "
|
||||
"'manual_upload_pending', 'reparse_failed', "
|
||||
"'cancelled', 'failed', 'closed'"
|
||||
")"
|
||||
)
|
||||
_LIFECYCLE_OLD = (
|
||||
"lifecycle_status IN ("
|
||||
"'queued', 'layout_parsing', 'extracting', 'pending_review', "
|
||||
"'building_order', 'inventory_matching', 'generating_excel', "
|
||||
"'excel_ready', 'reparse_failed', 'cancelled', 'failed', 'closed'"
|
||||
")"
|
||||
)
|
||||
# 待人工上传登记仍属开放;仅真正终态排除。
|
||||
_OPEN_WHERE_NEW = "lifecycle_status NOT IN ('closed', 'cancelled')"
|
||||
_OPEN_WHERE_OLD = "lifecycle_status NOT IN ('closed', 'cancelled', 'excel_ready')"
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""
|
||||
将 excel_ready 全部迁移为 manual_upload_pending,并从 CHECK 移除 excel_ready;
|
||||
重建 open 部分索引使 manual_upload_pending 计入开放项。
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
dialect = bind.dialect.name
|
||||
tables = set(sa.inspect(bind).get_table_names())
|
||||
if 'shipping_notice_workflow_items' not in tables:
|
||||
return
|
||||
|
||||
op.execute(
|
||||
sa.text(
|
||||
"UPDATE shipping_notice_workflow_items "
|
||||
"SET lifecycle_status = 'manual_upload_pending', "
|
||||
"current_stage = 'manual_upload_pending', "
|
||||
"closed_at = NULL "
|
||||
"WHERE lifecycle_status = 'excel_ready'"
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
op.drop_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
table_name='shipping_notice_workflow_items',
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if dialect == 'postgresql':
|
||||
op.drop_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
type_='check',
|
||||
)
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
_LIFECYCLE_NEW,
|
||||
)
|
||||
else:
|
||||
with op.batch_alter_table('shipping_notice_workflow_items', recreate='always') as batch:
|
||||
batch.drop_constraint('ck_shipping_notice_workflow_items_lifecycle', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
_LIFECYCLE_NEW,
|
||||
)
|
||||
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
'shipping_notice_workflow_items',
|
||||
['conversation_id', 'updated_at'],
|
||||
postgresql_where=sa.text(_OPEN_WHERE_NEW),
|
||||
sqlite_where=sa.text(_OPEN_WHERE_NEW),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回退 manual_upload_pending → excel_ready,并恢复 b1 时代 CHECK / 索引。"""
|
||||
bind = op.get_bind()
|
||||
dialect = bind.dialect.name
|
||||
tables = set(sa.inspect(bind).get_table_names())
|
||||
if 'shipping_notice_workflow_items' not in tables:
|
||||
return
|
||||
|
||||
op.execute(
|
||||
sa.text(
|
||||
"UPDATE shipping_notice_workflow_items "
|
||||
"SET lifecycle_status = 'excel_ready', current_stage = 'excel_ready' "
|
||||
"WHERE lifecycle_status = 'manual_upload_pending'"
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
op.drop_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
table_name='shipping_notice_workflow_items',
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if dialect == 'postgresql':
|
||||
op.drop_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
type_='check',
|
||||
)
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
'shipping_notice_workflow_items',
|
||||
_LIFECYCLE_OLD,
|
||||
)
|
||||
else:
|
||||
with op.batch_alter_table('shipping_notice_workflow_items', recreate='always') as batch:
|
||||
batch.drop_constraint('ck_shipping_notice_workflow_items_lifecycle', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_notice_workflow_items_lifecycle',
|
||||
_LIFECYCLE_OLD,
|
||||
)
|
||||
|
||||
op.create_index(
|
||||
'ix_shipping_notice_workflow_items_open_conversation',
|
||||
'shipping_notice_workflow_items',
|
||||
['conversation_id', 'updated_at'],
|
||||
postgresql_where=sa.text(_OPEN_WHERE_OLD),
|
||||
sqlite_where=sa.text(_OPEN_WHERE_OLD),
|
||||
)
|
||||
@@ -0,0 +1,158 @@
|
||||
"""
|
||||
backend/scripts/verify_shipping_audit_pg_immutability.py
|
||||
|
||||
用途:在真实 PostgreSQL 上验收 shipping_audit_events 触发器不可篡改(绕过 ORM)。
|
||||
依赖:Flask create_app、SQLAlchemy、已 upgrade 的 a0e1f2b3c4d5 触发器迁移。
|
||||
逻辑:本地/预发用 DATABASE_URL 指向 PG 后执行本脚本;UPDATE/无 purge GUC 的 DELETE
|
||||
须失败,INSERT 须成功。pytest testing 配置强制 SQLite,故单独提供本脚本。
|
||||
|
||||
用法(仓库根或 backend):
|
||||
cd backend && ./venv/Scripts/python.exe scripts/verify_shipping_audit_pg_immutability.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# 允许以 scripts/ 直接运行时找到 app 包。
|
||||
_BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||
_REPO_ROOT = _BACKEND_ROOT.parent
|
||||
if str(_BACKEND_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_BACKEND_ROOT))
|
||||
|
||||
|
||||
def _prepare_dev_database_url() -> None:
|
||||
"""
|
||||
在导入 app 前强制以 .env.local 的 DATABASE_URL 为准(dev)。
|
||||
|
||||
核心逻辑:pytest / 其它进程可能污染 ENV;本脚本只验收 PostgreSQL 触发器。
|
||||
"""
|
||||
os.environ['ENV_NAME'] = 'dev'
|
||||
try:
|
||||
from dotenv import dotenv_values
|
||||
except ImportError:
|
||||
return
|
||||
local_file = _REPO_ROOT / '.env.local'
|
||||
if not local_file.exists():
|
||||
return
|
||||
values = {k: v for k, v in dotenv_values(local_file).items() if v is not None}
|
||||
db_url = str(values.get('DATABASE_URL') or '').strip()
|
||||
if db_url:
|
||||
os.environ['DATABASE_URL'] = db_url
|
||||
|
||||
|
||||
def _safe_database_target(uri: str) -> str:
|
||||
"""
|
||||
将数据库连接串脱敏为可日志输出的目标描述(不含用户名/密码)。
|
||||
|
||||
Args:
|
||||
uri: SQLALCHEMY_DATABASE_URI 原文。
|
||||
|
||||
Returns:
|
||||
如 ``postgresql@127.0.0.1:5432/hxops_db``;无法解析时仅返回 scheme。
|
||||
"""
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
raw = str(uri or '').strip()
|
||||
if not raw:
|
||||
return '(empty)'
|
||||
parts = urlsplit(raw)
|
||||
scheme = parts.scheme or 'unknown'
|
||||
host = parts.hostname or 'unknown-host'
|
||||
port = f':{parts.port}' if parts.port else ''
|
||||
db_name = (parts.path or '').lstrip('/') or '(no-db)'
|
||||
# 禁止回显 netloc(含凭据)。
|
||||
return f'{scheme}@{host}{port}/{db_name}'
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""
|
||||
连接当前环境数据库并验证审计触发器。
|
||||
|
||||
Returns:
|
||||
0 成功;非 0 失败或非 PostgreSQL。
|
||||
"""
|
||||
_prepare_dev_database_url()
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from app import create_app, db
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
app = create_app('dev')
|
||||
with app.app_context():
|
||||
uri = str(app.config.get('SQLALCHEMY_DATABASE_URI') or '')
|
||||
dialect_name = str(db.engine.dialect.name or '')
|
||||
if dialect_name != 'postgresql':
|
||||
print(
|
||||
'FAIL: DATABASE_URL is not PostgreSQL; refuse to claim trigger verification. '
|
||||
f'dialect={dialect_name!r} target={_safe_database_target(uri)!r}'
|
||||
)
|
||||
return 2
|
||||
|
||||
# [STEP 1] 确认触发器存在。
|
||||
rows = db.session.execute(
|
||||
text(
|
||||
"SELECT tgname FROM pg_trigger "
|
||||
"WHERE tgrelid = 'shipping_audit_events'::regclass "
|
||||
"AND NOT tgisinternal"
|
||||
)
|
||||
).fetchall()
|
||||
names = {str(r[0]) for r in rows}
|
||||
if not names:
|
||||
print('FAIL: no triggers on shipping_audit_events; run flask db upgrade first.')
|
||||
return 3
|
||||
print(f'OK: triggers present: {sorted(names)}')
|
||||
|
||||
# [STEP 2] 追加一条可回滚探测事件。
|
||||
event = append_shipping_audit_event(
|
||||
event_type='workflow_created',
|
||||
aggregate_type='shipping_notice_workflow',
|
||||
aggregate_id='WF-PG-IMM-VERIFY',
|
||||
workflow_id='WF-PG-IMM-VERIFY',
|
||||
)
|
||||
db.session.commit()
|
||||
eid = int(event.id)
|
||||
print(f'OK: inserted audit event id={eid}')
|
||||
|
||||
# [STEP 3] Core UPDATE 必须失败。
|
||||
try:
|
||||
db.session.execute(
|
||||
text('UPDATE shipping_audit_events SET reason_code = :rc WHERE id = :eid'),
|
||||
{'rc': 'tamper', 'eid': eid},
|
||||
)
|
||||
db.session.commit()
|
||||
print('FAIL: UPDATE succeeded; trigger missing or disabled.')
|
||||
return 4
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
print(f'OK: UPDATE blocked ({type(exc).__name__})')
|
||||
|
||||
# [STEP 4] 无 purge GUC 的 DELETE 必须失败。
|
||||
try:
|
||||
db.session.execute(
|
||||
text('DELETE FROM shipping_audit_events WHERE id = :eid'),
|
||||
{'eid': eid},
|
||||
)
|
||||
db.session.commit()
|
||||
print('FAIL: DELETE succeeded without purge GUC.')
|
||||
return 5
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
print(f'OK: DELETE blocked ({type(exc).__name__})')
|
||||
|
||||
remaining = db.session.execute(
|
||||
text('SELECT COUNT(1) FROM shipping_audit_events WHERE id = :eid'),
|
||||
{'eid': eid},
|
||||
).scalar()
|
||||
if int(remaining or 0) != 1:
|
||||
print('FAIL: probe event missing after blocked DELETE.')
|
||||
return 6
|
||||
print('OK: PostgreSQL audit immutability verified.')
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -1,3 +1,12 @@
|
||||
"""
|
||||
tests/conftest.py
|
||||
|
||||
用途:Flask testing app、库存配置种子与测试隔离夹具。
|
||||
依赖:pytest、app.create_app、shipping inventory 模型。
|
||||
逻辑:各测试用例共享;Windows 下将 basetemp 固定到 backend/.pytest_tmp,
|
||||
配合 pytest.ini 的 retention=0,避免 %TEMP%/pytest-current 清理 PermissionError。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from pathlib import Path
|
||||
|
||||
@@ -371,6 +380,12 @@ def rpa_callback_payload(
|
||||
|
||||
|
||||
def pytest_configure(config):
|
||||
"""
|
||||
注册自定义 markers,并把临时目录固定到仓库内可写路径。
|
||||
|
||||
核心逻辑:未显式传 --basetemp 时使用 backend/.pytest_tmp/run,避免系统 TEMP
|
||||
中 pytest-current 符号链接在 atexit 清理时触发 WinError 5,导致 exit code≠0。
|
||||
"""
|
||||
config.addinivalue_line(
|
||||
"markers",
|
||||
"auto_rpa: 发货通知测试启用 auto_progress + RPA 自动链",
|
||||
@@ -379,6 +394,11 @@ def pytest_configure(config):
|
||||
"markers",
|
||||
"inventory_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入",
|
||||
)
|
||||
# [STEP] Windows 质量门禁:basetemp 落仓内 + retention=0(见 pytest.ini)。
|
||||
if not getattr(config.option, 'basetemp', None):
|
||||
basetemp = Path(__file__).resolve().parents[1] / '.pytest_tmp' / 'run'
|
||||
basetemp.mkdir(parents=True, exist_ok=True)
|
||||
config.option.basetemp = str(basetemp)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -38,6 +38,24 @@ def test_claim_next_returns_none_when_empty(app):
|
||||
assert store.claim_next(queues=['kb']) is None
|
||||
|
||||
|
||||
def test_claim_next_shipping_recovers_stale_layout_jobs(app, monkeypatch):
|
||||
"""Shipping worker 认领前必须回收卡住的版面解析任务。"""
|
||||
from app.jobs import store
|
||||
from app.services.shipping_notice import queue_service
|
||||
|
||||
recovered = []
|
||||
monkeypatch.setattr(
|
||||
queue_service,
|
||||
'recover_stale_shipping_notice_jobs',
|
||||
lambda: recovered.append(True) or (0, ''),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
assert store.claim_next(queues=['shipping']) is None
|
||||
|
||||
assert recovered == [True]
|
||||
|
||||
|
||||
def test_find_shipping_notice_job_id_matches_task_no(app):
|
||||
from app import db
|
||||
from app.jobs.queue import _find_shipping_notice_job_id
|
||||
|
||||
@@ -156,6 +156,10 @@ def test_list_profile_families_prefers_published_then_draft_then_retired(app):
|
||||
t01 = next(item for item in families if item['profile_code'] == 'T01')
|
||||
t02 = next(item for item in families if item['profile_code'] == 'T02')
|
||||
assert t01['published_version'] == 2
|
||||
assert t01['published_schema_version_id'] == schema.id
|
||||
assert t01['published_schema_version'] == schema.version
|
||||
assert t01['current_schema_version_id'] == schema.id
|
||||
assert t01['current_schema_version'] == schema.version
|
||||
assert t01['draft_version'] == 3
|
||||
assert t01['default_profile_id'] == published.id
|
||||
assert t01['default_version'] == 2
|
||||
|
||||
@@ -78,6 +78,16 @@ def test_table_contract_rejects_forbidden_reservation_header():
|
||||
assert caught.value.details['forbidden_reservation_headers'] == ['Allocation ID']
|
||||
|
||||
|
||||
def test_table_contract_includes_internal_line_number():
|
||||
"""内部项次 line_no 可作为 PDF/表格抽取字段;与客户 PO 行号并列映射。"""
|
||||
contract = compile_table_header_contract(_definition(
|
||||
_field('line_no', ['Item No']), _field('customer_po_line_no', ['Customer Item']),
|
||||
))
|
||||
|
||||
assert contract.header_to_field['Item No'] == 'line_no'
|
||||
assert contract.header_to_field['Customer Item'] == 'customer_po_line_no'
|
||||
|
||||
|
||||
def test_runtime_reports_duplicate_columns_as_ambiguous():
|
||||
"""同一字段在一行命中多个列时不得静默选第一列。"""
|
||||
contract = compile_table_header_contract(_definition(
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
backend/tests/test_shipping_audit_db_immutability.py
|
||||
|
||||
用途:验收 shipping_audit_events 不可变约束(ORM 层始终;PostgreSQL 触发器在 CI/生产)。
|
||||
依赖:ShippingAuditEvent ORM 守卫、audit_service.append_shipping_audit_event、SQLAlchemy dialect。
|
||||
逻辑:pytest TestingConfig 强制 SQLite create_all,无 DB 触发器 —— 仅断言 ORM append-only;
|
||||
触发器断言在非 PostgreSQL 时 pytest.skip(迁移 a0e1f2b3c4d5 仅对 PG 生效)。
|
||||
目标 PostgreSQL 环境请另跑:
|
||||
``python scripts/verify_shipping_audit_pg_immutability.py``(日志不输出连接凭据)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def _is_postgresql() -> bool:
|
||||
"""当前应用绑定是否为 PostgreSQL。"""
|
||||
bind = db.session.bind
|
||||
return bind is not None and bind.dialect.name == 'postgresql'
|
||||
|
||||
|
||||
def test_shipping_audit_orm_immutability_still_holds(app):
|
||||
"""任意方言:已提交审计经 ORM update/delete 必须被拒绝(测试库通常无 DB 触发器)。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='workflow_item_created',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id='WFI-DB-IMM-1',
|
||||
workflow_id='WF-DB-IMM-1',
|
||||
workflow_item_id='WFI-DB-IMM-1',
|
||||
)
|
||||
db.session.commit()
|
||||
event_id = int(event.id)
|
||||
|
||||
event.reason_code = 'tampered'
|
||||
with pytest.raises(ValidationError, match='append-only'):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
persisted = db.session.get(ShippingAuditEvent, event_id)
|
||||
db.session.delete(persisted)
|
||||
with pytest.raises(ValidationError, match='append-only'):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
# 关键断言:删除失败后记录仍在。
|
||||
assert db.session.get(ShippingAuditEvent, event_id) is not None
|
||||
|
||||
|
||||
def test_shipping_audit_pg_trigger_blocks_core_update(app):
|
||||
"""PostgreSQL:Core UPDATE 须被触发器拒绝;SQLite 跳过。"""
|
||||
with app.app_context():
|
||||
if not _is_postgresql():
|
||||
pytest.skip('DB triggers only exist on PostgreSQL after migration a0e1f2b3c4d5')
|
||||
event = append_shipping_audit_event(
|
||||
event_type='workflow_created',
|
||||
aggregate_type='shipping_notice_workflow',
|
||||
aggregate_id='WF-DB-IMM-TRIG',
|
||||
workflow_id='WF-DB-IMM-TRIG',
|
||||
)
|
||||
db.session.commit()
|
||||
with pytest.raises(Exception):
|
||||
db.session.execute(
|
||||
text('UPDATE shipping_audit_events SET reason_code = :rc WHERE id = :eid'),
|
||||
{'rc': 'x', 'eid': int(event.id)},
|
||||
)
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_shipping_audit_pg_trigger_blocks_core_delete_without_purge_guc(app):
|
||||
"""PostgreSQL:未设置 purge GUC 时 Core DELETE 须被触发器拒绝;SQLite 跳过。"""
|
||||
with app.app_context():
|
||||
if not _is_postgresql():
|
||||
pytest.skip('DB triggers only exist on PostgreSQL after migration a0e1f2b3c4d5')
|
||||
event = append_shipping_audit_event(
|
||||
event_type='workflow_created',
|
||||
aggregate_type='shipping_notice_workflow',
|
||||
aggregate_id='WF-DB-IMM-DEL',
|
||||
workflow_id='WF-DB-IMM-DEL',
|
||||
)
|
||||
db.session.commit()
|
||||
with pytest.raises(Exception):
|
||||
db.session.execute(
|
||||
text('DELETE FROM shipping_audit_events WHERE id = :eid'),
|
||||
{'eid': int(event.id)},
|
||||
)
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
assert db.session.get(ShippingAuditEvent, int(event.id)) is not None
|
||||
@@ -46,7 +46,7 @@ def test_append_shipping_audit_event_hashes_state_and_rejects_sensitive_metadata
|
||||
assert event.after_snapshot_json == {'status': 'processing'}
|
||||
assert event.operation_id == 'op-stage0-1'
|
||||
assert event.metadata_json == {'target_status': 'processing'}
|
||||
assert event.retention_expires_at is not None
|
||||
assert event.retention_expires_at is None
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
append_shipping_audit_event(
|
||||
event_type='invalid',
|
||||
@@ -120,14 +120,16 @@ def test_shipping_audit_event_rejects_orm_update_and_delete(app):
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_append_shipping_audit_event_hashes_client_context_and_session_item(app):
|
||||
"""会话工作项审计必须记录属主/工作项软引用,且 IP/UA 仅存哈希。"""
|
||||
def test_append_shipping_audit_event_hashes_client_context_and_workflow_refs(app):
|
||||
"""Workflow 审计必须记录属主/软引用与哈希链,且 IP/UA 仅存哈希。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='session_work_item_created',
|
||||
aggregate_type='session_pdf_work_item',
|
||||
aggregate_id='SPWI-1',
|
||||
session_item_id='SPWI-1',
|
||||
event_type='workflow_item_created',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id='SWI-1',
|
||||
workflow_id='SWF-1',
|
||||
workflow_item_id='SWI-1',
|
||||
version_no=1,
|
||||
owner_user_id=42,
|
||||
conversation_id='conv-session-1',
|
||||
client_ip='203.0.113.9',
|
||||
@@ -135,13 +137,18 @@ def test_append_shipping_audit_event_hashes_client_context_and_session_item(app)
|
||||
after={
|
||||
'lifecycle_status': 'pending_review',
|
||||
'current_version_no': 1,
|
||||
'item_no': 'SPWI-1',
|
||||
'item_no': 'SWI-1',
|
||||
'workflow_no': 'SWF-1',
|
||||
},
|
||||
metadata={'source': 'upload'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
assert event.session_item_id == 'SPWI-1'
|
||||
assert event.workflow_id == 'SWF-1'
|
||||
assert event.workflow_item_id == 'SWI-1'
|
||||
assert event.version_no == 1
|
||||
assert event.event_hash
|
||||
assert event.diff_json is not None
|
||||
assert event.owner_user_id == '42'
|
||||
assert event.client_ip_hash == hash_client_context_value('203.0.113.9')
|
||||
assert event.user_agent_hash == hash_client_context_value('Mozilla/5.0 TestAgent')
|
||||
@@ -149,13 +156,14 @@ def test_append_shipping_audit_event_hashes_client_context_and_session_item(app)
|
||||
assert event.after_snapshot_json == {
|
||||
'lifecycle_status': 'pending_review',
|
||||
'current_version_no': 1,
|
||||
'item_no': 'SPWI-1',
|
||||
'item_no': 'SWI-1',
|
||||
'workflow_no': 'SWF-1',
|
||||
}
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
append_shipping_audit_event(
|
||||
event_type='probe',
|
||||
aggregate_type='session_pdf_work_item',
|
||||
aggregate_id='SPWI-2',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id='SWI-2',
|
||||
metadata={'client_ip': '203.0.113.9'},
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN'
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
backend/tests/test_shipping_audit_hash_verification_job.py
|
||||
|
||||
用途:验收货代审计哈希链日检 Job(shipping-audit-retention / shipping-audit-hash-verify)。
|
||||
依赖:shipping_audit_retention_job、audit_service、job_registry、Flask config。
|
||||
逻辑:开关关闭时 skipped;开启时校验通过;Core 篡改后 failed_chains>0;
|
||||
job_registry 已注册日检 Job 且含 hash_sample_limit。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.schedule.job_registry import get_platform_job, list_platform_jobs
|
||||
from app.services.schedule.shipping_audit_retention_job import run_shipping_audit_retention_schedule
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def _task(**params):
|
||||
"""构造最小 Job task 桩。"""
|
||||
return SimpleNamespace(id=9001, job_params=params)
|
||||
|
||||
|
||||
def test_job_registry_registers_hash_verify_jobs(app):
|
||||
"""平台 Job 注册表包含清理+哈希校验与专用日检入口。"""
|
||||
with app.app_context():
|
||||
keys = {item.key for item in list_platform_jobs()}
|
||||
# 关键断言:日检可走 retention 或专用 hash-verify Job。
|
||||
assert 'shipping-audit-retention' in keys
|
||||
assert 'shipping-audit-hash-verify' in keys
|
||||
|
||||
retention = get_platform_job('shipping-audit-retention')
|
||||
assert retention is not None
|
||||
schema_keys = {field['key'] for field in retention.params_schema}
|
||||
assert 'hash_sample_limit' in schema_keys
|
||||
|
||||
verify = get_platform_job('shipping-audit-hash-verify')
|
||||
assert verify is not None
|
||||
assert verify.defaults.get('dry_run') is True
|
||||
assert int(verify.defaults.get('hash_sample_limit') or 0) >= 1
|
||||
|
||||
|
||||
def test_hash_verify_skipped_when_disabled(app):
|
||||
"""SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED=false 时跳过校验。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED'] = False
|
||||
result = run_shipping_audit_retention_schedule(
|
||||
_task(limit=10, dry_run=True, hash_sample_limit=50),
|
||||
SimpleNamespace(),
|
||||
)
|
||||
# 关键断言:跳过时 checked/failed 为 0 且 skipped=True。
|
||||
assert result['hash_verify']['skipped'] is True
|
||||
assert result['hash_verify']['checked_chains'] == 0
|
||||
assert result['hash_verify']['failed_chains'] == 0
|
||||
|
||||
|
||||
def test_hash_verify_passes_for_intact_chain(app):
|
||||
"""完整哈希链抽样校验通过。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED'] = True
|
||||
aggregate_id = 'WFI-JOB-HASH-OK'
|
||||
for index in range(3):
|
||||
append_shipping_audit_event(
|
||||
event_type='workflow_stage_changed',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id=aggregate_id,
|
||||
workflow_id='WF-JOB-HASH',
|
||||
workflow_item_id=aggregate_id,
|
||||
action=f'ok-{index}',
|
||||
after={'lifecycle_status': f's-{index}'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
result = run_shipping_audit_retention_schedule(
|
||||
_task(limit=1, dry_run=True, hash_sample_limit=200),
|
||||
SimpleNamespace(),
|
||||
)
|
||||
# 关键断言:至少校验到本测试聚合且无失败链。
|
||||
assert result['hash_verify'].get('skipped') is not True
|
||||
assert int(result['hash_verify']['checked_chains']) >= 1
|
||||
assert int(result['hash_verify']['failed_chains']) == 0
|
||||
|
||||
|
||||
def test_hash_verify_detects_tampered_chain(app):
|
||||
"""Core UPDATE 篡改 event_hash 后日检 failed_chains > 0。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED'] = True
|
||||
aggregate_id = 'WFI-JOB-HASH-BAD'
|
||||
for index in range(3):
|
||||
append_shipping_audit_event(
|
||||
event_type='workflow_stage_changed',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id=aggregate_id,
|
||||
workflow_id='WF-JOB-HASH-BAD',
|
||||
workflow_item_id=aggregate_id,
|
||||
action=f'bad-{index}',
|
||||
after={'lifecycle_status': f't-{index}'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
middle = (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(aggregate_type='shipping_notice_workflow_item', aggregate_id=aggregate_id)
|
||||
.order_by(ShippingAuditEvent.id.asc())
|
||||
.offset(1)
|
||||
.first()
|
||||
)
|
||||
assert middle is not None
|
||||
db.session.execute(
|
||||
text('UPDATE shipping_audit_events SET event_hash = :h WHERE id = :id'),
|
||||
{'h': '0' * 64, 'id': int(middle.id)},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
result = run_shipping_audit_retention_schedule(
|
||||
_task(limit=1, dry_run=True, hash_sample_limit=500),
|
||||
SimpleNamespace(),
|
||||
)
|
||||
# 关键断言:篡改链被日检检出。
|
||||
assert int(result['hash_verify']['failed_chains']) >= 1
|
||||
assert result['hash_verify']['failures_sample']
|
||||
@@ -0,0 +1,84 @@
|
||||
"""
|
||||
backend/tests/test_shipping_audit_immutability.py
|
||||
|
||||
用途:验收 ShippingAuditEvent ORM 层 append-only 与哈希链字段落库。
|
||||
依赖:ShippingAuditEvent 模型事件守卫、audit_service.append_shipping_audit_event。
|
||||
逻辑:已提交事件禁止 ORM update/delete;新写入必须带 event_hash / previous_event_hash 字段语义。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def test_shipping_audit_event_orm_update_raises(app):
|
||||
"""已提交审计事件经 ORM 更新必须抛 ValidationError。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='workflow_item_created',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id='WFI-IMM-1',
|
||||
workflow_id='WF-IMM-1',
|
||||
workflow_item_id='WFI-IMM-1',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
event.reason_code = 'tampered'
|
||||
with pytest.raises(ValidationError, match='append-only'):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_shipping_audit_event_orm_delete_raises(app):
|
||||
"""已提交审计事件经 ORM 删除必须抛 ValidationError。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='workflow_item_created',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id='WFI-IMM-2',
|
||||
workflow_id='WF-IMM-2',
|
||||
workflow_item_id='WFI-IMM-2',
|
||||
)
|
||||
db.session.commit()
|
||||
event_id = int(event.id)
|
||||
|
||||
persisted = db.session.get(ShippingAuditEvent, event_id)
|
||||
db.session.delete(persisted)
|
||||
with pytest.raises(ValidationError, match='append-only'):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
# 关键断言:删除失败后记录仍在。
|
||||
assert db.session.get(ShippingAuditEvent, event_id) is not None
|
||||
|
||||
|
||||
def test_append_only_persists_hash_chain_fields(app):
|
||||
"""append 写入后必须带 event_hash;同聚合第二条 previous 指向首条。"""
|
||||
with app.app_context():
|
||||
first = append_shipping_audit_event(
|
||||
event_type='workflow_created',
|
||||
aggregate_type='shipping_notice_workflow',
|
||||
aggregate_id='WF-IMM-CHAIN',
|
||||
workflow_id='WF-IMM-CHAIN',
|
||||
after={'workflow_no': 'WF-IMM-CHAIN', 'lifecycle_status': 'open'},
|
||||
)
|
||||
second = append_shipping_audit_event(
|
||||
event_type='workflow_stage_changed',
|
||||
aggregate_type='shipping_notice_workflow',
|
||||
aggregate_id='WF-IMM-CHAIN',
|
||||
workflow_id='WF-IMM-CHAIN',
|
||||
after={'workflow_no': 'WF-IMM-CHAIN', 'lifecycle_status': 'extracting'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:哈希链字段已落库,形成 append-only 可校验事实。
|
||||
assert first.event_hash
|
||||
assert first.previous_event_hash is None
|
||||
assert second.event_hash
|
||||
assert second.previous_event_hash == first.event_hash
|
||||
assert first.diff_json is not None or first.after_snapshot_json is not None
|
||||
@@ -0,0 +1,186 @@
|
||||
"""
|
||||
backend/tests/test_shipping_audit_permissions.py
|
||||
|
||||
用途:验收货代审计敏感读权限裁剪与关联链追溯契约。
|
||||
依赖:User 功能权限、audit_query_service、audit_service。
|
||||
逻辑:无 shipping_notice.audit_sensitive_read 时敏感详情脱敏;有权限返回快照/Diff;
|
||||
关联链可按 workflow/item/run/document/case/task 扩张追溯。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent, User
|
||||
from app.services.shipping_notice.audit_query_service import (
|
||||
get_shipping_audit_event,
|
||||
list_shipping_audit_association_chain,
|
||||
serialize_shipping_audit_event,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def _make_user(*, role: str, overrides: dict | None = None) -> User:
|
||||
"""构造带功能权限覆盖的内存用户(不落库,仅测 has_feature_permission)。"""
|
||||
user = User(username=f'u-{role}', role=role)
|
||||
if overrides is not None:
|
||||
user.feature_permissions = overrides
|
||||
return user
|
||||
|
||||
|
||||
def test_admin_default_has_audit_sensitive_read_permission(app):
|
||||
"""admin 角色默认具备 shipping_notice.audit_sensitive_read;普通用户默认无。"""
|
||||
with app.app_context():
|
||||
admin = _make_user(role='admin')
|
||||
user = _make_user(role='user')
|
||||
# 关键断言:默认权限不新建角色,仅功能键裁剪。
|
||||
assert admin.has_feature_permission('shipping_notice.audit_sensitive_read') is True
|
||||
assert user.has_feature_permission('shipping_notice.audit_sensitive_read') is False
|
||||
|
||||
|
||||
def test_admin_can_explicitly_disable_audit_sensitive_read(app):
|
||||
"""admin 可显式关闭敏感读权限覆盖项。"""
|
||||
with app.app_context():
|
||||
admin = _make_user(role='admin', overrides={'shipping_notice.audit_sensitive_read': False})
|
||||
# 关键断言:显式覆盖优先于角色默认。
|
||||
assert admin.has_feature_permission('shipping_notice.audit_sensitive_read') is False
|
||||
|
||||
|
||||
def test_sensitive_detail_redacted_without_permission(app):
|
||||
"""敏感事件在无 include_sensitive 时脱敏 before/after/diff。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='order_review_confirmed',
|
||||
aggregate_type='shipping_order_review_case',
|
||||
aggregate_id='SRC-SENS-1',
|
||||
review_case_no='SRC-SENS-1',
|
||||
workflow_id='WF-SENS-1',
|
||||
workflow_item_id='WFI-SENS-1',
|
||||
sensitivity_level='sensitive',
|
||||
before={'status': 'pending_review', 'progress_version': 1},
|
||||
after={'status': 'confirmed', 'progress_version': 2},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
redacted = serialize_shipping_audit_event(
|
||||
event, include_snapshots=True, include_sensitive=False,
|
||||
)
|
||||
# 关键断言:无权限不回传敏感快照正文,并标记 sensitive_redacted。
|
||||
assert redacted['sensitive_redacted'] is True
|
||||
assert redacted['before_snapshot'] is None
|
||||
assert redacted['after_snapshot'] is None
|
||||
assert redacted['diff'] == []
|
||||
|
||||
detail = get_shipping_audit_event(
|
||||
admin_user_id=1,
|
||||
request_id='req-sens-deny',
|
||||
event_id=int(event.id),
|
||||
include_sensitive=False,
|
||||
)
|
||||
assert detail['sensitive_redacted'] is True
|
||||
assert detail['before_snapshot'] is None
|
||||
|
||||
|
||||
def test_sensitive_detail_visible_with_permission(app):
|
||||
"""具备 include_sensitive 时返回白名单 Diff。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='order_review_confirmed',
|
||||
aggregate_type='shipping_order_review_case',
|
||||
aggregate_id='SRC-SENS-2',
|
||||
review_case_no='SRC-SENS-2',
|
||||
sensitivity_level='sensitive',
|
||||
before={'status': 'pending_review'},
|
||||
after={'status': 'confirmed'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
detail = get_shipping_audit_event(
|
||||
admin_user_id=1,
|
||||
request_id='req-sens-allow',
|
||||
event_id=int(event.id),
|
||||
include_sensitive=True,
|
||||
)
|
||||
# 关键断言:有权限可见敏感快照与 Diff。
|
||||
assert detail['sensitive_redacted'] is False
|
||||
assert detail['before_snapshot'] == {'status': 'pending_review'}
|
||||
assert detail['after_snapshot'] == {'status': 'confirmed'}
|
||||
assert {row['key'] for row in detail['diff']} == {'status'}
|
||||
|
||||
|
||||
def test_normal_detail_visible_without_sensitive_permission(app):
|
||||
"""非敏感事件即使无敏感读权限也可看白名单 Diff。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='order_extraction_run_status_changed',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-NORM-1',
|
||||
run_no='SNER-NORM-1',
|
||||
sensitivity_level='normal',
|
||||
before={'status': 'queued'},
|
||||
after={'status': 'processing'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
detail = get_shipping_audit_event(
|
||||
admin_user_id=1,
|
||||
request_id='req-norm',
|
||||
event_id=int(event.id),
|
||||
include_sensitive=False,
|
||||
)
|
||||
assert detail['sensitive_redacted'] is False
|
||||
assert detail['before_snapshot'] == {'status': 'queued'}
|
||||
|
||||
|
||||
def test_association_chain_expands_across_workflow_keys(app):
|
||||
"""关联链按 workflow/item/run/case/task 扩张追溯。"""
|
||||
with app.app_context():
|
||||
append_shipping_audit_event(
|
||||
event_type='workflow_item_created',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id='WFI-CHAIN-1',
|
||||
workflow_id='WF-CHAIN-1',
|
||||
workflow_item_id='WFI-CHAIN-1',
|
||||
document_id='42',
|
||||
action='create',
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type='order_extraction_run_status_changed',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-CHAIN-1',
|
||||
workflow_id='WF-CHAIN-1',
|
||||
workflow_item_id='WFI-CHAIN-1',
|
||||
run_no='SNER-CHAIN-1',
|
||||
document_id='42',
|
||||
action='status',
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type='order_review_confirmed',
|
||||
aggregate_type='shipping_order_review_case',
|
||||
aggregate_id='SRC-CHAIN-1',
|
||||
workflow_id='WF-CHAIN-1',
|
||||
workflow_item_id='WFI-CHAIN-1',
|
||||
run_no='SNER-CHAIN-1',
|
||||
review_case_no='SRC-CHAIN-1',
|
||||
task_no='ST-CHAIN-1',
|
||||
action='confirm',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
chain = list_shipping_audit_association_chain(
|
||||
admin_user_id=1,
|
||||
request_id='req-chain',
|
||||
filters={'run_no': 'SNER-CHAIN-1'},
|
||||
limit=100,
|
||||
)
|
||||
# 关键断言:从 run_no 种子可扩张到 workflow / case / task 关联事件。
|
||||
event_types = {item['event_type'] for item in chain['items']}
|
||||
assert 'workflow_item_created' in event_types
|
||||
assert 'order_extraction_run_status_changed' in event_types
|
||||
assert 'order_review_confirmed' in event_types
|
||||
assert 'WF-CHAIN-1' in chain['association_keys'].get('workflow_id', [])
|
||||
assert 'SRC-CHAIN-1' in chain['association_keys'].get('review_case_no', [])
|
||||
|
||||
access = ShippingAuditEvent.query.filter_by(
|
||||
event_type='audit_access', action='list_audit_association_chain',
|
||||
).count()
|
||||
assert access >= 1
|
||||
@@ -104,25 +104,27 @@ def test_export_csv_omits_snapshots_and_writes_access_audit(app):
|
||||
assert access.metadata_json.get('format') == 'csv'
|
||||
|
||||
|
||||
def test_list_filters_session_work_item_context_fields(app):
|
||||
"""会话工作项相关筛选:conversation / session_item / case / owner 精确匹配。"""
|
||||
def test_list_filters_workflow_item_context_fields(app):
|
||||
"""Workflow 相关筛选:conversation / workflow_item / case / owner 精确匹配。"""
|
||||
with app.app_context():
|
||||
target = append_shipping_audit_event(
|
||||
event_type='session_work_item_reparse_started',
|
||||
aggregate_type='shipping_session_pdf_work_item',
|
||||
event_type='document_reparse_requested',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id='SPWI-FILTER-1',
|
||||
conversation_id='conv-filter-1',
|
||||
session_item_id='SPWI-FILTER-1',
|
||||
workflow_id='SWF-FILTER-1',
|
||||
workflow_item_id='SPWI-FILTER-1',
|
||||
review_case_no='SRC-FILTER-1',
|
||||
owner_user_id='8801',
|
||||
run_no='SNER-FILTER-1',
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type='session_work_item_reparse_started',
|
||||
aggregate_type='shipping_session_pdf_work_item',
|
||||
event_type='document_reparse_requested',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id='SPWI-FILTER-2',
|
||||
conversation_id='conv-filter-2',
|
||||
session_item_id='SPWI-FILTER-2',
|
||||
workflow_id='SWF-FILTER-2',
|
||||
workflow_item_id='SPWI-FILTER-2',
|
||||
review_case_no='SRC-FILTER-2',
|
||||
owner_user_id='8802',
|
||||
run_no='SNER-FILTER-2',
|
||||
@@ -136,7 +138,7 @@ def test_list_filters_session_work_item_context_fields(app):
|
||||
page_size=25,
|
||||
filters={
|
||||
'conversation_id': 'conv-filter-1',
|
||||
'session_item_id': 'SPWI-FILTER-1',
|
||||
'workflow_item_id': 'SPWI-FILTER-1',
|
||||
'review_case_no': 'SRC-FILTER-1',
|
||||
'owner_user_id': '8801',
|
||||
},
|
||||
@@ -144,22 +146,32 @@ def test_list_filters_session_work_item_context_fields(app):
|
||||
# 关键断言:四字段联合筛选仅命中目标事件。
|
||||
assert listed['total'] == 1
|
||||
assert listed['items'][0]['id'] == int(target.id)
|
||||
assert listed['items'][0]['session_item_id'] == 'SPWI-FILTER-1'
|
||||
assert listed['items'][0]['workflow_item_id'] == 'SPWI-FILTER-1'
|
||||
assert listed['items'][0]['workflow_id'] == 'SWF-FILTER-1'
|
||||
assert listed['items'][0]['owner_user_id'] == '8801'
|
||||
assert listed['items'][0]['event_hash']
|
||||
|
||||
|
||||
def test_purge_expired_supports_dry_run_and_core_delete(app):
|
||||
"""到期清理支持 dry_run;正式删除经 Core DELETE 并写清理审计。"""
|
||||
from sqlalchemy import update
|
||||
|
||||
with app.app_context():
|
||||
expired = append_shipping_audit_event(
|
||||
event_type='legacy_probe',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-EXPIRED',
|
||||
run_no='SNER-EXPIRED',
|
||||
retention_expires_at=datetime.utcnow() - timedelta(days=1),
|
||||
)
|
||||
db.session.commit()
|
||||
expired_id = int(expired.id)
|
||||
# 新写入永久保留;用 Core UPDATE 模拟历史遗留到期行(绕过 ORM 不可变守卫)。
|
||||
db.session.execute(
|
||||
update(ShippingAuditEvent)
|
||||
.where(ShippingAuditEvent.id == expired_id)
|
||||
.values(retention_expires_at=datetime.utcnow() - timedelta(days=1))
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
dry = purge_expired_shipping_audit_events(limit=100, dry_run=True)
|
||||
# 关键断言:演练只扫描不删除。
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
"""
|
||||
backend/tests/test_shipping_audit_snapshot_service.py
|
||||
|
||||
用途:验收审计快照白名单、Diff 计算与同聚合 event_hash 哈希链完整性。
|
||||
依赖:audit_snapshot_service、audit_service、ShippingAuditEvent、SQLAlchemy Core UPDATE。
|
||||
逻辑:sanitize/diff 只保留白名单键;连续 append 形成 previous→event 链;
|
||||
Core UPDATE 篡改后 verify_event_hash_chain 必须失败。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.audit_snapshot_service import (
|
||||
compute_snapshot_diff,
|
||||
sanitize_snapshot,
|
||||
verify_event_hash_chain,
|
||||
)
|
||||
|
||||
|
||||
def test_sanitize_snapshot_whitelists_keys(app):
|
||||
"""sanitize_snapshot 仅保留白名单键,未知业务键被剔除。"""
|
||||
with app.app_context():
|
||||
projected = sanitize_snapshot({
|
||||
'status': 'processing',
|
||||
'progress_version': 2,
|
||||
'orders': [{'po': '45001'}],
|
||||
'lifecycle_status': 'extracting',
|
||||
})
|
||||
# 关键断言:白名单键保留,订单正文类键不得进入快照。
|
||||
assert projected == {
|
||||
'status': 'processing',
|
||||
'progress_version': 2,
|
||||
'lifecycle_status': 'extracting',
|
||||
}
|
||||
|
||||
|
||||
def test_compute_snapshot_diff_detects_changed_keys(app):
|
||||
"""compute_snapshot_diff 输出 changed/added/removed 三段。"""
|
||||
with app.app_context():
|
||||
diff = compute_snapshot_diff(
|
||||
{'status': 'queued', 'progress_version': 1},
|
||||
{'status': 'processing', 'lifecycle_status': 'extracting'},
|
||||
)
|
||||
# 关键断言:status 变更、lifecycle 新增、progress_version 移除。
|
||||
assert diff is not None
|
||||
assert diff['changed']['status'] == {'from': 'queued', 'to': 'processing'}
|
||||
assert diff['added']['lifecycle_status'] == 'extracting'
|
||||
assert diff['removed']['progress_version'] == 1
|
||||
|
||||
|
||||
def test_append_builds_event_hash_chain_and_verify_passes(app):
|
||||
"""同聚合连续 3 条事件形成 previous_event_hash → event_hash 链,校验通过。"""
|
||||
with app.app_context():
|
||||
aggregate_type = 'shipping_notice_workflow_item'
|
||||
aggregate_id = 'WFI-HASH-CHAIN-1'
|
||||
events = []
|
||||
for index in range(3):
|
||||
events.append(
|
||||
append_shipping_audit_event(
|
||||
event_type='workflow_stage_changed',
|
||||
aggregate_type=aggregate_type,
|
||||
aggregate_id=aggregate_id,
|
||||
workflow_id='WF-HASH-1',
|
||||
workflow_item_id=aggregate_id,
|
||||
action=f'step-{index}',
|
||||
before={'lifecycle_status': f's-{index}'},
|
||||
after={'lifecycle_status': f's-{index + 1}'},
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:首条无前驱;后续 previous 等于上一条 event_hash。
|
||||
assert events[0].event_hash
|
||||
assert events[0].previous_event_hash is None
|
||||
assert events[1].previous_event_hash == events[0].event_hash
|
||||
assert events[2].previous_event_hash == events[1].event_hash
|
||||
assert len({e.event_hash for e in events}) == 3
|
||||
|
||||
ordered = (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(aggregate_type=aggregate_type, aggregate_id=aggregate_id)
|
||||
.order_by(ShippingAuditEvent.id.asc())
|
||||
.all()
|
||||
)
|
||||
ok, failures = verify_event_hash_chain(ordered)
|
||||
assert ok is True
|
||||
assert failures == []
|
||||
|
||||
|
||||
def test_verify_event_hash_chain_fails_after_core_tamper(app):
|
||||
"""经 Core UPDATE 篡改 event_hash 后,链校验必须失败。"""
|
||||
with app.app_context():
|
||||
aggregate_type = 'shipping_notice_workflow_item'
|
||||
aggregate_id = 'WFI-HASH-TAMPER-1'
|
||||
for index in range(3):
|
||||
append_shipping_audit_event(
|
||||
event_type='workflow_stage_changed',
|
||||
aggregate_type=aggregate_type,
|
||||
aggregate_id=aggregate_id,
|
||||
workflow_id='WF-HASH-T',
|
||||
workflow_item_id=aggregate_id,
|
||||
action=f'tamper-{index}',
|
||||
after={'lifecycle_status': f't-{index}'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
middle = (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(aggregate_type=aggregate_type, aggregate_id=aggregate_id)
|
||||
.order_by(ShippingAuditEvent.id.asc())
|
||||
.offset(1)
|
||||
.first()
|
||||
)
|
||||
assert middle is not None
|
||||
# Core UPDATE 绕过 ORM append-only 守卫,模拟存储层篡改。
|
||||
db.session.execute(
|
||||
text('UPDATE shipping_audit_events SET event_hash = :h WHERE id = :id'),
|
||||
{'h': 'deadbeef', 'id': middle.id},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
ordered = (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(aggregate_type=aggregate_type, aggregate_id=aggregate_id)
|
||||
.order_by(ShippingAuditEvent.id.asc())
|
||||
.all()
|
||||
)
|
||||
ok, failures = verify_event_hash_chain(ordered)
|
||||
# 关键断言:至少一条 event_hash_mismatch 或后续 previous_hash_mismatch。
|
||||
assert ok is False
|
||||
assert any(row['reason'] in {'event_hash_mismatch', 'previous_hash_mismatch'} for row in failures)
|
||||
@@ -0,0 +1,127 @@
|
||||
"""
|
||||
tests/test_shipping_auto_build_workflow_gate.py
|
||||
|
||||
用途:验收自动建单五门禁——失败仅 Review Case、禁止 STP 自动建单;can_build 仍供人工确认。
|
||||
依赖:order_build_eligibility_service、types.SimpleNamespace。
|
||||
逻辑:构造五门全绿 / 单门失败用例;断言 can_auto_create 与 failed_gates。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.order_build_eligibility_service import (
|
||||
AUTO_BUILD_GATE_KEYS,
|
||||
assess_auto_build_gates,
|
||||
assess_order_build_eligibility,
|
||||
)
|
||||
|
||||
|
||||
def test_auto_build_gates_pass_when_all_five_green():
|
||||
"""五门全绿时 can_auto_create=True。"""
|
||||
candidate = SimpleNamespace(
|
||||
acceptance_mode='automatic',
|
||||
candidate_status='accepted',
|
||||
evidence_json=[{'field': 'po'}],
|
||||
conflicts_json=None,
|
||||
duplicate_status='none',
|
||||
duplicate_resolution=None,
|
||||
)
|
||||
unit = SimpleNamespace(route_decision_json={'auto_create_approved': True})
|
||||
run = SimpleNamespace(auto_freeze_policy_json={'enabled': True})
|
||||
result = assess_auto_build_gates(
|
||||
fields_complete=True,
|
||||
candidate=candidate,
|
||||
unit=unit,
|
||||
run=run,
|
||||
)
|
||||
assert result['can_auto_create'] is True
|
||||
assert result['failed_gates'] == []
|
||||
assert set(result['gates']) == set(AUTO_BUILD_GATE_KEYS)
|
||||
assert all(result['gates'].values())
|
||||
|
||||
|
||||
def test_auto_build_gates_fail_without_approved_template():
|
||||
"""模板未批准 → Review Case,禁止自动建单。"""
|
||||
result = assess_auto_build_gates(
|
||||
fields_complete=True,
|
||||
candidate=SimpleNamespace(
|
||||
acceptance_mode='manual',
|
||||
candidate_status='provisional',
|
||||
evidence_json=[{'field': 'po'}],
|
||||
conflicts_json=None,
|
||||
duplicate_status='none',
|
||||
duplicate_resolution=None,
|
||||
),
|
||||
unit=SimpleNamespace(route_decision_json={'auto_create_approved': False}),
|
||||
run=SimpleNamespace(auto_freeze_policy_json={'enabled': True}),
|
||||
)
|
||||
assert result['can_auto_create'] is False
|
||||
assert 'approved_template' in result['failed_gates']
|
||||
|
||||
|
||||
def test_auto_build_gates_fail_on_conflict_or_missing_quality(app):
|
||||
"""冲突或质量门禁未过 → 不能自动建单。"""
|
||||
result = assess_auto_build_gates(
|
||||
fields_complete=True,
|
||||
candidate=SimpleNamespace(
|
||||
acceptance_mode='automatic',
|
||||
candidate_status='accepted',
|
||||
evidence_json=[{'field': 'po'}],
|
||||
conflicts_json=[{'code': 'qty_conflict'}],
|
||||
duplicate_status='none',
|
||||
duplicate_resolution=None,
|
||||
),
|
||||
unit=SimpleNamespace(route_decision_json={'auto_create_approved': True}),
|
||||
run=SimpleNamespace(auto_freeze_policy_json={'enabled': False}),
|
||||
)
|
||||
assert result['can_auto_create'] is False
|
||||
assert 'no_conflict_or_duplicate' in result['failed_gates']
|
||||
assert 'quality_gate_passed' in result['failed_gates']
|
||||
|
||||
|
||||
def test_eligibility_can_build_independent_of_auto_create_gates(app, monkeypatch):
|
||||
"""
|
||||
五门失败不阻断人工确认 can_build(库存/Reservation 齐备时)。
|
||||
"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_build_eligibility_service.list_database_inventory_sources',
|
||||
lambda enabled_only=True: [{'source_code': 'DBS_DUB'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_build_eligibility_service.evaluate_inventory_source_rules_for_field_values',
|
||||
lambda **kwargs: SimpleNamespace(
|
||||
status='resolved',
|
||||
source_codes=['DBS_DUB'],
|
||||
can_build=True,
|
||||
block_reason=None,
|
||||
matched_rule_ids=[1],
|
||||
evidence={},
|
||||
),
|
||||
)
|
||||
fields = {
|
||||
'f-res': {'field_id': 'f-res', 'field_code': 'reservation_id', 'scope': 'line'},
|
||||
'f-pn': {'field_id': 'f-pn', 'field_code': 'part_number', 'scope': 'line'},
|
||||
'f-qty': {'field_id': 'f-qty', 'field_code': 'qty', 'scope': 'line'},
|
||||
}
|
||||
result = assess_order_build_eligibility(
|
||||
fields=fields,
|
||||
header_by_code={},
|
||||
lines=[{'reservation_id': '2000484577', 'part_number': 'PN-1', 'qty': '2'}],
|
||||
line_metas=[{'line_key': 'L1'}],
|
||||
candidate=SimpleNamespace(
|
||||
acceptance_mode='manual',
|
||||
candidate_status='provisional',
|
||||
evidence_json=[],
|
||||
conflicts_json=None,
|
||||
duplicate_status='none',
|
||||
duplicate_resolution=None,
|
||||
),
|
||||
unit=SimpleNamespace(route_decision_json={'auto_create_approved': False}),
|
||||
run=SimpleNamespace(auto_freeze_policy_json={'enabled': False}),
|
||||
)
|
||||
# 关键断言:人工可建单,但自动建单被五门阻断。
|
||||
assert result['can_build'] is True
|
||||
assert result['can_auto_create'] is False
|
||||
assert 'approved_template' in result['failed_gates']
|
||||
assert any(item.get('severity') == 'auto_create_blocking' for item in result['issues'])
|
||||
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
tests/test_shipping_cancelled_task_readonly.py
|
||||
|
||||
用途:验收建单后取消将 Task 置 pending_void、Excel/Version 只读,禁止物理删除。
|
||||
依赖:freight_cancellation_service、workflow_ledger_service、_seed_run_input。
|
||||
逻辑:断言 lifecycle、void_reason、version.is_readonly、审计 before/after、文件路径保留。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingTask
|
||||
from app.models.shipping_notice_workflow import ShippingNoticeWorkflowItemVersion
|
||||
from app.services.shipping_notice.freight_cancellation_service import mark_cancelled_task_readonly
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
ensure_open_workflow,
|
||||
ensure_workflow_item_for_document,
|
||||
)
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
|
||||
def test_mark_cancelled_task_readonly_sets_pending_void_without_delete(app):
|
||||
"""取消后 Task 为 pending_void,导出路径保留,Version 只读。"""
|
||||
with app.app_context():
|
||||
user, agent, session, _intake, document = _seed_run_input(suffix='CANCEL-RO')
|
||||
workflow = ensure_open_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
)
|
||||
item = ensure_workflow_item_for_document(
|
||||
workflow=workflow,
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document.id),
|
||||
)
|
||||
task = ShippingTask(
|
||||
task_no='SN-CANCEL-RO-1',
|
||||
user_id=int(user.id),
|
||||
conversation_id=session.session_id,
|
||||
process_status='waiting_upload',
|
||||
lifecycle_status='active',
|
||||
export_file_path='/tmp/keep-excel.xlsx',
|
||||
export_file_name='keep-excel.xlsx',
|
||||
source_type='review_confirmation',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
item.current_task_no = task.task_no
|
||||
version = (
|
||||
ShippingNoticeWorkflowItemVersion.query
|
||||
.filter_by(workflow_item_id=int(item.id), is_current=True)
|
||||
.first()
|
||||
)
|
||||
assert version is not None
|
||||
version.task_id = int(task.id)
|
||||
version.task_no = task.task_no
|
||||
version.excel_artifact_no = 'ART-1'
|
||||
version.is_readonly = False
|
||||
db.session.commit()
|
||||
|
||||
result = mark_cancelled_task_readonly(
|
||||
task=task,
|
||||
actor_id=int(user.id),
|
||||
reason='user cancelled after excel',
|
||||
workflow_item_no=item.item_no,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:软作废 + 文件保留 + Version 只读。
|
||||
assert task.lifecycle_status == 'pending_void'
|
||||
assert task.void_reason == 'user cancelled after excel'
|
||||
assert task.export_file_path == '/tmp/keep-excel.xlsx'
|
||||
assert result['physical_delete'] is False
|
||||
assert result['readonly'] is True
|
||||
assert result['before']['lifecycle_status'] == 'active'
|
||||
assert result['after']['lifecycle_status'] == 'pending_void'
|
||||
refreshed = db.session.get(ShippingNoticeWorkflowItemVersion, int(version.id))
|
||||
assert refreshed is not None
|
||||
assert refreshed.is_readonly is True
|
||||
@@ -2,15 +2,19 @@
|
||||
验证坐标重建仅在可信列锚点下生成可审计的 needs_review 订单行候选。
|
||||
|
||||
依赖:coordinate_table_reconstruction、LayoutBBox。逻辑:覆盖 x 列归属、y 新行、续行与
|
||||
删除标记;没有强行号锚点的行不能被伪装成独立订单明细。
|
||||
删除标记;没有有效起行锚点(customer_po_line_no)的行不能被伪装成独立订单明细。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
|
||||
reconstruct_coordinate_profile_rows,
|
||||
reconstruct_table_from_positioned_text,
|
||||
resolve_line_start_field_code,
|
||||
suggest_header_layouts,
|
||||
suggest_header_regions,
|
||||
suggest_multi_subrow_layouts,
|
||||
@@ -19,6 +23,7 @@ from app.services.shipping_notice.document_layout.order_profile import (
|
||||
CoordinateReconstructionProfile,
|
||||
OrderDocumentProfile,
|
||||
OrderProfileColumnRule,
|
||||
TableRegionProfile,
|
||||
order_profile_structure_fingerprint,
|
||||
parse_html_table_with_order_profile,
|
||||
reconstruct_order_profile_html,
|
||||
@@ -159,7 +164,7 @@ def test_coordinate_profile_rows_merge_only_declared_physical_layouts():
|
||||
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
line_layouts=[
|
||||
{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': .75, 'y1': 1}},
|
||||
{'field_code': 'qty', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
@@ -170,7 +175,22 @@ def test_coordinate_profile_rows_merge_only_declared_physical_layouts():
|
||||
)
|
||||
|
||||
assert len(rows) == 1
|
||||
assert rows[0].fields == {'line_no': '00010', 'part_number': 'PART-A', 'qty': '5', 'required_date': '2026-08-01'}
|
||||
assert rows[0].fields == {'customer_po_line_no': '00010', 'part_number': 'PART-A', 'qty': '5', 'required_date': '2026-08-01'}
|
||||
|
||||
|
||||
def test_line_number_can_be_used_as_a_configured_coordinate_anchor():
|
||||
"""用户选择项次字段时,坐标模板可用 line_no 启动明细。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs([('00010', 10), ('PART-A', 65)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
line_start_field_code='line_no',
|
||||
)
|
||||
|
||||
assert [row.fields for row in rows] == [{'line_no': '00010', 'part_number': 'PART-A'}]
|
||||
|
||||
|
||||
def test_coordinate_profile_row_layout_repeats_across_the_table():
|
||||
@@ -182,32 +202,49 @@ def test_coordinate_profile_row_layout_repeats_across_the_table():
|
||||
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
table_region={'x0': 0, 'y0': .15, 'x1': 1, 'y1': .35},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .15, 'x1': 1, 'y1': .35}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .25, 'y1': .35}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .25, 'y1': .35}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': .15, 'x1': .75, 'y1': .35}},
|
||||
]}],
|
||||
)
|
||||
|
||||
# 断言样例框的 X 版式重复应用到第二条明细,Y 只用于表达该物理子行的相对顺序。
|
||||
assert [row.fields for row in rows] == [
|
||||
{'line_no': '00010', 'part_number': 'PART-A'},
|
||||
{'line_no': '00020', 'part_number': 'PART-B'},
|
||||
{'customer_po_line_no': '00010', 'part_number': 'PART-A'},
|
||||
{'customer_po_line_no': '00020', 'part_number': 'PART-B'},
|
||||
]
|
||||
|
||||
|
||||
def test_coordinate_profile_preview_can_expose_unanchored_main_row_for_review():
|
||||
"""仅预览模式在缺少有效起行值时保留字段证据,正式重建仍严格过滤。"""
|
||||
kwargs = {
|
||||
'characters': _glyphs([('PART-A', 65), ('5', 160)]),
|
||||
'table_bbox': {'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
|
||||
'line_layouts': [{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': .75, 'y1': 1}},
|
||||
{'field_code': 'qty', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
}
|
||||
|
||||
assert reconstruct_coordinate_profile_rows(**kwargs) == []
|
||||
preview_rows = reconstruct_coordinate_profile_rows(**kwargs, include_unanchored_rows=True)
|
||||
assert [row.fields for row in preview_rows] == [{'part_number': 'PART-A', 'qty': '5'}]
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_apply_registered_composite_extractors_atomically():
|
||||
"""qty/uom、金额/币种和单价/币种必须成对拆分;格式无效时不写入任何半截字段。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs([('00010', 10), ('3 EA', 65), ('USD 10.50', 115), ('12.00 USD', 165)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 60},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'extractor_key': 'direct', 'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'extractor_key': 'direct', 'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1}},
|
||||
{'field_code': 'qty', 'extractor_key': 'quantity_uom', 'region': {'x0': .2, 'y0': 0, 'x1': .5, 'y1': 1}},
|
||||
{'field_code': 'line_amount_before_tax', 'extractor_key': 'amount_currency', 'region': {'x0': .5, 'y0': 0, 'x1': .75, 'y1': 1}},
|
||||
{'field_code': 'unit_price', 'extractor_key': 'price_currency', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
)
|
||||
assert rows[0].fields == {
|
||||
'line_no': '00010', 'qty': '3', 'uom': 'EA', 'line_amount_before_tax': '10.50',
|
||||
'customer_po_line_no': '00010', 'qty': '3', 'uom': 'EA', 'line_amount_before_tax': '10.50',
|
||||
'currency': 'USD', 'unit_price': '12.00',
|
||||
}
|
||||
|
||||
@@ -215,11 +252,11 @@ def test_coordinate_profile_rows_apply_registered_composite_extractors_atomicall
|
||||
characters=_glyphs([('00010', 10), ('not-a-quantity', 65)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'qty', 'extractor_key': 'quantity_uom', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
)
|
||||
assert invalid[0].fields == {'line_no': '00010'}
|
||||
assert invalid[0].fields == {'customer_po_line_no': '00010'}
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_marks_conflicting_composite_values_for_review():
|
||||
@@ -229,7 +266,7 @@ def test_coordinate_profile_rows_marks_conflicting_composite_values_for_review()
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 80},
|
||||
line_layouts=[
|
||||
{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'qty', 'extractor_key': 'quantity_uom', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'continuation', 'row_offset': 1, 'field_regions': [
|
||||
@@ -245,7 +282,7 @@ def test_coordinate_profile_rows_treat_vertical_regions_as_repeatable_layout_sam
|
||||
"""物理行纵向框表达子行顺序而非绝对页坐标,模板才能重复读取后续明细。"""
|
||||
base_layouts = [
|
||||
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .25}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'continuation', 'row_offset': 1, 'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': .5}, 'field_regions': [
|
||||
@@ -276,7 +313,7 @@ def test_coordinate_profile_rows_reject_swapped_physical_region_order():
|
||||
)
|
||||
layouts = [
|
||||
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .25}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'delivery', 'row_offset': 1, 'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': .5}, 'field_regions': [
|
||||
@@ -296,7 +333,7 @@ def test_coordinate_profile_rows_reject_swapped_physical_region_order():
|
||||
rejected = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, line_layouts=layouts,
|
||||
)
|
||||
assert rejected[0].fields == {'line_no': '00010', 'part_number': 'PART-A'}
|
||||
assert rejected[0].fields == {'customer_po_line_no': '00010', 'part_number': 'PART-A'}
|
||||
assert rejected[0].issues == ['coordinate_profile_layout_region_mismatch']
|
||||
|
||||
|
||||
@@ -306,7 +343,7 @@ def test_coordinate_profile_rows_restore_pdf_visual_spaces():
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'shipway', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
)
|
||||
@@ -323,11 +360,11 @@ def test_coordinate_profile_rows_hide_deleted_records_by_default_and_expose_them
|
||||
[('TOTAL AMOUNT', 65)],
|
||||
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
)
|
||||
assert [row.fields for row in rows] == [{'line_no': '00020', 'part_number': 'PART-KEEP'}]
|
||||
assert [row.fields for row in rows] == [{'customer_po_line_no': '00020', 'part_number': 'PART-KEEP'}]
|
||||
|
||||
preview_rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
@@ -336,12 +373,12 @@ def test_coordinate_profile_rows_hide_deleted_records_by_default_and_expose_them
|
||||
[('00020', 10), ('PART-KEEP', 65)],
|
||||
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}], include_deleted=True,
|
||||
)
|
||||
# 关键断言:预览保留被删除的原始明细,但角色明确标识为不可纳入结果。
|
||||
assert [(row.fields['line_no'], row.role) for row in preview_rows] == [('00010', 'deleted'), ('00020', 'data')]
|
||||
assert [(row.fields['customer_po_line_no'], row.role) for row in preview_rows] == [('00010', 'deleted'), ('00020', 'data')]
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_replay_f9a1_four_physical_rows_with_bound_schema_fields():
|
||||
@@ -357,7 +394,7 @@ def test_coordinate_profile_rows_replay_f9a1_four_physical_rows_with_bound_schem
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 300, 'y1': 100},
|
||||
line_layouts=[
|
||||
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .3}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .12, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .12, 'y1': 1}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .12, 'y0': 0, 'x1': .58, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .58, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
@@ -380,7 +417,7 @@ def test_coordinate_profile_rows_replay_f9a1_four_physical_rows_with_bound_schem
|
||||
assert len(rows) == 1
|
||||
assert rows[0].source_row_indices == [0, 1, 2, 3]
|
||||
assert rows[0].fields == {
|
||||
'line_no': '10', 'customer_part_number': '541-000175-007', 'part_number': 'B3-A08AR10000018-A7',
|
||||
'customer_po_line_no': '10', 'customer_part_number': '541-000175-007', 'part_number': 'B3-A08AR10000018-A7',
|
||||
'qty': '3.000', 'uom': 'PCS', 'required_date': '2026/05/05', 'incoterm': 'EXW SGSIN DBS',
|
||||
'unit_price': '1,645.11000', 'line_amount_before_tax': '4,935.33', 'reservation_id': '@ 3000092530',
|
||||
}
|
||||
@@ -403,7 +440,7 @@ def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_l
|
||||
'row_offset': 0,
|
||||
'region': {'x0': 0, 'y0': .15, 'x1': 1, 'y1': .48},
|
||||
'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .12, 'y1': .25}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .12, 'y1': .25}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .38, 'y0': .15, 'x1': 1, 'y1': .25}},
|
||||
{'field_code': 'qty', 'region': {'x0': .38, 'y0': .26, 'x1': .52, 'y1': .36}},
|
||||
{'field_code': 'uom', 'region': {'x0': .52, 'y0': .26, 'x1': .63, 'y1': .36}},
|
||||
@@ -417,12 +454,12 @@ def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_l
|
||||
# 数量与单位不得从同一横向范围内、但位于首视觉行的内部料号尾数读取。
|
||||
assert [row.fields for row in rows] == [
|
||||
{
|
||||
'line_no': '10', 'part_number': 'B3-A08AR10000018-A7', 'qty': '3.000', 'uom': 'PCS',
|
||||
'customer_po_line_no': '10', 'part_number': 'B3-A08AR10000018-A7', 'qty': '3.000', 'uom': 'PCS',
|
||||
'requested_receipt_date': '2026/05/05', 'unit_price': '1,645.11000',
|
||||
'line_amount_before_tax': '4,935.33',
|
||||
},
|
||||
{
|
||||
'line_no': '20', 'part_number': 'B3-A08AR10000027-A9', 'qty': '8.000', 'uom': 'EA',
|
||||
'customer_po_line_no': '20', 'part_number': 'B3-A08AR10000027-A9', 'qty': '8.000', 'uom': 'EA',
|
||||
'requested_receipt_date': '2026/06/01', 'unit_price': '2,100.00000',
|
||||
'line_amount_before_tax': '16,800.00',
|
||||
},
|
||||
@@ -439,7 +476,7 @@ def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_l
|
||||
'layout_id': 'detail', 'row_offset': 0,
|
||||
'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .65},
|
||||
'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .12, 'y1': .35}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .12, 'y1': .35}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .38, 'y0': .2, 'x1': 1, 'y1': .35}},
|
||||
{'field_code': 'qty', 'region': {'x0': .38, 'y0': .36, 'x1': .52, 'y1': .5}},
|
||||
],
|
||||
@@ -467,7 +504,7 @@ def test_coordinate_profile_rows_replay_sample_visual_band_offsets_despite_paren
|
||||
# 样例父框包含第三子行后的留白;线性压缩会让第二子行字段落入空白。
|
||||
'region': {'x0': 0, 'y0': .05, 'x1': 1, 'y1': .53},
|
||||
'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .12, 'x1': .2, 'y1': .19}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .12, 'x1': .2, 'y1': .19}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .12, 'x1': .64, 'y1': .19}},
|
||||
{'field_code': 'qty', 'region': {'x0': .76, 'y0': .12, 'x1': .86, 'y1': .19}},
|
||||
{'field_code': 'uom', 'region': {'x0': .86, 'y0': .12, 'x1': 1, 'y1': .19}},
|
||||
@@ -479,11 +516,11 @@ def test_coordinate_profile_rows_replay_sample_visual_band_offsets_despite_paren
|
||||
|
||||
assert [row.fields for row in rows] == [
|
||||
{
|
||||
'line_no': '00010', 'customer_part_number': '6Y70B2501901', 'qty': '0', 'uom': 'EA',
|
||||
'customer_po_line_no': '00010', 'customer_part_number': '6Y70B2501901', 'qty': '0', 'uom': 'EA',
|
||||
'part_number': 'D4-A08AR12000002', 'requested_receipt_date': '06/22/2026',
|
||||
},
|
||||
{
|
||||
'line_no': '00020', 'customer_part_number': '6Y70B2501901', 'qty': '30', 'uom': 'EA',
|
||||
'customer_po_line_no': '00020', 'customer_part_number': '6Y70B2501901', 'qty': '30', 'uom': 'EA',
|
||||
'part_number': 'D4-A08AR12000002', 'requested_receipt_date': '06/29/2026',
|
||||
},
|
||||
]
|
||||
@@ -503,7 +540,7 @@ def test_coordinate_profile_rows_calibrate_unbound_visual_bands_from_sample_evid
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 240, 'y1': 120},
|
||||
line_layouts=[{'layout_id': 'detail', 'row_offset': 0,
|
||||
'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .8}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .2, 'y1': .25}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .2, 'y1': .25}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .15, 'x1': .6, 'y1': .25}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .2, 'y0': .38, 'x1': .6, 'y1': .48}},
|
||||
]}],
|
||||
@@ -525,7 +562,7 @@ def test_coordinate_profile_rows_realign_a_record_with_an_extra_unbound_visual_b
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 240, 'y1': 100},
|
||||
line_layouts=[{'layout_id': 'detail', 'row_offset': 0,
|
||||
'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .7}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .2, 'y1': .3}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .2, 'y1': .3}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .2, 'x1': .6, 'y1': .3}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .2, 'y0': .34, 'x1': .6, 'y1': .44}},
|
||||
]}],
|
||||
@@ -547,7 +584,7 @@ def test_coordinate_profile_rows_leave_an_ambiguous_shifted_field_for_review():
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 240, 'y1': 100},
|
||||
line_layouts=[{'layout_id': 'detail', 'row_offset': 0,
|
||||
'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .7}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .2, 'y1': .3}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .2, 'y1': .3}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .2, 'x1': .6, 'y1': .3}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .2, 'y0': .34, 'x1': .6, 'y1': .44}},
|
||||
]}],
|
||||
@@ -574,7 +611,7 @@ def test_coordinate_profile_rows_replay_4518838152_deletion_and_summary_boundary
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 260, 'y1': 160},
|
||||
line_layouts=[
|
||||
{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .18, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .18, 'y1': 1}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .18, 'y0': 0, 'x1': .7, 'y1': 1}},
|
||||
{'field_code': 'qty', 'region': {'x0': .7, 'y0': 0, 'x1': .85, 'y1': 1}},
|
||||
{'field_code': 'uom', 'region': {'x0': .85, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
@@ -592,7 +629,7 @@ def test_coordinate_profile_rows_replay_4518838152_deletion_and_summary_boundary
|
||||
assert len(rows) == 1
|
||||
assert rows[0].source_row_indices == [4, 5, 6]
|
||||
assert rows[0].fields == {
|
||||
'line_no': '00020', 'customer_part_number': '6Y70B2501901', 'qty': '30', 'uom': 'EA',
|
||||
'customer_po_line_no': '00020', 'customer_part_number': '6Y70B2501901', 'qty': '30', 'uom': 'EA',
|
||||
'part_number': 'D4-A08AR12000002', 'required_date': '06/29/2026', 'incoterm': 'EXW AWS HUB',
|
||||
}
|
||||
|
||||
@@ -615,19 +652,19 @@ def test_coordinate_profile_rows_honor_configured_table_exclusion_and_terminatio
|
||||
'region': {'x0': 0, 'y0': .6, 'x1': 1, 'y1': .75},
|
||||
}}],
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
)
|
||||
|
||||
assert [row.fields for row in rows] == [{'line_no': '00010', 'part_number': 'PART-A'}]
|
||||
assert [row.fields for row in rows] == [{'customer_po_line_no': '00010', 'part_number': 'PART-A'}]
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_can_continue_only_explicit_carry_state_on_next_page():
|
||||
"""跨页续行由调用方传入已验证的 carry;当前页自身没有主行锚点时不会擅自建行。"""
|
||||
layouts = [
|
||||
{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'delivery', 'row_offset': 1, 'field_regions': [
|
||||
@@ -641,9 +678,9 @@ def test_coordinate_profile_rows_can_continue_only_explicit_carry_state_on_next_
|
||||
|
||||
continued = reconstruct_coordinate_profile_rows(
|
||||
characters=page_two, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60}, line_layouts=layouts,
|
||||
initial_fields={'line_no': '00010', 'part_number': 'PART-A'}, initial_next_offset=1,
|
||||
initial_fields={'customer_po_line_no': '00010', 'part_number': 'PART-A'}, initial_next_offset=1,
|
||||
)
|
||||
assert continued[0].fields == {'line_no': '00010', 'part_number': 'PART-A', 'required_date': '2026-08-01'}
|
||||
assert continued[0].fields == {'customer_po_line_no': '00010', 'part_number': 'PART-A', 'required_date': '2026-08-01'}
|
||||
|
||||
|
||||
def test_currency_composite_output_becomes_header_only_when_all_rows_agree():
|
||||
@@ -761,7 +798,7 @@ def test_coordinate_profile_parses_one_logical_line_from_multiple_visual_rows():
|
||||
"""端到端验证:一条数据行加两条续行只能产出一条可审核订单明细。"""
|
||||
settings = CoordinateReconstructionProfile(
|
||||
column_boundaries=[0, 0.2, 0.7, 1],
|
||||
column_field_codes=['line_no', 'part_number', 'qty'],
|
||||
column_field_codes=['customer_po_line_no', 'part_number', 'qty'],
|
||||
)
|
||||
html = reconstruct_order_profile_html(
|
||||
characters=_glyphs(
|
||||
@@ -778,14 +815,14 @@ def test_coordinate_profile_parses_one_logical_line_from_multiple_visual_rows():
|
||||
structure_fingerprint=order_profile_structure_fingerprint(grid, header_row_index=0),
|
||||
header_row_index=0, data_start_row_index=1,
|
||||
column_rules=[
|
||||
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['line_no']),
|
||||
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['customer_po_line_no']),
|
||||
OrderProfileColumnRule(column_index=1, extractor_key='direct', target_field_codes=['part_number']),
|
||||
OrderProfileColumnRule(column_index=2, extractor_key='direct', target_field_codes=['qty']),
|
||||
],
|
||||
coordinate_reconstruction=settings,
|
||||
)
|
||||
contract = compile_table_header_contract({'fields': [
|
||||
{'field_code': 'line_no', 'display_name': 'Line', 'enabled': True},
|
||||
{'field_code': 'customer_po_line_no', 'display_name': 'Customer PO Line', 'enabled': True},
|
||||
{'field_code': 'part_number', 'display_name': 'Part', 'enabled': True},
|
||||
{'field_code': 'qty', 'display_name': 'Qty', 'value_type': 'decimal', 'enabled': True},
|
||||
]})
|
||||
@@ -795,7 +832,7 @@ def test_coordinate_profile_parses_one_logical_line_from_multiple_visual_rows():
|
||||
assert parsed.matched is True
|
||||
assert len(parsed.rows) == 1
|
||||
assert parsed.rows[0].fields == {
|
||||
'line_no': '00020', 'part_number': '6Y70B2501901 D4-A08AR1200002 RoHS2', 'qty': 30,
|
||||
'customer_po_line_no': '00020', 'part_number': '6Y70B2501901 D4-A08AR1200002 RoHS2', 'qty': 30,
|
||||
}
|
||||
|
||||
|
||||
@@ -805,7 +842,7 @@ def test_multi_subrow_profile_uses_independent_overlapping_boundaries():
|
||||
{
|
||||
'role': 'main', 'row_offset': 0,
|
||||
'column_boundaries': [0, 0.12, 0.32, 0.5, 0.68, 0.84, 1],
|
||||
'column_field_codes': ['line_no', 'part_number', 'remark', 'unit_price', 'qty', 'uom'],
|
||||
'column_field_codes': ['customer_po_line_no', 'part_number', 'remark', 'unit_price', 'qty', 'uom'],
|
||||
},
|
||||
{
|
||||
'role': 'continuation', 'row_offset': 1,
|
||||
@@ -840,7 +877,7 @@ def test_multi_subrow_profile_parses_merged_fields_with_existing_profile_parser(
|
||||
"""多子行输出必须继续由既有固定列 Profile 解析器消费,避免另造运行链路。"""
|
||||
settings = CoordinateReconstructionProfile(subrow_layouts=[
|
||||
{'role': 'main', 'row_offset': 0, 'column_boundaries': [0, 0.2, 0.65, 1],
|
||||
'column_field_codes': ['line_no', 'part_number', 'qty']},
|
||||
'column_field_codes': ['customer_po_line_no', 'part_number', 'qty']},
|
||||
{'role': 'continuation', 'row_offset': 1, 'column_boundaries': [0, 0.4, 0.7, 1],
|
||||
'column_field_codes': [None, 'required_date', 'line_remark']},
|
||||
])
|
||||
@@ -853,7 +890,7 @@ def test_multi_subrow_profile_parses_merged_fields_with_existing_profile_parser(
|
||||
reconstruction=settings,
|
||||
)
|
||||
grid = parse_html_grid(html, table_id='multi-subrow')
|
||||
headers = ['line_no', 'part_number', 'qty', 'required_date', 'line_remark']
|
||||
headers = ['customer_po_line_no', 'part_number', 'qty', 'required_date', 'line_remark']
|
||||
profile = OrderDocumentProfile(
|
||||
profile_code='MULTI_SUBROW', version=1,
|
||||
structure_fingerprint=order_profile_structure_fingerprint(grid, header_row_index=0),
|
||||
@@ -865,7 +902,7 @@ def test_multi_subrow_profile_parses_merged_fields_with_existing_profile_parser(
|
||||
coordinate_reconstruction=settings,
|
||||
)
|
||||
contract = compile_table_header_contract({'fields': [
|
||||
{'field_code': 'line_no', 'enabled': True},
|
||||
{'field_code': 'customer_po_line_no', 'enabled': True},
|
||||
{'field_code': 'part_number', 'enabled': True},
|
||||
{'field_code': 'qty', 'value_type': 'decimal', 'enabled': True},
|
||||
{'field_code': 'required_date', 'value_type': 'date', 'enabled': True},
|
||||
@@ -886,7 +923,7 @@ def test_multi_subrow_profile_supports_four_or_more_physical_rows():
|
||||
"""逻辑明细行数由模板动态定义,四行版式不得被固定三行实现截断。"""
|
||||
settings = CoordinateReconstructionProfile(subrow_layouts=[
|
||||
{'role': 'main', 'row_offset': 0, 'column_boundaries': [0, 0.25, 0.7, 1],
|
||||
'column_field_codes': ['line_no', 'part_number', 'qty']},
|
||||
'column_field_codes': ['customer_po_line_no', 'part_number', 'qty']},
|
||||
{'role': 'continuation', 'row_offset': 1, 'column_boundaries': [0, 0.5, 1],
|
||||
'column_field_codes': [None, 'customer_part_number']},
|
||||
{'role': 'continuation', 'row_offset': 2, 'column_boundaries': [0, 0.5, 1],
|
||||
@@ -926,8 +963,37 @@ def test_layout_suggestion_uses_real_rows_and_dynamic_column_counts():
|
||||
)
|
||||
|
||||
assert len(suggestions) == 3
|
||||
assert suggestions[0].suggested_field_codes[0] == 'line_no'
|
||||
assert suggestions[0].suggested_field_codes[0] == 'customer_po_line_no'
|
||||
assert suggestions[0].column_samples[0] == ['00020']
|
||||
assert 'B3-AR1000270A1' in suggestions[1].column_samples[0]
|
||||
assert suggestions[2].column_boundaries[0] == 0
|
||||
assert suggestions[2].column_boundaries[-1] == 1
|
||||
|
||||
|
||||
|
||||
def test_resolve_line_start_defaults_to_customer_po_line_no():
|
||||
"""缺省起行锚点为客户 PO 行号;内部项次 line_no 亦可显式配置。"""
|
||||
assert resolve_line_start_field_code(None) == 'customer_po_line_no'
|
||||
assert resolve_line_start_field_code('customer_po_line_no') == 'customer_po_line_no'
|
||||
assert resolve_line_start_field_code('line_no') == 'line_no'
|
||||
|
||||
|
||||
def test_table_region_profile_allows_binding_internal_line_no():
|
||||
"""内部项次 line_no 可作为坐标模板明细字段绑定。"""
|
||||
payload = {
|
||||
'region_id': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'line_start_field_code': 'line_no',
|
||||
'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [{
|
||||
'field_id': 'line', 'field_code': 'line_no',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
}],
|
||||
}],
|
||||
}
|
||||
profile = TableRegionProfile.model_validate(payload)
|
||||
assert profile.line_layouts[0].field_regions[0].field_code == 'line_no'
|
||||
assert profile.line_start_field_code == 'line_no'
|
||||
@@ -79,11 +79,14 @@ def test_pending_customer_blocks_every_downstream_entry(app):
|
||||
ensure_inventory_via_rpa(task, mode='auto'),
|
||||
match_inventory({'task_id': task.task_no}),
|
||||
generate_excel({'task_id': task.task_no}),
|
||||
upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'}),
|
||||
]
|
||||
for result in results:
|
||||
_assert_customer_gate_response(result)
|
||||
|
||||
# upload_to_freight(manual_confirm) 仍受客户门禁约束(不再范围外硬拒绝)。
|
||||
upload = upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'})
|
||||
_assert_customer_gate_response(upload)
|
||||
|
||||
callback = _validate_rpa_callback_gate(task)
|
||||
assert callback is not None
|
||||
assert callback['status'] == 'failed'
|
||||
|
||||
@@ -118,8 +118,8 @@ def test_layout_schedule_is_idempotent_and_force_creates_next_version(app):
|
||||
assert job.payload_json == {'layout_version_id': forced.id}
|
||||
|
||||
|
||||
def test_layout_schedule_reuses_same_owner_completed_layout_for_duplicate_document(app):
|
||||
"""相同管理员重复上传相同文件时,新 Document 必须直接复用可用布局。"""
|
||||
def test_layout_schedule_localizes_same_owner_completed_layout_for_duplicate_document(app):
|
||||
"""相同管理员重复上传相同文件时,新 Document 必须拥有自己的可用布局版本。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
with app.app_context():
|
||||
original = _document()
|
||||
@@ -142,9 +142,13 @@ def test_layout_schedule_reuses_same_owner_completed_layout_for_duplicate_docume
|
||||
reused = schedule_layout_version(duplicate)
|
||||
db.session.commit()
|
||||
|
||||
assert reused.id == ready.id
|
||||
assert duplicate.current_layout_version_id == ready.id
|
||||
assert ShippingDocumentLayoutVersion.query.count() == 1
|
||||
# Layout 版本归属当前 Document;只复用冻结 payload,禁止跨 Document 外键引用。
|
||||
assert reused.id != ready.id
|
||||
assert reused.document_id == duplicate.id
|
||||
assert duplicate.current_layout_version_id == reused.id
|
||||
assert reused.status == 'ready'
|
||||
assert reused.payload_json == ready.payload_json
|
||||
assert ShippingDocumentLayoutVersion.query.count() == 2
|
||||
|
||||
|
||||
def test_layout_parser_revision_change_creates_new_version_without_force(app):
|
||||
|
||||
Loaded 100 of 225 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user