feat(shipping-notice): 增强订单抽取与审计功能,支持取消与保留策略

- 在环境配置中新增进度细化、订单提取取消与审计导出相关的开关
- 实现订单抽取运行的取消功能,允许管理员在运行中进行操作
- 引入审计事件的保留策略,支持三年保留期的自动清理
- 更新相关模型与服务,确保新功能的完整性与可追溯性
- 增强文档与代码注释,反映新的业务逻辑与审计要求
This commit is contained in:
hugo committed 2026-07-30 14:52:21 +08:00
1 parent c85997884b
commit 95cdfe66b0
158 files changed
+19005 -1201

No files matched your search

@@ -131,6 +131,7 @@ def _register_builtin_platform_jobs() -> None:
from app.services.schedule.faq_hot_aggregate_job import run_faq_hot_aggregate_schedule
from app.services.schedule.file_asset_cleanup_job import run_file_asset_cleanup_schedule
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
from app.services.schedule.shipping_audit_retention_job import run_shipping_audit_retention_schedule
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
from app.services.schedule.shipping_order_extraction_progress_cleanup_job import run_shipping_order_extraction_progress_cleanup_schedule
@@ -143,6 +144,18 @@ def _register_builtin_platform_jobs() -> None:
params_schema=({"key": "limit", "type": "number", "label": "单批上限", "required": False, "default": 1000},),
defaults={"limit": 1000},
))
register_platform_job(PlatformJobDefinition(
key="shipping-audit-retention",
label="货代审计到期清理",
handler=run_shipping_audit_retention_schedule,
description="按三年保留期分批清理到期的货代统一审计事件;支持 dry_run 观测。",
category="shipping",
params_schema=(
{"key": "limit", "type": "number", "label": "单批上限", "required": False, "default": 1000},
{"key": "dry_run", "type": "boolean", "label": "仅演练", "required": False, "default": False},
),
defaults={"limit": 1000, "dry_run": False},
))
register_platform_job(PlatformJobDefinition(
key="shipping-inventory-rpa",
label="货代库存 RPA",
@@ -0,0 +1,35 @@
"""
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。
"""
from __future__ import annotations
from typing import Any
from app.services.shipping_notice.audit_query_service import purge_expired_shipping_audit_events
from app.services.shipping_notice.progress_feature_flags import audit_retention_days
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 观测扫描量。
"""
_ = run
params = getattr(task, 'job_params', None) or {}
dry_raw = params.get('dry_run', False)
dry_run = dry_raw in (True, 1, '1', 'true', 'True', 'yes')
result = purge_expired_shipping_audit_events(
limit=int(params.get('limit') or 1000),
dry_run=dry_run,
actor_id=f'schedule:{getattr(task, "id", "unknown")}',
)
result['retention_days'] = audit_retention_days()
return result
@@ -0,0 +1,421 @@
"""
services/shipping_notice/audit_query_service.py
用途:管理员货代审计查询、前后差异投影、受控导出与到期清理。
依赖:ShippingAuditEvent、audit_service 投影规则、fulfillment_audit、progress_audit_contract、SQLAlchemy。
逻辑:由 admin API 调用;列表/详情/导出均做管理员访问审计(失败阻断查询);清理使用 Core DELETE
绕过 ORM 不可变守卫并写清理审计。
"""
from __future__ import annotations
import csv
import io
import json
from datetime import datetime
from typing import Any
from sqlalchemy import delete, or_
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.fulfillment_audit import resolve_request_audit_context
from app.services.shipping_notice.progress_audit_contract import AUDIT_SNAPSHOT_ALLOWED_KEYS
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 _parse_iso(value: str | None) -> datetime | None:
"""解析可选 ISO 时间;非法值抛 ValidationError。"""
text = str(value or '').strip()
if not text:
return None
try:
normalized = text.replace('Z', '+00:00') if text.endswith('Z') else text
return datetime.fromisoformat(normalized).replace(tzinfo=None)
except ValueError as exc:
raise ValidationError('invalid datetime filter', code='SHIPPING_NOTICE.AUDIT_QUERY_INVALID') from exc
def _diff_snapshots(
before: dict[str, Any] | None,
after: dict[str, Any] | None,
) -> list[dict[str, Any]]:
"""
计算白名单快照前后差异。
核心逻辑:仅比较 AUDIT_SNAPSHOT_ALLOWED_KEYS;输出 changed/added/removed,不含敏感值猜测。
"""
left = {k: before.get(k) for k in AUDIT_SNAPSHOT_ALLOWED_KEYS if isinstance(before, dict) and k in before}
right = {k: after.get(k) for k in AUDIT_SNAPSHOT_ALLOWED_KEYS if isinstance(after, dict) and k in after}
keys = sorted(set(left) | set(right))
rows: list[dict[str, Any]] = []
for key in keys:
if key not in left:
rows.append({'key': key, 'change': 'added', 'before': None, 'after': right.get(key)})
elif key not in right:
rows.append({'key': key, 'change': 'removed', 'before': left.get(key), 'after': None})
elif left.get(key) != right.get(key):
rows.append({'key': key, 'change': 'changed', 'before': left.get(key), 'after': right.get(key)})
return rows
def serialize_shipping_audit_event(event: ShippingAuditEvent, *, include_snapshots: bool = False) -> dict[str, Any]:
"""序列化管理员可读审计事件;默认不含完整快照,详情/导出按需打开。"""
payload: dict[str, Any] = {
'id': int(event.id),
'event_type': event.event_type,
'aggregate_type': event.aggregate_type,
'aggregate_id': event.aggregate_id,
'run_no': event.run_no,
'task_no': event.task_no,
'intake_no': event.intake_no,
'actor_type': event.actor_type,
'actor_id': event.actor_id,
'actor_role': event.actor_role,
'request_id': event.request_id,
'operation_id': event.operation_id,
'correlation_id': event.correlation_id,
'source': event.source,
'result': event.result,
'error_code': event.error_code,
'conversation_id': event.conversation_id,
'unit_id': event.unit_id,
'document_id': event.document_id,
'review_case_no': event.review_case_no,
'session_item_id': event.session_item_id,
'owner_user_id': event.owner_user_id,
'client_ip_hash': event.client_ip_hash,
'user_agent_hash': event.user_agent_hash,
'attempt_no': event.attempt_no,
'action': event.action,
'reason_code': event.reason_code,
'reason': event.reason,
'before_hash': event.before_hash,
'after_hash': event.after_hash,
'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 [],
'context_refs': event.context_refs_json if isinstance(event.context_refs_json, dict) else {},
'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),
}
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)
return payload
def _apply_filters(query, *, filters: dict[str, Any]):
"""按管理员筛选条件收窄查询;禁止自由文本全文检索正文。"""
if filters.get('event_type'):
query = query.filter(ShippingAuditEvent.event_type == str(filters['event_type'])[:64])
if filters.get('actor_type'):
query = query.filter(ShippingAuditEvent.actor_type == str(filters['actor_type'])[:16])
if filters.get('actor_id'):
query = query.filter(ShippingAuditEvent.actor_id == str(filters['actor_id'])[:128])
if filters.get('run_no'):
query = query.filter(ShippingAuditEvent.run_no == str(filters['run_no'])[:64])
if filters.get('task_no'):
query = query.filter(ShippingAuditEvent.task_no == str(filters['task_no'])[:64])
if filters.get('document_id'):
query = query.filter(ShippingAuditEvent.document_id == str(filters['document_id'])[:64])
if filters.get('operation_id'):
query = query.filter(ShippingAuditEvent.operation_id == str(filters['operation_id'])[:64])
if filters.get('request_id'):
query = query.filter(ShippingAuditEvent.request_id == str(filters['request_id'])[:64])
if filters.get('aggregate_type'):
query = query.filter(ShippingAuditEvent.aggregate_type == str(filters['aggregate_type'])[:64])
if filters.get('aggregate_id'):
query = query.filter(ShippingAuditEvent.aggregate_id == str(filters['aggregate_id'])[:128])
if filters.get('result'):
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('review_case_no'):
query = query.filter(ShippingAuditEvent.review_case_no == str(filters['review_case_no'])[:64])
if filters.get('owner_user_id'):
query = query.filter(ShippingAuditEvent.owner_user_id == str(filters['owner_user_id'])[:64])
created_from = _parse_iso(filters.get('created_from'))
created_to = _parse_iso(filters.get('created_to'))
if created_from is not None:
query = query.filter(ShippingAuditEvent.created_at >= created_from)
if created_to is not None:
query = query.filter(ShippingAuditEvent.created_at <= created_to)
q = str(filters.get('q') or '').strip()
if q:
# 仅匹配稳定业务编号字段,禁止对 metadata/snapshot 做模糊检索。
like = f'%{q[:64]}%'
query = query.filter(
or_(
ShippingAuditEvent.run_no.ilike(like),
ShippingAuditEvent.task_no.ilike(like),
ShippingAuditEvent.operation_id.ilike(like),
ShippingAuditEvent.request_id.ilike(like),
ShippingAuditEvent.aggregate_id.ilike(like),
ShippingAuditEvent.document_id.ilike(like),
ShippingAuditEvent.session_item_id.ilike(like),
ShippingAuditEvent.review_case_no.ilike(like),
ShippingAuditEvent.conversation_id.ilike(like),
)
)
return query
def _write_access_audit(
*,
admin_user_id: int,
action: str,
request_id: str | None,
summary: dict[str, Any],
) -> None:
"""
记录管理员审计查询/导出访问。
核心逻辑:与履约链路一致,落库失败时回滚并抛错,禁止未留痕的敏感访问继续返回。
"""
ctx = resolve_request_audit_context()
resolved_request_id = request_id or ctx.get('request_id')
try:
append_shipping_audit_event(
event_type='audit_access',
aggregate_type='shipping_audit',
aggregate_id=f'access:{action}',
actor_type='admin',
actor_id=admin_user_id,
request_id=resolved_request_id,
operation_id=resolved_request_id,
client_ip=ctx.get('client_ip'),
user_agent=ctx.get('user_agent'),
source='admin_api',
result='success',
action=action,
metadata=summary,
persist_snapshots=False,
)
db.session.commit()
except Exception as exc:
db.session.rollback()
raise ServiceUnavailableError(
'Shipping audit access persistence failed',
code='SHIPPING_NOTICE.AUDIT_PERSIST_FAILED',
details={'action': action},
) from exc
def list_shipping_audit_events(
*,
admin_user_id: int,
request_id: str | None,
page: int = 1,
page_size: int = 25,
filters: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""分页查询货代统一审计事件;写访问审计。"""
safe_page = max(1, int(page or 1))
safe_page_size = min(100, max(1, int(page_size or 25)))
query = _apply_filters(ShippingAuditEvent.query, filters=filters or {})
total = query.count()
rows = (
query.order_by(ShippingAuditEvent.created_at.desc(), ShippingAuditEvent.id.desc())
.offset((safe_page - 1) * safe_page_size)
.limit(safe_page_size)
.all()
)
payload = {
'items': [serialize_shipping_audit_event(row, include_snapshots=False) for row in rows],
'total': total,
'page': safe_page,
'page_size': safe_page_size,
}
_write_access_audit(
admin_user_id=admin_user_id,
action='list_audit_events',
request_id=request_id,
summary={
'page': safe_page,
'page_size': safe_page_size,
'total': total,
'filters': {
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',
)
if (filters or {}).get(key)
},
},
)
return payload
def get_shipping_audit_event(
*,
admin_user_id: int,
request_id: str | None,
event_id: int,
) -> dict[str, Any]:
"""读取单条审计详情(含白名单快照与 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)
_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},
)
return payload
def export_shipping_audit_events(
*,
admin_user_id: int,
request_id: str | None,
filters: dict[str, Any] | None = None,
limit: int = 2000,
format: str = 'csv',
) -> dict[str, Any]:
"""
受控导出审计事件。
核心逻辑:上限 5000;CSV 仅稳定字段;禁止导出快照全文与敏感 metadata 嵌套;
受 SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED 灰度开关控制。
"""
from app.services.shipping_notice.progress_feature_flags import audit_export_enabled
if not audit_export_enabled():
raise ValidationError(
'Shipping audit export is disabled by feature flag',
code='SHIPPING_NOTICE.AUDIT_EXPORT_FEATURE_DISABLED',
)
safe_limit = min(5000, max(1, int(limit or 2000)))
fmt = str(format or 'csv').strip().lower()
if fmt not in {'csv', 'json'}:
raise ValidationError('export format must be csv or json', code='SHIPPING_NOTICE.AUDIT_EXPORT_INVALID')
query = _apply_filters(ShippingAuditEvent.query, filters=filters or {})
rows = query.order_by(ShippingAuditEvent.created_at.desc(), ShippingAuditEvent.id.desc()).limit(safe_limit).all()
items = [serialize_shipping_audit_event(row, include_snapshots=False) for row in rows]
_write_access_audit(
admin_user_id=admin_user_id,
action='export_audit_events',
request_id=request_id,
summary={'format': fmt, 'exported': len(items), 'limit': safe_limit},
)
if fmt == 'json':
content = json.dumps({'items': items, 'exported': len(items)}, ensure_ascii=False, separators=(',', ':'))
return {
'filename': f'shipping-audit-{datetime.utcnow().strftime("%Y%m%d%H%M%S")}.json',
'content_type': 'application/json; charset=utf-8',
'content': content,
'exported': len(items),
}
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',
]
writer = csv.DictWriter(buffer, fieldnames=fieldnames, extrasaction='ignore')
writer.writeheader()
for item in items:
writer.writerow({key: item.get(key) for key in fieldnames})
return {
'filename': f'shipping-audit-{datetime.utcnow().strftime("%Y%m%d%H%M%S")}.csv',
'content_type': 'text/csv; charset=utf-8',
'content': buffer.getvalue(),
'exported': len(items),
}
def purge_expired_shipping_audit_events(
*,
limit: int = 1000,
dry_run: bool = False,
now: datetime | None = None,
actor_id: str | int | None = 'system',
) -> dict[str, Any]:
"""
清理已过保留期的审计事件。
核心逻辑:先统计候选;dry_run 不删除;正式删除使用 Core DELETE(绕过 ORM append-only 守卫),
并写入一条 system 清理审计说明批次规模。
Args:
limit: 单批上限 1-5000。
dry_run: True 时只返回将删除数量。
now: 可注入当前时间。
actor_id: 清理执行者标识。
Returns:
{dry_run, scanned, deleted, cutoff}。
"""
current = now or datetime.utcnow()
safe_limit = min(5000, max(1, int(limit or 1000)))
candidate_ids = [
int(row[0])
for row in db.session.query(ShippingAuditEvent.id)
.filter(
ShippingAuditEvent.retention_expires_at.isnot(None),
ShippingAuditEvent.retention_expires_at < current,
)
.order_by(ShippingAuditEvent.retention_expires_at.asc(), ShippingAuditEvent.id.asc())
.limit(safe_limit)
.all()
]
if dry_run or not candidate_ids:
return {
'dry_run': bool(dry_run),
'scanned': len(candidate_ids),
'deleted': 0,
'cutoff': _iso(current),
}
# Core bulk delete 不加载 ORM 实例,避免触发 before_delete 不可变守卫。
# [STEP 1] 先从 identity map 取出候选,防止随后 flush 把已删行重新持久化。
tracked = [
obj
for eid in candidate_ids
if (obj := db.session.get(ShippingAuditEvent, eid)) is not None
]
result = db.session.execute(
delete(ShippingAuditEvent).where(ShippingAuditEvent.id.in_(candidate_ids))
)
deleted = int(result.rowcount or 0)
for obj in tracked:
db.session.expunge(obj)
# [STEP 2] 写入系统清理审计(新行),与删除同事务提交。
append_shipping_audit_event(
event_type='audit_retention_purged',
aggregate_type='shipping_audit',
aggregate_id=f'purge:{current.strftime("%Y%m%d%H%M%S")}',
actor_type='system',
actor_id=actor_id,
source='retention_job',
result='success',
action='purge_expired',
metadata={'deleted': deleted, 'limit': safe_limit, 'dry_run': False},
persist_snapshots=False,
)
db.session.commit()
return {
'dry_run': False,
'scanned': len(candidate_ids),
'deleted': deleted,
'cutoff': _iso(current),
}
@@ -1,26 +1,29 @@
"""
backend/app/services/shipping_notice/audit_service.py
用途:集中追加货代领域审计事件并拒绝含敏感业务载荷的元数据。
依赖:ShippingAuditEvent、SQLAlchemy 会话。
逻辑:Run、Task、库存和 Chatflow 服务调用本模块写入状态与决策事实;本服务不提交事务,由调用方保证业务与审计原子性。
用途:集中追加货代领域审计事件并拒绝含敏感业务载荷的元数据与快照。
依赖:ShippingAuditEvent、progress_audit_contract、SQLAlchemy 会话。
逻辑:Run、Task、会话 PDF 工作项、库存和 Chatflow 服务调用本模块写入状态与决策事实;
本服务不提交事务,由调用方保证业务与审计原子性。支持 operation_id、白名单前后快照、
证据引用、会话工作项关联、属主与三年保留到期;IP / User-Agent 仅持久化哈希。
"""
from __future__ import annotations
import hashlib
import json
from datetime import datetime, timedelta
from typing import Any
from app import db
from app.core.errors import ValidationError
from app.models import ShippingAuditEvent
_FORBIDDEN_METADATA_KEYS = frozenset({
'api_key', 'api_base_url', 'authorization', 'body', 'content', 'document_text', 'email_body',
'password', 'prompt', 'provider_config', 'quote', 'token',
})
from app.services.shipping_notice.progress_audit_contract import (
AUDIT_FORBIDDEN_KEYS,
AUDIT_SNAPSHOT_ALLOWED_KEYS,
is_forbidden_audit_key,
)
from app.services.shipping_notice.progress_feature_flags import audit_retention_days
def _stable_hash(value: Any) -> str:
@@ -29,43 +32,210 @@ def _stable_hash(value: Any) -> str:
return hashlib.sha256(encoded.encode('ascii')).hexdigest()
def hash_client_context_value(raw: str | None) -> str | None:
"""
将客户端上下文(IP / User-Agent)转为不可逆哈希。
核心逻辑:空白返回 None;否则 UTF-8 SHA-256 十六进制,永不落库原文。
Args:
raw: 原始 IP 或 User-Agent;禁止已是哈希的二次哈希由调用方自行保证。
Returns:
64 位十六进制哈希,或 None。
"""
text = str(raw or '').strip()
if not text:
return None
return hashlib.sha256(text.encode('utf-8')).hexdigest()
def _collect_forbidden_keys(payload: Any, *, path: str = '') -> list[str]:
"""
递归收集命中敏感黑名单的键路径。
核心逻辑:遍历 dict/list;键名大小写不敏感匹配;返回稳定排序路径便于测试断言。
"""
found: list[str] = []
if isinstance(payload, dict):
for key, child in payload.items():
key_text = str(key)
child_path = f'{path}.{key_text}' if path else key_text
if is_forbidden_audit_key(key_text):
found.append(child_path)
found.extend(_collect_forbidden_keys(child, path=child_path))
elif isinstance(payload, list):
for index, child in enumerate(payload):
found.extend(_collect_forbidden_keys(child, path=f'{path}[{index}]'))
return found
def _sanitize_metadata(metadata: dict[str, Any] | None) -> dict[str, Any]:
"""验证元数据仅含脱敏诊断事实,阻断正文、凭据和字段值进入统一审计。"""
safe = dict(metadata or {})
forbidden = sorted(key for key in safe if str(key).lower() in _FORBIDDEN_METADATA_KEYS)
forbidden = _collect_forbidden_keys(safe)
if forbidden:
raise ValidationError(
'Shipping audit metadata contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN',
details={'forbidden_keys': sorted(set(forbidden))},
)
return safe
def project_audit_snapshot(value: Any | None) -> dict[str, Any] | None:
"""
将业务状态投影为审计白名单快照。
核心逻辑:仅保留 AUDIT_SNAPSHOT_ALLOWED_KEYS 顶层键;命中敏感键直接拒绝而非静默丢弃。
Args:
value: 受控状态 dict;非 dict 返回 None。
Returns:
白名单快照,或 None。
Raises:
ValidationError: 包含禁止键。
"""
if value is None:
return None
if not isinstance(value, dict):
raise ValidationError(
'Shipping audit snapshot must be an object',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
)
# 敏感键拒绝入库;未授权业务键静默剔除,避免“悄悄丢敏感字段”造成审计假完整。
sensitive = [key for key in value if is_forbidden_audit_key(str(key))]
if sensitive:
raise ValidationError(
'Shipping audit snapshot contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(str(k) for k in sensitive))},
)
projected = {
str(key): value[key]
for key in value
if str(key) in AUDIT_SNAPSHOT_ALLOWED_KEYS
}
nested_forbidden = _collect_forbidden_keys(projected)
if nested_forbidden:
raise ValidationError(
'Shipping audit snapshot contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(nested_forbidden))},
)
return projected or None
def _sanitize_refs(refs: list[dict[str, Any]] | None, *, field_name: str) -> list[dict[str, Any]] | None:
"""校验证据/产物引用仅含标识类字段,拒绝 URL 与正文。"""
if refs is None:
return None
if not isinstance(refs, list):
raise ValidationError(
f'Shipping audit {field_name} must be a list',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
)
forbidden = _collect_forbidden_keys(refs)
if forbidden:
raise ValidationError(
f'Shipping audit {field_name} contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(forbidden))},
)
return refs
def default_retention_expires_at(*, now: datetime | None = None) -> datetime:
"""
计算审计默认保留到期时间(默认三年,可由 SHIPPING_NOTICE_AUDIT_RETENTION_DAYS 覆盖)。
Args:
now: 可选当前时间,便于测试注入。
Returns:
UTC naive 到期时间。
"""
base = now or datetime.utcnow()
return base + timedelta(days=audit_retention_days())
def append_shipping_audit_event(
*, event_type: str, aggregate_type: str, aggregate_id: str, run_no: str | None = None,
task_no: str | None = None, intake_no: str | None = None, actor_type: str = 'system',
actor_id: str | int | None = None, request_id: str | None = None,
correlation_id: str | None = None, reason_code: str | None = None,
before: Any = None, after: Any = None, metadata: dict[str, Any] | None = None,
*,
event_type: str,
aggregate_type: str,
aggregate_id: str,
run_no: str | None = None,
task_no: str | None = None,
intake_no: str | None = None,
actor_type: str = 'system',
actor_id: str | int | None = None,
actor_role: str | None = None,
request_id: str | None = None,
operation_id: str | None = None,
correlation_id: str | None = None,
source: str | None = None,
result: str | None = None,
error_code: str | None = None,
conversation_id: str | None = None,
unit_id: str | int | None = None,
document_id: str | int | None = None,
review_case_no: str | None = None,
session_item_id: str | None = None,
owner_user_id: str | int | None = None,
client_ip: str | None = None,
user_agent: str | None = None,
client_ip_hash: str | None = None,
user_agent_hash: str | None = None,
attempt_no: int | None = None,
action: str | None = None,
reason_code: str | None = None,
reason: str | None = None,
before: Any = None,
after: Any = None,
evidence_refs: list[dict[str, Any]] | None = None,
artifact_refs: list[dict[str, Any]] | None = None,
context_refs: dict[str, Any] | None = None,
metadata: dict[str, Any] | None = None,
retention_expires_at: datetime | None = None,
persist_snapshots: bool = True,
) -> ShippingAuditEvent:
"""
追加一条货代审计事实。
Args:
event_type: 稳定业务事件名,例如 ``run_status_changed``;禁止传入用户自由文本。
event_type: 稳定业务事件名,例如 ``session_work_item_created``;禁止传入用户自由文本。
aggregate_type/aggregate_id: 业务聚合类型与稳定编号,不使用可删除记录的外键。
before/after: 可复现的受控状态投影;只持久化其哈希。
operation_id: 同一次用户/系统操作的关联键,与 request_id 共同贯通事件链。
session_item_id: 会话 PDF 工作项 item_no;软引用。
owner_user_id: 业务属主,与 actor_id(实际操作者)区分,支撑代操作审计。
client_ip/user_agent: 原始客户端上下文,仅哈希后入库;也可直接传 *_hash。
before/after: 可复现的受控状态投影;持久化白名单快照及其哈希。
evidence_refs/artifact_refs: FileAsset ID、SHA-256、版本与证据坐标,禁止 URL/正文。
metadata: 仅允许原因码、计数、版本等脱敏诊断事实。
persist_snapshots: False 时只写哈希(兼容历史调用方仅传 before/after 哈希语义)。
Returns:
尚未提交的审计事件,由调用方与业务写入在同一事务提交。
Raises:
ValidationError: actor 类型或元数据包含正文、凭据等敏感字段。
ValidationError: actor 类型、元数据或快照包含正文、凭据等敏感字段。
"""
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')
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
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)
event = ShippingAuditEvent(
event_type=str(event_type)[:64],
aggregate_type=str(aggregate_type)[:64],
@@ -75,13 +245,40 @@ def append_shipping_audit_event(
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_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,
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,
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,
before_hash=_stable_hash(before) if before is not None else None,
after_hash=_stable_hash(after) if after is not None else None,
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,
after_hash=_stable_hash(after_snapshot if after_snapshot is not None else after)
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,
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(),
)
db.session.add(event)
return event
# 供测试与 OpenAPI 契约引用的冻结黑名单导出。
FORBIDDEN_AUDIT_METADATA_KEYS = AUDIT_FORBIDDEN_KEYS
@@ -194,6 +194,20 @@ def promote_candidate(*, user_id: int, candidate_no: str) -> dict[str, Any]:
candidate.acceptance_policy_version = 'manual-review-v1'
candidate.selected = True
_append_candidate_decision_history(candidate, action='promoted', user_id=user_id)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='candidate_promoted',
aggregate_type='order_candidate',
aggregate_id=candidate.candidate_no,
action='promote',
actor_type='user',
actor_id=user_id,
run_no=getattr(candidate, 'run_no', None) or None,
document_id=getattr(document, 'id', None),
before={'status': 'provisional'},
after={'status': 'accepted'},
metadata={'acceptance_mode': 'manual'},
)
db.session.commit()
return _serialize_candidate_brief(candidate)
@@ -214,6 +228,19 @@ def reject_candidate(*, user_id: int, candidate_no: str, reason: str | None = No
candidate.acceptance_policy_version = 'manual-review-v1'
candidate.updated_at = datetime.utcnow()
_append_candidate_decision_history(candidate, action='rejected', user_id=user_id, reason=reason)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='candidate_rejected',
aggregate_type='order_candidate',
aggregate_id=candidate.candidate_no,
action='reject',
actor_type='user',
actor_id=user_id,
run_no=getattr(candidate, 'run_no', None) or None,
reason_code='manual_rejected',
before={'status': 'provisional'},
after={'status': 'rejected'},
)
db.session.commit()
return _serialize_candidate_brief(candidate)
@@ -151,6 +151,20 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
source=event_source,
comment=comment,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_decision',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='reject',
actor_id=payload.get('user_id') or payload.get('actor_id'),
task_no=task.task_no,
conversation_id=task.conversation_id,
before={'status': 'active'},
after={'status': 'rejected'},
metadata={'decision': 'reject'},
source=event_source,
)
db.session.commit()
return tool_response(
status="ok",
@@ -168,6 +182,20 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
source=event_source,
comment=comment,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_decision',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='close',
actor_id=payload.get('user_id') or payload.get('actor_id'),
task_no=task.task_no,
conversation_id=task.conversation_id,
before={'status': 'active'},
after={'status': 'closed'},
metadata={'decision': 'close'},
source=event_source,
)
db.session.commit()
return tool_response(
status="ok",
@@ -553,12 +553,14 @@ def persist_documents_and_candidates(
supplement = parse_email_allocation_tables(
html_tables=canonical_html_tables,
content_hash=str(body_doc.content_hash or ''),
schema_definition=definition,
)
# Outlook 等客户端可能把正文表展平成纯文本行;HTML 表为空时再使用严格序列解析。
if not supplement.get('rows') and not canonical_html_tables:
supplement = parse_email_allocation_text(
body_text=body_text,
content_hash=str(body_doc.content_hash or ''),
schema_definition=definition,
)
supplement['document_id'] = int(body_doc.id)
body_doc.order_extraction_result_json = {'email_supplement': supplement}
@@ -497,9 +497,9 @@ def _matches_termination_rule(
if not absolute.y0 <= center_y <= absolute.y1:
continue
if str(anchor.get('match_mode') or 'contains') == 'exact':
if text.casefold() == expected.casefold():
if text == expected:
return True
elif expected.casefold() in text.casefold():
elif expected in text:
return True
return False
@@ -1116,8 +1116,8 @@ def _text_in_horizontal_region(
def _normalized_header_text(value: str) -> str:
"""标准化表头候选,允许空格、斜线和标点差异但不执行模糊语义猜测。"""
return re.sub(r'[^a-z0-9]+', '', value.lower())
"""标准化表头候选,允许空格、斜线和标点差异但严格保留大小写。"""
return re.sub(r'[^A-Za-z0-9]+', '', value)
def _group_visual_rows(glyphs: list[tuple[int, PositionedCharacter]]) -> list[list[tuple[int, PositionedCharacter]]]:
@@ -430,9 +430,9 @@ def _not_ready(grid: HtmlGrid, issue: str) -> OpenCVTableGeometryResult:
def _normalized_cell_text(value: Any) -> str:
"""以 NFKC、大小写折叠和字母数字/中日韩字符保留生成文本一致性比较键。"""
"""以 NFKC 和字母数字/中日韩字符保留生成严格大小写的一致性比较键。"""
import re
import unicodedata
text = unicodedata.normalize('NFKC', str(value or '')).casefold()
return re.sub(r'[^0-9a-z\u4e00-\u9fff]+', '', text)
text = unicodedata.normalize('NFKC', str(value or ''))
return re.sub(r'[^0-9A-Za-z\u4e00-\u9fff]+', '', text)
@@ -283,9 +283,11 @@ def _find_anchor_matches(
pair for pair in row if str(pair[1].get('text') or '').strip()
]
row_text = ''.join(str(item.get('text') or '') for _index, item in compact)
folded = row_text.casefold()
# 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
for label in expected:
normalized = re.sub(r'\s+', '', label).casefold()
normalized = re.sub(r'\s+', '', label)
start = 0
while normalized and (position := folded.find(normalized, start)) >= 0:
consumed = compact[position:position + len(normalized)]
@@ -94,9 +94,9 @@ class AnchorRule(OrderProfileModel):
def validate_aliases(self) -> 'AnchorRule':
"""只接受有限、去重的精确别名,避免把模糊词表当作自由匹配规则。"""
aliases = [item.strip() for item in self.aliases]
if any(not item for item in aliases) or len({item.casefold() for item in aliases}) != len(aliases):
if any(not item for item in aliases) or len(set(aliases)) != len(aliases):
raise ValueError('anchor aliases must be non-empty and unique')
if self.text.casefold() in {item.casefold() for item in aliases}:
if self.text in set(aliases):
raise ValueError('anchor aliases must not repeat anchor text')
return self
@@ -305,13 +305,26 @@ class TableRegionProfile(OrderProfileModel):
return self
class DocumentMatchAnchor(OrderProfileModel):
"""文档匹配锚点以管理员框选的标签和值区域验证关系,禁止全文纯文本命中。"""
anchor_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
label: str = Field(min_length=1, max_length=160)
value: str = Field(min_length=1, max_length=200)
value_position: Literal['right', 'below'] = 'right'
page_no: int | None = Field(default=None, ge=1)
label_region: RelativeRegion | None = None
value_region: RelativeRegion | None = None
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
class DocumentMatchProfile(OrderProfileModel):
"""定义模板唯一匹配所需的静态证据;动态订单业务值不可进入此对象。"""
"""定义模板唯一匹配所需的标签-值证据;动态订单业务值不可进入此对象。"""
document_type: Literal['purchase_order'] = 'purchase_order'
page_pattern: Literal['one_or_more'] = 'one_or_more'
required_anchors: list[AnchorRule] = Field(default_factory=list)
optional_anchors: list[AnchorRule] = Field(default_factory=list)
required_anchors: list[DocumentMatchAnchor] = Field(default_factory=list)
optional_anchors: list[DocumentMatchAnchor] = Field(default_factory=list)
minimum_score: float = Field(default=0.9, ge=0, le=1)
minimum_margin: float = Field(default=0.15, ge=0, le=1)
@@ -15,6 +15,11 @@ from pydantic import BaseModel, ConfigDict, Field
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfileV2
def _anchor_comparable_text(value: Any) -> str:
"""规范化锚点比较文本,兼容 PDF 字符逐字拼接后丢失的版面空白。"""
return ''.join(str(value or '').casefold().split())
class ProfileMatchCandidate(BaseModel):
"""记录单个冻结 Profile 的非敏感匹配分数和失败原因。"""
@@ -103,19 +108,47 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
)
def _page_text_lines(glyphs: list[dict[str, Any]]) -> list[str]:
"""按视觉行重组冻结字符,供标签和值的相对位置校验使用。"""
lines: list[list[dict[str, Any]]] = []
for glyph in sorted(glyphs, key=lambda item: (item.get('bbox', {}).get('y0', 0), item.get('bbox', {}).get('x0', 0))):
bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else {}
try:
center_y = (float(bbox.get('y0')) + float(bbox.get('y1'))) / 2
height = float(bbox.get('y1')) - float(bbox.get('y0'))
except (TypeError, ValueError):
continue
if lines:
previous = lines[-1]
previous_bbox = previous[0].get('bbox') or {}
previous_center_y = (float(previous_bbox.get('y0', 0)) + float(previous_bbox.get('y1', 0))) / 2
previous_height = float(previous_bbox.get('y1', 0)) - float(previous_bbox.get('y0', 0))
if abs(center_y - previous_center_y) <= max(height, previous_height) * .55:
previous.append(glyph)
continue
lines.append([glyph])
return [
_anchor_comparable_text(''.join(str(item.get('text') or '') for item in sorted(line, key=lambda item: item.get('bbox', {}).get('x0', 0))))
for line in lines
]
def _anchor_present(
anchor: dict[str, Any], *, tables: list[dict[str, Any]], glyph_tables: dict[str, Any],
page_glyphs: dict[str, Any], pages: dict[str, Any],
) -> bool:
"""检查静态锚点是否在整页冻结字符中出现;旧快照才受限回退到表内证据。"""
expected = str(anchor.get('text') or '').strip()
candidates = [expected, *[str(item).strip() for item in anchor.get('aliases') or []]]
if not expected or not all(candidates):
"""只在固定标签右侧或下方验证固定值,避免备注中的同文案误命中模板。"""
label = _anchor_comparable_text(anchor.get('label'))
expected = _anchor_comparable_text(anchor.get('value'))
position = str(anchor.get('value_position') or '')
if not label or not expected or position not in {'right', 'below'}:
return False
page_numbers = sorted({str(item.get('page_no') or '') for item in tables if item.get('page_no')})
if not page_numbers:
page_numbers = sorted(str(page_no) for page_no in pages)
for page_no in page_numbers:
if anchor.get('page_no') is not None and str(anchor.get('page_no')) != page_no:
continue
glyphs = page_glyphs.get(page_no)
# v1 frozen snapshots do not have page glyphs. Preserve historical matching
# rather than silently invalidating published profiles, but never merge rows here.
@@ -127,21 +160,47 @@ def _anchor_present(
page = pages.get(page_no)
if not isinstance(glyphs, list) or not isinstance(page, dict):
continue
selected = glyphs
region = anchor.get('region')
if isinstance(region, dict):
lines = _page_text_lines(glyphs)
label_region = anchor.get('label_region')
value_region = anchor.get('value_region')
if isinstance(label_region, dict) and isinstance(value_region, dict):
try:
width, height = float(page['width']), float(page['height'])
x0, y0, x1, y1 = float(region['x0']) * width, float(region['y0']) * height, float(region['x1']) * width, float(region['y1']) * height
def region_text(region: dict[str, Any]) -> str:
# Center containment separates adjacent lines. Existing edge-only
# regions keep a narrow same-line overlap fallback below.
selected = [item for item in glyphs if isinstance(item.get('bbox'), dict)
and float(region['x0']) * width <= (float(item['bbox'].get('x0', 0)) + float(item['bbox'].get('x1', 0))) / 2 <= float(region['x1']) * width
and float(region['y0']) * height <= (float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 <= float(region['y1']) * height]
if not selected:
overlaps = [item for item in glyphs if isinstance(item.get('bbox'), dict)
and float(item['bbox'].get('x1', 0)) >= float(region['x0']) * width
and float(item['bbox'].get('x0', 0)) <= float(region['x1']) * width
and float(item['bbox'].get('y1', 0)) >= float(region['y0']) * height
and float(item['bbox'].get('y0', 0)) <= float(region['y1']) * height]
if overlaps:
target_y = (float(region['y0']) + float(region['y1'])) * height / 2
reference = min(overlaps, key=lambda item: abs(
(float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 - target_y,
))
reference_box = reference['bbox']
reference_y = (float(reference_box.get('y0', 0)) + float(reference_box.get('y1', 0))) / 2
reference_height = max(1.0, float(reference_box.get('y1', 0)) - float(reference_box.get('y0', 0)))
selected = [item for item in overlaps if abs(
(float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 - reference_y,
) <= max(reference_height, float(item['bbox'].get('y1', 0)) - float(item['bbox'].get('y0', 0))) * .55]
return _anchor_comparable_text(''.join(str(item.get('text') or '') for item in sorted(selected, key=lambda item: (item.get('bbox', {}).get('y0', 0), item.get('bbox', {}).get('x0', 0)))))
if label in region_text(label_region) and expected in region_text(value_region):
return True
except (KeyError, TypeError, ValueError):
continue
selected = [item for item in glyphs if isinstance(item, dict) and isinstance(item.get('bbox'), dict)
and x0 <= (float(item['bbox'].get('x0', 0)) + float(item['bbox'].get('x1', 0))) / 2 <= x1
and y0 <= (float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 <= y1]
text = ''.join(str(item.get('text') or '') for item in sorted(selected, key=lambda item: (item.get('bbox', {}).get('y0', 0), item.get('bbox', {}).get('x0', 0))))
if str(anchor.get('match_mode') or 'contains') == 'exact':
if any(candidate.casefold() == text.casefold() for candidate in candidates):
continue
for index, line in enumerate(lines):
label_index = line.find(label)
if label_index < 0:
continue
if position == 'right' and expected in line[label_index + len(label):]:
return True
if position == 'below' and index + 1 < len(lines) and expected in lines[index + 1]:
return True
elif any(candidate.casefold() in text.casefold() for candidate in candidates):
return True
return False
@@ -168,9 +168,9 @@ def _normalized_character_stream(
def _normalize_text(value: Any) -> str:
"""以 NFKC/casefold 保留字母数字和中日韩字符,忽略版面空白及标点。"""
text = unicodedata.normalize('NFKC', str(value or '')).casefold()
return re.sub(r'[^0-9a-z\u4e00-\u9fff]+', '', text)
"""以 NFKC 保留字母数字和中日韩字符,忽略版面空白及标点但保留大小写。"""
text = unicodedata.normalize('NFKC', str(value or ''))
return re.sub(r'[^0-9A-Za-z\u4e00-\u9fff]+', '', text)
def _bbox_center_within(parent: LayoutBBox, child: LayoutBBox) -> bool:
@@ -302,9 +302,25 @@ def list_independent_samples(*, suite_id: int, actor_id: int) -> dict[str, Any]:
for table in tables:
if not isinstance(table, dict) or not str(table.get('table_id') or ''):
continue
table_id = str(table['table_id'])
try:
grid = parse_html_grid(str(table.get('html') or ''), table_id=table_id)
except ValidationError:
# 候选列表只展示已有布局摘要;异常表格留给预览接口返回精确错误。
continue
header_preview = [
slot.text for slot in (grid.rows[0] if grid.rows else [])
if slot is not None and slot.text
][:3]
result.append({
'document_id': document.id, 'table_id': str(table['table_id']),
'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)
),
'row_count': grid.row_count, 'column_count': grid.column_count,
'header_preview': header_preview,
})
return {'samples': result}
@@ -762,6 +778,14 @@ def assert_profile_publishable(profile: ShippingOrderDocumentProfile) -> None:
"""执行坐标模板发布门禁:训练样本、独立盲测与跨页声明覆盖均不可绕过。"""
from app.models import ShippingOrderDocumentProfileSample
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
document_match = definition.get('document_match') if isinstance(definition.get('document_match'), dict) else {}
required_anchors = document_match.get('required_anchors') if isinstance(document_match.get('required_anchors'), list) else []
if not required_anchors:
raise ConflictError(
'At least one required static document anchor is required before publishing',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_REQUIRED_ANCHOR',
)
draft_checksum = _quality_checksum(profile)
training_count = ShippingOrderDocumentProfileSample.query.filter_by(
profile_id=profile.id, sample_role='training',
@@ -1,7 +1,8 @@
"""解析 EML 正文 HTML 补充表并保留每格可追溯证据。
依赖:受控 HTML 网格解析、PO/Reservation 标准化。
逻辑:只接受明确表头;表格歧义或缺 PO 保留原因,不将正文直接转成订单。
依赖:受控 HTML 网格解析、冻结订单 Schema 表头契约、PO/Reservation 标准化。
逻辑:订单字段表头只复用 Run/当前发布 Schema 的显式别名;邮件专属的分配事实
仍使用受控固定列。表格歧义或缺 PO 保留原因,不将正文直接转成订单。
"""
from __future__ import annotations
@@ -18,29 +19,34 @@ from app.services.shipping_notice.po_number import normalize_po_number
from app.services.shipping_notice.reservation_id import validated_reservation_id
_HEADERS = {
'po_number': {'po', 'po number', 'po no', 'po #', 'purchase order', 'purchase order number'},
'mpn': {'mpn', 'manufacturer part number', 'manufacturer pn', 'part number', 'mfr part number'},
'reservation_id': {'reservation id', 'reservation', 'reservation no', 'reservation number'},
_STATIC_HEADERS = {
'allocation_id': {'allocation id', 'allocation'},
'source_type': {'source type', 'source', 'hub code', 'hub'},
'source_from_party': {'source from party', 'source from', 'from party', 'supplier'},
'allocated_entity': {'allocated entity', 'allocation entity'},
'allocated_qty': {'allocated qty', 'allocated quantity', 'allocation qty', 'allocation quantity'},
}
_NORMALIZED_HEADERS = {
field: {normalize_table_header(item) for item in aliases}
for field, aliases in _HEADERS.items()
_NORMALIZED_STATIC_HEADERS = {
field: {normalize_table_header(item).casefold() for item in aliases}
for field, aliases in _STATIC_HEADERS.items()
}
_SCHEMA_FIELD_TO_SUPPLEMENT_FIELD = {
'customer_po_number': 'po_number',
'part_number': 'mpn',
'reservation_id': 'reservation_id',
'inventory_source_hint': 'source_type',
}
def _field_map(grid: Any) -> tuple[dict[int, str], list[str]]:
"""只选择唯一映射的首行表头;重复字段映射直接标为复核。"""
def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[int, str], list[str]]:
"""将首行映射为 Schema 订单字段或邮件专属字段;重复映射直接标为复核。"""
schema_headers = _schema_headers(schema_definition)
mapped: dict[int, str] = {}
issues: list[str] = []
for column, slot in enumerate(grid.rows[0]):
normalized = normalize_table_header(slot.text if slot is not None else '')
hits = [field for field, aliases in _NORMALIZED_HEADERS.items() if normalized in aliases]
normalized = normalize_table_header(slot.text if slot is not None else '').casefold()
schema_field = schema_headers.get(normalized)
static_hits = [field for field, aliases in _NORMALIZED_STATIC_HEADERS.items() if normalized in aliases]
hits = ([schema_field] if schema_field else []) + static_hits
if len(hits) == 1:
if hits[0] in mapped.values():
issues.append('email_supplement_duplicate_header')
@@ -53,8 +59,27 @@ def _field_map(grid: Any) -> tuple[dict[int, str], list[str]]:
return mapped, sorted(set(issues))
def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str) -> dict[str, Any]:
"""输出正文补充行和 DOM 单元格证据,不处理 PDF 合并或数量覆盖。"""
def _schema_headers(schema_definition: dict[str, Any]) -> dict[str, str | None]:
"""收集邮件补充允许的 Schema 别名;跨字段冲突必须显式保留为不可映射。"""
headers: dict[str, str | None] = {}
for raw in schema_definition.get('fields') or []:
if not isinstance(raw, dict) or not raw.get('enabled', True):
continue
supplement_field = _SCHEMA_FIELD_TO_SUPPLEMENT_FIELD.get(str(raw.get('field_code') or ''))
if not supplement_field:
continue
for value in (raw.get('display_name'), *(raw.get('aliases') or [])):
normalized = normalize_table_header(value).casefold()
if normalized:
if normalized not in headers:
headers[normalized] = supplement_field
elif headers[normalized] != supplement_field:
headers[normalized] = None
return headers
def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str, schema_definition: dict[str, Any]) -> dict[str, Any]:
"""输出正文补充行和 DOM 单元格证据;订单字段别名必须来自冻结 Schema。"""
result = empty_email_supplement_result()
rows: list[dict[str, Any]] = []
issues: list[str] = []
@@ -64,7 +89,7 @@ def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str)
except Exception:
issues.append('email_supplement_table_invalid')
continue
mapping, table_issues = _field_map(grid)
mapping, table_issues = _field_map(grid, schema_definition=schema_definition)
issues.extend(table_issues)
if table_issues:
continue
@@ -101,7 +126,7 @@ def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str)
return result
def parse_email_allocation_text(*, body_text: str, content_hash: str) -> dict[str, Any]:
def parse_email_allocation_text(*, body_text: str, content_hash: str, schema_definition: dict[str, Any]) -> dict[str, Any]:
"""解析无 HTML 的纵向表头正文,只有完整唯一表头序列才会产出补充行。
这类邮件客户端会把一行表头和数据单元格都展平成换行文本。按固定表头序列
@@ -114,13 +139,19 @@ def parse_email_allocation_text(*, body_text: str, content_hash: str) -> dict[st
'allocated_entity', 'mpn', 'allocated_qty', 'po_number',
]
normalized = [normalize_table_header(token) for token in tokens]
aliases = {
field: {normalize_table_header(alias) for alias in values}
for field, values in _HEADERS.items()
schema_headers = _schema_headers(schema_definition)
aliases: dict[str, set[str]] = {
field: {header for header, mapped_field in schema_headers.items() if mapped_field == field}
for field in _SCHEMA_FIELD_TO_SUPPLEMENT_FIELD.values()
}
aliases.update(_NORMALIZED_STATIC_HEADERS)
casefold_aliases = {
field: {value.casefold() for value in values}
for field, values in aliases.items()
}
start = next((
index for index in range(0, len(tokens) - len(expected) + 1)
if all(normalized[index + offset] in aliases[field] for offset, field in enumerate(expected))
if all(normalized[index + offset].casefold() in casefold_aliases[field] for offset, field in enumerate(expected))
), None)
if start is None:
return result
@@ -0,0 +1,202 @@
"""
services/shipping_notice/fulfillment_audit.py
用途:履约关键节点与敏感访问写入统一审计事件的轻量封装。
依赖:audit_service.append_shipping_audit_event、Flask g.request_id / request、AppError。
逻辑:由 candidate / decision / fulfillment_workflow / workspace 读取与导出 / 工作项写路径调用;
默认 strict=True,审计写入失败时抛错,禁止业务成功而审计缺失;访问审计逐次留痕;
自动附带 request_id 与客户端 IP/UA(仅哈希入库)。
"""
from __future__ import annotations
import logging
from typing import Any
from app.core.errors import ServiceUnavailableError
from app.services.shipping_notice.audit_service import append_shipping_audit_event
_LOGGER = logging.getLogger(__name__)
def _request_id() -> str | None:
"""尽量读取当前请求 ID;Worker 场景允许为空。"""
try:
from flask import g
return str(getattr(g, 'request_id', '') or '') or None
except RuntimeError:
return None
def _client_request_context() -> tuple[str | None, str | None]:
"""
读取当前请求客户端 IP 与 User-Agent(仅供哈希入库)。
核心逻辑:优先 X-Forwarded-For 首段;无请求上下文时返回 (None, None)。
"""
try:
from flask import request
forwarded = str(request.headers.get('X-Forwarded-For') or '').split(',')[0].strip()
ip = forwarded or str(request.remote_addr or '').strip() or None
ua = str(request.headers.get('User-Agent') or '').strip() or None
return ip, ua
except RuntimeError:
return None, None
def resolve_request_audit_context() -> dict[str, str | None]:
"""
解析当前 HTTP 请求的审计关联上下文。
核心逻辑:合并 request_id 与原始 IP/UA(供 append 侧哈希);无 Flask 请求时全空。
Returns:
含 request_id / client_ip / user_agent 的字典;值均可为 None。
"""
client_ip, user_agent = _client_request_context()
return {
'request_id': _request_id(),
'client_ip': client_ip,
'user_agent': user_agent,
}
def record_fulfillment_audit(
*,
event_type: str,
aggregate_type: str,
aggregate_id: str,
action: str,
actor_type: str = 'user',
actor_id: str | int | None = None,
run_no: str | None = None,
task_no: str | None = None,
document_id: str | int | None = None,
review_case_no: str | None = None,
conversation_id: str | None = None,
session_item_id: str | None = None,
owner_user_id: str | int | None = None,
reason_code: str | None = None,
reason: str | None = None,
result: str = 'success',
before: dict[str, Any] | None = None,
after: dict[str, Any] | None = None,
metadata: dict[str, Any] | None = None,
source: str = 'api',
strict: bool = True,
) -> None:
"""
追加履约审计。
核心逻辑:默认与业务同事务写入;strict=True 时失败抛错,保证必须留存;
自动附带 request_id 与客户端 IP/UA 哈希。
Args:
event_type/action: 稳定事件与动作码。
before/after: 必须已是白名单可投影的状态摘要。
strict: True 时审计失败阻断调用方;False 时仅记日志(仅限显式降级场景)。
"""
request_id = _request_id()
client_ip, user_agent = _client_request_context()
try:
append_shipping_audit_event(
event_type=event_type,
aggregate_type=aggregate_type,
aggregate_id=str(aggregate_id),
action=action,
actor_type=actor_type,
actor_id=actor_id,
request_id=request_id,
operation_id=request_id,
run_no=run_no,
task_no=task_no,
document_id=document_id,
review_case_no=review_case_no,
conversation_id=conversation_id,
session_item_id=session_item_id,
owner_user_id=owner_user_id,
client_ip=client_ip,
user_agent=user_agent,
reason_code=reason_code,
reason=reason,
result=result,
before=before,
after=after,
metadata=metadata or {},
source=source,
)
except Exception as exc:
_LOGGER.exception('fulfillment audit append failed event_type=%s aggregate_id=%s', event_type, aggregate_id)
if strict:
raise ServiceUnavailableError(
'Shipping audit persistence failed',
code='SHIPPING_NOTICE.AUDIT_PERSIST_FAILED',
details={'event_type': event_type, 'aggregate_id': str(aggregate_id)},
) from exc
def record_access_audit(
*,
action: str,
aggregate_type: str,
aggregate_id: str,
actor_id: str | int | None,
actor_type: str = 'user',
run_no: str | None = None,
task_no: str | None = None,
document_id: str | int | None = None,
review_case_no: str | None = None,
conversation_id: str | None = None,
session_item_id: str | None = None,
owner_user_id: str | int | None = None,
metadata: dict[str, Any] | None = None,
strict: bool = True,
) -> bool:
"""
记录敏感读取/导出访问审计(无业务正文);每次调用均落库。
核心逻辑:自行提交;失败时回滚并按 strict 抛错,禁止静默丢审计;附带客户端哈希。
Returns:
True 表示本次写入了新事件。
"""
from app import db
request_id = _request_id()
client_ip, user_agent = _client_request_context()
try:
append_shipping_audit_event(
event_type='shipping_resource_accessed',
aggregate_type=str(aggregate_type)[:64],
aggregate_id=str(aggregate_id)[:128],
action=str(action)[:64],
actor_type=actor_type,
actor_id=actor_id,
request_id=request_id,
operation_id=request_id,
run_no=run_no,
task_no=task_no,
document_id=document_id,
review_case_no=review_case_no,
conversation_id=conversation_id,
session_item_id=session_item_id,
owner_user_id=owner_user_id,
client_ip=client_ip,
user_agent=user_agent,
result='success',
metadata=metadata or {'access': True},
source='api',
persist_snapshots=False,
)
db.session.commit()
return True
except Exception as exc:
db.session.rollback()
_LOGGER.exception('access audit append failed action=%s aggregate_id=%s', action, aggregate_id)
if strict:
raise ServiceUnavailableError(
'Shipping access audit persistence failed',
code='SHIPPING_NOTICE.AUDIT_PERSIST_FAILED',
details={'action': action, 'aggregate_id': str(aggregate_id)},
) from exc
return False
@@ -615,6 +615,21 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
detail=filename,
)
log_task_event(task, "export_generated", {"file_name": filename, "artifact_no": artifact.artifact_no}, actor_id=actor_id, source='workspace_api' if actor_id else 'system')
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='excel_generated',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='generate_excel',
actor_type='user' if actor_id else 'system',
actor_id=actor_id,
task_no=task.task_no,
conversation_id=task.conversation_id,
before={'status': 'matched'},
after={'status': 'waiting_upload'},
metadata={'artifact_no': artifact.artifact_no},
source='workspace_api' if actor_id else 'system',
)
_commit_generated_export(path)
return tool_response(
status="ok",
@@ -843,6 +858,26 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
"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",
@@ -950,6 +985,21 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
detail=t("workflow.fulfillment.task_completed", lang=lang),
)
log_task_event(task, "upload_rpa_success", {"artifact_id": completed.artifact_id, "attempt_id": completed.id})
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='rpa_upload_result',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='upload_rpa_success',
actor_type='rpa',
task_no=task.task_no,
conversation_id=task.conversation_id,
result='success',
before={'status': 'uploading'},
after={'status': 'uploaded'},
metadata={'attempt_id': int(completed.id), 'artifact_id': int(completed.artifact_id or 0) or None},
source='rpa_callback',
)
db.session.commit()
return tool_response(
status="ok",
@@ -20,6 +20,7 @@ from app.models import (
ShippingOrderExtraction,
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
ShippingOrderSchemaVersion,
)
from app.services.shipping_notice.customer_normalization import (
normalize_customer_name,
@@ -82,16 +83,58 @@ def _accepted_header_values(candidate: ShippingNoticeCandidate) -> tuple[Shippin
}
def definition_context_field_is_compatible(
definition: dict[str, Any], extraction: ShippingOrderExtraction, actual_field_id: str,
) -> bool:
"""校验新版 Schema 字段能否承接旧规则快照,防止字段 UUID 漂移误伤稳定业务语义。"""
expected_id = str(definition.get('context_field_id') or '')
if actual_field_id == expected_id:
return True
field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
field_code = str(field_config.get('field_code') or '').strip()
expected_scope = str(field_config.get('scope') or '')
expected_type = str(field_config.get('value_type') or '')
schema_version = db.session.get(ShippingOrderSchemaVersion, extraction.schema_version_id)
fields = (schema_version.definition_json or {}).get('fields') if schema_version else []
actual = next((item for item in fields or [] if str(item.get('field_id') or '') == actual_field_id), None)
return bool(
field_code
and actual
and str(actual.get('field_code') or '') == field_code
and str(actual.get('scope') or '') == expected_scope == 'header'
and str(actual.get('value_type') or '') == expected_type
and actual.get('enabled', True)
and actual.get('available_for_customer_identity')
)
def _resolved_context_field_id(
definition: dict[str, Any], extraction: ShippingOrderExtraction | None, header_values: dict[str, dict[str, Any]],
) -> str | None:
"""优先使用快照 UUID;Schema 升级仅在字段业务语义未变化时按 field_code 映射到新 UUID。"""
expected_id = str(definition.get('context_field_id') or '')
if expected_id in header_values:
return expected_id
if extraction is None:
return None
for field_id in header_values:
if definition_context_field_is_compatible(definition, extraction, field_id):
return field_id
return None
def _source_evidence(
definitions: list[dict[str, Any]], *, candidate: ShippingNoticeCandidate, intake: ShippingNoticeIntake,
) -> tuple[list[dict[str, Any]], ShippingOrderExtraction | None]:
"""按规则快照的 context_field_id 编译证据,只消费统一已裁决字段值。"""
"""按规则快照编译证据;Schema UUID 漂移时仅映射语义兼容的 Header 字段。"""
extraction, header_values = _accepted_header_values(candidate)
evidence: list[dict[str, Any]] = []
for definition in definitions:
definition_id = str(definition.get('id') or '')
code = str(definition.get('definition_code') or '')
field_id = str(definition.get('context_field_id') or '')
field_id = _resolved_context_field_id(definition, extraction, header_values)
if field_id is None:
continue
accepted = header_values.get(field_id)
if not accepted:
continue
@@ -599,6 +599,71 @@ def page_text_candidates(profile_id: int, *, document_id: int, page_no: int, act
return {'document_id': document.id, 'page_no': int(page_no), 'tables': candidates, 'status': 'needs_review'}
def read_preview_page_region_text(
profile_id: int, *, data: dict[str, Any], page_no: int, actor_id: int | None,
) -> dict[str, Any]:
"""读取管理员框选区域的冻结坐标文字,供画布创建标签-值匹配锚点。
Args:
profile_id: 当前草稿模板;只允许读取其绑定样本。
data: 必须含 document_id 和相对坐标 region,禁止传入资产路径或任意正文。
page_no: 当前受控预览页号。
actor_id: 当前管理员;缺失时按不存在样本关闭。
Returns:
仅返回框内恢复的纯文本和证据来源,不返回坐标、页面内容或存储信息。
"""
if actor_id is None:
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
try:
document_id = int(data.get('document_id'))
region = data.get('region')
x0, y0, x1, y1 = (float(region[key]) for key in ('x0', 'y0', 'x1', 'y1'))
except (KeyError, TypeError, ValueError) as exc:
raise ValidationError('region is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') from exc
if not (0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1):
raise ValidationError('region is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
document = _bound_sample_document(profile_id, document_id)
layout = _ensure_page_coordinate_evidence(document=document, layout=_document_layout(document), page_no=page_no)
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
page = (evidence.get('pages') or {}).get(str(page_no)) or {}
try:
width, height = float(page['width']), float(page['height'])
except (KeyError, TypeError, ValueError) as exc:
raise ValidationError('Page coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc
glyphs, source = _page_coordinate_characters(layout, page_no=page_no)
# Prefer character centers: this is the only rule that reliably separates
# adjacent document lines. The overlap fallback is used solely for an edge-only
# selection and is constrained to the nearest visual line.
selected_by_center = []
overlapping = []
for glyph in glyphs:
bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None
if not bbox:
continue
try:
glyph_x0, glyph_x1 = float(bbox['x0']) / width, float(bbox['x1']) / width
glyph_y0, glyph_y1 = float(bbox['y0']) / height, float(bbox['y1']) / height
except (KeyError, TypeError, ValueError, ZeroDivisionError):
continue
center_x, center_y = (glyph_x0 + glyph_x1) / 2, (glyph_y0 + glyph_y1) / 2
if x0 <= center_x <= x1 and y0 <= center_y <= y1:
selected_by_center.append(glyph)
elif glyph_x1 >= x0 and glyph_x0 <= x1 and glyph_y1 >= y0 and glyph_y0 <= y1:
overlapping.append(glyph)
selected = selected_by_center
if not selected and overlapping:
target_y = (y0 + y1) / 2
lines = _page_text_lines(overlapping)
nearest = min(lines, key=lambda line: abs(((line[1]['y0'] + line[1]['y1']) / 2 / height) - target_y))
selected = nearest[2]
text = ' '.join(line[0].strip() for line in _page_text_lines(selected) if line[0].strip()).strip()
_audit(profile_id=int(profile_id), document_id=document.id, event_type='preview_region_text_read', actor_id=actor_id, detail={
'page_no': int(page_no), 'character_count': len(text), 'source': source,
})
db.session.commit()
return {'document_id': document.id, 'page_no': int(page_no), 'text': text, 'source': source, 'status': 'needs_review'}
def preview_profile_region(
profile_id: int, *, data: dict[str, Any], actor_id: int | None,
) -> dict[str, Any]:
@@ -2119,7 +2184,7 @@ def save_draft(
def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""从不可变版本复制新草稿;同编码只允许一个草稿。"""
"""从不可变版本复制新草稿,并继承编辑画布所需的标注样本;同编码只允许一个草稿。"""
source = db.session.get(ShippingOrderDocumentProfile, profile_id)
if source is None:
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
@@ -2152,6 +2217,18 @@ def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
)
db.session.add(clone)
db.session.flush()
annotation_samples = ShippingOrderDocumentProfileSample.query.filter_by(
profile_id=source.id, sample_role='annotation',
).all()
for sample in annotation_samples:
# 草稿编辑器需要 annotation 样本加载 PDF;训练和盲测样本仍须重新绑定以保留发布门禁。
db.session.add(ShippingOrderDocumentProfileSample(
profile_id=clone.id,
document_id=sample.document_id,
table_id=sample.table_id,
sample_role='annotation',
created_by_id=actor_id,
))
revision = ShippingOrderDocumentProfileDraftRevision(
profile_id=clone.id,
revision_no=1,
@@ -2167,7 +2244,10 @@ def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
)
db.session.add(revision)
_audit(profile_id=clone.id, event_type='draft_cloned', actor_id=actor_id, detail={
'source_profile_id': source.id, 'version': clone.version, 'revision_no': revision.revision_no,
'source_profile_id': source.id,
'version': clone.version,
'revision_no': revision.revision_no,
'inherited_annotation_sample_count': len(annotation_samples),
})
db.session.commit()
result = payload(clone)
@@ -0,0 +1,586 @@
"""
services/shipping_notice/order_extraction_cancel_service.py
用途:处理订单抽取 Run/Unit 的取消请求,实现取消请求语义与权限校验。
依赖:order_extraction_plan 状态机、order_extraction_progress、audit_service、progress_audit_contract、progress_feature_flags。
逻辑:排队 Unit 立即 cancelled;执行中 Unit 仅标记 cancellation_requested,由 Worker 在安全点收口;
已完成结果保留。业务变更、Progress Event 与审计必须同事务追加。功能开关关闭时拒绝取消。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from flask import g
from app import db
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
from app.models import (
ShippingOrderExtractionProgressEvent,
ShippingOrderExtractionRun,
ShippingOrderExtractionUnit,
User,
)
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
from app.services.shipping_notice.order_extraction_progress import (
record_order_extraction_progress_event,
record_unit_progress,
)
from app.services.shipping_notice.progress_feature_flags import order_extraction_cancel_enabled
ACTIVE_RUN_STATUSES = frozenset({'queued', 'processing'})
PENDING_UNIT_STATUS = 'pending'
IN_FLIGHT_UNIT_STATUSES = frozenset({'routing', 'matching_profile', 'extracting', 'merging_supplement'})
PRESERVE_UNIT_STATUSES = frozenset({'candidate_ready', 'review_required', 'failed', 'cancelled'})
def _require_cancel_feature_enabled() -> None:
"""灰度关闭取消能力时拒绝 API,避免投影已隐藏动作后仍被直调。"""
if not order_extraction_cancel_enabled():
raise ValidationError(
'Order extraction cancel is disabled by feature flag',
code='SHIPPING_NOTICE.CANCEL_FEATURE_DISABLED',
)
def _request_id() -> str | None:
"""读取当前请求 ID,用于审计串联。"""
value = getattr(g, 'request_id', None)
return str(value) if value else None
def _operation_id(explicit: str | None = None) -> str:
"""生成或复用 operation_id。"""
text = str(explicit or '').strip()
if text:
return text[:64]
request_id = _request_id()
if request_id:
return request_id[:64]
return f'cancel-{datetime.utcnow().strftime("%Y%m%d%H%M%S")}-{id(object()) % 10_000_000}'
def _resolve_cancellation_operation_id(run: ShippingOrderExtractionRun, explicit: str | None = None) -> str:
"""
复用取消请求时的 operation_id,避免 Worker 收口生成新链路。
核心逻辑:显式参数 > progress 事件 summary.operation_id > 新建。
"""
if str(explicit or '').strip():
return _operation_id(explicit)
event = (
ShippingOrderExtractionProgressEvent.query
.filter_by(run_id=int(run.id), event_code='cancellation_requested')
.order_by(ShippingOrderExtractionProgressEvent.sequence_no.desc())
.first()
)
if event is not None and isinstance(event.summary_json, dict):
previous = str(event.summary_json.get('operation_id') or '').strip()
if previous:
return previous[:64]
return _operation_id()
def _is_admin(actor: User) -> bool:
"""判断操作者是否具备管理员取消权限。"""
return str(getattr(actor, 'role', '') or '') == 'admin'
def _lock_run_for_actor(*, actor: User, run_no: str) -> ShippingOrderExtractionRun:
"""
按权限锁定 Run。
核心逻辑:普通用户只能锁定自己的 Run;管理员可锁定任意 Run。
"""
query = db.session.query(ShippingOrderExtractionRun).filter_by(run_no=str(run_no or '').strip())
if not _is_admin(actor):
query = query.filter_by(user_id=int(actor.id))
run = query.with_for_update().first()
if run is None:
raise NotFoundError(
'Shipping order extraction run not found',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_FOUND',
)
return run
def _validate_cancel_permission(*, actor: User, run: ShippingOrderExtractionRun, reason: str | None) -> None:
"""
校验取消权限与原因。
Raises:
ForbiddenError: 普通用户取消他人 Run。
ValidationError: 管理员代取消缺少原因。
"""
admin = _is_admin(actor)
if not admin and int(run.user_id) != int(actor.id):
raise ForbiddenError(
'Cannot cancel another user order extraction run',
code='SHIPPING_NOTICE.CANCEL_FORBIDDEN',
)
if admin and int(run.user_id) != int(actor.id) and not str(reason or '').strip():
raise ValidationError(
'Admin cancel requires a reason',
code='SHIPPING_NOTICE.CANCEL_REASON_REQUIRED',
)
def _cancellation_payload(*, actor: User, reason: str | None, reason_code: str | None, now: datetime) -> dict[str, Any]:
"""构造取消元数据写入字段。"""
return {
'cancellation_requested_at': now,
'cancellation_actor_type': 'admin' if _is_admin(actor) else 'user',
'cancellation_actor_id': str(actor.id),
'cancellation_reason': str(reason).strip()[:2000] if reason else None,
'cancellation_reason_code': str(reason_code).strip()[:64] if reason_code else None,
}
def _apply_fields(target: Any, fields: dict[str, Any]) -> None:
"""把取消元数据写到 Run 或 Unit。"""
for key, value in fields.items():
setattr(target, key, value)
def _unit_snapshot(unit: ShippingOrderExtractionUnit) -> dict[str, Any]:
"""Unit 审计白名单投影。"""
return {
'status': unit.status,
'activity_version': int(getattr(unit, 'activity_version', 1) or 1),
'cancellation_requested': bool(getattr(unit, 'cancellation_requested_at', None)),
'attempt_count': int(unit.attempt_count or 0),
}
def _run_snapshot(run: ShippingOrderExtractionRun) -> dict[str, Any]:
"""Run 审计白名单投影。"""
return {
'status': run.status,
'phase': run.phase,
'progress_version': int(run.progress_version or 0),
'cancellation_requested': bool(run.cancellation_requested_at),
}
def _cancel_pending_unit(
*,
run: ShippingOrderExtractionRun,
unit: ShippingOrderExtractionUnit,
fields: dict[str, Any],
operation_id: str,
) -> None:
"""立即取消排队 Unit,并写入进度与审计。"""
before = _unit_snapshot(unit)
_apply_fields(unit, fields)
unit.activity_version = int(getattr(unit, 'activity_version', 1) or 1) + 1
unit.cancellation_completed_at = fields['cancellation_requested_at']
transition_order_extraction_unit(unit, target_status='cancelled', error_code='ORDER_EXTRACTION_CANCELLED')
record_unit_progress(
run=run,
unit=unit,
event_code='unit_cancelled',
reason_code=fields.get('cancellation_reason_code') or 'user_cancelled',
summary={'operation_id': operation_id},
commit=False,
)
append_shipping_audit_event(
event_type='order_extraction_unit_cancel_completed',
aggregate_type='order_extraction_unit',
aggregate_id=str(unit.id),
run_no=run.run_no,
actor_type=fields['cancellation_actor_type'],
actor_id=fields['cancellation_actor_id'],
request_id=_request_id(),
operation_id=operation_id,
source='api',
result='success',
action='cancel_unit',
reason=fields.get('cancellation_reason'),
reason_code=fields.get('cancellation_reason_code') or 'user_cancelled',
conversation_id=run.conversation_id,
unit_id=unit.id,
document_id=unit.document_id,
before=before,
after=_unit_snapshot(unit),
)
def _request_inflight_unit_cancel(
*,
run: ShippingOrderExtractionRun,
unit: ShippingOrderExtractionUnit,
fields: dict[str, Any],
operation_id: str,
) -> None:
"""对执行中 Unit 仅写入取消请求,等待 Worker 安全点生效。"""
if unit.cancellation_requested_at is not None:
return
before = _unit_snapshot(unit)
_apply_fields(unit, fields)
unit.activity_version = int(getattr(unit, 'activity_version', 1) or 1) + 1
unit.last_activity_at = fields['cancellation_requested_at']
record_unit_progress(
run=run,
unit=unit,
event_code='cancellation_requested',
reason_code=fields.get('cancellation_reason_code') or 'user_cancelled',
summary={'operation_id': operation_id},
commit=False,
)
append_shipping_audit_event(
event_type='order_extraction_unit_cancel_requested',
aggregate_type='order_extraction_unit',
aggregate_id=str(unit.id),
run_no=run.run_no,
actor_type=fields['cancellation_actor_type'],
actor_id=fields['cancellation_actor_id'],
request_id=_request_id(),
operation_id=operation_id,
source='api',
result='success',
action='cancel_unit',
reason=fields.get('cancellation_reason'),
reason_code=fields.get('cancellation_reason_code') or 'user_cancelled',
conversation_id=run.conversation_id,
unit_id=unit.id,
document_id=unit.document_id,
before=before,
after=_unit_snapshot(unit),
)
def _has_inflight_units(units: list[ShippingOrderExtractionUnit]) -> bool:
"""是否仍有执行中、尚未取消完成的 Unit。"""
for unit in units:
if unit.status in IN_FLIGHT_UNIT_STATUSES and unit.cancellation_completed_at is None:
return True
if unit.status == PENDING_UNIT_STATUS and unit.cancellation_completed_at is None:
return True
return False
def finalize_run_cancellation_if_ready(
*,
run: ShippingOrderExtractionRun,
operation_id: str | None = None,
actor_type: str = 'system',
actor_id: str | None = None,
) -> bool:
"""
若取消已请求且无剩余活跃 Unit,则将 Run 收口为 cancelled。
核心逻辑:保留 candidate_ready/review_required/failed 结果;仅在无 pending/in-flight 时终态化。
Returns:
是否完成 Run 取消收口。
"""
if run.cancellation_requested_at is None:
return False
if run.status == 'cancelled' and run.cancellation_completed_at is not None:
return True
units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else []
if _has_inflight_units(units):
return False
before = _run_snapshot(run)
op = _resolve_cancellation_operation_id(run, operation_id)
now = datetime.utcnow()
if run.status in ACTIVE_RUN_STATUSES:
from app.services.shipping_notice.order_extraction_run_service import transition_order_extraction_run
transition_order_extraction_run(
run,
target_status='cancelled',
phase='cancellation_completed',
result={
'cancelled': True,
'completed_count': sum(1 for unit in units if unit.status == 'candidate_ready'),
'review_required_count': sum(1 for unit in units if unit.status == 'review_required'),
'failed_count': sum(1 for unit in units if unit.status == 'failed'),
'cancelled_count': sum(1 for unit in units if unit.status == 'cancelled'),
},
)
run.cancellation_completed_at = now
record_order_extraction_progress_event(
run_no=run.run_no,
event={
'event_code': 'cancellation_completed',
'status': 'cancelled',
'reason_code': run.cancellation_reason_code or 'user_cancelled',
'summary': {'operation_id': op},
},
commit=False,
)
append_shipping_audit_event(
event_type='order_extraction_run_cancel_completed',
aggregate_type='order_extraction_run',
aggregate_id=run.run_no,
run_no=run.run_no,
actor_type=actor_type or run.cancellation_actor_type or 'system',
actor_id=actor_id or run.cancellation_actor_id,
request_id=_request_id(),
operation_id=op,
source='worker' if actor_type == 'system' else 'api',
result='success',
action='cancel_run',
reason=run.cancellation_reason,
reason_code=run.cancellation_reason_code or 'user_cancelled',
conversation_id=run.conversation_id,
before=before,
after=_run_snapshot(run),
)
return True
def apply_worker_cancellation_checkpoint(*, run: ShippingOrderExtractionRun) -> bool:
"""
Worker 安全检查点:取消剩余 pending,并收口已请求取消的 in-flight Unit。
Returns:
True 表示调用方应停止启动新的 Unit 工作。
"""
if run.cancellation_requested_at is None:
return False
units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else []
now = datetime.utcnow()
fields = {
'cancellation_requested_at': run.cancellation_requested_at,
'cancellation_actor_type': run.cancellation_actor_type or 'system',
'cancellation_actor_id': run.cancellation_actor_id,
'cancellation_reason': run.cancellation_reason,
'cancellation_reason_code': run.cancellation_reason_code or 'user_cancelled',
}
op = _resolve_cancellation_operation_id(run)
for unit in units:
if unit.status == PENDING_UNIT_STATUS and unit.cancellation_completed_at is None:
_cancel_pending_unit(run=run, unit=unit, fields=fields, operation_id=op)
elif (
unit.status in IN_FLIGHT_UNIT_STATUSES
and unit.cancellation_requested_at is not None
and unit.cancellation_completed_at is None
):
before = _unit_snapshot(unit)
transition_order_extraction_unit(unit, target_status='cancelled', error_code='ORDER_EXTRACTION_CANCELLED')
unit.cancellation_completed_at = now
unit.activity_version = int(getattr(unit, 'activity_version', 1) or 1) + 1
record_unit_progress(
run=run,
unit=unit,
event_code='unit_cancelled',
reason_code=unit.cancellation_reason_code or 'user_cancelled',
summary={'operation_id': op, 'source': 'worker_checkpoint'},
commit=False,
)
append_shipping_audit_event(
event_type='order_extraction_unit_cancel_completed',
aggregate_type='order_extraction_unit',
aggregate_id=str(unit.id),
run_no=run.run_no,
actor_type='system',
actor_id='shipping_order_extraction_worker',
request_id=_request_id(),
operation_id=op,
source='worker',
result='success',
action='cancel_unit',
reason=unit.cancellation_reason,
reason_code=unit.cancellation_reason_code or 'user_cancelled',
conversation_id=run.conversation_id,
unit_id=unit.id,
document_id=unit.document_id,
before=before,
after=_unit_snapshot(unit),
)
finalize_run_cancellation_if_ready(
run=run,
operation_id=op,
actor_type='system',
actor_id='shipping_order_extraction_worker',
)
return True
def should_abort_unit_for_cancellation(*, run: ShippingOrderExtractionRun, unit: ShippingOrderExtractionUnit) -> bool:
"""
判断 Unit 在外部副作用前是否应中止。
核心逻辑:Run 或 Unit 已请求取消时返回 True。
"""
return bool(run.cancellation_requested_at or unit.cancellation_requested_at)
def cancel_order_extraction_run(
*,
actor: User,
run_no: str,
reason: str | None = None,
reason_code: str | None = None,
operation_id: str | None = None,
) -> ShippingOrderExtractionRun:
"""
请求取消整批订单抽取 Run。
核心逻辑:写入 Run 取消请求;立即取消 pending Unit;执行中 Unit 进入正在取消;
若无活跃 Unit 则立即收口为 cancelled。
Args:
actor: 当前用户;管理员代取消必须提供 reason。
run_no: Run 编号。
reason/reason_code: 取消原因。
operation_id: 可选操作关联键。
Returns:
更新后的 Run。
"""
_require_cancel_feature_enabled()
run = _lock_run_for_actor(actor=actor, run_no=run_no)
_validate_cancel_permission(actor=actor, run=run, reason=reason)
if run.status not in ACTIVE_RUN_STATUSES:
raise ConflictError(
'Only active order extraction runs can be cancelled',
code='SHIPPING_NOTICE.CANCEL_NOT_ACTIVE',
details={'status': run.status},
)
op = _operation_id(operation_id)
if run.cancellation_requested_at is not None:
finalize_run_cancellation_if_ready(
run=run,
operation_id=op,
actor_type='admin' if _is_admin(actor) else 'user',
actor_id=str(actor.id),
)
return run
before = _run_snapshot(run)
now = datetime.utcnow()
fields = _cancellation_payload(actor=actor, reason=reason, reason_code=reason_code, now=now)
_apply_fields(run, fields)
run.progress_version = int(run.progress_version or 0) + 1
run.last_activity_at = now
units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else []
for unit in units:
if unit.status == PENDING_UNIT_STATUS:
_cancel_pending_unit(run=run, unit=unit, fields=fields, operation_id=op)
elif unit.status in IN_FLIGHT_UNIT_STATUSES:
_request_inflight_unit_cancel(run=run, unit=unit, fields=fields, operation_id=op)
elif unit.status in PRESERVE_UNIT_STATUSES:
continue
record_order_extraction_progress_event(
run_no=run.run_no,
event={
'event_code': 'cancellation_requested',
'status': 'cancellation_requested',
'reason_code': fields.get('cancellation_reason_code') or 'user_cancelled',
'summary': {'operation_id': op},
},
commit=False,
)
append_shipping_audit_event(
event_type='order_extraction_run_cancel_requested',
aggregate_type='order_extraction_run',
aggregate_id=run.run_no,
run_no=run.run_no,
actor_type=fields['cancellation_actor_type'],
actor_id=fields['cancellation_actor_id'],
request_id=_request_id(),
operation_id=op,
source='api',
result='success',
action='cancel_run',
reason=fields.get('cancellation_reason'),
reason_code=fields.get('cancellation_reason_code') or 'user_cancelled',
conversation_id=run.conversation_id,
before=before,
after=_run_snapshot(run),
)
finalize_run_cancellation_if_ready(
run=run,
operation_id=op,
actor_type=fields['cancellation_actor_type'],
actor_id=fields['cancellation_actor_id'],
)
db.session.flush()
return run
def cancel_order_extraction_unit(
*,
actor: User,
run_no: str,
document_id: int,
reason: str | None = None,
reason_code: str | None = None,
operation_id: str | None = None,
) -> ShippingOrderExtractionUnit:
"""
请求取消单个 PDF Unit。
核心逻辑:仅活跃 Unit 可取消;pending 立即生效,执行中写请求;完成后尝试收口 Run。
"""
_require_cancel_feature_enabled()
run = _lock_run_for_actor(actor=actor, run_no=run_no)
_validate_cancel_permission(actor=actor, run=run, reason=reason)
if run.status not in ACTIVE_RUN_STATUSES:
raise ConflictError(
'Only active order extraction runs can cancel units',
code='SHIPPING_NOTICE.CANCEL_NOT_ACTIVE',
details={'status': run.status},
)
units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else []
unit = next((row for row in units if int(row.document_id) == int(document_id)), None)
if unit is None:
raise NotFoundError(
'Shipping order extraction unit not found',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_NOT_FOUND',
)
if unit.status in PRESERVE_UNIT_STATUSES and unit.status != 'cancelled':
raise ConflictError(
'Completed or failed units cannot be cancelled',
code='SHIPPING_NOTICE.CANCEL_NOT_ACTIVE',
details={'status': unit.status},
)
if unit.status == 'cancelled':
return unit
op = _operation_id(operation_id)
now = datetime.utcnow()
fields = _cancellation_payload(actor=actor, reason=reason, reason_code=reason_code, now=now)
if run.cancellation_requested_at is None and unit.status == PENDING_UNIT_STATUS:
# 单文件取消不强制把整批标记为取消请求,除非全部活跃项已取消。
pass
if unit.status == PENDING_UNIT_STATUS:
_cancel_pending_unit(run=run, unit=unit, fields=fields, operation_id=op)
elif unit.status in IN_FLIGHT_UNIT_STATUSES:
_request_inflight_unit_cancel(run=run, unit=unit, fields=fields, operation_id=op)
else:
raise ConflictError(
'Unit is not cancellable',
code='SHIPPING_NOTICE.CANCEL_NOT_ACTIVE',
details={'status': unit.status},
)
remaining_active = [
row for row in units
if row.status in (IN_FLIGHT_UNIT_STATUSES | {PENDING_UNIT_STATUS})
and row.cancellation_completed_at is None
and int(row.id) != int(unit.id)
]
if not remaining_active and all(
row.status in PRESERVE_UNIT_STATUSES or row.cancellation_completed_at is not None
for row in units
):
if run.cancellation_requested_at is None:
_apply_fields(run, fields)
run.progress_version = int(run.progress_version or 0) + 1
finalize_run_cancellation_if_ready(
run=run,
operation_id=op,
actor_type=fields['cancellation_actor_type'],
actor_id=fields['cancellation_actor_id'],
)
db.session.flush()
return unit
@@ -70,6 +70,30 @@ def _selected_attachment_keys_for_intake(
return selected
def _require_selected_document_keys(
*, intake: ShippingNoticeIntake, selected_attachment_keys: set[str],
) -> None:
"""校验本次授权附件已全部物化,阻止空输入进入版面和订单任务。
AI 触发时机:发送阶段深度解析并持久化 EML 附件后调用。附件目录与原始邮件
载荷可能因损坏或解析差异而不一致;此时必须明确报输入准备失败,不能继续尝试
创建版面任务并误报版面服务不可用。
"""
existing_keys = _existing_document_keys(intake)
missing_keys = sorted(selected_attachment_keys - existing_keys)
if not missing_keys:
return
raise ConflictError(
'Selected shipping notice attachments could not be materialized',
code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE',
details={
'intake_nos': [str(intake.intake_no or '')],
'reason': 'selected_attachment_document_missing',
'missing_attachment_keys': missing_keys,
},
)
def _parse_attachment_payload(
*, payload: bytes, filename: str, mime_type: str, flask_app: Any | None = None,
) -> tuple[str, dict[str, Any]]:
@@ -310,3 +334,8 @@ def ensure_order_extraction_input_documents(
),
schema_definition=definition,
)
# 持久化是后续版面任务唯一允许的输入来源,必须逐项与冻结选择计划一致。
_require_selected_document_keys(
intake=intake,
selected_attachment_keys=selected_attachment_keys,
)
@@ -421,16 +421,37 @@ def transition_order_extraction_unit(
unit.technical_failure_reason_code = None
plan_run = getattr(unit.plan, 'run', None)
if plan_run is not None and getattr(plan_run, 'run_no', None):
request_id = None
try:
from flask import g
request_id = str(getattr(g, 'request_id', '') or '') or None
except RuntimeError:
request_id = None
operation_id = request_id or f'unit-status-{unit.id}-{int(unit.attempt_count or 0)}-{target_status}'
append_shipping_audit_event(
event_type='order_extraction_unit_status_changed',
aggregate_type='order_extraction_unit',
aggregate_id=str(unit.id),
run_no=str(plan_run.run_no),
document_id=int(unit.document_id),
actor_type='system',
actor_id='shipping_order_extraction_worker',
request_id=request_id,
operation_id=operation_id[:64],
source='worker',
result='success',
action='unit_status_transition',
attempt_no=int(unit.attempt_count or 0),
reason_code=unit.reason_code if target_status in {'review_required', 'cancelled'} else unit.error_code if target_status == 'failed' else None,
before=before_projection,
after={'status': target_status, 'attempt_count': int(unit.attempt_count or 0)},
metadata={'target_status': target_status},
after={
'status': target_status,
'attempt_count': int(unit.attempt_count or 0),
'retry_status': unit.retry_status,
'reason_code': unit.reason_code,
'error_code': unit.error_code,
},
metadata={'target_status': target_status, 'from_status': current},
)
_refresh_plan_status(unit.plan)
return unit
@@ -2,8 +2,9 @@
services/shipping_notice/order_extraction_progress.py
用途:记录订单抽取 Run/Unit 的确定性业务事件,作为用户态进度与管理员诊断的共同事实源。
依赖:ShippingOrderExtractionRun/Unit/ProgressEvent ORM、统一数据库会话。
依赖:ShippingOrderExtractionRun/Unit/ProgressEvent ORM、统一数据库会话、progress_audit_contract。
逻辑:调用方只能写入受控 event_code;服务负责幂等、顺序号、终态保护和最小化 Run 投影。
阶段 0 冻结 cancellation_* 事件码与 mapping v3;写入取消事实在阶段 1 与 Worker 检查点实现。
"""
from __future__ import annotations
@@ -24,7 +25,7 @@ from app.models import (
)
_LOGGER = logging.getLogger(__name__)
MAPPING_VERSION = 'shipping-order-progress-v2'
MAPPING_VERSION = 'shipping-order-progress-v3'
EVENT_RETENTION_DAYS = 90
EVENT_CODE_ORDER = {
'plan_created': 5,
@@ -42,9 +43,47 @@ EVENT_CODE_ORDER = {
'candidate_ready': 70,
'review_required': 70,
'technical_failed': 70,
'cancellation_requested': 75,
'unit_cancelled': 76,
'cancellation_completed': 77,
'budget_stopped': 80,
'run_completed': 90,
}
def _progress_event_status(*, event_code: str, entity_status: str | None = None) -> str:
"""
将进度事件映射为可检索的过程状态,禁止一律写 completed。
核心逻辑:取消/失败/排队优先;否则回落到实体当前状态或运行中。
"""
code = str(event_code or '').strip()
if code in {'cancellation_requested'}:
return 'cancellation_requested'
if code in {'unit_cancelled', 'cancellation_completed'}:
return 'cancelled'
if code in {'technical_failed'}:
return 'failed'
if code in {'technical_retrying'}:
return 'retrying'
if code in {'document_queued', 'plan_created'}:
return 'queued'
if code in {'layout_parsing_started', 'layout_parsing_completed', 'waiting_layout'}:
return 'running'
if code in {'candidate_ready', 'run_completed'}:
return 'completed'
if code in {'review_required'}:
return 'review_required'
status = str(entity_status or '').strip()
if status == 'pending':
return 'queued'
if status in {'routing', 'matching_profile', 'extracting', 'merging_supplement', 'queued', 'processing'}:
return 'running'
if status in {'failed', 'cancelled', 'review_required', 'candidate_ready', 'completed', 'partially_completed'}:
return status if status != 'candidate_ready' else 'completed'
return 'running'
WORKSPACE_EVENT_CODES = {
'plan_created',
'layout_parsing_started',
@@ -61,6 +100,9 @@ WORKSPACE_EVENT_CODES = {
'review_required',
'technical_retrying',
'technical_failed',
'cancellation_requested',
'unit_cancelled',
'cancellation_completed',
'budget_stopped',
'run_completed',
}
@@ -165,7 +207,10 @@ def record_order_extraction_progress_event(
run = ShippingOrderExtractionRun.query.filter_by(run_no=normalized_no).with_for_update().first()
if run is None:
return False
if run.status in TERMINAL_RUN_STATUSES and event_code not in {'run_completed', 'technical_failed'}:
if run.status in TERMINAL_RUN_STATUSES and event_code not in {
'run_completed', 'technical_failed', 'cancellation_requested',
'cancellation_completed', 'unit_cancelled',
}:
return False
unit_id = int(event['unit_id']) if event.get('unit_id') is not None else None
document_id = int(event['document_id']) if event.get('document_id') is not None else None
@@ -234,7 +279,7 @@ def record_unit_progress(
'unit_id': int(unit.id),
'document_id': int(unit.document_id),
'event_code': event_code,
'status': 'completed',
'status': _progress_event_status(event_code=event_code, entity_status=unit.status),
'summary': summary,
'reason_code': reason_code,
'visibility': visibility,
@@ -261,7 +306,7 @@ def record_run_progress(
commit=commit,
event={
'event_code': event_code,
'status': 'completed',
'status': _progress_event_status(event_code=event_code, entity_status=run.status),
'summary': summary,
'reason_code': reason_code,
'visibility': visibility,
@@ -296,7 +341,7 @@ def record_layout_document_progress(*, document_id: int, event_code: str, commit
event={
'document_id': normalized_document_id,
'event_code': event_code,
'status': 'completed',
'status': _progress_event_status(event_code=event_code, entity_status=run.status),
'visibility': 'workspace',
'occurred_at': datetime.utcnow(),
},
@@ -21,7 +21,7 @@ from typing import Any
from flask import current_app
from sqlalchemy.exc import IntegrityError
from sqlalchemy import or_
from sqlalchemy import and_, or_
from app import db
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
@@ -349,7 +349,10 @@ def _build_snapshot(
documents_by_intake: dict[int, list[dict[str, Any]]] = {intake.id: [] for intake in intakes}
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
from app.services.shipping_notice.document_layout.schema_mapping import map_layout_document_to_schema
from app.services.shipping_notice.email_allocation_table_parser import parse_email_allocation_text
from app.services.shipping_notice.email_allocation_table_parser import (
parse_email_allocation_tables,
parse_email_allocation_text,
)
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
table_contract = compile_table_header_contract(dict(schema_version.definition_json or {}))
@@ -387,13 +390,27 @@ def _build_snapshot(
and isinstance(document.order_extraction_result_json, dict)
else None
)
# 旧 Intake 已经持久化时,也在重新识别的冻结边界补齐纯文本正文补充事实。
# 结果只进入本 Run 快照,原始解析记录保持不变,确保可审计。
if document.document_type == 'email_body' and not isinstance(email_supplement, dict):
email_supplement = parse_email_allocation_text(
body_text=str(document.extracted_text or ''),
content_hash=str(document.content_hash or ''),
)
# [STEP 1] 按本 Run 冻结 Schema 重建正文补充事实。上传阶段的预解析
# 可能使用较早 Schema;优先复用 Intake 保存的 HTML 表,避免表格展平后丢失列关系。
if document.document_type == 'email_body' and (
not isinstance(email_supplement, dict) or not list(email_supplement.get('rows') or [])
):
intake = next((item for item in intakes if int(item.id) == int(document.intake_id)), None)
structured = intake.structured_result_json if intake and isinstance(intake.structured_result_json, dict) else {}
email = structured.get('email') if isinstance(structured.get('email'), dict) else {}
html_tables = [str(item) for item in (email.get('body_html_tables') or []) if str(item).strip()]
if html_tables:
email_supplement = parse_email_allocation_tables(
html_tables=html_tables,
content_hash=str(document.content_hash or ''),
schema_definition=dict(schema_version.definition_json or {}),
)
else:
email_supplement = parse_email_allocation_text(
body_text=str(document.extracted_text or ''),
content_hash=str(document.content_hash or ''),
schema_definition=dict(schema_version.definition_json or {}),
)
email_supplement['document_id'] = int(document.id)
documents_by_intake[document.intake_id].append({
'document_id': document.id,
@@ -539,19 +556,51 @@ def order_extraction_layouts_failed(run: ShippingOrderExtractionRun) -> bool:
def schedule_order_extraction_layouts(
run: ShippingOrderExtractionRun, *, created_by_id: int | None,
) -> bool:
"""发送后为本 Run 已选附件创建版面任务,并返回是否需要等待其完成。"""
"""
发送后为本 Run 已选附件创建版面任务,并返回是否需要等待其完成。
核心逻辑:调用 schedule_document_layouts;用返回值与库查询确认每份 PDF 已有布局版本,
避免 ORM 关系未刷新导致误报「未创建版面 Job」。
"""
from app.services.shipping_notice.document_layout.lifecycle import schedule_document_layouts
from app.core.errors import ValidationError
documents = _run_layout_documents(run)
schedule_document_layouts(documents, created_by_id=created_by_id)
# 排程函数不能再静默跳过订单 PDF;否则后续路由只能看到空表格并误判业务失败。
missing = [
scheduled = schedule_document_layouts(documents, created_by_id=created_by_id)
# [STEP] 以本轮排程结果与库内版本为准,禁止依赖可能未 refresh 的 layout_versions 关系。
scheduled_document_ids = {
int(version.document_id)
for version in scheduled
if getattr(version, 'document_id', None) is not None
}
from app.models import ShippingDocumentLayoutVersion
pdf_document_ids = [
int(document.id) for document in documents
if Path(str(document.filename or '')).suffix.lower() == '.pdf'
# queued/running 版本尚不会成为 current,但它们已经满足“已创建布局 Job”。
and not document.layout_versions
]
existing_version_ids = {
int(document_id)
for (document_id,) in db.session.query(ShippingDocumentLayoutVersion.document_id).filter(
ShippingDocumentLayoutVersion.document_id.in_(pdf_document_ids or [-1]),
).distinct().all()
}
# 内容级复用的 ready 版本属于历史 Document;lifecycle 已把其 ID 绑定到当前
# Document.current_layout_version_id,不能因 version.document_id 不同误判为未排程。
reusable_document_ids = {
int(document.id)
for document in documents
if document.current_layout_version_id is not None
}
# 排程函数不能再静默跳过订单 PDF;否则后续路由只能看到空表格并误判业务失败。
missing = [
document_id for document_id in pdf_document_ids
if (
document_id not in scheduled_document_ids
and document_id not in existing_version_ids
and document_id not in reusable_document_ids
)
]
if missing:
raise ValidationError(
@@ -612,8 +661,14 @@ def materialize_order_extraction_run_inputs(
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
# 已完成物化并建计划的 Run 重试时直接复用,避免再次抽取或改变执行证据快照。
if ShippingOrderExtractionPlan.query.filter_by(run_id=int(run.id)).first() is not None:
return ensure_order_extraction_plan(run)
# 早期链路可能留下 0 Unit 的空计划;它不含可执行输入,必须丢弃后重新物化,
# 否则重试会永远跳过 EML 附件物化并误报版面任务未创建。
existing_plan = ShippingOrderExtractionPlan.query.filter_by(run_id=int(run.id)).first()
if existing_plan is not None:
if int(existing_plan.unit_count or 0) > 0:
return ensure_order_extraction_plan(run)
db.session.delete(existing_plan)
db.session.flush()
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
@@ -1127,13 +1182,53 @@ def retry_order_extraction_run(*, user_id: int, run_no: str) -> tuple[ShippingOr
def list_order_extraction_runs(
*, user_id: int, conversation_id: str | None = None, limit: int = 50,
) -> list[ShippingOrderExtractionRun]:
"""列出当前用户 Run;可按会话过滤,最多返回 100 条。"""
*,
user_id: int,
conversation_id: str | None = None,
limit: int = 50,
status: str | None = None,
page: int | None = None,
page_size: int | None = None,
) -> list[ShippingOrderExtractionRun] | dict[str, Any]:
"""
列出当前用户 Run;可按会话/状态过滤。
核心逻辑:未传 page 时保持旧契约(最多 100 条列表);传 page 时返回分页字典供任务中心续办。
Args:
user_id: 当前用户主键。
conversation_id: 可选会话过滤。
limit: 非分页模式下的条数上限。
status: 可选业务状态过滤。
page: 分页页码(>=1);与 page_size 同时生效。
page_size: 分页大小(1-100)。
Returns:
非分页:Run 列表;分页:{items, total, page, page_size}。
"""
normalized_status = str(status or '').strip() or None
if normalized_status and normalized_status not in {
'queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled',
}:
raise ValidationError('status is invalid')
query = ShippingOrderExtractionRun.query.filter_by(user_id=user_id)
if conversation_id:
query = query.filter_by(conversation_id=conversation_id)
return query.order_by(ShippingOrderExtractionRun.created_at.desc()).limit(min(max(limit, 1), 100)).all()
if normalized_status:
query = query.filter_by(status=normalized_status)
query = query.order_by(ShippingOrderExtractionRun.created_at.desc())
if page is None and page_size is None:
return query.limit(min(max(int(limit or 50), 1), 100)).all()
safe_page = max(1, int(page or 1))
safe_page_size = min(100, max(1, int(page_size or 20)))
total = query.count()
rows = query.offset((safe_page - 1) * safe_page_size).limit(safe_page_size).all()
return {
'items': rows,
'total': total,
'page': safe_page,
'page_size': safe_page_size,
}
def _reparse_difference_summary(run: ShippingOrderExtractionRun) -> dict[str, Any] | None:
@@ -1338,6 +1433,15 @@ def serialize_order_extraction_run(run: ShippingOrderExtractionRun) -> dict[str,
'unit_summary': _unit_fact_summary(run),
'current_activity': workspace_projection['current_activity'],
'available_actions': workspace_projection['available_actions'],
'handling_items': workspace_projection.get('handling_items') or [],
'primary_notice': workspace_projection.get('primary_notice'),
'user_visible_stage': workspace_projection.get('user_visible_stage'),
'health_tips': workspace_projection.get('health_tips') or [],
'cancellation': workspace_projection.get('cancellation'),
'progress_version': workspace_projection.get('progress_version'),
'elapsed_seconds': workspace_projection.get('elapsed_seconds'),
'last_activity_at': workspace_projection.get('last_activity_at'),
'feature_flags': workspace_projection.get('feature_flags') or {},
'result': run.result_json,
# Worker/provider error text can contain upstream details. Workspace cards only need a
# stable code to select a safe, actionable user hint; full diagnostics stay admin-only.
@@ -1515,14 +1619,18 @@ def _diagnostic_auto_freeze_policy(run: ShippingOrderExtractionRun) -> dict[str,
def _serialize_order_extraction_diagnostic_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
"""构建管理员 Run 摘要,只包含状态、标识、计数、时间和脱敏事件,不含输入输出或错误正文。"""
result = run.result_json if isinstance(run.result_json, dict) else {}
cancellation_requested = run.cancellation_requested_at is not None
cancellation_completed = run.cancellation_completed_at is not None
return {
'run_no': run.run_no,
'status': run.status,
'phase': run.phase,
'conversation_id': run.conversation_id,
'user_id': int(run.user_id or 0) or None,
'parser_engine_version': run.parser_engine_version,
'parser_policy_version': run.parser_policy_version,
'attempt_count': int(run.attempt_count or 0),
'progress_version': int(run.progress_version or 0),
'current_event_code': run.current_stage_code,
'active_stage_codes': list(run.active_stage_codes_json or []),
'completed_stage_codes': list(run.completed_stage_codes_json or []),
@@ -1537,6 +1645,11 @@ def _serialize_order_extraction_diagnostic_run(run: ShippingOrderExtractionRun)
'deterministic_parsing': _diagnostic_elapsed_ms(run.started_at, run.extraction_completed_at),
'candidate_materialization': _diagnostic_elapsed_ms(run.extraction_completed_at, run.result_persisted_at),
'total': _diagnostic_elapsed_ms(run.created_at, run.finished_at),
'elapsed_active': (
_diagnostic_elapsed_ms(run.started_at or run.created_at, datetime.utcnow())
if run.status in {'queued', 'processing'}
else None
),
},
'result_counts': {
'created': int(result.get('created_count') or 0),
@@ -1544,6 +1657,15 @@ def _serialize_order_extraction_diagnostic_run(run: ShippingOrderExtractionRun)
'pending': int(result.get('pending_count') or 0),
'non_shipping': int(result.get('non_shipping_count') or 0),
},
'cancellation': {
'requested': cancellation_requested,
'completed': cancellation_completed,
'in_flight': cancellation_requested and not cancellation_completed,
'requested_at': _diagnostic_iso(run.cancellation_requested_at),
'completed_at': _diagnostic_iso(run.cancellation_completed_at),
'actor_type': run.cancellation_actor_type,
'reason_code': run.cancellation_reason_code,
},
'auto_freeze_policy': _diagnostic_auto_freeze_policy(run),
# 仅错误码可用于运维归类,错误正文可能含上游响应内容,严禁返回。
'error_code': run.error_code,
@@ -1575,27 +1697,82 @@ def _commit_order_extraction_diagnostic_audit_safely() -> None:
def list_order_extraction_diagnostic_runs(
*, admin_user_id: int, request_id: str | None, page: int = 1, page_size: int = 25, status: str | None = None,
*,
admin_user_id: int,
request_id: str | None,
page: int = 1,
page_size: int = 25,
status: str | None = None,
stale_only: bool = False,
cancellation_in_flight: bool = False,
queued_stale_seconds: int = 300,
running_stale_seconds: int = 1800,
now: datetime | None = None,
) -> dict[str, Any]:
"""分页读取管理员诊断 Run 摘要,并写入只读访问审计。"""
"""
分页读取管理员诊断 Run 摘要,并写入只读访问审计。
核心逻辑:支持状态、积压卡住、取消中筛选;不返回正文/Provider。
"""
normalized_status = str(status or '').strip() or None
if normalized_status and normalized_status not in {'queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'}:
raise ValidationError('status is invalid')
safe_page = max(1, int(page))
safe_page_size = min(100, max(1, int(page_size)))
current = now or datetime.utcnow()
queued_threshold = min(max(int(queued_stale_seconds or 300), 30), 86400)
running_threshold = min(max(int(running_stale_seconds or 1800), 60), 86400)
query = ShippingOrderExtractionRun.query
if normalized_status:
query = query.filter_by(status=normalized_status)
if cancellation_in_flight:
query = query.filter(
ShippingOrderExtractionRun.cancellation_requested_at.isnot(None),
ShippingOrderExtractionRun.cancellation_completed_at.is_(None),
)
if stale_only:
# [STEP 1] 积压筛选在服务端按阈值计算,避免前端全量拉取后再猜。
queued_cutoff = current - timedelta(seconds=queued_threshold)
running_cutoff = current - timedelta(seconds=running_threshold)
query = query.filter(
or_(
and_(
ShippingOrderExtractionRun.status == 'queued',
ShippingOrderExtractionRun.created_at <= queued_cutoff,
),
and_(
ShippingOrderExtractionRun.status == 'processing',
or_(
ShippingOrderExtractionRun.started_at <= running_cutoff,
and_(
ShippingOrderExtractionRun.started_at.is_(None),
ShippingOrderExtractionRun.created_at <= running_cutoff,
),
),
),
)
)
total = query.count()
rows = query.order_by(ShippingOrderExtractionRun.created_at.desc(), ShippingOrderExtractionRun.id.desc()).offset(
(safe_page - 1) * safe_page_size,
).limit(safe_page_size).all()
payload = {'items': [_serialize_order_extraction_diagnostic_run(row) for row in rows], 'total': total, 'page': safe_page, 'page_size': safe_page_size}
payload = {
'items': [_serialize_order_extraction_diagnostic_run(row) for row in rows],
'total': total,
'page': safe_page,
'page_size': safe_page_size,
}
_write_order_extraction_diagnostic_audit(
admin_user_id=admin_user_id,
action='list_runs',
request_id=request_id,
summary={'page': safe_page, 'page_size': safe_page_size, 'status': normalized_status},
summary={
'page': safe_page,
'page_size': safe_page_size,
'status': normalized_status,
'stale_only': bool(stale_only),
'cancellation_in_flight': bool(cancellation_in_flight),
},
)
_commit_order_extraction_diagnostic_audit_safely()
return payload
@@ -1775,12 +1952,24 @@ def transition_order_extraction_run(
run.status = target_status
run.phase = phase or target_status
run.lock_version = int(run.lock_version or 0) + 1
request_id = None
try:
from flask import g
request_id = str(getattr(g, 'request_id', '') or '') or None
except RuntimeError:
request_id = None
append_shipping_audit_event(
event_type='order_extraction_run_status_changed',
aggregate_type='order_extraction_run',
aggregate_id=run.run_no,
run_no=run.run_no,
actor_type='system',
request_id=request_id,
operation_id=request_id,
conversation_id=run.conversation_id,
source='worker' if request_id is None else 'api',
result='success',
action='status_transition',
reason_code=error_code if target_status == 'failed' else None,
before=before_projection,
after={'status': target_status, 'phase': phase or target_status, 'lock_version': int(run.lock_version or 0)},
@@ -1960,15 +2149,65 @@ def sync_order_extraction_run_after_job_recovery(job: Any) -> None:
error_message=str(job.error_message or '订单抽取后台任务执行超时'),
)
def sync_order_extraction_run_after_job_failure(job: Any) -> None:
"""
同步最终失败的订单抽取 Job 到用户态 Run。
AI 触发时机:无需直接调用;通用队列在 Job 重试耗尽后调用。
核心逻辑:Handler 启动前的异常也会使 Job 失败,因此必须将 Run 收口为 failed;
若 Job 错误信息指向版面排程失败,则写入更具体的 LAYOUT_SCHEDULING_FAILED 便于前端文案。
Args:
job: 已更新为 failed 的 `shipping_order_extraction` Job。
"""
if str(getattr(job, 'job_type', '') or '') != 'shipping_order_extraction':
return
if str(getattr(job, 'status', '') or '') != 'failed':
return
run = ShippingOrderExtractionRun.query.filter_by(
run_no=str(getattr(job, 'business_ref', '') or ''),
).with_for_update().first()
if run is None or run.status in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'}:
return
error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_JOB_FAILED'
job_error = str(getattr(job, 'error_message', '') or '')
if 'layout job was not created' in job_error.lower():
error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_SCHEDULING_FAILED'
if run.status == 'queued':
transition_order_extraction_run(run, target_status='processing', phase='job_failure')
transition_order_extraction_run(
run,
target_status='failed',
phase='job_failed',
error_code=error_code,
error_message=job_error or '订单抽取后台任务失败',
)
record_run_progress(
run=run,
event_code='technical_failed',
reason_code=error_code,
summary={
'job_id': int(getattr(job, 'id', 0) or 0),
'job_attempts': int(getattr(job, 'attempts', 0) or 0),
'job_max_attempts': int(getattr(job, 'max_attempts', 0) or 0),
},
job_id=int(getattr(job, 'id', 0) or 0) or None,
commit=False,
)
def _latency_summary(values: list[int]) -> dict[str, int | None]:
"""汇总毫秒耗时样本;空集合返回空指标,避免监控端猜测零耗时。"""
if not values:
return {'count': 0, 'avg_ms': None, 'p95_ms': None, 'max_ms': None}
return {'count': 0, 'avg_ms': None, 'p50_ms': None, 'p95_ms': None, 'max_ms': None}
ordered = sorted(max(0, int(value)) for value in values)
p50_index = max(0, min(len(ordered) - 1, ((len(ordered) * 50 + 99) // 100) - 1))
p95_index = max(0, min(len(ordered) - 1, ((len(ordered) * 95 + 99) // 100) - 1))
return {
'count': len(ordered),
'avg_ms': int(sum(ordered) / len(ordered)),
'p50_ms': ordered[p50_index],
'p95_ms': ordered[p95_index],
'max_ms': ordered[-1],
}
@@ -3,14 +3,18 @@ backend/app/services/shipping_notice/order_extraction_workspace_projection.py
用途:把订单抽取 Run/Unit 的数据库事实投影为工作台摘要和按 PDF 的详情列表。
依赖:ShippingNoticeCandidate、ShippingOrderExtractionRun/Unit/RouteDecision/ProgressEvent ORM、
冻结 snapshot 和 Unit 结果 JSON。
progress_audit_contract、progress_feature_flags、冻结 snapshot 和 Unit 结果 JSON。
逻辑:只输出用户可理解的业务信息;文件名、原因码、模板摘要、重复订单 open_existing 入口
与可操作按钮都在这里统一裁剪与组装。
与可操作按钮都在这里统一裁剪与组装。阶段 1 起由后端唯一投影 user_visible_stage、
queue_position、elapsed_seconds、health_tips 与 cancellation;阶段 5 按功能开关裁剪取消动作与健康提示。
Run 级 handling_items 拆分「待补信息 / 冲突 / 自动冻结受阻 / PDF 复核 / 技术失败 / 预算停扩」,
供聊天卡与右侧「本次处理」按原因展示与跳转,避免仅依赖部分完成/需复核状态码。
"""
from __future__ import annotations
from collections import Counter
from datetime import datetime
from typing import Any
from app.models import (
@@ -20,8 +24,39 @@ from app.models import (
ShippingOrderExtractionRun,
ShippingOrderExtractionUnit,
)
from app.services.shipping_notice.progress_audit_contract import HEALTH_TIP_THRESHOLDS_SECONDS
from app.services.shipping_notice.progress_feature_flags import (
order_extraction_cancel_enabled,
progress_feature_flags_payload,
progress_ui_v3_enabled,
)
ACTIVE_UNIT_STATUSES = {'pending', 'routing', 'matching_profile', 'extracting', 'merging_supplement'}
IN_FLIGHT_UNIT_STATUSES = {'routing', 'matching_profile', 'extracting', 'merging_supplement'}
# 候选待处理原因中偏「冲突/歧义」的码;其余有 missing_fields 或待补语义的归入待补信息。
_CANDIDATE_CONFLICT_REASON_CODES = frozenset({
'email_supplement_conflict',
'duplicate_decision_required',
'blocking_conflict',
'profile_ambiguous',
'multiple_business_tables',
'multiple_po_detected',
'supplement_relation_ambiguous',
'email_supplement_ambiguous',
'order_must_be_object',
})
# Run 级处理事项展示顺序:越靠前越优先作为 primary_notice。
_HANDLING_ITEM_PRIORITY = (
'technical_failure',
'document_review',
'candidate_conflict',
'candidate_missing_info',
'auto_freeze_blocked',
'budget_stopped',
'candidate_confirmation',
)
def _safe_file_name(value: Any) -> str | None:
@@ -29,8 +64,231 @@ def _safe_file_name(value: Any) -> str | None:
text = str(value or '').strip().replace('\\', '/')
if not text:
return None
name = text.split('/')[-1].strip()
return name[:255] or None
return text.rsplit('/', 1)[-1][:255]
def _elapsed_seconds(*, started_at: datetime | None, finished_at: datetime | None, now: datetime | None = None) -> int | None:
"""按后端时钟计算已用秒数;未开始返回 None。"""
if started_at is None:
return None
end = finished_at or now or datetime.utcnow()
return max(0, int((end - started_at).total_seconds()))
def _cancellation_projection(target: Any) -> dict[str, Any] | None:
"""投影取消请求元数据;不向普通用户回传管理员代取消的长文本时可仍保留 reason 供本人查看。"""
requested_at = getattr(target, 'cancellation_requested_at', None)
if requested_at is None and getattr(target, 'cancellation_completed_at', None) is None:
return None
return {
'requested': requested_at is not None,
'requested_at': requested_at.isoformat() + 'Z' if requested_at else None,
'completed_at': (
target.cancellation_completed_at.isoformat() + 'Z'
if getattr(target, 'cancellation_completed_at', None) else None
),
'actor_type': getattr(target, 'cancellation_actor_type', None),
'actor_id': getattr(target, 'cancellation_actor_id', None),
'reason': getattr(target, 'cancellation_reason', None),
'reason_code': getattr(target, 'cancellation_reason_code', None),
}
def _unit_user_visible_stage(unit: ShippingOrderExtractionUnit, *, run: ShippingOrderExtractionRun | None = None) -> str:
"""
将 Unit 事实投影为用户可见阶段。
核心逻辑:取消请求优先于业务态;review_required 不得映射为 failed。
"""
if unit.cancellation_requested_at is not None and unit.cancellation_completed_at is None and unit.status != 'cancelled':
return 'cancellation_requested'
status = str(unit.status or '')
if status == 'pending':
return 'document_queued'
if status in {'routing', 'matching_profile', 'extracting', 'merging_supplement', 'candidate_ready', 'review_required', 'failed', 'cancelled'}:
return status
if run is not None and str(run.phase or '') == 'waiting_layout':
return 'layout_parsing_started'
return status or 'pending'
def _run_user_visible_stage(run: ShippingOrderExtractionRun, units: list[ShippingOrderExtractionUnit]) -> str:
"""Run 级用户可见阶段;取消请求优先。"""
if run.cancellation_requested_at is not None and run.cancellation_completed_at is None and run.status != 'cancelled':
return 'cancellation_requested'
if run.status == 'cancelled':
return 'cancelled'
if run.status in {'completed', 'partially_completed'}:
return 'completed'
if run.status == 'review_required':
return 'review_required'
if run.status == 'failed':
return 'failed'
if str(run.phase or '') == 'waiting_layout':
return 'layout_parsing_started'
active = next((unit for unit in units if unit.status in ACTIVE_UNIT_STATUSES), None)
if active is not None:
return _unit_user_visible_stage(active, run=run)
return 'document_queued' if run.status == 'queued' else 'extracting'
def _queue_positions(units: list[ShippingOrderExtractionUnit]) -> dict[int, int]:
"""按 position 为 pending Unit 计算 1-based 队列位置。"""
pending = sorted(
(unit for unit in units if unit.status == 'pending' and unit.cancellation_completed_at is None),
key=lambda row: (int(row.position or 0), int(row.id or 0)),
)
return {int(unit.id): index for index, unit in enumerate(pending, start=1)}
def _health_tips_for_unit(
unit: ShippingOrderExtractionUnit,
*,
run: ShippingOrderExtractionRun,
now: datetime | None = None,
) -> list[dict[str, Any]]:
"""
按 Unit 事实计算健康提示。
核心逻辑:仅对未终态 Unit 计算;排队看等待时长,执行中看空闲与累计耗时。
"""
if unit.status in {'candidate_ready', 'review_required', 'failed', 'cancelled'}:
return []
if run.status not in {'queued', 'processing'}:
return []
clock = now or datetime.utcnow()
tips: list[dict[str, Any]] = []
if unit.status == 'pending':
stamp = unit.created_at or run.created_at
if stamp is not None:
waited = int((clock - stamp).total_seconds())
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['queue_backlog']
if waited >= threshold:
tips.append({
'code': 'queue_backlog',
'threshold_seconds': threshold,
'idle_or_elapsed_seconds': waited,
})
return tips
last_activity = unit.last_activity_at or unit.started_at or unit.created_at
if last_activity is not None:
idle = int((clock - last_activity).total_seconds())
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['processing_slow']
if idle >= threshold:
tips.append({
'code': 'processing_slow',
'threshold_seconds': threshold,
'idle_or_elapsed_seconds': idle,
})
started = unit.started_at or unit.created_at
if started is not None:
elapsed = int((clock - started).total_seconds())
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['processing_attention']
if elapsed >= threshold:
tips.append({
'code': 'processing_attention',
'threshold_seconds': threshold,
'idle_or_elapsed_seconds': elapsed,
})
return tips
def _health_tips_for_planned_document(
*,
run: ShippingOrderExtractionRun,
stage: str,
started_at: datetime | None,
now: datetime | None = None,
) -> list[dict[str, Any]]:
"""
Unit 未物化时按 Run/版面等待事实计算健康提示。
核心逻辑:终态不提醒;排队看创建等待,版面解析看空闲与累计耗时。
"""
if stage in {'failed', 'cancelled', 'completed', 'candidate_ready'}:
return []
if run.status not in {'queued', 'processing'}:
return []
clock = now or datetime.utcnow()
tips: list[dict[str, Any]] = []
if stage in {'document_queued', 'waiting_layout', 'pending'}:
stamp = run.created_at
if stamp is not None:
waited = int((clock - stamp).total_seconds())
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['queue_backlog']
if waited >= threshold:
tips.append({
'code': 'queue_backlog',
'threshold_seconds': threshold,
'idle_or_elapsed_seconds': waited,
})
last_activity = run.last_activity_at or started_at or run.created_at
if last_activity is not None and stage in {'layout_parsing_started', 'waiting_layout', 'document_queued'}:
idle = int((clock - last_activity).total_seconds())
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['processing_slow']
if idle >= threshold:
tips.append({
'code': 'processing_slow',
'threshold_seconds': threshold,
'idle_or_elapsed_seconds': idle,
})
anchor = started_at or run.created_at
if anchor is not None:
elapsed = int((clock - anchor).total_seconds())
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['processing_attention']
if elapsed >= threshold:
tips.append({
'code': 'processing_attention',
'threshold_seconds': threshold,
'idle_or_elapsed_seconds': elapsed,
})
return tips
def _health_tips_for_run(run: ShippingOrderExtractionRun, units: list[ShippingOrderExtractionUnit], *, now: datetime | None = None) -> list[dict[str, Any]]:
"""根据冻结阈值计算健康提示;仅活跃 Run 返回。"""
if run.status not in {'queued', 'processing'}:
return []
clock = now or datetime.utcnow()
tips: list[dict[str, Any]] = []
last_activity = run.last_activity_at or run.updated_at or run.created_at
if last_activity is not None:
idle = int((clock - last_activity).total_seconds())
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['processing_slow']
if idle >= threshold:
tips.append({
'code': 'processing_slow',
'threshold_seconds': threshold,
'idle_or_elapsed_seconds': idle,
})
oldest_pending = None
for unit in units:
if unit.status != 'pending' or unit.cancellation_completed_at is not None:
continue
stamp = unit.created_at or run.created_at
if stamp is not None and (oldest_pending is None or stamp < oldest_pending):
oldest_pending = stamp
if oldest_pending is not None:
waited = int((clock - oldest_pending).total_seconds())
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['queue_backlog']
if waited >= threshold:
tips.append({
'code': 'queue_backlog',
'threshold_seconds': threshold,
'idle_or_elapsed_seconds': waited,
})
started = run.started_at or run.created_at
if started is not None:
elapsed = int((clock - started).total_seconds())
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['processing_attention']
if elapsed >= threshold:
tips.append({
'code': 'processing_attention',
'threshold_seconds': threshold,
'idle_or_elapsed_seconds': elapsed,
})
return tips
def _snapshot_documents(run: ShippingOrderExtractionRun) -> dict[int, dict[str, Any]]:
@@ -228,15 +486,394 @@ def _open_existing_document_ids(run: ShippingOrderExtractionRun) -> set[int]:
}
def _trim_reason_codes(values: Any, *, limit: int = 12) -> list[str]:
"""去重并截断原因码列表,避免工作台响应膨胀。"""
codes: list[str] = []
seen: set[str] = set()
for raw in values or []:
code = str(raw or '').strip()
if not code or code in seen:
continue
seen.add(code)
codes.append(code[:96])
if len(codes) >= limit:
break
return codes
def _trim_pending_order_item(item: dict[str, Any]) -> dict[str, Any]:
"""裁剪待处理候选事实,只保留用户可见标识与原因。"""
missing = item.get('missing_fields') if isinstance(item.get('missing_fields'), list) else []
return {
'candidate_no': str(item.get('candidate_no') or '').strip() or None,
'po_number': str(item.get('po_number') or '').strip() or None,
'reasons': _trim_reason_codes(item.get('reasons')),
'missing_fields': [str(field).strip() for field in missing if str(field or '').strip()][:20],
'duplicate_status': str(item.get('duplicate_status') or '').strip() or None,
}
def _pending_order_facts(run: ShippingOrderExtractionRun) -> list[dict[str, Any]]:
"""
读取本轮仍待人工处理的候选事实。
核心逻辑:优先使用 result_json.pending_orders(Worker 收口快照);缺失时回查当前版本 provisional 候选。
"""
result = run.result_json if isinstance(getattr(run, 'result_json', None), dict) else {}
stored = result.get('pending_orders')
if isinstance(stored, list) and stored:
return [
_trim_pending_order_item(item)
for item in stored
if isinstance(item, dict)
][:50]
if getattr(run, 'id', None) is None:
return []
rows = (
ShippingNoticeCandidate.query.filter(
ShippingNoticeCandidate.order_extraction_run_id == int(run.id),
ShippingNoticeCandidate.is_current_version.is_(True),
ShippingNoticeCandidate.candidate_status == 'provisional',
).all()
)
pending: list[dict[str, Any]] = []
for candidate in rows:
if str(candidate.duplicate_resolution or '').strip() == 'open_existing':
continue
reasons: list[str] = []
if isinstance(candidate.conflicts_json, list):
for conflict in candidate.conflicts_json:
if isinstance(conflict, dict):
code = str(conflict.get('code') or conflict.get('reason') or '').strip()
else:
code = str(conflict or '').strip()
if code:
reasons.append(code)
missing = list(candidate.missing_fields_json or []) if isinstance(candidate.missing_fields_json, list) else []
if missing and 'required_field_missing' not in reasons:
reasons.append('required_field_missing')
if str(candidate.duplicate_status or '').strip() in {'conflict', 'needs_decision'}:
reasons.append('duplicate_decision_required')
if str(candidate.validation_status or '') != 'ready' and not reasons and not missing:
reasons.append('required_field_missing')
pending.append(_trim_pending_order_item({
'candidate_no': candidate.candidate_no,
'po_number': candidate.po_number,
'reasons': reasons,
'missing_fields': missing,
'duplicate_status': candidate.duplicate_status,
}))
return pending[:50]
def _auto_freeze_block_facts(run: ShippingOrderExtractionRun) -> dict[str, Any]:
"""汇总自动冻结门禁受阻事实:阻断任务与策略层 blocking_reason_codes。"""
result = run.result_json if isinstance(getattr(run, 'result_json', None), dict) else {}
auto_freeze = result.get('auto_freeze') if isinstance(result.get('auto_freeze'), dict) else {}
blocked_raw = auto_freeze.get('blocked_tasks') if isinstance(auto_freeze.get('blocked_tasks'), list) else []
blocked_tasks: list[dict[str, Any]] = []
blocked_codes: list[str] = []
for item in blocked_raw[:30]:
if not isinstance(item, dict):
continue
code = str(item.get('code') or '').strip()
blocked_tasks.append({
'candidate_no': str(item.get('candidate_no') or '').strip() or None,
'task_no': str(item.get('task_no') or '').strip() or None,
'code': code or None,
})
if code:
blocked_codes.append(code)
policy_raw = getattr(run, 'auto_freeze_policy_json', None)
policy = policy_raw if isinstance(policy_raw, dict) else {}
policy_codes = _trim_reason_codes(policy.get('blocking_reason_codes'))
created_count = max(0, int(result.get('created_count') or 0))
# 已建单但策略未放行,或执行阶段有阻断任务,均视为自动冻结受阻。
policy_blocked = (
created_count > 0
and not bool(policy.get('enabled'))
and bool(policy_codes)
and bool(policy.get('evaluated_from_run'))
)
return {
'blocked_tasks': blocked_tasks,
'reason_codes': _trim_reason_codes([*blocked_codes, *policy_codes]),
'blocked': bool(blocked_tasks) or policy_blocked,
'blocked_task_count': len(blocked_tasks),
}
def _budget_stopped_for_run(run: ShippingOrderExtractionRun) -> bool:
"""判断本轮是否因预算停扩;优先读 result 快照,其次读选择计划受限计数。"""
result = run.result_json if isinstance(getattr(run, 'result_json', None), dict) else {}
if bool(result.get('budget_stopped')):
return True
snapshot = getattr(run, 'input_snapshot_json', None)
if not isinstance(snapshot, dict):
snapshot = {}
selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {}
budget_limited = max(0, int(selection.get('budget_limited_attachment_count') or 0))
pending_expansion = max(0, int(selection.get('pending_expansion_attachment_count') or 0))
if str(getattr(run, 'status', '') or '') in {'partially_completed', 'review_required', 'failed'} and (
budget_limited > 0 or pending_expansion > 0
):
return True
return False
def _handling_item(
*,
category: str,
count: int,
reason_codes: list[str] | None = None,
affected_refs: list[dict[str, Any]] | None = None,
primary_action: str,
) -> dict[str, Any]:
"""组装单条 Run 级处理事项。"""
return {
'category': category,
'count': max(0, int(count)),
'reason_codes': _trim_reason_codes(reason_codes or []),
'affected_refs': (affected_refs or [])[:20],
'primary_action': primary_action,
}
def _budget_limited_attachment_refs(run: ShippingOrderExtractionRun) -> list[dict[str, Any]]:
"""从冻结选择计划提取预算受限附件引用,供 handling_items 直达定位。"""
snapshot = getattr(run, 'input_snapshot_json', None)
if not isinstance(snapshot, dict):
return []
selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {}
items = selection.get('items') if isinstance(selection.get('items'), list) else []
budget_codes = {'budget_initial_limit', 'budget_total_limit', 'budget_total_bytes'}
refs: list[dict[str, Any]] = []
for item in items:
if not isinstance(item, dict):
continue
codes = {str(code).strip() for code in (item.get('skip_reason_codes') or []) if str(code or '').strip()}
if not (codes & budget_codes):
continue
document_id = int(item.get('document_id') or 0)
refs.append({
'type': 'attachment',
'file_name': _safe_file_name(item.get('filename') or item.get('file_name')),
'content_hash': str(item.get('content_hash') or '').strip()[:64] or None,
'document_id': document_id if document_id > 0 else None,
})
if len(refs) >= 10:
break
return refs
def build_handling_items(
run: ShippingOrderExtractionRun,
units: list[ShippingOrderExtractionUnit] | None = None,
*,
open_existing_doc_ids: set[int] | None = None,
) -> list[dict[str, Any]]:
"""
将 Run 收口后的混合状态拆成可展示、可跳转的处理事项。
核心逻辑:不依赖单一 Run.status;分别统计 PDF 复核、技术失败、候选待补/冲突、
自动冻结受阻与预算停扩。前端应以本列表为主提示,避免用 heuristic 掩盖后端事实。
Args:
run: 订单抽取 Run。
units: 可选 Unit 列表;缺省时从 extraction_plan 读取。
open_existing_doc_ids: 已 open_existing 的 document_id,避免误报复核。
Returns:
按优先级排序的 handling_items 列表。
"""
unit_rows = list(units) if units is not None else (
list(run.extraction_plan.units or []) if run.extraction_plan is not None else []
)
open_ids = open_existing_doc_ids if open_existing_doc_ids is not None else _open_existing_document_ids(run)
items: list[dict[str, Any]] = []
# [STEP 1] PDF 技术失败与人工复核(排除已 open_existing)。
failed_units = [unit for unit in unit_rows if str(unit.status or '') == 'failed']
if failed_units:
codes = _trim_reason_codes([
getattr(unit, 'technical_failure_reason_code', None) or getattr(unit, 'reason_code', None)
for unit in failed_units
])
items.append(_handling_item(
category='technical_failure',
count=len(failed_units),
reason_codes=codes or ['technical_failure'],
affected_refs=[
{'type': 'document', 'document_id': int(unit.document_id), 'unit_id': int(unit.id)}
for unit in failed_units[:10]
if getattr(unit, 'document_id', None) is not None
],
primary_action='retry_failed_attachments',
))
review_units = [
unit for unit in unit_rows
if str(unit.status or '') == 'review_required' and int(unit.document_id or 0) not in open_ids
]
review_count = max(
len(review_units),
_unresolved_review_document_count(run, open_existing_doc_ids=open_ids),
)
if review_count > 0:
codes = _trim_reason_codes([
getattr(unit, 'reason_code', None)
for unit in review_units
])
items.append(_handling_item(
category='document_review',
count=review_count,
reason_codes=codes,
affected_refs=[
{'type': 'document', 'document_id': int(unit.document_id), 'unit_id': int(unit.id)}
for unit in review_units[:10]
if getattr(unit, 'document_id', None) is not None
],
primary_action='enter_manual_review',
))
# [STEP 2] 候选待补信息 / 冲突(来自 pending_orders 或 provisional 候选)。
pending_orders = _pending_order_facts(run)
conflict_orders: list[dict[str, Any]] = []
missing_orders: list[dict[str, Any]] = []
confirmation_only: list[dict[str, Any]] = []
for item in pending_orders:
reasons = {str(code) for code in item.get('reasons') or []}
missing_fields = item.get('missing_fields') or []
has_conflict = bool(reasons & _CANDIDATE_CONFLICT_REASON_CODES)
has_missing = bool(missing_fields) or bool(reasons - _CANDIDATE_CONFLICT_REASON_CODES - {'auto_create_disabled'})
if has_conflict:
conflict_orders.append(item)
elif has_missing:
missing_orders.append(item)
else:
confirmation_only.append(item)
if conflict_orders:
items.append(_handling_item(
category='candidate_conflict',
count=len(conflict_orders),
reason_codes=[code for item in conflict_orders for code in (item.get('reasons') or [])],
affected_refs=[
{
'type': 'candidate',
'candidate_no': item.get('candidate_no'),
'po_number': item.get('po_number'),
}
for item in conflict_orders[:10]
if item.get('candidate_no')
],
primary_action='review_candidate',
))
if missing_orders:
items.append(_handling_item(
category='candidate_missing_info',
count=len(missing_orders),
reason_codes=[code for item in missing_orders for code in (item.get('reasons') or [])]
or ['required_field_missing'],
affected_refs=[
{
'type': 'candidate',
'candidate_no': item.get('candidate_no'),
'po_number': item.get('po_number'),
'missing_fields': item.get('missing_fields') or [],
}
for item in missing_orders[:10]
if item.get('candidate_no')
],
primary_action='review_candidate',
))
# [STEP 3] 自动冻结受阻与预算停扩。
freeze = _auto_freeze_block_facts(run)
if freeze['blocked']:
items.append(_handling_item(
category='auto_freeze_blocked',
count=max(int(freeze['blocked_task_count'] or 0), 1),
reason_codes=list(freeze['reason_codes'] or []),
affected_refs=[
{
'type': 'task',
'task_no': item.get('task_no'),
'candidate_no': item.get('candidate_no'),
}
for item in freeze['blocked_tasks'][:10]
if item.get('task_no') or item.get('candidate_no')
],
primary_action='view_details',
))
if _budget_stopped_for_run(run):
budget_refs = _budget_limited_attachment_refs(run)
items.append(_handling_item(
category='budget_stopped',
count=max(len(budget_refs), 1),
reason_codes=['budget_initial_limit'],
affected_refs=budget_refs,
primary_action='view_details',
))
# [STEP 4] 仅候选确认(无缺失/冲突);已有缺失/冲突事项时不再叠加笼统「待确认」。
has_candidate_issue = any(
item['category'] in {'candidate_conflict', 'candidate_missing_info'} for item in items
)
if not has_candidate_issue:
confirmation_count = len(confirmation_only)
if confirmation_count == 0:
candidate_ready_units = [
unit for unit in unit_rows
if str(unit.status or '') == 'candidate_ready' and int(unit.document_id or 0) not in open_ids
]
result = run.result_json if isinstance(run.result_json, dict) else {}
pending_count = max(0, int(result.get('pending_count') or 0))
if candidate_ready_units and run.status in {'review_required', 'partially_completed'} and (
pending_count > 0 or not items
):
confirmation_count = max(pending_count, len(candidate_ready_units))
if confirmation_count > 0:
items.append(_handling_item(
category='candidate_confirmation',
count=confirmation_count,
reason_codes=['auto_create_disabled'] if confirmation_only else [],
affected_refs=[
{
'type': 'candidate',
'candidate_no': item.get('candidate_no'),
'po_number': item.get('po_number'),
}
for item in confirmation_only[:10]
if item.get('candidate_no')
],
primary_action='review_candidate',
))
priority = {name: index for index, name in enumerate(_HANDLING_ITEM_PRIORITY)}
items.sort(key=lambda row: priority.get(str(row.get('category') or ''), 99))
return items
def _primary_notice_from_handling_items(items: list[dict[str, Any]]) -> str | None:
"""取优先级最高的处理事项类别,供聊天卡一句通知。"""
if not items:
return None
return str(items[0].get('category') or '') or None
def _run_available_actions(
run: ShippingOrderExtractionRun,
units: list[ShippingOrderExtractionUnit],
*,
open_existing_doc_ids: set[int] | None = None,
handling_items: list[dict[str, Any]] | None = None,
) -> list[str]:
"""根据 Run 与 Unit 事实返回用户可见操作;纯 open_existing 不暴露人工复核入口。"""
open_ids = open_existing_doc_ids if open_existing_doc_ids is not None else _open_existing_document_ids(run)
actions = ['view_details']
actions = ['view_details', 'refresh_status']
needs_manual_review = any(
str(unit.status or '') == 'review_required'
and int(unit.document_id) not in open_ids
@@ -247,8 +884,24 @@ def _run_available_actions(
needs_manual_review = True
if needs_manual_review:
actions.append('enter_manual_review')
if run.status == 'failed' or any(unit.status == 'failed' for unit in units):
actions.append('retry_failed_attachments')
items = handling_items if handling_items is not None else []
categories = {str(item.get('category') or '') for item in items}
if categories & {'candidate_conflict', 'candidate_missing_info', 'candidate_confirmation'}:
if 'review_candidate' not in actions:
actions.append('review_candidate')
if 'enter_manual_review' not in actions:
actions.append('enter_manual_review')
if categories & {'document_review'} and 'enter_manual_review' not in actions:
actions.append('enter_manual_review')
if run.status == 'failed' or any(unit.status == 'failed' for unit in units) or 'technical_failure' in categories:
if 'retry_failed_attachments' not in actions:
actions.append('retry_failed_attachments')
if (
order_extraction_cancel_enabled()
and run.status in {'queued', 'processing'}
and run.cancellation_completed_at is None
):
actions.append('cancel_run')
return actions
@@ -325,6 +978,7 @@ def _document_available_actions(
unit: ShippingOrderExtractionUnit,
*,
duplicate: dict[str, Any] | None = None,
run: ShippingOrderExtractionRun | None = None,
) -> list[str]:
"""
按单元状态与重复决策返回详情项可见操作。
@@ -332,16 +986,30 @@ def _document_available_actions(
核心逻辑:open_existing 且已有任务号时优先暴露 open_existing,不再映射为人工复核入口。
"""
dup = duplicate if isinstance(duplicate, dict) else {}
actions: list[str] = []
if (
str(dup.get('duplicate_resolution') or '') == 'open_existing'
and str(dup.get('existing_task_no') or '').strip()
):
return ['open_existing', 'view_evidence']
if unit.status == 'candidate_ready':
return ['view_evidence', 'review_candidate']
if unit.status == 'review_required':
return ['view_evidence', 'manual_review']
return []
actions = ['open_existing', 'view_evidence']
elif unit.status == 'candidate_ready':
actions = ['view_evidence', 'review_candidate']
elif unit.status == 'review_required':
actions = ['view_evidence', 'manual_review']
elif unit.status == 'failed':
actions = ['view_details']
else:
actions = ['view_details']
if (
order_extraction_cancel_enabled()
and run is not None
and run.status in {'queued', 'processing'}
and unit.status in (ACTIVE_UNIT_STATUSES)
and unit.cancellation_completed_at is None
):
actions.append('cancel_unit')
actions.append('refresh_status')
return actions
def _document_reason_code(
@@ -377,7 +1045,7 @@ def _planned_layout_documents(
documents: dict[int, dict[str, Any]],
event_map: dict[tuple[int, str], ShippingOrderExtractionProgressEvent],
) -> list[dict[str, Any]]:
"""在 Unit 尚未物化时投影已选 PDF,避免版面解析期的详情列表显示为空。"""
"""在 Unit 尚未物化时投影已选 PDF,并继承 Run 终态避免展示假处理中。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {}
selected = [item for item in selection.get('items') or [] if isinstance(item, dict) and item.get('selected')]
@@ -387,36 +1055,80 @@ def _planned_layout_documents(
if str(item.get('content_hash') or '').strip()
}
items: list[dict[str, Any]] = []
run_failed = str(run.status or '') == 'failed'
run_failure_code = str(run.error_code or '').strip() or 'technical_failure'
run_cancelled = str(run.status or '') == 'cancelled'
now = datetime.utcnow()
for index, selected_item in enumerate(selected, start=1):
document = by_hash.get(str(selected_item.get('content_hash') or '').strip(), {})
document_id = int(document.get('document_id') or 0)
started = event_map.get((document_id, 'layout_parsing_started'))
completed = event_map.get((document_id, 'layout_parsing_completed'))
if run_failed:
status = 'failed'
stage = 'failed'
elif run_cancelled:
status = 'cancelled'
stage = 'cancelled'
elif str(run.phase or '') == 'waiting_layout':
status = 'pending'
stage = 'layout_parsing_started' if started and not completed else 'waiting_layout'
else:
status = 'pending'
stage = 'document_queued'
started_at = (started.occurred_at or started.received_at or started.created_at) if started else None
items.append({
# Unit 尚不存在时没有稳定 unit_id;使用负序号仅作 UI 列表 key,不可用于写接口。
'unit_id': -index,
'document_id': document_id,
'file_name': _safe_file_name(selected_item.get('filename')) or document.get('file_name'),
'status': 'pending',
# Job 可在 Unit 物化前最终失败;此时每份计划 PDF 都不能继续显示为 pending。
'status': status,
'user_visible_stage': stage,
'queue_position': index if status == 'pending' and not run_failed and not run_cancelled else None,
'elapsed_seconds': _elapsed_seconds(started_at=started_at or run.created_at, finished_at=run.finished_at, now=now)
if (started_at or run.created_at) else None,
'health_tips': (
_health_tips_for_planned_document(
run=run,
stage=stage,
started_at=started_at,
now=now,
) if progress_ui_v3_enabled() else []
),
'cancellation': _cancellation_projection(run) if run_cancelled or getattr(run, 'cancellation_requested_at', None) else None,
'selection_batch': int(selected_item.get('selection_batch') or 0) or None,
'group_key': str(selected_item.get('group_key') or '').strip() or None,
'retry_status': None,
'technical_failure_reason_code': None,
'technical_failure_reason_code': run_failure_code if run_failed else None,
'budget_cost': None,
'po_number': None,
'line_count': 0,
'profile': None,
'email_supplement': {'status': 'none', 'relation_codes': [], 'conflict_count': 0},
'reason_code': None,
'reason_code': run_failure_code if run_failed else None,
'review_details': [],
'duplicate_resolution': None,
'existing_task_no': None,
'duplicate_status': None,
'available_actions': [],
'activity_event_code': 'layout_parsing_completed' if completed else 'layout_parsing_started' if started else None,
'started_at': (started.occurred_at or started.received_at or started.created_at).isoformat() + 'Z' if started else None,
'last_activity_at': None,
'finished_at': (completed.occurred_at or completed.received_at or completed.created_at).isoformat() + 'Z' if completed else None,
'available_actions': (['cancel_unit'] if (
order_extraction_cancel_enabled()
and run.status in {'queued', 'processing'}
and getattr(run, 'cancellation_completed_at', None) is None
) else []),
'activity_event_code': 'technical_failed' if run_failed else ('layout_parsing_completed' if completed else 'layout_parsing_started' if started else None),
'started_at': started_at.isoformat() + 'Z' if started_at else None,
'last_activity_at': (
(completed.occurred_at or completed.received_at or completed.created_at).isoformat() + 'Z'
if completed else (
started_at.isoformat() + 'Z' if started_at else (
run.last_activity_at.isoformat() + 'Z' if getattr(run, 'last_activity_at', None) else None
)
)
),
'finished_at': (run.finished_at.isoformat() + 'Z' if run_failed and run.finished_at else (
(completed.occurred_at or completed.received_at or completed.created_at).isoformat() + 'Z' if completed else None
)),
})
return items
@@ -500,16 +1212,29 @@ def serialize_workspace_run_documents(run: ShippingOrderExtractionRun) -> list[d
field_codes = _schema_field_codes(run)
route_by_unit = _latest_route_decisions(run)
duplicates_by_doc = _duplicate_projection_by_document(run)
queue_positions = _queue_positions(units)
now = datetime.utcnow()
items: list[dict[str, Any]] = []
for unit in units:
orders = _orders_from_unit(unit)
document = documents.get(int(unit.document_id), {})
duplicate = duplicates_by_doc.get(int(unit.document_id), {})
started_at = getattr(unit, 'started_at', None) or (unit.created_at if unit.status != 'pending' else None)
items.append({
'unit_id': int(unit.id),
'document_id': int(unit.document_id),
'file_name': document.get('file_name'),
'status': unit.status,
'user_visible_stage': _unit_user_visible_stage(unit, run=run),
'queue_position': queue_positions.get(int(unit.id)),
'elapsed_seconds': _elapsed_seconds(
started_at=started_at,
finished_at=getattr(unit, 'finished_at', None),
now=now,
),
'health_tips': _health_tips_for_unit(unit, run=run, now=now) if progress_ui_v3_enabled() else [],
'cancellation': _cancellation_projection(unit),
'activity_version': int(getattr(unit, 'activity_version', 1) or 1),
'selection_batch': int(unit.selection_batch) if unit.selection_batch is not None else None,
'group_key': str(unit.group_key or '').strip() or None,
'retry_status': str(unit.retry_status or '').strip() or None,
@@ -524,7 +1249,7 @@ def serialize_workspace_run_documents(run: ShippingOrderExtractionRun) -> list[d
'duplicate_resolution': duplicate.get('duplicate_resolution'),
'existing_task_no': duplicate.get('existing_task_no'),
'duplicate_status': duplicate.get('duplicate_status'),
'available_actions': _document_available_actions(unit, duplicate=duplicate),
'available_actions': _document_available_actions(unit, duplicate=duplicate, run=run),
'activity_event_code': None,
'started_at': getattr(unit, 'started_at', None).isoformat() + 'Z' if getattr(unit, 'started_at', None) else None,
'last_activity_at': getattr(unit, 'last_activity_at', None).isoformat() + 'Z' if getattr(unit, 'last_activity_at', None) else None,
@@ -588,6 +1313,30 @@ def serialize_workspace_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
_unresolved_review_document_count(run, open_existing_doc_ids=open_existing_doc_ids),
)
opened_existing_count = max(open_existing_units, _result_opened_existing_count(run))
handling_items = build_handling_items(run, units, open_existing_doc_ids=open_existing_doc_ids)
now = datetime.utcnow()
if current_activity is not None:
active_unit = None
if current_activity.get('unit_id') is not None:
active_unit = next((unit for unit in units if int(unit.id) == int(current_activity['unit_id'])), None)
current_activity = {
**current_activity,
'user_visible_stage': (
_unit_user_visible_stage(active_unit, run=run)
if active_unit is not None
else _run_user_visible_stage(run, units)
),
'elapsed_seconds': _elapsed_seconds(
started_at=(active_unit.started_at if active_unit is not None else run.started_at) or run.created_at,
finished_at=active_unit.finished_at if active_unit is not None else run.finished_at,
now=now,
),
'last_activity_at': (
(active_unit.last_activity_at.isoformat() + 'Z')
if active_unit is not None and active_unit.last_activity_at
else (run.last_activity_at.isoformat() + 'Z' if run.last_activity_at else None)
),
}
return {
'summary': {
'total_documents': _planned_document_count(run, units),
@@ -596,11 +1345,27 @@ def serialize_workspace_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
'completed_documents': status_counter.get('candidate_ready', 0),
'review_required_documents': review_document_count,
'failed_documents': status_counter.get('failed', 0),
'cancelled_documents': status_counter.get('cancelled', 0),
'candidate_count': sum(_candidate_count(unit) for unit in units),
'opened_existing_documents': opened_existing_count,
},
'current_activity': current_activity,
'available_actions': _run_available_actions(run, units, open_existing_doc_ids=open_existing_doc_ids),
'handling_items': handling_items,
'primary_notice': _primary_notice_from_handling_items(handling_items),
'available_actions': _run_available_actions(
run,
units,
open_existing_doc_ids=open_existing_doc_ids,
handling_items=handling_items,
),
'user_visible_stage': _run_user_visible_stage(run, units),
# 回滚进度 UI v3 时不下发健康提示,避免前端展示灰度未启用的细化提醒。
'health_tips': _health_tips_for_run(run, units, now=now) if progress_ui_v3_enabled() else [],
'cancellation': _cancellation_projection(run),
'progress_version': int(run.progress_version or 0),
'elapsed_seconds': _elapsed_seconds(started_at=run.started_at or run.created_at, finished_at=run.finished_at, now=now),
'last_activity_at': run.last_activity_at.isoformat() + 'Z' if run.last_activity_at else None,
'feature_flags': progress_feature_flags_payload(),
}
@@ -623,6 +1388,7 @@ def serialize_workspace_run_chat_state(run: ShippingOrderExtractionRun) -> dict[
'completedDocuments': int(summary.get('completed_documents') or 0),
'reviewRequiredDocuments': int(summary.get('review_required_documents') or 0),
'failedDocuments': int(summary.get('failed_documents') or 0),
'cancelledDocuments': int(summary.get('cancelled_documents') or 0),
'candidateCount': int(summary.get('candidate_count') or 0),
'openedExistingCount': int(summary.get('opened_existing_documents') or 0),
},
@@ -631,12 +1397,31 @@ def serialize_workspace_run_chat_state(run: ShippingOrderExtractionRun) -> dict[
'unitId': int(current_activity.get('unit_id') or 0),
'fileName': current_activity.get('file_name'),
'eventCode': str(current_activity.get('event_code') or ''),
'userVisibleStage': current_activity.get('user_visible_stage'),
'selectionBatch': int(current_activity.get('selection_batch') or 0) or None,
'reasonCodes': [str(code) for code in current_activity.get('reason_codes') or [] if str(code).strip()],
'elapsedSeconds': current_activity.get('elapsed_seconds'),
'lastActivityAt': current_activity.get('last_activity_at'),
}
if current_activity else None
),
'availableActions': [str(action) for action in projection.get('available_actions') or []],
'handlingItems': [
{
'category': str(item.get('category') or ''),
'count': int(item.get('count') or 0),
'reasonCodes': [str(code) for code in item.get('reason_codes') or [] if str(code).strip()],
'affectedRefs': list(item.get('affected_refs') or []),
'primaryAction': str(item.get('primary_action') or '') or None,
}
for item in (projection.get('handling_items') or [])
if isinstance(item, dict) and str(item.get('category') or '').strip()
],
'primaryNotice': projection.get('primary_notice'),
'userVisibleStage': projection.get('user_visible_stage'),
'healthTips': projection.get('health_tips') or [],
'cancellation': projection.get('cancellation'),
'progressVersion': projection.get('progress_version'),
'terminal': str(run.status or '') not in {'queued', 'processing'},
'errorCode': str(run.error_code or '') or None,
'startedAt': run.started_at.isoformat() + 'Z' if run.started_at else None,
@@ -2,10 +2,12 @@
backend/app/services/shipping_notice/order_review_confirmation_service.py
用途:按 PDF 确认复核草稿并独立创建发货任务,确认后复用同一 auto_progress 链。
依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task、progress_workflow.auto_progress。
依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task、fulfillment_audit、
progress_workflow.auto_progress。
逻辑:确认在单事务内分别锁定 Case 与 Draft(避免 joinedload+FOR UPDATE),
冻结不可变 Revision,物化仅供履约的人工 Candidate 与 accepted Extraction;
全程不改写机器 Candidate,也不创建 Batch。由 workspace shipping_notice API 调用;
全程不改写机器 Candidate,也不创建 Batch。确认成功后无条件写 Case 级统一审计
(不依赖工作项是否绑定),再尝试关闭会话工作项。由 workspace shipping_notice API 调用;
API commit 后触发 progress_workflow.auto_progress(禁止平行推进链)。
"""
@@ -24,6 +26,7 @@ from app.models import (
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingOrderExtraction,
ShippingOrderExtractionRun,
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
ShippingOrderLine,
@@ -31,6 +34,7 @@ from app.models import (
ShippingOrderReviewCaseEvent,
ShippingOrderReviewConfirmedRevision,
ShippingOrderReviewDraft,
ShippingSessionPdfWorkItem,
ShippingTask,
)
from app.services.shipping_notice.batch_create_idempotency import (
@@ -44,6 +48,7 @@ from app.services.shipping_notice.candidate_service import ensure_candidate_fulf
from app.services.shipping_notice.candidate_validation import normalize_candidate_business_summary
from app.services.shipping_notice.duplicate_detection import apply_duplicate_result_to_candidate, detect_duplicates_for_candidate
from app.services.shipping_notice.document_candidate_persist import generate_candidate_no
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.order_review_draft_service import build_confirmable_draft_summary
from app.services.shipping_notice.order_review_projection import serialize_review_case
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
@@ -192,6 +197,81 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su
return extraction
def _session_item_no_for_case(case: ShippingOrderReviewCase) -> str | None:
"""
按 current_case_id 反查会话工作项编号。
核心逻辑:确认审计不得因工作项缺失而跳过;仅用于填充关联字段。
Args:
case: 当前复核 Case。
Returns:
工作项编号;未绑定时为 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
def _conversation_id_for_case(case: ShippingOrderReviewCase) -> str | None:
"""
从 Case 所属 Run 读取会话 ID。
Args:
case: 当前复核 Case。
Returns:
conversation_id;Run 缺失时为 None。
"""
run = case.run
if run is None and case.run_id:
run = db.session.get(ShippingOrderExtractionRun, int(case.run_id))
return str(run.conversation_id) if run is not None and run.conversation_id else None
def _record_unified_confirmation_audit(
case: ShippingOrderReviewCase,
*,
actor_id: int,
before: dict[str, Any],
after: dict[str, Any],
task_no: str | None,
idempotency_key: str,
) -> None:
"""
将确认建单写入统一 ShippingAuditEvent,供审计中心无条件覆盖。
核心逻辑:与 CaseEvent / 工作项关闭同事务;即使未绑定工作项也必须落库,
保证操作人、请求关联与前后快照可追溯。
Args:
case: 已置为 confirmed 的 Case。
actor_id: 确认操作人用户 ID。
before: 确认前状态摘要(白名单字段)。
after: 确认后状态摘要(含 task_no)。
task_no: 新建任务号。
idempotency_key: 建单幂等键。
"""
record_fulfillment_audit(
event_type='review_confirmed',
aggregate_type='order_review_case',
aggregate_id=str(case.case_no),
action='confirm_review_case',
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),
session_item_id=_session_item_no_for_case(case),
task_no=task_no,
before=before,
after=after,
metadata={'idempotency_key': idempotency_key},
source='order_review',
)
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)
@@ -225,7 +305,22 @@ 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` 统一审计(含操作人与前后快照),
再尝试关闭绑定的会话工作项;工作项缺失不得跳过统一审计。
Args:
user_id: Case 属主用户 ID。
case_no: 复核 Case 编号。
expected_draft_version: 客户端声明的草稿版本。
idempotency_key: 建单幂等键。
warning_acknowledgements: 警告确认列表。
Returns:
含 task_no / case / 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')
@@ -262,7 +357,14 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
'source_file_name': document.filename,
'duplicate_resolution_type': 'normal',
}])
previous_status = str(case.status or '')
previous_disposition = case.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,
)
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))
@@ -300,6 +402,28 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
case_id=int(case.id), event_type='case_confirmed', draft_version=int(case.current_draft.draft_version),
actor_user_id=int(user_id), operation_json={'task_no': task.task_no, 'idempotency_key': key, 'warning_acknowledgements': acknowledgements},
))
# Case 级统一审计必须先写:即使工作项尚未绑定,审计中心仍可按 Case 追溯确认事实。
_record_unified_confirmation_audit(
case,
actor_id=int(user_id),
before={'status': previous_status, 'disposition': previous_disposition},
after={
'status': case.status,
'disposition': case.disposition,
'confirmed_task_no': task.task_no,
'draft_version': int(case.current_draft.draft_version),
},
task_no=task.task_no,
idempotency_key=key,
)
close_work_item_for_case(
case=case,
closed_reason='confirmed',
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()
# 调用方须在 commit 后调用 trigger_auto_progress_after_review_confirm。
@@ -2,10 +2,11 @@
backend/app/services/shipping_notice/order_review_disposition_service.py
用途:建单前订单复核的 PDF 处置与单文件重识别服务。
依赖:Review Case/Draft/Event、冻结 Run/Document、抽取 Run 创建服务。
依赖:Review Case/Draft/Event、冻结 Run/Document、抽取 Run 创建服务、fulfillment_audit。
逻辑:处置只改变当前 PDF 的 Case 生命周期;锁定时分别 FOR UPDATE Case 与 Draft,
禁止 joinedload+FOR UPDATE。单文件重识别通过新的 Run 保留原始 PDF 与机器结果,
成功后才由 Run 终态钩子替代旧 Case。由 workspace shipping_notice API 调用。
成功后才由 Run 终态钩子替代旧 Case。每次关键处置同时写 CaseEvent + 统一 ShippingAuditEvent;
质量异常原因码 `other` 时备注必填。由 workspace shipping_notice API 调用。
"""
from __future__ import annotations
@@ -23,6 +24,7 @@ from app.models import (
ShippingOrderReviewDraft,
User,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
from app.services.shipping_notice.order_review_projection import serialize_review_case
@@ -63,7 +65,7 @@ def _reason(value: Any, *, allowed: frozenset[str], code: str) -> str:
def _append_event(case: ShippingOrderReviewCase, *, actor_id: int, event_type: str, operation: dict[str, Any]) -> None:
"""追加脱敏处置审计,不保存 PDF 正文、原始模型响应或对象存储定位。"""
"""追加 Case 域事件;不保存 PDF 正文、原始模型响应或对象存储定位。"""
db.session.add(ShippingOrderReviewCaseEvent(
case_id=int(case.id), event_type=event_type,
draft_version=int(case.current_draft.draft_version) if case.current_draft else None,
@@ -71,6 +73,58 @@ 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
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=int(case.id)).first()
return str(item.item_no) if item is not None else None
def _conversation_id_for_case(case: ShippingOrderReviewCase) -> str | None:
"""从 Case 所属 Run 读取会话 ID。"""
run = ShippingOrderExtractionRun.query.get(int(case.run_id)) if case.run_id else None
return str(run.conversation_id) if run is not None and run.conversation_id else None
def _record_unified_disposition_audit(
case: ShippingOrderReviewCase,
*,
actor_id: int,
event_type: str,
action: str,
before: dict[str, Any] | None,
after: dict[str, Any] | None,
reason_code: str | None = None,
reason: str | None = None,
metadata: dict[str, Any] | None = None,
) -> None:
"""
将处置写入统一 ShippingAuditEvent,供管理员审计中心覆盖。
核心逻辑:与 CaseEvent 同事务;附带会话/工作项关联与请求客户端哈希。
"""
record_fulfillment_audit(
event_type=event_type,
aggregate_type='order_review_case',
aggregate_id=str(case.case_no),
action=action,
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),
session_item_id=_session_item_no_for_case(case),
reason_code=reason_code,
reason=reason,
before=before,
after=after,
metadata=metadata or {},
source='order_review',
)
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)
@@ -86,6 +140,15 @@ def create_manual_draft(*, user_id: int, case_no: str, comment: str | None = Non
_append_event(case, actor_id=user_id, event_type='manual_draft_created', operation={
'previous_status': previous, 'comment': str(comment or '').strip()[:500] or None,
})
_record_unified_disposition_audit(
case,
actor_id=user_id,
event_type='review_manual_draft_created',
action='create_manual_draft',
before={'status': previous},
after={'status': case.status, 'disposition': case.disposition},
reason=str(comment or '').strip()[:500] or None,
)
db.session.flush()
return serialize_review_case(case)
@@ -96,31 +159,88 @@ def mark_non_order(*, user_id: int, case_no: str, reason: str, comment: str | 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')
previous = case.status
previous_disposition = case.disposition
case.status = 'non_order'
case.disposition = normalized
comment_text = str(comment or '').strip()[:500] or None
if case.candidate_id is not None:
candidate = db.session.get(ShippingNoticeCandidate, int(case.candidate_id))
if candidate is not None and candidate.consumed_task_id is None and candidate.candidate_status == 'provisional':
candidate.selected = False
candidate.candidate_status = 'rejected'
_append_event(case, actor_id=user_id, event_type='marked_non_order', operation={
'reason': normalized, 'comment': str(comment or '').strip()[:500] or None,
'reason': normalized, 'comment': comment_text,
})
# Case 级统一审计必须先写:即使工作项尚未绑定,审计中心仍可按 Case 追溯。
_record_unified_disposition_audit(
case,
actor_id=user_id,
event_type='review_marked_non_order',
action='mark_non_order',
before={'status': previous, 'disposition': previous_disposition},
after={'status': case.status, 'disposition': normalized},
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(
case=case,
closed_reason='non_order',
actor_type='user',
actor_id=user_id,
reason=comment_text or normalized,
event_type='review_marked_non_order',
)
db.session.flush()
return serialize_review_case(case)
def mark_quality_issue(*, user_id: int, case_no: str, reason: str, comment: str | None = None) -> dict[str, Any]:
"""标记文件质量异常并保留 PDF、草稿和机器值,供补件或单文件重识别恢复。"""
"""
标记文件质量异常并保留 PDF、草稿和机器值,供补件或单文件重识别恢复。
核心逻辑:原因码 `other` 时备注必填,确保统一审计可复盘具体业务理由。
Args:
user_id: Case 属主用户 ID。
case_no: 复核 Case 编号。
reason: 质量原因码(见 `_QUALITY_REASONS`)。
comment: 备注;`other` 时不可为空。
Returns:
序列化后的 Case。
Raises:
ValidationError: 原因码无效,或 `other` 缺少备注。
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')
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',
)
previous = case.status
case.status = 'quality_issue'
case.disposition = normalized
_append_event(case, actor_id=user_id, event_type='marked_quality_issue', operation={
'reason': normalized, 'comment': str(comment or '').strip()[:500] or None,
'reason': normalized, 'comment': comment_text,
})
_record_unified_disposition_audit(
case,
actor_id=user_id,
event_type='review_marked_quality_issue',
action='mark_quality_issue',
before={'status': previous},
after={'status': case.status, 'disposition': normalized},
reason_code=normalized,
reason=comment_text or normalized,
)
db.session.flush()
return serialize_review_case(case)
@@ -166,6 +286,14 @@ def reparse_case_document(*, user_id: int, case_no: str, reason: str, comment: s
_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
mark_reparse_started(
case=case,
successor_run=run,
reason=normalized,
comment=comment,
actor_id=user_id,
)
db.session.flush()
return run, reused
@@ -192,6 +320,15 @@ def create_replacement_upload_intake(*, user_id: int, case_no: str, asset_no: st
_append_event(case, actor_id=user_id, event_type='replacement_upload_created', operation={
'replacement_intake_no': intake['intake_no'],
})
_record_unified_disposition_audit(
case,
actor_id=user_id,
event_type='review_replacement_intake_created',
action='create_replacement_intake',
before={'status': case.status},
after={'status': case.status, 'replacement_intake_no': intake['intake_no']},
metadata={'replacement_intake_no': intake['intake_no']},
)
db.session.flush()
return intake
@@ -233,6 +370,32 @@ def create_replacement_document_run(*, user_id: int, case_no: str, intake_no: st
'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,
},
)
from app.services.shipping_notice.session_pdf_work_item_service import mark_reparse_started
mark_reparse_started(
case=case,
successor_run=run,
reason='document_quality',
comment=f'replacement for {case.case_no}',
actor_id=user_id,
replacement_document_id=int(pdfs[0].id),
)
db.session.flush()
return run, reused
@@ -263,6 +426,7 @@ def finalize_document_reparse(*, run: ShippingOrderExtractionRun, succeeded: boo
_append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_succeeded', operation={
'successor_run_no': run.run_no,
})
# 成功切换由 bind_cases_for_run(新 Case 初始化)完成版本指针;此处不提前改指针。
return
previous = 'quality_issue'
event = ShippingOrderReviewCaseEvent.query.filter(
@@ -277,3 +441,9 @@ 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
mark_reparse_failed_and_restore(
source_case=source_case,
failed_run=run,
failure_stage=str(run.status or 'failed'),
)
@@ -1,9 +1,11 @@
"""
建单前订单复核草稿的编辑、校验与审计服务。
services/shipping_notice/order_review_draft_service.py
依赖:Review Case/Draft、Run 冻结 Schema、订单字段规则和 Candidate 履约硬门禁。
逻辑:只修改独立 Draft JSON;每次写入锁定 Case/Draft、校验草稿版本并追加事件,
绝不修改机器 Candidate。确认建单不属于本模块,留给阶段 6 的原子确认服务。
用途:建单前订单复核草稿的编辑、校验与统一审计。
依赖: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。
"""
from __future__ import annotations
@@ -200,19 +202,122 @@ def build_confirmable_draft_summary(case: ShippingOrderReviewCase) -> tuple[dict
return {**header, 'lines': lines}, validation
def _record_change(case: ShippingOrderReviewCase, *, actor_id: int, event_type: str, operation: dict[str, Any]) -> dict[str, Any]:
"""更新版本、状态和可重放的最小审计事件;不保存 PDF 正文或机器原始响应。"""
def _audit_scalar(value: Any, *, limit: int = 200) -> Any:
"""
将字段值投影为审计可存的受控标量。
核心逻辑:Decimal/date 转字符串;过长字符串截断;拒绝嵌套大对象。
"""
if value is None:
return None
if isinstance(value, Decimal):
return format(value.normalize(), 'f')
if isinstance(value, date):
return value.isoformat()
if isinstance(value, bool) or isinstance(value, (int, float)):
return value
text = str(value)
if len(text) > limit:
return text[:limit]
return text
def _session_item_no_for_case(case: ShippingOrderReviewCase) -> str | None:
"""按 current_case_id 反查会话工作项编号。"""
from app.models import ShippingSessionPdfWorkItem
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=int(case.id)).first()
return str(item.item_no) if item is not None else None
def _conversation_id_for_case(case: ShippingOrderReviewCase) -> str | None:
"""从 Case 所属 Run 读取会话 ID。"""
from app.models import ShippingOrderExtractionRun
run = ShippingOrderExtractionRun.query.get(int(case.run_id)) if case.run_id else None
return str(run.conversation_id) if run is not None and run.conversation_id else None
def _record_change(
case: ShippingOrderReviewCase, *, actor_id: int, event_type: str,
operation: dict[str, Any], validate: bool = False,
) -> dict[str, Any]:
"""
保存草稿变更并写入统一审计。
核心逻辑:仅显式校验时跑整单门禁;审计附带 request_id/operation_id、字段前后值与工作项关联。
"""
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,
)
assert_case_is_current_work_item_version(case=case)
draft = case.current_draft
result = _validation(case)
before_version = int(draft.draft_version)
previous_status = str(case.status or 'draft')
result = _validation(case) if validate else {'status': 'not_validated', 'issues': []}
draft.validation_result_json = result
draft.issue_summary_json = list(result['issues'])
draft.updated_by_id = int(actor_id)
draft.draft_version = int(draft.draft_version) + 1
case.status = 'ready' if result['status'] == 'ready' else 'draft'
case.status = 'ready' if validate and result['status'] == 'ready' else 'draft'
db.session.add(ShippingOrderReviewCaseEvent(
case_id=int(case.id), event_type=event_type, draft_version=int(draft.draft_version), actor_user_id=int(actor_id),
operation_json=operation,
))
changed_paths = [
key for key in ('field_id', 'line_key', 'action')
if key in operation and operation.get(key) is not None
]
field_id = operation.get('field_id')
line_key = operation.get('line_key')
previous_value = _audit_scalar(operation.get('previous_value'))
new_value = _audit_scalar(operation.get('value') if 'value' in operation else operation.get('new_value'))
value_source = str(operation.get('source') or '')[:32] or None
before_snapshot: dict[str, Any] = {
'draft_version': before_version,
'status': previous_status,
}
after_snapshot: dict[str, Any] = {
'draft_version': int(draft.draft_version),
'status': case.status,
'changed_field_paths': changed_paths,
'validation_blocking_count': len([
issue for issue in (result.get('issues') or [])
if isinstance(issue, dict) and str(issue.get('severity') or '').lower() == 'blocking'
]),
'validation_warning_count': len([
issue for issue in (result.get('issues') or [])
if isinstance(issue, dict) and str(issue.get('severity') or '').lower() != 'blocking'
]),
}
if field_id is not None:
before_snapshot['field_id'] = str(field_id)[:64]
after_snapshot['field_id'] = str(field_id)[:64]
before_snapshot['previous_value'] = previous_value
after_snapshot['new_value'] = new_value
if value_source:
after_snapshot['value_source'] = value_source
if line_key is not None:
before_snapshot['line_key'] = str(line_key)[:64]
after_snapshot['line_key'] = str(line_key)[:64]
record_fulfillment_audit(
event_type='review_draft_changed',
aggregate_type='order_review_case',
aggregate_id=str(case.case_no),
action=event_type,
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),
session_item_id=_session_item_no_for_case(case),
before=before_snapshot,
after=after_snapshot,
metadata={'case_event_type': event_type},
source='order_review',
)
db.session.flush()
return serialize_review_case(case)
@@ -223,9 +328,15 @@ def patch_header_field(*, user_id: int, case_no: str, field_id: str, value: Any,
_assert_version(case, expected_draft_version)
field = _require_field(case, field_id, 'header')
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)
case.current_draft.header_values_json = header
return _record_change(case, actor_id=user_id, event_type='header_field_changed', operation={'field_id': field_id, **change})
return _record_change(
case,
actor_id=user_id,
event_type='header_field_changed',
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]:
@@ -235,9 +346,20 @@ def patch_line_field(*, user_id: int, case_no: str, line_key: str, field_id: str
field = _require_field(case, field_id, 'line')
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
target = _find_line(lines, line_key)
previous_value = _current_value(target, field_id)
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', operation={'line_key': line_key, 'field_id': field_id, **change})
return _record_change(
case,
actor_id=user_id,
event_type='line_field_changed',
operation={
'line_key': line_key,
'field_id': field_id,
'previous_value': previous_value,
**change,
},
)
def add_line(*, user_id: int, case_no: str, expected_draft_version: Any) -> dict[str, Any]:
@@ -277,4 +399,4 @@ def validate_draft(*, user_id: int, case_no: str, expected_draft_version: 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={})
return _record_change(case, actor_id=user_id, event_type='draft_validated', operation={}, validate=True)
@@ -39,6 +39,113 @@ def _safe_bbox(value: Any) -> dict[str, float] | None:
return bbox
def _frozen_page_dimensions(case: ShippingOrderReviewCase, page_no: int) -> tuple[float, float] | None:
"""从当前 Run 的冻结版面快照读取页面尺寸,拒绝回读可变 PDF 布局。"""
snapshot = case.run.input_snapshot_json if isinstance(case.run.input_snapshot_json, dict) else {}
for intake in snapshot.get('intakes') or []:
if not isinstance(intake, dict):
continue
for document in intake.get('documents') or []:
if not isinstance(document, dict) or int(document.get('document_id') or 0) != int(case.document_id):
continue
layout = document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {}
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
page = pages.get(str(page_no)) if isinstance(pages.get(str(page_no)), dict) else {}
try:
width, height = float(page['width']), float(page['height'])
except (KeyError, TypeError, ValueError):
return None
return (width, height) if width > 0 and height > 0 else None
return None
def _frozen_document_layout(case: ShippingOrderReviewCase) -> dict[str, Any]:
"""返回当前 PDF 的冻结布局快照;禁止查询可变 Document 版面版本。"""
snapshot = case.run.input_snapshot_json if isinstance(case.run.input_snapshot_json, dict) else {}
for intake in snapshot.get('intakes') or []:
if not isinstance(intake, dict):
continue
for document in intake.get('documents') or []:
if isinstance(document, dict) and int(document.get('document_id') or 0) == int(case.document_id):
layout = document.get('layout_snapshot')
return layout if isinstance(layout, dict) else {}
return {}
def _frozen_cell_coordinate(
case: ShippingOrderReviewCase, observation: dict[str, Any],
) -> tuple[int | None, dict[str, float] | None, str | None]:
"""按冻结 table_id/cell_id 反查明细单元格 bbox,缺失时只返回空而不猜测。"""
table_id = str(observation.get('table_id') or '').strip()
cell_id = str(observation.get('cell_id') or '').strip()
if not table_id or not cell_id:
return None, None, None
candidate = _frozen_document_layout(case).get('layout_candidate')
if not isinstance(candidate, dict):
return None, None, None
for page in candidate.get('pages') or []:
if not isinstance(page, dict):
continue
try:
page_no = int(page.get('page_no'))
width, height = float(page.get('width')), float(page.get('height'))
except (TypeError, ValueError):
continue
if page_no < 1 or width <= 0 or height <= 0:
continue
for table in page.get('tables') or []:
if not isinstance(table, dict) or str(table.get('table_id') or '') != table_id:
continue
for row in table.get('rows') or []:
if not isinstance(row, dict):
continue
for cell in row.get('cells') or []:
if not isinstance(cell, dict) or str(cell.get('cell_id') or '') != cell_id:
continue
bbox = cell.get('bbox') if isinstance(cell.get('bbox'), dict) else {}
try:
normalized = {
'x0': float(bbox['x0']) / width,
'y0': float(bbox['y0']) / height,
'x1': float(bbox['x1']) / width,
'y1': float(bbox['y1']) / height,
}
except (KeyError, TypeError, ValueError):
return page_no, None, None
return page_no, _safe_bbox(normalized), 'frozen_layout_cell'
return None, None, None
def _layout_coordinate_evidence(
case: ShippingOrderReviewCase, observation: dict[str, Any],
) -> tuple[int | None, dict[str, float] | None, str | None]:
"""将冻结的绝对坐标证据转为审阅器可绘制的归一化页内 bbox。"""
raw = observation.get('layout_evidence') if isinstance(observation.get('layout_evidence'), dict) else {}
try:
page_no = int(raw.get('page_no'))
except (TypeError, ValueError):
return None, None, None
if page_no < 1:
return None, None, None
source = str(raw.get('source') or '')[:64] or None
dimensions = _frozen_page_dimensions(case, page_no)
value_bbox = raw.get('value_bbox') if isinstance(raw.get('value_bbox'), dict) else None
if dimensions is None or value_bbox is None:
return page_no, None, source
width, height = dimensions
try:
normalized = {
'x0': float(value_bbox['x0']) / width,
'y0': float(value_bbox['y0']) / height,
'x1': float(value_bbox['x1']) / width,
'y1': float(value_bbox['y1']) / height,
}
except (KeyError, TypeError, ValueError):
return page_no, None, source
return page_no, _safe_bbox(normalized), source
def _observations(case: ShippingOrderReviewCase) -> list[dict[str, Any]]:
"""展开本 Case Unit 的机器字段 Observation;不会查询其他 Run 或 Document 的结果。"""
result = case.unit.result_json if isinstance(case.unit.result_json, dict) else {}
@@ -56,6 +163,8 @@ def _observations(case: ShippingOrderReviewCase) -> list[dict[str, Any]]:
for index, observation in enumerate(field.get('observations') or []):
if not isinstance(observation, dict):
continue
coordinate_page, coordinate_bbox, coordinate_source = _layout_coordinate_evidence(case, observation)
cell_page, cell_bbox, cell_source = _frozen_cell_coordinate(case, observation)
page_no = observation.get('page_no')
try:
page = int(page_no) if page_no is not None else None
@@ -69,11 +178,11 @@ def _observations(case: ShippingOrderReviewCase) -> list[dict[str, Any]]:
'line_index': field.get('_line_index'),
'machine_value': observation.get('value'),
'quote': _safe_quote(observation.get('quote') or observation.get('evidence_quote')),
'page_no': page,
'page_no': coordinate_page or cell_page or page,
'table_id': str(observation.get('table_id') or '')[:128] or None,
'cell_id': str(observation.get('cell_id') or '')[:128] or None,
'bbox': _safe_bbox(observation.get('normalized_bbox') or observation.get('bbox')),
'source': str(observation.get('source') or 'machine_extraction')[:64],
'bbox': coordinate_bbox or cell_bbox or _safe_bbox(observation.get('normalized_bbox') or observation.get('bbox')),
'source': coordinate_source or cell_source or str(observation.get('source') or 'machine_extraction')[:64],
})
return items
@@ -116,4 +116,10 @@ def serialize_review_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
'issue_count': len(case.current_draft.issue_summary_json or []) if case.current_draft is not None else 0,
'available_actions': _allowed_actions(case),
})
return {'run_no': run.run_no, 'summary': counts, 'items': items}
return {
'run_no': run.run_no,
# 已被新版识别替代的 Run 不可继续编辑,前端据此跳转而非渲染空白旧 Case。
'superseded_by_run_no': run.superseding_run.run_no if run.superseding_run is not None else None,
'summary': counts,
'items': items,
}
@@ -11,6 +11,8 @@ from __future__ import annotations
import uuid
from typing import Any
from sqlalchemy.orm.attributes import flag_modified
from app import db
from app.core.errors import NotFoundError
from app.models import (
@@ -23,6 +25,43 @@ from app.models import (
)
def _restore_machine_field_source_case(field: Any) -> bool:
"""以坐标证据的原始引文修正机器文本大小写,不改写人工值或类型化字段。
历史坐标抽取曾在上游将部分字符串转小写;`quote` 是同一 PDF 的原文证据,
仅当两者忽略大小写和空白后完全相同才可安全恢复展示值。
"""
if not isinstance(field, dict):
return False
observations = field.get('observations') if isinstance(field.get('observations'), list) else []
changed = False
for observation in observations:
if not isinstance(observation, dict):
continue
value, quote = observation.get('value'), observation.get('quote')
if not isinstance(value, str) or not isinstance(quote, str):
continue
source = ' '.join(value.split())
original = ' '.join(quote.split())
if source and original and source.casefold() == original.casefold() and source != original:
observation['value'] = quote
changed = True
return changed
def _restore_machine_source_case(header: dict[str, Any], lines: list[dict[str, Any]]) -> bool:
"""修复现有机器快照的原文大小写;只遍历机器层,绝不触碰人工覆盖层。"""
fields = list(header.get('machine_fields') or []) if isinstance(header, dict) else []
for line in lines:
if isinstance(line, dict):
fields.extend(line.get('machine_fields') or [])
changed = False
for field in fields:
# Do not use any(generator): its short-circuit would leave later fields uncorrected.
changed = _restore_machine_field_source_case(field) or changed
return changed
def _is_pdf_unit(run: ShippingOrderExtractionRun, unit: ShippingOrderExtractionUnit) -> bool:
"""仅为冻结快照中的 PDF 文档创建 Case,邮件关系单元不属于人工订单复核。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
@@ -44,10 +83,30 @@ def _single_candidate_id(run: ShippingOrderExtractionRun, unit: ShippingOrderExt
return int(rows[0].id) if len(rows) == 1 else None
def _initial_draft_payload(unit: ShippingOrderExtractionUnit) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
"""把唯一订单的冻结机器结果复制为草稿初值;无或多订单均保留空草稿与问题。"""
result = unit.result_json if isinstance(unit.result_json, dict) else {}
orders = [item for item in result.get('orders') or [] if isinstance(item, dict)]
def _machine_orders_for_unit(
run: ShippingOrderExtractionRun, unit: ShippingOrderExtractionUnit,
) -> list[dict[str, Any]]:
"""读取当前 PDF 的最终机器订单,优先使用完成合并后的 Run 结果。
Worker 会在邮件正文补充事实合并后把最终订单写入 Run,而 Unit 可保留合并前中间
结果。复核草稿必须按 primary_document_id 读取最终订单,避免页面显示空白机器值。
"""
result = run.execution_result_json if isinstance(run.execution_result_json, dict) else {}
final_orders = [
item for item in result.get('orders') or []
if isinstance(item, dict) and int(item.get('primary_document_id') or 0) == int(unit.document_id)
]
if final_orders:
return final_orders
unit_result = unit.result_json if isinstance(unit.result_json, dict) else {}
return [item for item in unit_result.get('orders') or [] if isinstance(item, dict)]
def _initial_draft_payload(
run: ShippingOrderExtractionRun, unit: ShippingOrderExtractionUnit,
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
"""把当前 PDF 的唯一最终机器订单复制为草稿初值;无或多订单保留问题。"""
orders = _machine_orders_for_unit(run, unit)
issues = [
{'code': str(item.get('reason') or 'review_required'), 'severity': str(item.get('severity') or 'blocking')}
for order in orders for item in order.get('conflicts') or []
@@ -62,9 +121,19 @@ def _initial_draft_payload(unit: ShippingOrderExtractionUnit) -> tuple[dict[str,
{'line_key': f'machine-{index + 1}', 'machine_fields': list(line.get('fields') or [])}
for index, line in enumerate(order.get('lines') or []) if isinstance(line, dict)
]
_restore_machine_source_case(header, lines)
return header, lines, issues
def _can_backfill_machine_draft(case: ShippingOrderReviewCase) -> bool:
"""仅回填从旧中间结果生成的空白草稿,绝不覆盖人工编辑。"""
draft = case.current_draft
if draft is None or draft.header_values_json or draft.lines_json:
return False
issues = list(draft.issue_summary_json or [])
return any(str(item.get('code') or '') == 'machine_order_unavailable' for item in issues if isinstance(item, dict))
def ensure_run_review_cases(*, run: ShippingOrderExtractionRun) -> list[ShippingOrderReviewCase]:
"""为 Run 的每个 PDF Unit 幂等初始化唯一 Case 和 Draft,供 Worker 结果持久化后调用。"""
plan = run.extraction_plan
@@ -76,9 +145,35 @@ def ensure_run_review_cases(*, run: ShippingOrderExtractionRun) -> list[Shipping
continue
case = ShippingOrderReviewCase.query.filter_by(unit_id=int(unit.id)).first()
if case is not None:
if _can_backfill_machine_draft(case):
header, lines, issues = _initial_draft_payload(run, unit)
if header or lines:
# 旧 Case 在 Unit 尚未写入最终结果时已初始化;只修复这种空白机器草稿。
case.current_draft.header_values_json = header
case.current_draft.lines_json = lines
case.current_draft.issue_summary_json = issues
case.current_draft.change_reason_json = {
'source': 'machine_result_backfill',
}
db.session.add(ShippingOrderReviewCaseEvent(
case_id=int(case.id), event_type='machine_result_backfilled',
draft_version=int(case.current_draft.draft_version), actor_user_id=None,
operation_json={'document_id': int(unit.document_id)},
))
elif _restore_machine_source_case(
case.current_draft.header_values_json or {}, list(case.current_draft.lines_json or []),
):
# JSON columns do not detect nested dict mutations automatically.
flag_modified(case.current_draft, 'header_values_json')
flag_modified(case.current_draft, 'lines_json')
db.session.add(ShippingOrderReviewCaseEvent(
case_id=int(case.id), event_type='machine_source_case_restored',
draft_version=int(case.current_draft.draft_version), actor_user_id=None,
operation_json={'document_id': int(unit.document_id)},
))
cases.append(case)
continue
header, lines, issues = _initial_draft_payload(unit)
header, lines, issues = _initial_draft_payload(run, unit)
candidate_id = _single_candidate_id(run, unit)
case = ShippingOrderReviewCase(
case_no=f'SORC-{uuid.uuid4().hex[:16].upper()}',
@@ -102,6 +197,9 @@ 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
bind_cases_for_run(run=run, cases=cases)
return cases
@@ -17,7 +17,11 @@ from app.services.shipping_notice.reservation_id import validated_reservation_id
def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any:
"""按冻结字段类型与 normalizer 规范化候选值;类型错误抛稳定业务异常。"""
"""按冻结字段类型解析候选值,同时保留原始文本大小写。
`uppercase_trim` / `lowercase_trim` 仅可用于比较、索引和规则匹配,不能改写
PDF/邮件证据对应的业务展示值;否则料号、客户名称、地址和币种会偏离原文件。
"""
if value in (None, ''):
return None
value_type = str(config.get('value_type') or 'string')
@@ -52,10 +56,6 @@ def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any:
'Dynamic field value type is invalid', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT'
) from exc
text = str(value).strip()
if normalizer == 'uppercase_trim':
text = text.upper()
elif normalizer == 'lowercase_trim':
text = text.lower()
if normalizer == 'reservation_id':
text = validated_reservation_id(text) or ''
if value_type == 'enum' and text not in set(config.get('enum_options') or []):
@@ -188,8 +188,10 @@ def _quote_supports_value(value: Any, config: dict[str, Any], quote: str) -> boo
continue
return False
normalized_quote = ' '.join(quote.upper().split())
normalized_value = ' '.join(str(_json_value(value)).upper().split())
# Text evidence is case-sensitive in Schema v1. Whitespace variation in a PDF
# remains harmless, but ``abc`` must not prove the distinct value ``ABC``.
normalized_quote = ' '.join(quote.split())
normalized_value = ' '.join(str(_json_value(value)).split())
return bool(normalized_value) and normalized_value in normalized_quote
@@ -203,10 +205,25 @@ def _verified_observations(
for item in items:
if not isinstance(item, dict) or not str(item.get('document_id') or '').isdigit():
continue
document = documents.get(int(item['document_id']))
document_id = int(item['document_id'])
document = documents.get(document_id)
value = _normalize(item.get('value'), config)
quote = str(item.get('quote') or '').strip()
if document is None or value is None or not _validate(value, config):
if value is None or not _validate(value, config):
continue
supplement_evidence = item.get('email_supplement_evidence')
if isinstance(supplement_evidence, dict):
verified_supplement = _verified_email_supplement_observation(
document_id=document_id,
documents=documents,
value=value,
quote=quote,
evidence=supplement_evidence,
)
if verified_supplement is not None:
verified.append(verified_supplement)
continue
if document is None:
continue
layout_evidence = item.get('layout_evidence') if raw.get('_hxops_order_field_evidence') is True else None
if isinstance(layout_evidence, dict) and _valid_coordinate_evidence(layout_evidence):
@@ -242,6 +259,41 @@ def _verified_observations(
return verified
def _verified_email_supplement_observation(
*, document_id: int, documents: dict[int, ShippingNoticeDocument], value: Any,
quote: str, evidence: dict[str, Any],
) -> dict[str, Any] | None:
"""验证服务端邮件表合并证据,禁止把任意邮件值伪装成当前 PDF 字段。"""
try:
table_index = int(evidence.get('table_index'))
row_index = int(evidence.get('row_index'))
column_index = int(evidence.get('column_index'))
except (TypeError, ValueError):
return None
cell_id = str(evidence.get('cell_id') or '').strip()
if table_index < 0 or row_index < 0 or column_index < 0 or not cell_id.startswith('email-supplement:'):
return None
intake_ids = {int(document.intake_id) for document in documents.values()}
document = db.session.get(ShippingNoticeDocument, document_id)
if (
document is None
or int(document.intake_id) not in intake_ids
or str(document.document_type or '') != 'email_body'
or not quote
or not _quote_supports_value(value, {'value_type': 'string'}, quote)
):
return None
return {
'value': value, 'document': document, 'quote': quote, 'confidence': 1.0,
'source_type': 'email_body_table', 'extractor': 'email_allocation_table',
'evidence_ref': f'document:{document_id}:cell:{cell_id}',
'evidence_metadata': {
'kind': 'email_supplement_table_cell', 'table_index': table_index,
'row_index': row_index, 'column_index': column_index, 'cell_id': cell_id,
},
}
def _valid_coordinate_evidence(raw: dict[str, Any]) -> bool:
"""只接受后端确认的最小页级坐标证据,缺页号、来源或字符索引时不提升为已验证。"""
return (
@@ -41,8 +41,10 @@ class TableHeaderContract:
def normalize_table_header(value: Any) -> str:
"""以 NFKC、大小写折叠和标点空白折叠生成稳定表头比较键。"""
text = unicodedata.normalize('NFKC', str(value or '')).strip().casefold()
"""以 NFKC 和标点空白折叠生成严格大小写的 Schema v1 表头键。"""
# Schema v1 treats case as business data: ``Part No`` and ``PART NO`` are
# distinct configured labels, so a permissive match cannot silently bind a column.
text = unicodedata.normalize('NFKC', str(value or '')).strip()
text = re.sub(r"[^\w\u4e00-\u9fff]+", ' ', text, flags=re.UNICODE)
return re.sub(r'[_\s]+', ' ', text).strip()
@@ -75,7 +77,9 @@ def compile_table_header_contract(definition: dict[str, Any]) -> TableHeaderCont
normalized = normalize_table_header(candidate)
if not normalized:
continue
if field_code == 'reservation_id' and normalized in RESERVATION_ID_FORBIDDEN_HEADERS:
# This is a safety denylist, not a business-field match. Keep it
# case-insensitive so changing capitalization cannot bypass it.
if field_code == 'reservation_id' and normalized.casefold() in RESERVATION_ID_FORBIDDEN_HEADERS:
forbidden.append(str(candidate))
continue
previous = mapping.get(normalized)
@@ -65,6 +65,21 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
if len(candidates) == 1 or len(reservations) == 1:
selected = candidates
relation = 'po_fallback'
if not selected and not candidates:
# 邮件正文的 PO 可能被上游人工录入错误;仅唯一精确 MPN 才能安全补证。
mpn_matches = [
row for row in rows
if str(row.get('mpn') or '').strip().upper() in mpn_values
]
distinct_matches = {
tuple(str(row.get(field) or '').strip() for field in (
'po_number', 'mpn', 'reservation_id', 'allocation_id', 'source_type',
)): row
for row in mpn_matches
}
if len(distinct_matches) == 1:
selected = list(distinct_matches.values())
relation = 'mpn_fallback'
if not selected:
if candidates:
order.setdefault('conflicts', []).append({'severity': 'blocking', 'reason': 'supplement_relation_ambiguous'})
@@ -0,0 +1,286 @@
"""
services/shipping_notice/progress_audit_contract.py
用途:冻结货代发货通知进度审计与「会话 PDF 工作项」领域契约词典。
依赖:无外部 IO;被 progress / audit / session work item / projection / OpenAPI 与测试引用。
逻辑:状态、用户可见阶段、健康提示、取消语义、会话工作项生命周期、审计事件字典、
快照白名单与敏感键黑名单的唯一代码源;UI 与 Worker 行为变更在后续阶段实现,
本模块只冻结名称与规则,禁止运行时猜测。
"""
from __future__ import annotations
from typing import Final
# 进度映射版本;投影与 i18n 必须与此对齐,禁止前端私自发明阶段码。
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
# 会话 PDF 工作项生命周期(真相源);closed 以外均为未关闭。
SESSION_WORK_ITEM_LIFECYCLE_STATUSES: Final[frozenset[str]] = frozenset({
'pending_review',
'extracting',
'reparse_failed',
'closed',
})
SESSION_WORK_ITEM_CLOSED_REASONS: Final[frozenset[str]] = frozenset({
'confirmed',
'non_order',
'user_cancelled',
'admin_terminated',
})
# 会话工作项 / 版本切换 / 人工复核 / 监管相关审计事件字典(阶段 1+ 落库)。
SESSION_WORK_ITEM_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
'session_work_item_created',
'document_extraction_started',
'document_reparse_requested',
'document_version_replaced',
'document_reparse_failed',
'document_previous_version_restored',
'review_draft_changed',
'review_confirmed',
'review_marked_non_order',
'review_marked_quality_issue',
'review_manual_draft_created',
'review_replacement_intake_created',
'review_replacement_reparse_started',
'session_work_item_cancelled',
'admin_impersonated_review_action',
'review_confirmation_revoked',
'audit_access',
'shipping_resource_accessed',
})
# Run 业务状态(真相源);cancellation_requested 不是 Run.status,而是取消请求元数据投影。
RUN_STATUSES: Final[frozenset[str]] = frozenset({
'queued',
'processing',
'completed',
'partially_completed',
'review_required',
'failed',
'cancelled',
})
# Unit 业务状态(真相源);执行中取消请求不伪造即时 cancelled。
UNIT_STATUSES: Final[frozenset[str]] = frozenset({
'pending',
'routing',
'matching_profile',
'extracting',
'merging_supplement',
'candidate_ready',
'review_required',
'failed',
'cancelled',
})
# 用户可见阶段;由后端投影,前端只做 i18n,禁止自行重算。
USER_VISIBLE_STAGES: Final[tuple[str, ...]] = (
'pending',
'document_queued',
'waiting_layout',
'layout_parsing_started',
'routing',
'matching_profile',
'extracting',
'merging_supplement',
'candidate_ready',
'review_required',
'technical_retrying',
'failed',
'cancellation_requested',
'cancelled',
'completed',
)
# 健康提示码;阈值由后端统一计算,前端不得用本地时钟臆造。
HEALTH_TIP_CODES: Final[frozenset[str]] = frozenset({
'processing_slow', # 连续 60 秒无新活动
'queue_backlog', # 排队超过 5 分钟
'processing_attention', # 处理超过 30 分钟
})
HEALTH_TIP_THRESHOLDS_SECONDS: Final[dict[str, int]] = {
'processing_slow': 60,
'queue_backlog': 5 * 60,
'processing_attention': 30 * 60,
}
# 取消作用域与权限语义(阶段 1 实现校验)。
CANCEL_SCOPES: Final[frozenset[str]] = frozenset({'run', 'unit'})
CANCEL_ACTOR_TYPES: Final[frozenset[str]] = frozenset({'user', 'admin', 'system'})
# 新增/扩展的用户态进度事件;与既有 WORKSPACE_EVENT_CODES 合并后生效。
CANCEL_PROGRESS_EVENT_CODES: Final[frozenset[str]] = frozenset({
'cancellation_requested',
'cancellation_completed',
'unit_cancelled',
})
# 工作台可用动作扩展(阶段 1/2 下发);既有动作保持兼容。
WORKSPACE_AVAILABLE_ACTIONS: Final[frozenset[str]] = frozenset({
'view_details',
'enter_manual_review',
'retry_failed_attachments',
'refresh_status',
'cancel_run',
'cancel_unit',
'view_evidence',
'review_candidate',
'manual_review',
})
# 审计快照与元数据禁止键(大小写不敏感);原件只允许 FileAsset 标识关联。
AUDIT_FORBIDDEN_KEYS: Final[frozenset[str]] = frozenset({
'api_key',
'api_base_url',
'authorization',
'body',
'client_ip',
'content',
'document_text',
'email_body',
'minio',
'object_key',
'object_url',
'password',
'prompt',
'provider_config',
'quote',
'raw_content',
'raw_output',
'secret',
'token',
'url',
'user_agent',
})
# 审计前后快照允许的顶层业务键白名单;未列出的键不得进入 snapshot。
AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
'status',
'phase',
'reason_code',
'error_code',
'attempt_count',
'retry_status',
'progress_version',
'activity_version',
'current_stage_code',
'user_visible_stage',
'cancellation_requested',
'unit_count',
'document_count',
'completed_count',
'failed_count',
'review_required_count',
'cancelled_count',
'schema_version_id',
'schema_checksum',
'profile_code',
'profile_version',
'profile_checksum',
'policy_version',
'policy_checksum',
'queue_position',
'selection_batch',
# 会话 PDF 工作项 / 版本指针(禁止字段正文与附件 URL)。
'lifecycle_status',
'closed_reason',
'lock_version',
'current_version_no',
'current_run_no',
'current_case_no',
'previous_run_no',
'previous_case_no',
'root_document_id',
'current_document_id',
'session_item_no',
'item_no',
'owner_user_id',
'conversation_id',
'reparse_failure_stage',
'restore_target_case_no',
'admin_action',
'revocation_blocked',
'inventory_matched',
'changed_field_paths',
'draft_version',
'validation_blocking_count',
'validation_warning_count',
'field_id',
'line_key',
'previous_value',
'new_value',
'value_source',
'disposition',
'confirmed_task_no',
'task_no',
'replacement_intake_no',
'successor_run_no',
})
# 四语言 i18n key 清单(阶段 2 补齐文案;此处仅冻结路径,禁止前端硬编码)。
I18N_KEY_INVENTORY: Final[tuple[str, ...]] = (
'chat.shippingOrderExtractionUserStage.pending',
'chat.shippingOrderExtractionUserStage.document_queued',
'chat.shippingOrderExtractionUserStage.waiting_layout',
'chat.shippingOrderExtractionUserStage.layout_parsing_started',
'chat.shippingOrderExtractionUserStage.routing',
'chat.shippingOrderExtractionUserStage.matching_profile',
'chat.shippingOrderExtractionUserStage.extracting',
'chat.shippingOrderExtractionUserStage.merging_supplement',
'chat.shippingOrderExtractionUserStage.candidate_ready',
'chat.shippingOrderExtractionUserStage.review_required',
'chat.shippingOrderExtractionUserStage.technical_retrying',
'chat.shippingOrderExtractionUserStage.failed',
'chat.shippingOrderExtractionUserStage.cancellation_requested',
'chat.shippingOrderExtractionUserStage.cancelled',
'chat.shippingOrderExtractionUserStage.completed',
'chat.shippingOrderExtractionHealthTip.processing_slow',
'chat.shippingOrderExtractionHealthTip.queue_backlog',
'chat.shippingOrderExtractionHealthTip.processing_attention',
'chat.shippingOrderExtractionAction.refresh_status',
'chat.shippingOrderExtractionAction.cancel_run',
'chat.shippingOrderExtractionAction.cancel_unit',
'chat.shippingOrderExtractionCancel.confirmTitle',
'chat.shippingOrderExtractionCancel.confirmImpact',
'chat.shippingOrderExtractionCancel.reasonRequired',
'chat.shippingOrderExtractionCancel.reasonOptional',
'chat.shippingOrderExtractionActivity.cancellation_requested',
'chat.shippingOrderExtractionActivity.cancellation_completed',
'chat.shippingOrderExtractionActivity.unit_cancelled',
'errors.SHIPPING_NOTICE.CANCEL_FORBIDDEN',
'errors.SHIPPING_NOTICE.CANCEL_REASON_REQUIRED',
'errors.SHIPPING_NOTICE.CANCEL_NOT_ACTIVE',
'errors.SHIPPING_NOTICE.CANCEL_CONFLICT',
'errors.SHIPPING_NOTICE.CANCEL_FEATURE_DISABLED',
'errors.SHIPPING_NOTICE.AUDIT_EXPORT_FEATURE_DISABLED',
'errors.SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN',
'errors.SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
'admin.shippingAudit.title',
'admin.shippingAudit.export',
'admin.shippingAudit.diff',
)
def is_forbidden_audit_key(key: str) -> bool:
"""
判断键名是否命中审计敏感黑名单。
核心逻辑:大小写不敏感精确匹配冻结集合。
Args:
key: 元数据或快照字段名。
Returns:
True 表示禁止写入审计表。
"""
return str(key or '').strip().lower() in AUDIT_FORBIDDEN_KEYS
@@ -0,0 +1,47 @@
"""
services/shipping_notice/progress_feature_flags.py
用途:处理进度细化与全链路审计的灰度/回滚功能开关及审计保留期读取。
依赖:tool_common.cfg_bool/cfg_int、Flask config、progress_audit_contract 默认常量。
逻辑:取消 API/投影动作、进度 UI v3 健康提示、管理员审计导出分别受控;审计保留天数由
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS 覆盖默认三年;关闭开关不删除已写审计事实。
"""
from __future__ import annotations
from app.services.shipping_notice.progress_audit_contract import AUDIT_RETENTION_DAYS
from app.services.shipping_notice.tool_common import cfg_bool, cfg_int
def progress_ui_v3_enabled() -> bool:
"""是否启用新进度展示(健康提示、细化阶段文案依赖);默认开启。"""
return cfg_bool('SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED', True)
def order_extraction_cancel_enabled() -> bool:
"""是否允许 Run/Unit 取消请求;关闭后投影不暴露取消动作且 API 拒绝。"""
return cfg_bool('SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED', True)
def audit_export_enabled() -> bool:
"""是否允许管理员审计导出;关闭后 list/detail 仍可读(诊断),导出拒绝。"""
return cfg_bool('SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED', True)
def audit_retention_days() -> int:
"""
读取货代统一审计默认保留天数。
核心逻辑:优先 Flask config / 环境变量 SHIPPING_NOTICE_AUDIT_RETENTION_DAYS;
缺失或非法时回退 progress_audit_contract 默认 1095 天。
"""
return cfg_int('SHIPPING_NOTICE_AUDIT_RETENTION_DAYS', AUDIT_RETENTION_DAYS, min_value=1)
def progress_feature_flags_payload() -> dict[str, bool]:
"""供工作台投影下发的开关快照;前端不得本地臆造。"""
return {
'progress_ui_v3': progress_ui_v3_enabled(),
'cancel_enabled': order_extraction_cancel_enabled(),
'audit_export_enabled': audit_export_enabled(),
}
@@ -0,0 +1,441 @@
"""
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),
}
@@ -0,0 +1,949 @@
"""
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,9 +1,10 @@
"""
services/shipping_notice/tool_common.py
用途:发货通知 Tool 链共享配置、payload 合并与消息拼接(无阶段业务编排)。
依赖:constants、models.ShippingTaskEvent。
逻辑:task_workflow / inventory_workflow / fulfillment_workflow 共用,避免 tools 循环依赖。
用途:发货通知 Tool 链共享配置、payload 合并、消息拼接与任务事件写入(无阶段业务编排)。
依赖:constants、models.ShippingTaskEvent、fulfillment_audit(库存/RPA/导出双写,strict)。
逻辑:task_workflow / inventory_workflow / fulfillment_workflow 共用;log_task_event 对
inventory_rpa_/inventory_source_/export_ 前缀事件同步投影到 ShippingAuditEvent,失败阻断业务。
"""
from __future__ import annotations
@@ -292,6 +293,43 @@ def log_task_event(
before_json=before,
after_json=after,
))
# 库存/RPA/导出关键节点双写统一审计;失败必须阻断,保证审计中心可检索。
if str(event_type or '').startswith(('inventory_rpa_', 'inventory_source_', 'export_')):
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
safe_before = None
safe_after = None
if isinstance(before, dict):
safe_before = {
key: before[key]
for key in ('status', 'phase', 'reason_code', 'error_code', 'attempt_count')
if key in before
} or None
if isinstance(after, dict):
safe_after = {
key: after[key]
for key in ('status', 'phase', 'reason_code', 'error_code', 'attempt_count')
if key in after
} or None
meta: dict[str, Any] = {'dual_write': 'shipping_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
record_fulfillment_audit(
event_type=f'task_{event_type}'[:64],
aggregate_type='shipping_task',
aggregate_id=str(task.task_no),
action=str(event_type)[:64],
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=str(task.task_no),
result='success',
before=safe_before,
after=safe_after or {'status': getattr(task, 'process_status', None)},
metadata=meta,
source=str(source or 'system')[:32],
strict=True,
)
def log_task_action_event(