Merge branch 'dev' into test

This commit is contained in:
hugo committed 2026-08-11 14:39:07 +08:00
commit 08c4bc01ea
1482 files changed
+360264 -29255

No files matched your search

+1
View File
@@ -28,6 +28,7 @@ MANIFEST
# Pytest / local temp
backend/.pytest_tmp/
backend/.pytest-*/
.pytest_tmp/
*.py[cod]
*$py.class
+10
View File
@@ -157,6 +157,16 @@ docker compose logs -f hxops-backend
- ⚠️ **错误处理统一契约**:JSON API 使用 `{ success, data | error, request_id }` envelope;后端业务失败 **`raise AppError` 子类**(`app/core/errors.py`),禁止新写 `jsonify({"error": ...})`;前端 HTTP 统一 **`requestJson`**(`@/shared/api/client`),失败为 **`BusinessError`**,在 composable/view 用 **`useMessage()`** 展示;新增 `error.code` 须同步四语言 **`locales/*/errors.json`**。详见 **[docs/convention/error_handling.md](docs/convention/error_handling.md)**。
- ⚠️ 改动**数据库结构、部署脚本(`scripts/`、`Jenkinsfile`、`docker-compose.yml`)或敏感配置**前,先说明影响面再动手。
### 8.1 环境变量文件与排序规则
- **文件职责**:`.env.shared` 仅放 dev/test/prod 完全一致的共享项;`.env.dev`、`.env.test`、`.env.prod` 仅放环境差异项;`.env.local` 仅放开发者个人覆盖项且不得提交。高优先级文件只写需要覆盖的变量,不完整复制低优先级文件。
- **文件内章节顺序**:① 环境与应用标识 → ② 应用运行与进程 → ③ 公共地址与网络入口 → ④ 安全、认证与身份源 → ⑤ 数据库与基础设施 → ⑥ AI 平台、模型与内部工具 → ⑦ 企业系统集成 → ⑧ 知识库与文件处理 → ⑨ 业务模块 → ⑩ 运维、告警与维护工具;文件没有某类变量时直接省略该章节。
- **章节内组织**:先按业务域及子域聚合(如 Casdoor、MinIO、WeCom、HR、PLM、SRM、FAQ、Shipping Notice、Fixed Asset),不得把同一域拆散后做全局字母排序;同一域内按“开关/模式 → 地址 → 标识 → 凭据 → 路径 → 业务参数 → 超时/重试/并发 → 兼容/Mock”排列,同级变量再按字母排序。
- **数据库连接固定顺序**:`HOST → PORT → DATABASE/SID → USERNAME → PASSWORD → DRIVER → ENCRYPT/TRUST_CERT → TIMEOUT`;完整连接串(如 `DATABASE_URL`、`*_DSN`)置于该数据源首位。
- **RPA 命名空间(强制)**:货代发货通知 RPA 统一使用 `SHIPPING_NOTICE_RPA_*`。后端业务参数使用 `SHIPPING_NOTICE_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `SHIPPING_NOTICE_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `SHIPPING_NOTICE_RPA_WORKER_*`,平台凭据主密钥使用 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。禁止新增 `FREIGHT_RPA_*`、`SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`;历史名称只能存在于兼容映射和迁移说明中。
- **跨环境一致性**:`.env.dev`、`.env.test`、`.env.prod` 使用相同章节骨架;同名变量保持相同相对位置,便于审查差异;新增变量时同步检查所有适用环境文件和上述权威文档。
- **调整红线**:重排环境变量时只能移动“注释 + 完整赋值行”,禁止修改变量名或值,禁止删除变量、注释或示例;真实密码、密钥、Token、Webhook 与生产连接信息必须由系统环境变量、Jenkins/CI 或 Secret 管理机制注入。
合并前最低自检(详见 [新人文档 §3.3](docs/新人环境搭建与配置文档.md)):前后端可启动、`frontend/` 改动后 `npm run build` 通过、关键页面与登录可用。
---
+14 -1
View File
@@ -4,7 +4,8 @@ backend/app/__init__.py
用途:应用工厂:创建 Flask 应用、挂载全局异常与响应处理。
依赖:app.extensions(db、migrate)、app.api.register_blueprints、app.core.config。
逻辑:create_app 初始化扩展后委托 api 层集中注册 Blueprint;启动时 load_context_adapters 注册 Dify 上下文 adapter;
并幂等补建 file-asset-cleanup 默认排程(覆盖空库先迁移后建用户)。
并幂等补建 file-asset-cleanup 默认排程(覆盖空库先迁移后建用户);
AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA 就绪(仅告警不阻断启动)。
"""
import logging
import uuid
@@ -71,6 +72,10 @@ def create_app(config_name='default'):
)
register_file_asset_cleanup_schedule_hooks()
ensure_default_file_asset_cleanup_schedule()
from app.services.shipping_notice.order_extraction_progress_cleanup_schedule import (
ensure_default_order_extraction_progress_cleanup_schedule,
)
ensure_default_order_extraction_progress_cleanup_schedule()
except Exception as exc: # pragma: no cover - 表未就绪时容忍
logger.warning('Failed to ensure file-asset-cleanup schedule: %s', exc)
try:
@@ -84,6 +89,14 @@ def create_app(config_name='default'):
logger.warning('Failed to ensure accounting-voucher-check schedule: %s', exc)
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
FixedAssetsSnapshotService.start_worker(app)
# AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。
try:
from app.services.shipping_notice.rpa_worker_heartbeat import (
log_auto_upload_readiness_at_startup,
)
log_auto_upload_readiness_at_startup(app)
except Exception as exc: # pragma: no cover - 启动容忍
logger.warning('Failed to check freight upload RPA readiness at startup: %s', exc)
@app.before_request
def _sync_persisted_settings():
+1 -1
View File
@@ -68,7 +68,7 @@ def list_agent_intent_routes():
@admin_bp.route('/agents', methods=['GET'])
@require_admin
def list_agents():
"""返回全部 Agent 列表。"""
"""列出全部应用。"""
return ok(agent_service.list_agents(), request_id=_request_id())
+329
View File
@@ -0,0 +1,329 @@
"""
backend/app/api/admin/shipping_customers.py
用途:货代客户主数据、识别证据与期初导入管理 API。
依赖:admin blueprint、require_admin、shipping_customer_* services、customer_shadow_resolution、customer_auto_resolution。
逻辑:薄路由完成鉴权、参数读取和文件响应;业务校验与事务全部委托服务层。
"""
from __future__ import annotations
from io import BytesIO
from flask import g, jsonify, request, send_file
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.errors import ValidationError
from app.services.admin import (
shipping_customer_import_service,
shipping_customer_lifecycle_service,
shipping_customer_merge_service,
shipping_customer_service,
)
from app.services.shipping_notice.customer_shadow_resolution import (
get_shadow_quality_report,
label_shadow_resolution,
)
from app.services.shipping_notice.customer_auto_resolution import (
correct_numbered_task_customer,
get_auto_resolution_metrics,
)
from app.services.shipping_notice.query_service import get_task_by_ref
XLSX_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
def _actor_id() -> int | None:
"""返回 require_admin 已解析的当前管理员 ID。"""
return getattr(getattr(g, 'current_user', None), 'id', None)
def _query_params() -> dict[str, str]:
"""将管理列表 query 参数转换为普通字符串字典。"""
return {key: str(value) for key, value in request.args.items()}
@admin_bp.route('/shipping-customers', methods=['GET'])
@require_admin
def list_shipping_customers():
"""分页查询货代标准客户。"""
return jsonify(shipping_customer_service.list_customers(_query_params()))
@admin_bp.route('/shipping-customers/<int:customer_id>', methods=['GET'])
@require_admin
def get_shipping_customer(customer_id: int):
"""查询单个标准客户及识别证据。"""
return jsonify(shipping_customer_service.get_customer(customer_id))
@admin_bp.route('/shipping-customers/<int:customer_id>/lifecycle-impact', methods=['GET'])
@require_admin
def get_shipping_customer_lifecycle_impact(customer_id: int):
"""预览永久删除的阻断引用与可级联识别证据,不执行删除。"""
return jsonify(shipping_customer_lifecycle_service.get_customer_lifecycle_impact(customer_id))
@admin_bp.route('/shipping-customers/<int:customer_id>/lifecycle-timeline', methods=['GET'])
@require_admin
def get_shipping_customer_lifecycle_timeline(customer_id: int):
"""查询客户创建、变更、证据、归并和删除相关的治理时间线。"""
try:
limit = int(request.args.get('limit') or 100)
except (TypeError, ValueError) as exc:
raise ValidationError('Invalid timeline limit') from exc
return jsonify(shipping_customer_lifecycle_service.get_customer_lifecycle_timeline(customer_id, limit=limit))
@admin_bp.route('/shipping-customers/governance-quality', methods=['GET'])
@require_admin
def get_shipping_customer_governance_quality():
"""查询客户识别质量、自动确认门禁和生命周期治理汇总。"""
try:
limit = int(request.args.get('limit') or 100)
except (TypeError, ValueError) as exc:
raise ValidationError('Invalid report limit') from exc
return jsonify(shipping_customer_lifecycle_service.get_customer_governance_quality(limit=limit))
@admin_bp.route('/shipping-customers/<int:customer_id>', methods=['DELETE'])
@require_admin
def delete_shipping_customer(customer_id: int):
"""受控永久删除无生命周期引用的误建客户,必须二次确认简码和原因。"""
data = request.get_json(silent=True) or {}
return jsonify(shipping_customer_lifecycle_service.delete_customer(
customer_id,
confirmation_short_code=data.get('confirmation_short_code'),
reason=data.get('reason'),
actor_id=_actor_id(),
))
@admin_bp.route('/shipping-customers/<int:customer_id>/merge-impact', methods=['GET'])
@require_admin
def get_shipping_customer_merge_impact(customer_id: int):
"""预览将源客户归并到目标客户时保留的历史引用和可迁移配置。"""
try:
target_customer_id = int(request.args.get('target_customer_id'))
except (TypeError, ValueError) as exc:
raise ValidationError('Target customer id is required', code='SHIPPING.CUSTOMER_MERGE_TARGET_REQUIRED') from exc
return jsonify(shipping_customer_merge_service.get_customer_merge_impact(customer_id, target_customer_id))
@admin_bp.route('/shipping-customers/<int:customer_id>/merge', methods=['POST'])
@require_admin
def merge_shipping_customer(customer_id: int):
"""受控归并重复客户;历史业务与审计不迁移,仅归并未来配置。"""
data = request.get_json(silent=True) or {}
try:
target_customer_id = int(data.get('target_customer_id'))
except (TypeError, ValueError) as exc:
raise ValidationError('Target customer id is required', code='SHIPPING.CUSTOMER_MERGE_TARGET_REQUIRED') from exc
return jsonify(shipping_customer_merge_service.merge_customer(
customer_id,
target_customer_id=target_customer_id,
confirmation_short_code=data.get('confirmation_short_code'),
reason=data.get('reason'),
actor_id=_actor_id(),
))
@admin_bp.route('/shipping-customers', methods=['POST'])
@require_admin
def create_shipping_customer():
"""创建货代标准客户。"""
return jsonify(shipping_customer_service.create_customer(request.get_json(silent=True) or {}, actor_id=_actor_id())), 201
@admin_bp.route('/shipping-customers/<int:customer_id>', methods=['PUT'])
@require_admin
def update_shipping_customer(customer_id: int):
"""更新货代标准客户。"""
return jsonify(shipping_customer_service.update_customer(
customer_id,
request.get_json(silent=True) or {},
actor_id=_actor_id(),
))
@admin_bp.route('/shipping-customers/<int:customer_id>/deactivate', methods=['POST'])
@require_admin
def deactivate_shipping_customer(customer_id: int):
"""停用标准客户并保留历史引用。"""
data = request.get_json(silent=True) or {}
return jsonify(shipping_customer_service.deactivate_customer(
customer_id,
reason=data.get('reason'),
actor_id=_actor_id(),
))
@admin_bp.route('/shipping-customers/<int:customer_id>/identifiers', methods=['POST'])
@require_admin
def create_shipping_customer_identifier(customer_id: int):
"""拒绝旧固定类型证据写入口;新增证据必须选择已发布识别定义。"""
raise ValidationError(
'Legacy customer identifier writes are disabled',
code='SHIPPING.CUSTOMER_LEGACY_IDENTIFIER_WRITE_DISABLED',
)
@admin_bp.route('/shipping-customer-identifiers/<int:identifier_id>', methods=['PUT'])
@require_admin
def update_shipping_customer_identifier(identifier_id: int):
"""拒绝旧固定类型证据写入口;历史记录仅供审计回看。"""
raise ValidationError(
'Legacy customer identifier writes are disabled',
code='SHIPPING.CUSTOMER_LEGACY_IDENTIFIER_WRITE_DISABLED',
)
@admin_bp.route('/shipping-customers/<int:customer_id>/external-refs', methods=['POST'])
@require_admin
def create_shipping_customer_external_ref(customer_id: int):
"""维护来源系统客户编码,供 Bill-to 精确匹配。"""
return jsonify(shipping_customer_service.create_external_ref(
customer_id, request.get_json(silent=True) or {},
)), 201
@admin_bp.route('/shipping-customers/<int:customer_id>/sites', methods=['POST'])
@require_admin
def create_shipping_customer_site(customer_id: int):
"""新增客户送货站点,供 Ship-to 匹配。"""
return jsonify(shipping_customer_service.create_site(
customer_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
)), 201
@admin_bp.route('/shipping-customer-sites/<int:site_id>/identifiers', methods=['POST'])
@require_admin
def create_shipping_customer_site_identifier(site_id: int):
"""新增站点名称别名、地址或外部 Ship-to Code。"""
return jsonify(shipping_customer_service.create_site_identifier(
site_id, request.get_json(silent=True) or {},
)), 201
@admin_bp.route('/shipping-customers/import-template', methods=['GET'])
@require_admin
def download_shipping_customer_import_template():
"""下载期初客户标准 Excel 模板。"""
content = shipping_customer_import_service.build_import_template()
return send_file(
BytesIO(content),
as_attachment=True,
download_name='shipping_customer_import_template.xlsx',
mimetype=XLSX_MIME_TYPE,
)
@admin_bp.route('/shipping-customer-imports', methods=['POST'])
@require_admin
def upload_shipping_customer_import():
"""上传并预检期初客户 Excel,不直接写正式客户表。"""
upload = request.files.get('file')
if upload is None:
raise ValidationError(
'Customer import file is required',
code='SHIPPING.CUSTOMER_IMPORT_FILE_REQUIRED',
)
source_system = str(request.form.get('source_system') or 'INITIAL_EXCEL').strip()
return jsonify(shipping_customer_import_service.create_import_batch(
upload,
source_system=source_system,
actor_id=_actor_id(),
)), 201
@admin_bp.route('/shipping-customer-imports/<int:batch_id>', methods=['GET'])
@require_admin
def get_shipping_customer_import(batch_id: int):
"""查询导入批次统计、错误、警告和逐行决定。"""
return jsonify(shipping_customer_import_service.get_import_batch(batch_id))
@admin_bp.route('/shipping-customer-import-rows/<int:row_id>/decision', methods=['PUT'])
@require_admin
def decide_shipping_customer_import_row(row_id: int):
"""保存警告行的新增、更新、合并或跳过决定。"""
return jsonify(shipping_customer_import_service.decide_import_row(
row_id,
request.get_json(silent=True) or {},
))
@admin_bp.route('/shipping-customer-imports/<int:batch_id>/publish', methods=['POST'])
@require_admin
def publish_shipping_customer_import(batch_id: int):
"""单事务发布已完成预检和冲突决定的客户导入批次。"""
return jsonify(shipping_customer_import_service.publish_import_batch(batch_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-customer-imports/<int:batch_id>/reconciliation', methods=['GET'])
@require_admin
def download_shipping_customer_import_reconciliation(batch_id: int):
"""下载导入批次逐行对账 CSV。"""
content, filename = shipping_customer_import_service.build_reconciliation_csv(batch_id)
return send_file(
BytesIO(content),
as_attachment=True,
download_name=filename,
mimetype='text/csv; charset=utf-8',
)
@admin_bp.route('/shipping-customer-shadow-report', methods=['GET'])
@require_admin
def get_shipping_customer_shadow_report():
"""查询客户影子识别分布、已标注准确率和最近样本。"""
try:
limit = int(request.args.get('limit') or 100)
except (TypeError, ValueError) as exc:
raise ValidationError('Invalid report limit') from exc
report = get_shadow_quality_report(limit=limit)
report['auto_resolution'] = get_auto_resolution_metrics()
return jsonify(report)
@admin_bp.route('/shipping-customers/numbered-task-correction', methods=['POST'])
@require_admin
def correct_shipping_numbered_task_customer():
"""管理员更正已编号任务客户;保留原号作废并生成有替代关系的新号。"""
data = request.get_json(silent=True) or {}
task_ref = str(data.get('task_ref') or data.get('task_no') or '').strip().upper()
if not task_ref:
raise ValidationError(
'Task reference is required',
code='SHIPPING.CUSTOMER_CORRECTION_TASK_REQUIRED',
)
try:
customer_id = int(data.get('customer_id'))
except (TypeError, ValueError) as exc:
raise ValidationError('Customer id is required', code='SHIPPING.CUSTOMER_CONFIRMATION_CUSTOMER_REQUIRED') from exc
task = get_task_by_ref(task_ref)
if task is None:
raise ValidationError('Shipping task not found', code='SHIPPING.CUSTOMER_CORRECTION_TASK_MISSING')
return jsonify(correct_numbered_task_customer(
task,
customer_id=customer_id,
reason=str(data.get('reason') or ''),
actor_id=_actor_id(),
))
@admin_bp.route('/shipping-customer-shadow-resolutions/<int:resolution_id>/label', methods=['PUT'])
@require_admin
def label_shipping_customer_shadow_resolution(resolution_id: int):
"""为影子识别样本写入人工客户真值,不执行业务绑定。"""
data = request.get_json(silent=True) or {}
try:
customer_id = int(data.get('customer_id'))
except (TypeError, ValueError) as exc:
raise ValidationError(
'Customer id is required',
code='SHIPPING.CUSTOMER_SHADOW_LABEL_REQUIRED',
details={'field': 'customer_id'},
) from exc
return jsonify(label_shadow_resolution(resolution_id, customer_id=customer_id, actor_id=_actor_id()))
@@ -0,0 +1,40 @@
"""
backend/app/api/admin/shipping_document_layouts.py
用途:提供发货通知 Document 布局版本诊断和显式重解析管理员 API。
依赖:admin blueprint、require_admin、document_layout.lifecycle。
逻辑:响应只含状态/checksum/计数,不返回 HTML、bbox、正文或 Provider 原始输出。
"""
from __future__ import annotations
from flask import g
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.response import ok
from app.services.shipping_notice.document_layout import lifecycle
def _actor_id() -> int | None:
"""读取当前管理员主键。"""
return getattr(getattr(g, 'current_user', None), 'id', None)
@admin_bp.route('/shipping-notice/documents/<int:document_id>/layout-versions', methods=['GET'])
@require_admin
def list_shipping_document_layout_versions(document_id: int):
"""列出单个 Document 的布局解析版本安全摘要。"""
return ok(
lifecycle.list_layout_versions(document_id), request_id=getattr(g, 'request_id', None),
)
@admin_bp.route('/shipping-notice/documents/<int:document_id>/layout-reparse', methods=['POST'])
@require_admin
def reparse_shipping_document_layout(document_id: int):
"""显式创建或复用当前活动布局版本。"""
return ok(
lifecycle.request_layout_reparse(document_id, created_by_id=_actor_id()),
request_id=getattr(g, 'request_id', None), status=202,
)
@@ -0,0 +1,120 @@
"""
backend/app/api/admin/shipping_field_assets.py
用途:货代字段资产治理管理 API(列表/详情/扩展 CRUD、弃用恢复、影响分析)。
依赖:admin blueprint、require_admin、field_asset_service、field_impact_analysis。
逻辑:路由只读取参数与管理员身份;资产校验、审计与事务由 field_asset_service 完成。
"""
from __future__ import annotations
from flask import g, request
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.response import ok
from app.services.shipping_notice import field_asset_service
from app.services.shipping_notice import field_impact_analysis
def _actor_id() -> int | None:
"""读取 require_admin 写入请求上下文的管理员 ID。"""
return getattr(getattr(g, 'current_user', None), 'id', None)
def _ok(data, *, status: int = 200):
"""按平台统一 envelope 返回管理 API 成功结果。"""
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
@admin_bp.route('/shipping-field-assets', methods=['GET'])
@require_admin
def list_shipping_field_assets():
"""分页列出全局字段资产,支持编码搜索与 kind/status/scope 筛选。"""
return _ok(field_asset_service.list_assets(
q=request.args.get('q'),
asset_kind=request.args.get('asset_kind'),
status=request.args.get('status'),
scope=request.args.get('scope'),
))
@admin_bp.route('/shipping-field-assets/<field_id>', methods=['GET'])
@require_admin
def get_shipping_field_asset(field_id: str):
"""读取单个字段资产详情。"""
return _ok(field_asset_service.get_asset(field_id))
@admin_bp.route('/shipping-field-assets', methods=['POST'])
@require_admin
def create_shipping_field_asset():
"""创建扩展字段资产;标准编码与 mail/context 编码由服务层拒绝。"""
return _ok(field_asset_service.create_extension(
request.get_json(silent=True) or {},
actor_id=_actor_id(),
request_id=getattr(g, 'request_id', None),
), status=201)
@admin_bp.route('/shipping-field-assets/<field_id>', methods=['PUT'])
@require_admin
def update_shipping_field_asset(field_id: str):
"""更新扩展字段显示属性;系统标准字段只读。"""
return _ok(field_asset_service.update_extension(
field_id,
request.get_json(silent=True) or {},
actor_id=_actor_id(),
request_id=getattr(g, 'request_id', None),
))
@admin_bp.route('/shipping-field-assets/<field_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_field_asset(field_id: str):
"""弃用扩展字段;请求体须含 reason;有阻断下游时须 confirm_impact=true。"""
payload = request.get_json(silent=True) or {}
return _ok(field_asset_service.retire_extension(
field_id,
reason=str(payload.get('reason') or ''),
actor_id=_actor_id(),
request_id=getattr(g, 'request_id', None),
confirm_impact=bool(payload.get('confirm_impact')),
))
@admin_bp.route('/shipping-field-assets/<field_id>/restore', methods=['POST'])
@require_admin
def restore_shipping_field_asset(field_id: str):
"""恢复已弃用的扩展字段。"""
payload = request.get_json(silent=True) or {}
return _ok(field_asset_service.restore_extension(
field_id,
reason=str(payload.get('reason') or 'restored via admin API'),
actor_id=_actor_id(),
request_id=getattr(g, 'request_id', None),
))
@admin_bp.route('/shipping-field-assets/<field_id>/impact', methods=['GET'])
@require_admin
def get_shipping_field_asset_impact(field_id: str):
"""只读分析字段资产在下游配置与历史运行中的引用影响。"""
return _ok(field_impact_analysis.analyze_field_impact(field_id))
@admin_bp.route('/shipping-field-assets/<field_id>/audits', methods=['GET'])
@require_admin
def list_shipping_field_asset_audits(field_id: str):
"""读取单字段审计时间线(含采用/取消采用与扩展生命周期事件)。"""
limit = request.args.get('limit', 50, type=int)
return _ok(field_asset_service.list_asset_audits(field_id, limit=limit or 50))
@admin_bp.route('/shipping-field-assets/<field_id>', methods=['DELETE'])
@require_admin
def delete_shipping_field_asset(field_id: str):
"""物理删除已禁止;应使用 retire 或取消 Schema 采用。"""
del field_id
field_asset_service.forbid_physical_delete()
return _ok({})
@@ -0,0 +1,135 @@
"""
backend/app/api/admin/shipping_identity_rules.py
用途:提供货代客户可配置识别定义、规则集和证据值的管理员 API。
依赖:admin blueprint、require_admin、identity_rules.service。
逻辑:路由只完成鉴权和参数读取;来源边界、版本化和事务由领域服务统一保证。
"""
from __future__ import annotations
from flask import g, request
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.response import ok
from app.services.shipping_notice.identity_rules import service
def _actor_id() -> int | None:
"""读取管理员身份,避免由客户端伪造审计操作者。"""
return getattr(getattr(g, 'current_user', None), 'id', None)
def _ok(data, *, status: int = 200):
"""按统一成功 envelope 返回,并透传请求关联 ID。"""
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
@admin_bp.route('/shipping-identity-rules/definitions', methods=['GET'])
@require_admin
def list_identity_definitions():
"""读取识别定义、可选订单 Header 字段和受控规则能力目录。"""
return _ok(service.list_definitions(
target_type=request.args.get('target_type'),
active_only=request.args.get('active_only') == 'true',
))
@admin_bp.route('/shipping-identity-rules/published-evidence-definitions', methods=['GET'])
@require_admin
def list_published_identity_evidence_definitions():
"""读取当前已发布规则中可由后台维护的客户或站点证据定义。"""
return _ok(service.list_published_evidence_definitions(target_type=request.args.get('target_type')))
@admin_bp.route('/shipping-identity-rules/definitions', methods=['POST'])
@require_admin
def create_identity_definition():
"""创建绑定平台受控来源适配器的业务识别定义。"""
return _ok(service.save_definition(
request.get_json(silent=True) or {}, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
), status=201)
@admin_bp.route('/shipping-identity-rules/definitions/<definition_id>', methods=['PUT'])
@require_admin
def update_identity_definition(definition_id: str):
"""更新业务识别定义;服务端校验来源适配器和自动化风险上限。"""
return _ok(service.save_definition(
request.get_json(silent=True) or {}, actor_id=_actor_id(), definition_id=definition_id,
request_id=getattr(g, 'request_id', None),
))
@admin_bp.route('/shipping-identity-rules/definitions/<definition_id>/retire', methods=['POST'])
@require_admin
def retire_identity_definition(definition_id: str):
"""退役业务识别定义,保留历史规则和证据审计。"""
return _ok(service.retire_definition(
definition_id, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
))
@admin_bp.route('/shipping-identity-rules/rule-sets', methods=['GET'])
@require_admin
def list_identity_rule_sets():
"""读取识别规则集版本概要。"""
return _ok(service.list_rule_sets())
@admin_bp.route('/shipping-identity-rules/rule-sets', methods=['POST'])
@require_admin
def create_identity_rule_set():
"""创建规则集草稿,可从历史发布/退役版本复制。"""
return _ok(service.create_rule_set(
request.get_json(silent=True) or {}, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
), status=201)
@admin_bp.route('/shipping-identity-rules/rule-sets/<int:rule_set_id>', methods=['PUT'])
@require_admin
def save_identity_rule_set(rule_set_id: int):
"""保存规则集草稿定义,服务端以锁版本阻止覆盖。"""
return _ok(service.save_rule_set(
rule_set_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
request_id=getattr(g, 'request_id', None),
))
@admin_bp.route('/shipping-identity-rules/rule-sets/<int:rule_set_id>/publish', methods=['POST'])
@require_admin
def publish_identity_rule_set(rule_set_id: int):
"""发布规则集并退役前一发布版本。"""
data = request.get_json(silent=True) or {}
return _ok(service.publish_rule_set(
rule_set_id, expected_lock_version=data.get('expected_lock_version'), actor_id=_actor_id(),
request_id=getattr(g, 'request_id', None),
))
@admin_bp.route('/shipping-customers/<int:customer_id>/identity-evidences', methods=['POST'])
@require_admin
def create_customer_identity_evidence(customer_id: int):
"""为客户主体新增按已发布定义约束的证据值。"""
return _ok(service.create_evidence(
target_type='customer', target_id=customer_id, data=request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-customer-sites/<int:site_id>/identity-evidences', methods=['POST'])
@require_admin
def create_site_identity_evidence(site_id: int):
"""为送货站点新增按已发布定义约束的证据值。"""
return _ok(service.create_evidence(
target_type='site', target_id=site_id, data=request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-identity-evidences/<int:evidence_id>', methods=['PUT'])
@require_admin
def update_identity_evidence(evidence_id: int):
"""审核、停用或调整证据自动化授权;服务端验证定义上限和审计原因。"""
return _ok(service.update_evidence(
evidence_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
))
+586
View File
@@ -0,0 +1,586 @@
"""
api/admin/shipping_inventory.py
用途:提供库存源、RPA Profile、路由规则及外部系统映射的管理 API。
依赖:admin blueprint、require_admin、shipping_inventory_service。
逻辑:路由只处理鉴权和 JSON 参数,业务校验、凭据加密及事务由服务层完成。
"""
from __future__ import annotations
import json
from flask import g, request, send_file
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.errors import ConflictError
from app.core.response import ok
from app.services.admin import shipping_inventory_service
from app.services.shipping_notice.order_schema import service as order_schema_service
from app.services.shipping_notice import inventory_parsing_profile
from app.services.shipping_notice import excel_template
from app.services.shipping_notice import inventory_field_catalog
from app.services.shipping_notice import inventory_structure_analysis
def _actor_id() -> int | None:
"""取得 require_admin 已写入请求上下文的管理员 ID。"""
return getattr(getattr(g, 'current_user', None), 'id', None)
def _ok(data, *, status: int = 200):
"""按平台统一 envelope 返回管理 API 成功结果。"""
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
@admin_bp.route('/shipping-notice/excel-templates', methods=['GET'])
@require_admin
def list_shipping_excel_templates():
"""列出版本化发货 Excel 模板。"""
return _ok(excel_template.list_templates())
@admin_bp.route('/shipping-notice/excel-templates', methods=['POST'])
@require_admin
def create_shipping_excel_template():
"""上传 xlsx 并创建模板草稿版本。"""
try:
definition = json.loads(request.form.get('definition') or '{}')
except json.JSONDecodeError as exc:
from app.core.errors import ValidationError
raise ValidationError('definition must be valid JSON', code='SHIPPING.EXCEL_TEMPLATE_INVALID') from exc
data = {
'template_code': request.form.get('template_code'),
'display_name': request.form.get('display_name'),
'definition': definition,
}
return _ok(excel_template.create_draft(request.files.get('file'), data, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>', methods=['PUT'])
@require_admin
def update_shipping_excel_template(template_id: int):
"""更新 Excel 模板草稿定义。"""
return _ok(excel_template.update_draft(template_id, request.get_json(silent=True) or {}))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/layout', methods=['GET'])
@require_admin
def get_shipping_excel_template_layout(template_id: int):
"""读取已保存模板的工作表和栏位,编辑时无需重新上传 Excel。"""
return _ok(excel_template.get_layout(template_id))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/new-version', methods=['POST'])
@require_admin
def create_shipping_excel_template_version(template_id: int):
"""复制现有模板文件和映射定义,创建新的草稿版本。"""
return _ok(excel_template.create_draft_from_existing(template_id, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/clone', methods=['POST'])
@require_admin
def clone_shipping_excel_template(template_id: int):
"""复制已有模板为使用新编码的独立 v1 草稿。"""
return _ok(excel_template.clone_as_new_template(
template_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/publish', methods=['POST'])
@require_admin
def publish_shipping_excel_template(template_id: int):
"""校验工作簿和字段映射后发布模板。"""
return _ok(excel_template.publish(template_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_excel_template(template_id: int):
"""退役没有启用库存源引用的模板。"""
return _ok(excel_template.retire(template_id))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>', methods=['DELETE'])
@require_admin
def delete_shipping_excel_template(template_id: int):
"""删除从未发布且未使用的模板草稿。"""
excel_template.delete_draft(template_id)
return '', 204
@admin_bp.route('/shipping-notice/rpa-profiles', methods=['GET'])
@require_admin
def list_shipping_rpa_profiles():
"""列出脱敏后的 RPA Profile 配置。"""
return _ok(shipping_inventory_service.list_profiles())
@admin_bp.route('/shipping-notice/rpa-profiles', methods=['POST'])
@require_admin
def create_shipping_rpa_profile():
"""创建 RPA Profile;明文凭据仅在本次请求内用于加密。"""
return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/rpa-profiles/<int:profile_id>', methods=['PUT'])
@require_admin
def update_shipping_rpa_profile(profile_id: int):
"""更新 RPA Profile;未提交密码字段时保留既有密文。"""
return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id))
@admin_bp.route('/shipping-notice/rpa-profiles/<int:profile_id>', methods=['DELETE'])
@require_admin
def delete_shipping_rpa_profile(profile_id: int):
"""删除没有库存源引用的错误连接配置。"""
shipping_inventory_service.delete_profile(profile_id)
return '', 204
@admin_bp.route('/shipping-notice/sources', methods=['GET'])
@require_admin
def list_shipping_inventory_sources():
"""列出库存业务来源。"""
return _ok(shipping_inventory_service.list_sources())
@admin_bp.route('/shipping-notice/sources', methods=['POST'])
@require_admin
def create_shipping_inventory_source():
"""保存停用的库存站点基础配置;正式启用由独立接口控制。"""
return _ok(shipping_inventory_service.save_source(
request.get_json(silent=True) or {}, actor_id=_actor_id(), allow_enable_transition=False,
), status=201)
@admin_bp.route('/shipping-notice/sources/<int:source_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_source(source_id: int):
"""更新库存站点业务配置;不能借由普通保存绕过启用门禁。"""
return _ok(shipping_inventory_service.save_source(
request.get_json(silent=True) or {}, actor_id=_actor_id(), source_id=source_id,
allow_enable_transition=False,
))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/bind-parsing-profile', methods=['POST'])
@require_admin
def bind_shipping_inventory_source_parsing_profile(source_id: int):
"""直接为停用库存站点绑定已发布解析方案;审计说明由系统自动记录。"""
payload = request.get_json(silent=True) or {}
rows = shipping_inventory_service.bind_source_parsing_profile(
[source_id], payload.get('parsing_profile_id'), actor_id=_actor_id(),
reason=str(payload.get('reason') or ''), operation='direct',
)
return _ok(rows[0])
@admin_bp.route('/shipping-notice/sources/bulk-bind-parsing-profile', methods=['POST'])
@require_admin
def bulk_bind_shipping_inventory_source_parsing_profile():
"""原子批量绑定已发布解析方案;任一站点预检失败则整批不写入。"""
payload = request.get_json(silent=True) or {}
source_ids = payload.get('source_ids')
if not isinstance(source_ids, list):
source_ids = []
return _ok(shipping_inventory_service.bind_source_parsing_profile(
source_ids, payload.get('parsing_profile_id'), actor_id=_actor_id(),
reason=str(payload.get('reason') or ''), operation='bulk',
))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/parsing-binding-audits', methods=['GET'])
@require_admin
def list_shipping_inventory_source_parsing_binding_audits(source_id: int):
"""返回库存站点的解析方案绑定审计,不包含任何 RPA 凭据。"""
return _ok(shipping_inventory_service.get_source_parsing_binding_audits(source_id))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/activate', methods=['POST'])
@require_admin
def activate_shipping_inventory_source(source_id: int):
"""仅在库存站点完成测试与必需绑定后启用正式运行。"""
return _ok(shipping_inventory_service.activate_source(source_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/deactivate', methods=['POST'])
@require_admin
def deactivate_shipping_inventory_source(source_id: int):
"""停用库存站点而不删除已有配置和运行审计。"""
return _ok(shipping_inventory_service.deactivate_source(source_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/sources/<int:source_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_source(source_id: int):
"""删除无运行/路由引用的错误库存源。"""
shipping_inventory_service.delete_source(source_id)
return '', 204
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export', methods=['POST'])
@require_admin
def start_shipping_inventory_configuration_test(source_id: int):
"""为停用库存站点发起异步测试导出,不产生生产库存快照。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.start_test_export(source_id, actor_id=_actor_id()), status=202)
@admin_bp.route('/shipping-notice/source-validation-batches', methods=['POST'])
@require_admin
def start_shipping_inventory_validation_batch():
"""为多个停用且已绑定发布解析方案的站点发起批量测试验证。"""
from app.services.shipping_notice import inventory_configuration_test
payload = request.get_json(silent=True) or {}
return _ok(inventory_configuration_test.start_batch_test_export(
payload.get('source_ids') or [], actor_id=_actor_id(),
), status=202)
@admin_bp.route('/shipping-notice/source-validation-batches/latest-active', methods=['GET'])
@require_admin
def get_latest_active_shipping_inventory_validation_batch():
"""恢复最近未结束的批量验证,避免页面刷新后丢失进度。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.get_latest_active_validation_batch())
@admin_bp.route('/shipping-notice/source-validation-batches/<int:batch_id>', methods=['GET'])
@require_admin
def get_shipping_inventory_validation_batch(batch_id: int):
"""读取批量验证汇总进度及每个站点的独立测试结果。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.get_validation_batch(batch_id))
@admin_bp.route('/shipping-notice/source-validation-batches/<int:batch_id>/retry-failed', methods=['POST'])
@require_admin
def retry_failed_shipping_inventory_validation_batch(batch_id: int):
"""只重试批次中失败或配置已过期的站点,不重复导出成功项。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.retry_failed_validation_batch(batch_id, actor_id=_actor_id()), status=202)
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/latest', methods=['GET'])
@require_admin
def get_latest_shipping_inventory_configuration_test(source_id: int):
"""读取当前库存站点配置对应的最近测试,使管理端可恢复异步执行状态。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.get_latest_test_run(source_id))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/<string:run_no>', methods=['GET'])
@require_admin
def get_shipping_inventory_configuration_test(source_id: int, run_no: str):
"""读取库存站点测试导出的异步执行状态与结构识别结果。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.get_test_run(source_id, run_no))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/<string:run_no>/confirm-profile', methods=['POST'])
@require_admin
def confirm_shipping_inventory_configuration_test_profile(source_id: int, run_no: str):
"""确认测试结果采用的解析方案,并更新仍停用的库存站点绑定。"""
from app.services.shipping_notice import inventory_configuration_test
payload = request.get_json(silent=True) or {}
return _ok(inventory_configuration_test.confirm_test_profile(
source_id, run_no, int(payload.get('profile_id') or 0), actor_id=_actor_id(),
))
@admin_bp.route('/shipping-notice/snapshots', methods=['GET'])
@require_admin
def list_shipping_inventory_snapshots():
"""列出库存快照的管理端只读记录。"""
return _ok(shipping_inventory_service.list_snapshots())
@admin_bp.route('/shipping-notice/snapshots/<int:snapshot_id>/download', methods=['GET'])
@require_admin
def download_shipping_inventory_snapshot(snapshot_id: int):
"""下载管理员选定的已托管库存快照,不向前端暴露服务器存储路径。"""
path, filename = shipping_inventory_service.get_snapshot_download(snapshot_id)
return send_file(path, as_attachment=True, download_name=filename)
@admin_bp.route('/shipping-notice/export-records', methods=['GET'])
@require_admin
def list_shipping_inventory_export_records():
"""列出 RPA 导出结果;失败后应修复配置并重新创建运行。"""
return _ok(shipping_inventory_service.list_export_records())
@admin_bp.route('/shipping-notice/routing-rules', methods=['GET'])
@require_admin
def list_shipping_inventory_rules():
"""列出库存源路由规则及条件。"""
return _ok(shipping_inventory_service.list_rules())
@admin_bp.route('/shipping-notice/routing-fields', methods=['GET'])
@require_admin
def list_shipping_inventory_routing_fields():
"""返回路由规则可引用的已发布订单字段;路由不再读取固定系统投影。"""
try:
contract = order_schema_service.get_published_contract()
order_fields = contract['fields']
published = True
except ConflictError as exc:
if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED':
raise
order_fields = []
published = False
return _ok({
'order_fields': order_fields,
'order_schema_published': published,
})
@admin_bp.route('/shipping-notice/inventory-fields', methods=['GET'])
@require_admin
def list_shipping_inventory_fields():
"""列出库存统一业务字段;管理工作区可查看已停用字段。"""
return _ok(inventory_field_catalog.list_fields(include_retired=request.args.get('include_retired') == 'true'))
@admin_bp.route('/shipping-notice/inventory-fields', methods=['POST'])
@require_admin
def create_shipping_inventory_field():
"""创建可由 DBS、Crane 等多个库存解析方案复用的扩展业务字段。"""
return _ok(inventory_field_catalog.create_field(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/inventory-fields/<int:field_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_field(field_id: int):
"""更新库存业务字段的名称、说明、格式和展示顺序。"""
return _ok(inventory_field_catalog.update_field(field_id, request.get_json(silent=True) or {}, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/inventory-fields/<int:field_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_inventory_field(field_id: int):
"""停用无引用的扩展库存字段,核心字段始终由服务层保护。"""
return _ok(inventory_field_catalog.retire_field(field_id))
@admin_bp.route('/shipping-notice/inventory-fields/<int:field_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_field(field_id: int):
"""删除未被配置引用的扩展库存字段。"""
inventory_field_catalog.delete_field(field_id)
return '', 204
@admin_bp.route('/shipping-notice/configuration-catalog', methods=['GET'])
@require_admin
def get_shipping_inventory_configuration_catalog():
"""返回 Profile、模板和路由编辑器共用的后端受控字段目录。"""
from app.services.shipping_notice.excel_template import (
ALLOWED_FORMATTERS,
ALLOWED_ROW_MODES,
ALLOWED_SOURCE_KINDS,
ALLOWED_SYSTEM_FACTS,
)
try:
contract = order_schema_service.get_published_contract()
order_fields = contract['fields']
published = True
except ConflictError as exc:
if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED':
raise
order_fields = []
published = False
return _ok({
'order_fields': order_fields,
'order_schema_published': published,
'inventory_fields': inventory_field_catalog.list_fields(),
'template_system_facts': sorted(ALLOWED_SYSTEM_FACTS),
'template_source_kinds': sorted(ALLOWED_SOURCE_KINDS),
'template_row_modes': sorted(ALLOWED_ROW_MODES),
'template_formatters': sorted(ALLOWED_FORMATTERS),
})
@admin_bp.route('/shipping-notice/parsing-profiles', methods=['GET'])
@require_admin
def list_shipping_inventory_parsing_profiles():
"""列出可复用库存解析 Profile 版本。"""
return _ok(inventory_parsing_profile.list_profiles())
@admin_bp.route('/shipping-notice/parsing-profiles', methods=['POST'])
@require_admin
def create_shipping_inventory_parsing_profile():
"""创建库存解析 Profile 草稿。"""
return _ok(inventory_parsing_profile.save_draft(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_parsing_profile(profile_id: int):
"""更新库存解析 Profile 草稿。"""
return _ok(inventory_parsing_profile.save_draft(
request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id,
))
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/sample-replacement-preview/<int:analysis_id>', methods=['POST'])
@require_admin
def preview_shipping_inventory_sample_replacement(profile_id: int, analysis_id: int):
"""比较库存映射草稿当前样本与候选样本,替换前必须由管理员确认差异。"""
return _ok(inventory_structure_analysis.preview_profile_sample_replacement(
profile_id, analysis_id, request.get_json(silent=True) or {},
))
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/publish', methods=['POST'])
@require_admin
def publish_shipping_inventory_parsing_profile(profile_id: int):
"""发布库存解析 Profile。"""
return _ok(inventory_parsing_profile.publish(profile_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_inventory_parsing_profile(profile_id: int):
"""退役无库存源引用的已发布解析 Profile。"""
return _ok(inventory_parsing_profile.retire(profile_id))
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_parsing_profile(profile_id: int):
"""删除从未发布的解析 Profile 草稿。"""
inventory_parsing_profile.delete_draft(profile_id)
return '', 204
@admin_bp.route('/shipping-notice/inventory-structure-analyses', methods=['POST'])
@require_admin
def create_shipping_inventory_structure_analysis():
"""上传库存样本并返回后端分析出的工作表、表头、栏位和建议。"""
return _ok(inventory_structure_analysis.create_sample_upload(
request.files.get('file'), actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-notice/inventory-structure-analyses/<int:analysis_id>', methods=['GET'])
@require_admin
def get_shipping_inventory_structure_analysis(analysis_id: int):
"""读取库存样本结构分析结果,供管理端继续配置解析方案。"""
return _ok(inventory_structure_analysis.get_analysis(analysis_id))
@admin_bp.route('/shipping-notice/inventory-structure-analyses/<int:analysis_id>/create-profile-draft', methods=['POST'])
@require_admin
def create_shipping_inventory_parsing_draft_from_analysis(analysis_id: int):
"""使用确认后的真实表头和匹配键创建库存文件解析方案草稿。"""
return _ok(inventory_structure_analysis.create_profile_draft(
analysis_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-notice/inventory-structure-analyses/<int:analysis_id>/adopt-profile', methods=['POST'])
@require_admin
def adopt_shipping_inventory_parsing_profile(analysis_id: int):
"""确认复用推荐的已发布库存文件解析方案,不修改库存站点绑定。"""
payload = request.get_json(silent=True) or {}
return _ok(inventory_structure_analysis.adopt_published_profile(
analysis_id, int(payload.get('profile_id') or 0),
))
@admin_bp.route('/shipping-notice/temporary-inventory-sessions', methods=['GET'])
@require_admin
def list_confirmed_shipping_temporary_inventory_sessions():
"""列出已通过质量校验、可供管理员沉淀为解析方案草稿的对话临时库存会话。"""
from app.services.shipping_notice import inventory_temporary_session
return _ok(inventory_temporary_session.list_confirmed_temporary_inventory_sessions())
@admin_bp.route('/shipping-notice/temporary-inventory-sessions/<string:session_no>/create-profile-draft', methods=['POST'])
@require_admin
def create_shipping_parsing_draft_from_temporary_inventory_session(session_no: str):
"""管理员将已确认临时会话锁定映射复制为解析方案草稿;发布仍走既有门禁。"""
from app.services.shipping_notice import inventory_temporary_session
return _ok(inventory_temporary_session.create_parsing_profile_draft_from_temporary_session(
session_no, request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-notice/routing-rules', methods=['POST'])
@require_admin
def create_shipping_inventory_rule():
"""创建草稿路由规则。"""
return _ok(shipping_inventory_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_rule(rule_id: int):
"""更新草稿规则;已发布规则由服务层拒绝原地修改。"""
return _ok(shipping_inventory_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id(), rule_id=rule_id))
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>/publish', methods=['POST'])
@require_admin
def publish_shipping_inventory_rule(rule_id: int):
"""发布草稿规则并写入不可变定义快照。"""
return _ok(shipping_inventory_service.publish_rule(rule_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_inventory_rule(rule_id: int):
"""归档已发布规则,保留其审计版本但停止新路由使用。"""
return _ok(shipping_inventory_service.retire_rule(rule_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_rule(rule_id: int):
"""删除从未发布的草稿规则。"""
shipping_inventory_service.delete_draft_rule(rule_id)
return '', 204
@admin_bp.route('/shipping-notice/external-mappings', methods=['GET'])
@require_admin
def list_shipping_inventory_external_mappings():
"""列出库存源到外部系统仓库映射。"""
return _ok(shipping_inventory_service.list_external_mappings())
@admin_bp.route('/shipping-notice/external-mappings', methods=['POST'])
@require_admin
def create_shipping_inventory_external_mapping():
"""创建精确或 Source 默认外部系统映射。"""
return _ok(shipping_inventory_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/external-mappings/<int:mapping_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_external_mapping(mapping_id: int):
"""更新外部系统映射,不参与任何调拨动作。"""
return _ok(shipping_inventory_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id(), mapping_id=mapping_id))
@admin_bp.route('/shipping-notice/external-mappings/<int:mapping_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_external_mapping(mapping_id: int):
"""删除错误的外部系统仓库映射。"""
shipping_inventory_service.delete_external_mapping(mapping_id)
return '', 204
@@ -0,0 +1,63 @@
"""
backend/app/api/admin/shipping_legacy_stp_jobs.py
用途:Phase 5-1 —— 管理后台「货代历史 STP Job(928/929)运维面板」只读 API。
依赖:admin Blueprint、require_admin、legacy_stp_job_admin_service。
逻辑:
• GET /admin/shipping-notice/legacy-stp-jobs 分页列表(支持 q/case_no/error_code/created_from/created_to)
• GET /admin/shipping-notice/legacy-stp-jobs/<job_id> 单条详情 + 回链 Review Case
• 所有接口严格 require_admin;不允许写任何 DB。
"""
from __future__ import annotations
from flask import g, request
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.errors import ValidationError
from app.core.response import ok
from app.services.shipping_notice.legacy_stp_job_admin_service import (
get_admin_legacy_stp_job,
list_admin_legacy_stp_jobs,
)
def _qint(name: str, default: int) -> int:
raw = request.args.get(name)
if raw in (None, ''):
return default
try:
return int(raw)
except (TypeError, ValueError) as exc:
raise ValidationError(f'{name} must be an integer') from exc
@admin_bp.route('/shipping-notice/legacy-stp-jobs', methods=['GET'])
@require_admin
def admin_list_legacy_stp_jobs():
"""历史失败 STP Job(failed/dead)分页列表,供管理员做 928/929 回放前筛选。"""
page = _qint('page', 1)
page_size = _qint('page_size', 25)
payload = list_admin_legacy_stp_jobs(
page=page,
page_size=page_size,
status=request.args.get('status'),
job_type=request.args.get('job_type'),
q=request.args.get('q'),
case_no=request.args.get('case_no'),
error_code=request.args.get('error_code'),
blocking_reason=request.args.get('blocking_reason'),
created_from=request.args.get('created_from'),
created_to=request.args.get('created_to'),
sort=request.args.get('sort') or '-created_at',
)
return ok(payload, request_id=getattr(g, 'request_id', None))
@admin_bp.route('/shipping-notice/legacy-stp-jobs/<int:job_id>', methods=['GET'])
@require_admin
def admin_get_legacy_stp_job(job_id: int):
"""单条历史失败 STP Job 详情 + 回链 Review Case + 回放建议(replay_plan)。"""
payload = get_admin_legacy_stp_job(int(job_id))
return ok(payload, request_id=getattr(g, 'request_id', None))
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,412 @@
"""
backend/app/api/admin/shipping_order_extraction.py
用途:提供订单抽取异步 Run 的管理员运维健康视图、任意 Run 取消与货代统一审计查询/导出/关联链/哈希校验。
依赖:admin Blueprint、require_admin、order_extraction_run_service、order_extraction_cancel_service、audit_query_service。
逻辑:健康/诊断只读;POST cancel 复用取消服务(代取消他人必须原因);审计接口只读查询/受控导出,
访问留痕;敏感详情受 shipping_notice.audit_sensitive_read 裁剪;筛选支持 workflow_id / workflow_item_id。
"""
from flask import Response, g, request
from app import db
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.errors import ValidationError
from app.core.response import ok
from app.services.shipping_notice.order_extraction_run_service import (
get_order_extraction_run_health,
get_order_extraction_diagnostic_run,
list_order_extraction_diagnostic_runs,
)
def _query_int(name: str, default: int) -> int:
"""读取可选整数查询参数;非整数抛出统一参数错误。"""
raw = request.args.get(name)
if raw in (None, ''):
return default
try:
return int(raw)
except (TypeError, ValueError) as exc:
raise ValidationError(f'{name} must be an integer') from exc
@admin_bp.route('/shipping-notice/order-extraction-runs/health', methods=['GET'])
@require_admin
def get_shipping_order_extraction_health():
"""返回 Run 积压、失败率、阶段分布和分段时延的管理员安全视图。"""
payload = get_order_extraction_run_health(
window_hours=_query_int('window_hours', 24),
queued_stale_seconds=_query_int('queued_stale_seconds', 300),
running_stale_seconds=_query_int('running_stale_seconds', 1800),
)
return ok(payload, request_id=getattr(g, 'request_id', None))
@admin_bp.route('/shipping-notice/order-extraction-runs', methods=['GET'])
@require_admin
def list_shipping_order_extraction_diagnostic_runs():
"""分页返回只读订单识别运行摘要;支持状态、积压卡住、取消中筛选,访问留痕。"""
page = _query_int('page', 1)
page_size = _query_int('page_size', 25)
if page < 1 or not 1 <= page_size <= 100:
raise ValidationError('page must be positive and page_size must be between 1 and 100')
stale_raw = str(request.args.get('stale_only') or '').strip().lower()
cancel_raw = str(request.args.get('cancellation_in_flight') or '').strip().lower()
payload = list_order_extraction_diagnostic_runs(
admin_user_id=g.current_user.id,
request_id=getattr(g, 'request_id', None),
page=page,
page_size=page_size,
status=request.args.get('status'),
stale_only=stale_raw in {'1', 'true', 'yes'},
cancellation_in_flight=cancel_raw in {'1', 'true', 'yes'},
queued_stale_seconds=_query_int('queued_stale_seconds', 300),
running_stale_seconds=_query_int('running_stale_seconds', 1800),
)
return ok(payload, request_id=getattr(g, 'request_id', None))
@admin_bp.route('/shipping-notice/order-extraction-runs/<run_no>', methods=['GET'])
@require_admin
def get_shipping_order_extraction_diagnostic_run_detail(run_no: str):
"""读取单次 Run 的脱敏诊断详情;访问留痕;取消走独立 POST。"""
payload = get_order_extraction_diagnostic_run(
admin_user_id=g.current_user.id,
request_id=getattr(g, 'request_id', None),
run_no=run_no,
)
return ok(payload, request_id=getattr(g, 'request_id', None))
@admin_bp.route('/shipping-notice/order-extraction-runs/<run_no>/cancel', methods=['POST'])
@require_admin
def admin_cancel_shipping_order_extraction_run(run_no: str):
"""
管理员取消任意活跃订单抽取 Run。
核心逻辑:复用 cancel_order_extraction_run;代取消他人必须提供 reason(服务层校验)。
"""
body = request.get_json(silent=True) or {}
if body and not isinstance(body, dict):
raise ValidationError('Request body must be an object')
from app.services.shipping_notice.order_extraction_cancel_service import cancel_order_extraction_run
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_run
run = cancel_order_extraction_run(
actor=g.current_user,
run_no=run_no,
reason=str(body.get('reason') or '') or None,
reason_code=str(body.get('reason_code') or 'admin_cancelled') or 'admin_cancelled',
operation_id=str(body.get('operation_id') or getattr(g, 'request_id', '') or '') or None,
)
db.session.commit()
return ok({'run': serialize_order_extraction_run(run)}, request_id=getattr(g, 'request_id', None), status=202)
@admin_bp.route('/shipping-notice/order-extraction/emergency-stop', methods=['GET'])
@require_admin
def get_shipping_order_extraction_emergency_stop():
"""读取订单解析紧急停止与分路径自动冻结开关状态(只读投影)。"""
from app.services.shipping_notice.tool_common import (
extraction_emergency_stop_enabled,
generic_auto_freeze_enabled,
generic_extraction_enabled,
llm_review_enabled,
profile_auto_selection_enabled,
)
return ok({
'emergency_stop': extraction_emergency_stop_enabled(),
'generic_extraction_enabled': generic_extraction_enabled(),
'generic_auto_freeze_enabled': generic_auto_freeze_enabled(),
'profile_auto_selection_enabled': profile_auto_selection_enabled(),
'llm_review_enabled': llm_review_enabled(),
}, request_id=getattr(g, 'request_id', None))
@admin_bp.route('/shipping-notice/order-extraction/emergency-stop', methods=['POST'])
@require_admin
def set_shipping_order_extraction_emergency_stop():
"""
运行期紧急停止开关(进程内覆盖)。
核心逻辑:写入 Flask config,立即阻断新 Run 自动冻结;持久化仍依赖环境变量/部署配置。
"""
body = request.get_json(silent=True) or {}
enabled = body.get('enabled')
if not isinstance(enabled, bool):
raise ValidationError('enabled must be a boolean')
from flask import current_app
from app.services.shipping_notice.audit_service import append_shipping_audit_event
before = bool(current_app.config.get('SHIPPING_NOTICE_EXTRACTION_EMERGENCY_STOP'))
current_app.config['SHIPPING_NOTICE_EXTRACTION_EMERGENCY_STOP'] = enabled
append_shipping_audit_event(
event_type='extraction_emergency_stop_changed',
aggregate_type='order_extraction_policy',
aggregate_id='global',
actor_type='admin',
actor_id=str(g.current_user.id),
reason_code='admin_emergency_stop' if enabled else 'admin_emergency_resume',
before={'enabled': before},
after={'enabled': enabled},
metadata={'request_id': getattr(g, 'request_id', None)},
)
db.session.commit()
return ok({'emergency_stop': enabled}, request_id=getattr(g, 'request_id', None))
@admin_bp.route('/shipping-notice/order-extraction-quality-batches', methods=['GET'])
@require_admin
def list_shipping_order_extraction_quality_batches():
"""列出指定 Owner 可用于自动建单门禁的已批准、仍达标批次。"""
owner_agent_id = _query_int('owner_agent_id', 0)
if owner_agent_id <= 0:
raise ValidationError('owner_agent_id must be positive')
from app.services.shipping_notice.order_extraction_quality_service import list_approved_quality_batches
return ok(
list_approved_quality_batches(owner_agent_id=owner_agent_id),
request_id=getattr(g, 'request_id', None),
)
@admin_bp.route('/shipping-notice/order-extraction-quality-batches', methods=['POST'])
@require_admin
def create_shipping_order_extraction_quality_batch():
"""创建 L7 影子验收批次;仅锁定 Owner/Schema,不复制任何订单内容。"""
body = request.get_json(silent=True)
if not isinstance(body, dict):
raise ValidationError('JSON body must be an object')
try:
owner_agent_id = int(body.get('owner_agent_id'))
schema_version_id = int(body.get('schema_version_id'))
except (TypeError, ValueError) as exc:
raise ValidationError('owner_agent_id and schema_version_id are required') from exc
from app.services.shipping_notice.order_extraction_quality_service import (
create_quality_batch, serialize_quality_batch,
)
batch = create_quality_batch(
owner_agent_id=owner_agent_id, schema_version_id=schema_version_id,
actor_id=g.current_user.id,
)
return ok(
serialize_quality_batch(batch), request_id=getattr(g, 'request_id', None), status=201,
)
@admin_bp.route('/shipping-notice/order-extraction-quality-batches/<int:batch_id>', methods=['GET'])
@require_admin
def get_shipping_order_extraction_quality_batch(batch_id: int):
"""读取批次脱敏指标和批准状态,不返回 Run 内容、订单值或单条标签。"""
from app.models import ShippingOrderExtractionQualityBatch
from app.services.shipping_notice.order_extraction_quality_service import serialize_quality_batch
batch = db.session.get(ShippingOrderExtractionQualityBatch, batch_id)
if batch is None:
from app.core.errors import NotFoundError
raise NotFoundError('Quality batch not found')
return ok(serialize_quality_batch(batch), request_id=getattr(g, 'request_id', None))
@admin_bp.route('/shipping-notice/order-extraction-quality-batches/<int:batch_id>/runs/<run_no>/label', methods=['PUT'])
@require_admin
def label_shipping_order_extraction_quality_run(batch_id: int, run_no: str):
"""提交当前管理员的匿名质量标签;同管理员重提为幂等覆盖。"""
from app.services.shipping_notice.order_extraction_quality_service import save_quality_label, serialize_quality_batch
batch = save_quality_label(
batch_id=batch_id, run_no=run_no, actor_id=g.current_user.id,
payload=request.get_json(silent=True),
)
return ok(serialize_quality_batch(batch), request_id=getattr(g, 'request_id', None))
@admin_bp.route('/shipping-notice/order-extraction-quality-batches/<int:batch_id>/approve', methods=['POST'])
@require_admin
def approve_shipping_order_extraction_quality_batch(batch_id: int):
"""提交 business/technical 批准;同一管理员不能承担两个角色。"""
body = request.get_json(silent=True)
if not isinstance(body, dict):
raise ValidationError('JSON body must be an object')
from app.services.shipping_notice.order_extraction_quality_service import approve_quality_batch, serialize_quality_batch
batch = approve_quality_batch(
batch_id=batch_id, role=str(body.get('role') or ''), actor_id=g.current_user.id,
)
return ok(serialize_quality_batch(batch), request_id=getattr(g, 'request_id', None))
def _audit_filters_from_request() -> dict:
"""从 query/json 收集审计筛选字段。"""
source = request.args if request.method == 'GET' else (request.get_json(silent=True) or {})
if not isinstance(source, dict):
raise ValidationError('filters must be an object')
keys = (
'event_type', 'event_type_group', 'actor_type', 'actor_id', 'run_no', 'task_no', 'document_id',
'operation_id', 'request_id', 'aggregate_type', 'aggregate_id', 'candidate_no',
'gate_code', 'node_code', 'result', 'reason_code',
'conversation_id', 'workflow_id', 'workflow_item_id', 'review_case_no', 'case_no',
'owner_user_id', 'created_from', 'created_to', 'q',
'profile_id', 'binding_id', 'revision_no', 'segment_id',
)
return {key: str(source.get(key) or '').strip() or None for key in keys}
def _caller_can_read_audit_sensitive() -> bool:
"""
判断当前管理员是否具备审计敏感快照读权限。
核心逻辑:读取 feature_permissions 键 shipping_notice.audit_sensitive_read;
不新建角色,仅按用户功能权限裁剪详情。
"""
user = getattr(g, 'current_user', None)
if user is None:
return False
return bool(user.has_feature_permission('shipping_notice.audit_sensitive_read'))
@admin_bp.route('/shipping-notice/audit-events', methods=['GET'])
@require_admin
def list_shipping_notice_audit_events():
"""分页查询货代统一审计事件;访问留痕,不返回快照全文。"""
from app.services.shipping_notice.audit_query_service import list_shipping_audit_events
page = _query_int('page', 1)
page_size = _query_int('page_size', 25)
if page < 1 or not 1 <= page_size <= 100:
raise ValidationError('page must be positive and page_size must be between 1 and 100')
payload = list_shipping_audit_events(
admin_user_id=g.current_user.id,
request_id=getattr(g, 'request_id', None),
page=page,
page_size=page_size,
filters=_audit_filters_from_request(),
)
return ok(payload, request_id=getattr(g, 'request_id', None))
@admin_bp.route('/shipping-notice/audit-events/<int:event_id>', methods=['GET'])
@require_admin
def get_shipping_notice_audit_event(event_id: int):
"""
读取单条审计详情,含白名单快照与前后差异。
敏感事件的 before/after/diff 仅当具备 shipping_notice.audit_sensitive_read 时返回。
"""
from app.services.shipping_notice.audit_query_service import get_shipping_audit_event
payload = get_shipping_audit_event(
admin_user_id=g.current_user.id,
request_id=getattr(g, 'request_id', None),
event_id=event_id,
include_sensitive=_caller_can_read_audit_sensitive(),
)
return ok(payload, request_id=getattr(g, 'request_id', None))
@admin_bp.route('/shipping-notice/audit-events/association-chain', methods=['GET'])
@require_admin
def list_shipping_notice_audit_association_chain():
"""
按 Workflow / Item / Run / Document / Case / Task 关联键追溯全链审计。
核心逻辑:至少提供一个关联种子;敏感快照仍受 audit_sensitive_read 裁剪(列表默认无快照)。
"""
from app.services.shipping_notice.audit_query_service import list_shipping_audit_association_chain
limit = _query_int('limit', 500)
if not 1 <= limit <= 2000:
raise ValidationError('limit must be between 1 and 2000')
payload = list_shipping_audit_association_chain(
admin_user_id=g.current_user.id,
request_id=getattr(g, 'request_id', None),
filters=_audit_filters_from_request(),
limit=limit,
include_sensitive=_caller_can_read_audit_sensitive(),
)
return ok(payload, request_id=getattr(g, 'request_id', None))
@admin_bp.route('/shipping-notice/audit-events/verify-hash-chain', methods=['POST'])
@require_admin
def verify_shipping_notice_audit_hash_chain():
"""
校验审计哈希链完整性。
核心逻辑:可按 aggregate / workflow / item 定点校验,或抽样近期聚合;访问留痕。
"""
from app.services.shipping_notice.audit_query_service import verify_shipping_audit_hash_chain
body = request.get_json(silent=True) or {}
if body and not isinstance(body, dict):
raise ValidationError('JSON body must be an object')
payload = verify_shipping_audit_hash_chain(
admin_user_id=g.current_user.id,
request_id=getattr(g, 'request_id', None),
aggregate_type=str(body.get('aggregate_type') or '').strip() or None,
aggregate_id=str(body.get('aggregate_id') or '').strip() or None,
workflow_id=str(body.get('workflow_id') or '').strip() or None,
workflow_item_id=str(body.get('workflow_item_id') or '').strip() or None,
sample_limit=int(body.get('sample_limit') or body.get('limit') or 200),
)
return ok(payload, request_id=getattr(g, 'request_id', None))
@admin_bp.route('/shipping-notice/audit-events/export', methods=['POST'])
@require_admin
def export_shipping_notice_audit_events():
"""受控导出审计 CSV/JSON;写导出访问审计,禁止敏感正文。"""
from app.services.shipping_notice.audit_query_service import export_shipping_audit_events
body = request.get_json(silent=True) or {}
if body and not isinstance(body, dict):
raise ValidationError('JSON body must be an object')
filters = {
key: str(body.get(key) or '').strip() or None
for key in (
'event_type', 'actor_type', 'actor_id', 'run_no', 'task_no', 'document_id',
'operation_id', 'request_id', 'aggregate_type', 'aggregate_id', 'result',
'conversation_id', 'workflow_id', 'workflow_item_id', 'review_case_no', 'case_no',
'owner_user_id', 'created_from', 'created_to', 'q',
)
}
exported = export_shipping_audit_events(
admin_user_id=g.current_user.id,
request_id=getattr(g, 'request_id', None),
filters=filters,
limit=int(body.get('limit') or 2000),
format=str(body.get('format') or 'csv'),
)
return Response(
exported['content'],
status=200,
mimetype=exported['content_type'],
headers={
'Content-Disposition': f'attachment; filename="{exported["filename"]}"',
'X-Exported-Count': str(exported['exported']),
},
)
@admin_bp.route('/shipping-notice/audit-snapshots/<string:snapshot_ref>', methods=['GET'])
@require_admin
def get_shipping_notice_xfa_audit_snapshot(snapshot_ref: str):
"""
读取 XFA 加密完整审计快照。
核心逻辑:仅 shipping_notice.audit_sensitive_read 可获明文;每次读取再写访问审计;
无权限时仅返回脱敏摘要。
"""
from app.services.shipping_notice.audit_query_service import get_xfa_audit_full_snapshot
payload = get_xfa_audit_full_snapshot(
admin_user_id=g.current_user.id,
request_id=getattr(g, 'request_id', None),
snapshot_ref=snapshot_ref,
include_sensitive=_caller_can_read_audit_sensitive(),
)
return ok(payload, request_id=getattr(g, 'request_id', None))
@@ -0,0 +1,278 @@
"""
backend/app/api/admin/shipping_order_schema.py
用途:提供唯一发货订单 Schema、字段目录和版本发布的管理 API。
依赖:admin blueprint、require_admin、order_schema.service、field_asset_service。
逻辑:路由读取管理员身份;字段校验、不可变性与事务由领域服务完成。
固定操作默认 Schema STANDARD_SHIPPING_NOTICE;不接受 family_code,不下线表结构。
"""
from __future__ import annotations
from flask import g, request
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.response import ok
from app.extensions import db
from app.models.shipping_order_schema import ShippingOrderField
from app.services.shipping_notice.order_schema import service
from app.services.shipping_notice import field_asset_service
from app.services.shipping_notice.standard_field_registry import DEFAULT_V1_ADOPTION_CODES
def _actor_id() -> int | None:
"""读取 require_admin 写入请求上下文的管理员 ID。"""
return getattr(getattr(g, 'current_user', None), 'id', None)
def _ok(data, *, status: int = 200):
"""按平台统一 envelope 返回管理 API 成功结果。"""
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
@admin_bp.route('/shipping-order-schema', methods=['GET'])
@require_admin
def get_shipping_order_schema():
"""读取唯一发货订单 Schema 管理状态和受控字段能力目录。"""
return _ok(service.get_state())
@admin_bp.route('/shipping-order-schema/auto-creation-policy', methods=['GET'])
@require_admin
def shipping_order_auto_creation_policy():
"""
读取已发布生效的自动建单策略。
说明:写操作已移除。修改须通过 Schema 草稿保存并发布
(PUT /shipping-order-schema/versions/:id 携带 auto_creation_policy)。
"""
return _ok(service.get_auto_creation_policy())
@admin_bp.route('/shipping-order-schema', methods=['POST'])
@require_admin
def initialize_shipping_order_schema():
"""初始化唯一发货订单 Schema。"""
return _ok(service.initialize_schema(
request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-order-schema/fields', methods=['POST'])
@require_admin
def create_shipping_order_field():
"""创建稳定订单字段身份。"""
return _ok(service.save_field(
request.get_json(silent=True) or {}, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
), status=201)
@admin_bp.route('/shipping-order-schema/fields/<field_id>', methods=['PUT'])
@require_admin
def update_shipping_order_field(field_id: str):
"""更新尚未发布的字段 code/scope/type;发布后服务层限制身份变更。"""
return _ok(service.save_field(
request.get_json(silent=True) or {}, actor_id=_actor_id(), field_id=field_id,
request_id=getattr(g, 'request_id', None),
))
@admin_bp.route('/shipping-order-schema/fields/order', methods=['PUT'])
@require_admin
def reorder_shipping_order_fields():
"""保存字段目录当前全局顺序,不创建或修改 Schema 版本。"""
return _ok(service.reorder_fields(
request.get_json(silent=True) or {}, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
))
@admin_bp.route('/shipping-order-schema/fields/<field_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_order_field(field_id: str):
"""退役订单字段,保留历史发布版本中的不可变定义。"""
return _ok(service.retire_field(
field_id, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
))
@admin_bp.route('/shipping-order-schema/fields/<field_id>', methods=['DELETE'])
@require_admin
def delete_shipping_order_field(field_id: str):
"""按字段是否存在历史引用自动物理删除或归档,并同步移出当前草稿。"""
return _ok(service.delete_field(
field_id, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
))
@admin_bp.route('/shipping-order-schema/versions', methods=['POST'])
@require_admin
def create_shipping_order_schema_version():
"""创建下一草稿,可从当前发布版复制。"""
return _ok(service.create_draft(
request.get_json(silent=True) or {},
actor_id=_actor_id(),
request_id=getattr(g, 'request_id', None),
), status=201)
@admin_bp.route('/shipping-order-schema/versions', methods=['GET'])
@require_admin
def list_shipping_order_schema_versions():
"""分页列出 Schema 版本;可按 version 数字精确过滤。"""
try:
page = int(request.args.get('page', '1'))
page_size = int(request.args.get('page_size', '20'))
version = request.args.get('version')
parsed_version = int(version) if version is not None else None
except ValueError as exc:
raise service.ValidationError('page must be an integer') from exc
return _ok(service.list_versions(page=page, page_size=page_size, version_number=parsed_version))
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>', methods=['GET'])
@require_admin
def get_shipping_order_schema_version(version_id: int):
"""读取指定版本完整快照。"""
return _ok(service.get_version_detail(version_id))
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>/diff', methods=['GET'])
@require_admin
def diff_shipping_order_schema_version(version_id: int):
"""比较两个 Schema 版本定义差异。"""
try:
against_version_id = int(request.args.get('against_version_id'))
except (TypeError, ValueError) as exc:
raise service.ValidationError('against_version_id must be an integer') from exc
return _ok(service.get_version_diff(
version_id, against_version_id=against_version_id,
))
@admin_bp.route('/shipping-order-schema/audit-events', methods=['GET'])
@require_admin
def list_shipping_order_schema_audit_events():
"""分页读取唯一 Schema 的只读配置审计时间线。"""
try:
page = int(request.args.get('page', '1'))
page_size = int(request.args.get('page_size', '20'))
version_id = request.args.get('version_id')
parsed_version_id = int(version_id) if version_id is not None else None
except ValueError as exc:
raise service.ValidationError('page must be an integer') from exc
return _ok(service.list_audit_events(
page=page,
page_size=page_size,
version_id=parsed_version_id,
))
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>/usage', methods=['GET'])
@require_admin
def get_shipping_order_schema_version_usage(version_id: int):
"""分页返回实际使用该版本的订单解析及状态汇总。"""
try:
page = int(request.args.get('page', '1'))
page_size = int(request.args.get('page_size', '20'))
except ValueError as exc:
raise service.ValidationError('page must be an integer') from exc
return _ok(service.get_version_usage(version_id, page=page, page_size=page_size))
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>/profile-impact', methods=['GET'])
@require_admin
def get_shipping_order_schema_version_profile_impact(version_id: int):
"""只读评估目标 Schema 版本对已发布订单文档模板的兼容性影响。"""
return _ok(service.get_profile_impact(version_id))
@admin_bp.route('/shipping-order-schema/order-extractions/<int:extraction_id>', methods=['GET'])
@require_admin
def get_shipping_order_schema_extraction_audit(extraction_id: int):
"""读取一次订单解析的完整只读审计详情与证据链。"""
return _ok(service.get_extraction_audit(extraction_id))
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>', methods=['PUT'])
@require_admin
def update_shipping_order_schema_version(version_id: int):
"""整体替换草稿字段配置。"""
return _ok(service.save_draft(
version_id,
request.get_json(silent=True) or {},
actor_id=_actor_id(),
request_id=getattr(g, 'request_id', None),
))
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>', methods=['DELETE'])
@require_admin
def delete_shipping_order_schema_version(version_id: int):
"""删除错误草稿;发布版本由服务端拒绝。"""
service.delete_draft(
version_id, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
)
return _ok(None)
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>/publish', methods=['POST'])
@require_admin
def publish_shipping_order_schema_version(version_id: int):
"""发布草稿并自动退役上一当前版本。"""
data = request.get_json(silent=True) or {}
return _ok(service.publish(
version_id, actor_id=_actor_id(), expected_lock_version=data.get('expected_lock_version'),
request_id=getattr(g, 'request_id', None),
confirm_profile_impact=bool(data.get('confirm_profile_impact', False)),
))
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>/simulate-derivation', methods=['POST'])
@require_admin
def simulate_shipping_order_schema_derivation(version_id: int):
"""
对 Schema 版本派生规则做样本模拟(不创建或修改订单)。
请求体:lines[] 或 sample_ref=`extraction:<id>`;可选 derivation_rules。
事务:服务层只写入审计实体,本路由统一 commit。
"""
payload = service.simulate_derivation(
version_id,
request.get_json(silent=True) or {},
actor_id=_actor_id(),
request_id=getattr(g, 'request_id', None),
)
db.session.commit()
return _ok(payload)
@admin_bp.route('/shipping-order-schema/derivation-simulate-samples', methods=['GET'])
@require_admin
def list_shipping_order_schema_derivation_simulate_samples():
"""列出可供派生规则模拟的历史 Extraction 样本摘要。"""
limit = request.args.get('limit', 20, type=int)
return _ok(service.list_derivation_simulate_samples(limit=limit or 20))
@admin_bp.route('/shipping-order-schema/published-contract', methods=['GET'])
@require_admin
def get_published_shipping_order_contract():
"""读取当前已发布精简字段契约,供配置验证和 Dify 文档维护使用。"""
return _ok(service.get_published_contract())
@admin_bp.route('/shipping-order-schema/suggested-adoption', methods=['GET'])
@require_admin
def get_suggested_field_adoption():
"""返回首发建议采用的标准 field_code 及对应 active 资产 ID,供 Schema 草稿勾选辅助。"""
field_asset_service.ensure_standard_assets_seeded()
codes = list(DEFAULT_V1_ADOPTION_CODES)
rows = ShippingOrderField.query.filter(
ShippingOrderField.field_code.in_(codes),
ShippingOrderField.status == 'active',
).all()
by_code = {row.field_code: row.id for row in rows}
return _ok({
'codes': codes,
'field_ids': [by_code[code] for code in codes if code in by_code],
})
@@ -0,0 +1,85 @@
"""
backend/app/api/admin/shipping_process_gate.py
用途:货代全门禁恢复 Admin API(Execution 列表/诊断、Gate Attempt 运维视图)。
依赖:admin Blueprint、require_admin、process_gate_api_service、process_gate_recovery_service。
逻辑:仅 shipping admin(platform admin 角色)可访问;只读诊断与 Attempt 详情,不含用户写路径。
"""
from __future__ import annotations
from flask import g, request
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.errors import ValidationError
from app.core.response import ok
from app.services.shipping_notice.process_gate_api_service import (
get_admin_gate_attempt,
get_admin_process_execution,
list_admin_gate_attempts,
list_admin_process_executions,
)
from app.services.shipping_notice.process_gate_recovery_service import get_execution_by_no
def _query_int(name: str, default: int) -> int:
"""读取可选整数查询参数;非整数抛出统一参数错误。"""
raw = request.args.get(name)
if raw in (None, ''):
return default
try:
return int(raw)
except (TypeError, ValueError) as exc:
raise ValidationError(f'{name} must be an integer') from exc
@admin_bp.route('/shipping-notice/process-executions', methods=['GET'])
@require_admin
def admin_list_process_executions():
"""分页返回 Process Execution 管理员摘要列表。"""
page = _query_int('page', 1)
page_size = _query_int('page_size', 25)
if page < 1 or not 1 <= page_size <= 100:
raise ValidationError('page must be positive and page_size must be between 1 and 100')
payload = list_admin_process_executions(
page=page,
page_size=page_size,
status=request.args.get('status'),
gate_code=request.args.get('gate_code'),
blocking_reason_code=request.args.get('blocking_reason_code'),
responsible_party=request.args.get('responsible_party'),
q=request.args.get('q'),
updated_from=request.args.get('updated_from'),
updated_to=request.args.get('updated_to'),
)
return ok(payload, request_id=getattr(g, 'request_id', None))
@admin_bp.route('/shipping-notice/process-executions/<execution_no>', methods=['GET'])
@require_admin
def admin_get_process_execution(execution_no: str):
"""读取单次 Execution 的完整 Gate 诊断投影。"""
execution = get_execution_by_no(execution_no)
payload = get_admin_process_execution(execution)
return ok(payload, request_id=getattr(g, 'request_id', None))
@admin_bp.route(
'/shipping-notice/process-executions/<execution_no>/gates/<gate_code>/attempts',
methods=['GET'],
)
@require_admin
def admin_list_process_gate_attempts(execution_no: str, gate_code: str):
"""返回指定 Gate 的全部 Attempt 摘要(含 Gate 诊断投影)。"""
execution = get_execution_by_no(execution_no)
payload = list_admin_gate_attempts(execution, gate_code)
return ok(payload, request_id=getattr(g, 'request_id', None))
@admin_bp.route('/shipping-notice/process-gate-attempts/<int:attempt_id>', methods=['GET'])
@require_admin
def admin_get_process_gate_attempt(attempt_id: int):
"""按主键读取 Attempt 详情及 Execution/Gate 上下文。"""
payload = get_admin_gate_attempt(attempt_id)
return ok(payload, request_id=getattr(g, 'request_id', None))
+1 -1
View File
@@ -67,7 +67,7 @@ def list_agent_guides(agent_id):
获取指定应用的新手指南列表 (需登录)
用途:客户端 Chat 界面点击新手指南
"""
get_current_user() # 确保已登录
get_current_user() # Ensure user is logged in.
if agent_id == 0:
generic_agent = (
+178 -30
View File
@@ -12,6 +12,7 @@ import ntpath
import posixpath
import tempfile
import os
import re
import subprocess
import uuid
import json
@@ -42,12 +43,103 @@ from app.core.errors import (
chat_bp = Blueprint('chat', __name__)
SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
CHAT_USER_ATTACHMENT_LIMIT = 20
CHAT_USER_ATTACHMENT_MAX_SIZE = 10 * 1024 * 1024 * 1024
CHAT_USER_ATTACHMENT_TYPES = {'image', 'document', 'audio', 'video', 'custom'}
CHAT_USER_ATTACHMENT_SOURCES = {'local', 'remote', 'shipping_notice'}
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None:
def _normalize_user_attachments(value) -> list[dict]:
"""
校验并清洗用户消息附件快照,供 ChatLog payload 与历史接口复用。
核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举,不接收 URL、上传 ID 或资产编号。
Args:
value: 前端 user_attachments 原始值;必须为列表,最多处理 20 项。
Returns:
可安全写入 JSON 的附件快照列表;非法项目被忽略。
"""
if not isinstance(value, list):
return []
normalized: list[dict] = []
for item in value[:CHAT_USER_ATTACHMENT_LIMIT]:
if not isinstance(item, dict):
continue
raw_name = str(item.get('name') or '')
basename = re.split(r'[\\/]+', raw_name)[-1]
name = re.sub(r'[\x00-\x1f\x7f]', '', basename).strip()[:255]
attachment_type = str(item.get('type') or '').strip().lower()
source = str(item.get('source') or '').strip().lower()
if not name or attachment_type not in CHAT_USER_ATTACHMENT_TYPES or source not in CHAT_USER_ATTACHMENT_SOURCES:
continue
snapshot = {
'name': name,
'type': attachment_type,
'source': source,
}
extension = str(item.get('extension') or '').strip().lower()
if re.fullmatch(r'[a-z0-9]{1,16}', extension):
snapshot['extension'] = extension
try:
size = int(item.get('size')) if item.get('size') is not None else None
except (TypeError, ValueError):
size = None
if size is not None and 0 <= size <= CHAT_USER_ATTACHMENT_MAX_SIZE:
snapshot['size'] = size
normalized.append(snapshot)
return normalized
def _merge_user_attachments_from_terminal_event(
event_data: dict,
*,
user_id: int,
agent_id: int,
session_id: str,
user_attachments: list[dict],
) -> bool:
"""
在终态 SSE 已给出 ChatLog ID 后,按归属校验合并用户附件快照。
Args:
event_data: 上游终态 SSE 数据,必须包含正整数 chat_log_id。
user_id: 当前用户 ID。
agent_id: 当前 Agent ID。
session_id: 当前 HXOPS 本地会话 ID。
user_attachments: 已完成白名单校验的附件快照。
Returns:
找到归属一致的 ChatLog 并成功合并时返回 True,否则返回 False。
"""
if not user_attachments:
return False
try:
chat_log_id = int(event_data.get('chat_log_id') or 0)
except (TypeError, ValueError):
return False
if chat_log_id <= 0:
return False
from app.services.chat.log_service import merge_chat_log_payload
return merge_chat_log_payload(
chat_log_id=chat_log_id,
user_id=int(user_id or 0),
agent_id=int(agent_id or 0),
session_id=session_id,
payload_patch={'user_attachments': user_attachments},
)
def _build_chat_adapter_hints(
*,
shipping_task_id: str | None = None,
shipping_batch_no: str | None = None,
shipping_intake_nos: list[str] | None = None,
) -> dict | None:
"""
构建聊天入口分发给领域 adapter 的提示字典。
@@ -56,12 +148,16 @@ def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_b
"""
task_id = str(shipping_task_id or '').strip()
batch_no = str(shipping_batch_no or '').strip()
if not task_id and not batch_no:
intake_nos = sorted({str(item or '').strip().upper() for item in (shipping_intake_nos or []) if str(item or '').strip()})
if not task_id and not batch_no and not intake_nos:
return None
return {
'shipping_notice': {
'task_id': task_id or None,
'batch_no': batch_no or None,
'intake_nos': intake_nos,
'capability': 'order_extraction' if intake_nos else None,
'contract_version': 'shipping-order-extraction-v1' if intake_nos else None,
}
}
@@ -1213,19 +1309,29 @@ def get_chat_messages():
messages = []
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
for log in logs:
if log.query:
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_code=agent_code)})
raw_payload = log.payload if isinstance(log.payload, dict) else {}
user_attachments = _normalize_user_attachments(raw_payload.get('user_attachments'))
assistant_payload = {
key: value
for key, value in raw_payload.items()
if key != 'user_attachments'
}
if log.query or user_attachments:
user_msg = {'role': 'user', 'content': _user_facing_chat_query(log.query or '', agent_code=agent_code)}
if user_attachments:
user_msg['attachments'] = user_attachments
messages.append(user_msg)
if (
not log.answer
and not log.message_type
and not log.payload
and not assistant_payload
):
continue
if (
log.query
and log.answer == log.query
and (not log.message_type or log.message_type == 'text')
and not log.payload
and not assistant_payload
):
continue
assistant_msg = {
@@ -1239,8 +1345,8 @@ def get_chat_messages():
assistant_msg['run_id'] = log.run_id
if log.message_type:
assistant_msg['type'] = log.message_type
if log.payload:
assistant_msg['payload'] = log.payload
if assistant_payload:
assistant_msg['payload'] = assistant_payload
messages.append(assistant_msg)
return jsonify(messages)
@@ -1462,12 +1568,24 @@ def chat_completions():
"""
data = request.get_json() or {}
query = data.get('query')
display_query = str(data.get('display_query') or query or '').strip()
display_query = str(
data.get('display_query') if 'display_query' in data else query or ''
).strip()
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
conversation_id = data.get('conversation_id')
shipping_task_id = str(data.get('task_id') or '').strip()
shipping_batch_no = str(data.get('batch_no') or '').strip()
raw_shipping_intakes = data.get('shipping_intake_nos')
if raw_shipping_intakes is not None and not isinstance(raw_shipping_intakes, list):
raise ValidationError('shipping_intake_nos must be a list')
shipping_intake_nos = sorted({
str(item or '').strip().upper()
for item in (raw_shipping_intakes or [])
if str(item or '').strip()
})
kb_type = data.get('kb_type', '企业知识库')
user_attachments = _normalize_user_attachments(data.get('user_attachments'))
session_title = display_query or (user_attachments[0]['name'] if user_attachments else str(query or '').strip())
files = data.get('files')
request_id = uuid.uuid4().hex[:12]
user = getattr(g, 'current_user', None)
@@ -1525,7 +1643,7 @@ def chat_completions():
user_id,
agent_id,
existing_session.session_id,
title=display_query,
title=session_title,
status='running',
)
external_conversation_id = session.external_conversation_id
@@ -1547,13 +1665,20 @@ def chat_completions():
user_id,
agent_id,
conversation_id,
title=display_query,
title=session_title,
status='running',
external_conversation_id=conversation_id,
)
external_conversation_id = session.external_conversation_id
else:
session = _ensure_chat_session(user_id, agent_id, None, title=display_query, status='running')
session = _ensure_chat_session(user_id, agent_id, None, title=session_title, status='running')
# [STEP 1] 流式响应可能在原请求 DB Session 清理后才开始迭代;提前快照会话标量,
# 避免 Handler 的事务提交使 ORM 对象过期后触发 DetachedInstanceError。
local_session_id = str(session.session_id)
initial_session_status = str(session.status or 'running')
initial_external_conversation_id = str(external_conversation_id or '').strip() or None
stream_session = SimpleNamespace(session_id=local_session_id)
normalized_files: list[dict] | None = None
if files is not None:
@@ -1589,13 +1714,14 @@ def chat_completions():
display_query=display_query,
user=user_proxy,
agent=agent_proxy,
session=session,
external_conversation_id=external_conversation_id,
session=stream_session,
external_conversation_id=initial_external_conversation_id,
request_id=request_id,
normalized_files=normalized_files,
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
shipping_intake_nos=shipping_intake_nos,
),
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
@@ -1612,8 +1738,8 @@ def chat_completions():
agent=agent_proxy,
query=query,
agent_id=agent_id,
session_id=session.session_id,
external_conversation_id=external_conversation_id,
session_id=local_session_id,
external_conversation_id=initial_external_conversation_id,
normalized_files=normalized_files,
kb_type=kb_type,
leave_supported=leave_supported,
@@ -1625,19 +1751,20 @@ def chat_completions():
query,
user_proxy.id,
agent_proxy,
external_conversation_id,
initial_external_conversation_id,
request_id=request_id,
session_id=session.session_id,
session_id=local_session_id,
files=normalized_files,
inputs=build_chat_dify_inputs(
agent_proxy,
session_id=session.session_id,
session_id=local_session_id,
request_id=request_id,
trigger_source="frontend_chat",
user_role=user_proxy.role,
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
shipping_intake_nos=shipping_intake_nos,
),
),
)
@@ -1653,14 +1780,14 @@ def chat_completions():
relay_first_chunk_at: float | None = None
created_event = {
'event': 'session_created',
'conversation_id': session.session_id,
'provider_conversation_id': session.external_conversation_id,
'session_status': session.status,
'conversation_id': local_session_id,
'provider_conversation_id': initial_external_conversation_id,
'session_status': initial_session_status,
}
yield f"data: {json.dumps(created_event, ensure_ascii=False)}\n\n"
known_provider_conversation_id = session.external_conversation_id
known_status = session.status
known_provider_conversation_id = initial_external_conversation_id
known_status = initial_session_status
emitted_handler_state_keys: set[str] = set()
from app.services.chat.stream_relay import (
@@ -1672,6 +1799,7 @@ def chat_completions():
yield preface_line
try:
merged_attachment_log_ids: set[int] = set()
for chunk in generator:
if relay_first_chunk_at is None:
relay_first_chunk_at = time.perf_counter()
@@ -1688,6 +1816,20 @@ def chat_completions():
provider_conversation_id = str(event_data.get('conversation_id') or known_provider_conversation_id or '').strip() or None
event_name = event_data.get('event')
if event_name in ('error', 'message_end', 'workflow_finished') and user_attachments:
try:
attachment_chat_log_id = int(event_data.get('chat_log_id') or 0)
except (TypeError, ValueError):
attachment_chat_log_id = 0
if attachment_chat_log_id > 0 and attachment_chat_log_id not in merged_attachment_log_ids:
if _merge_user_attachments_from_terminal_event(
event_data,
user_id=user_id,
agent_id=agent_id,
session_id=local_session_id,
user_attachments=user_attachments,
):
merged_attachment_log_ids.add(attachment_chat_log_id)
should_touch = False
if provider_conversation_id and provider_conversation_id != known_provider_conversation_id:
known_provider_conversation_id = provider_conversation_id
@@ -1703,7 +1845,7 @@ def chat_completions():
updated_session = _update_chat_session(
user_id,
agent_id,
session.session_id,
local_session_id,
status=known_status,
external_conversation_id=known_provider_conversation_id,
touch=True,
@@ -1712,7 +1854,7 @@ def chat_completions():
known_status = updated_session.status
event_data['provider_conversation_id'] = provider_conversation_id
event_data['conversation_id'] = session.session_id
event_data['conversation_id'] = local_session_id
event_data['session_status'] = known_status
if chat_perf_enabled() and event_name in ('message_end', 'workflow_finished'):
relay_first_ms = int((relay_first_chunk_at - relay_started) * 1000) if relay_first_chunk_at else None
@@ -1720,7 +1862,7 @@ def chat_completions():
current_app.logger.info(
'[chat-perf] relay request_id=%s session_id=%s first_chunk_ms=%s total_relay_ms=%s event=%s',
request_id,
session.session_id,
local_session_id,
relay_first_ms,
relay_total_ms,
event_name,
@@ -1730,7 +1872,7 @@ def chat_completions():
'total_relay_ms': relay_total_ms,
}
yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n"
if event_name in ('message_end', 'workflow_finished'):
if event_name in ('error', 'message_end', 'workflow_finished'):
for terminal_line in iter_handler_terminal_sse(
relay_stream_ctx,
event_data,
@@ -1738,9 +1880,15 @@ def chat_completions():
):
yield terminal_line
except Exception as exc:
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id)
payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'}
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, local_session_id)
payload = {'event': 'error', 'message': str(exc), 'conversation_id': local_session_id, 'session_status': 'error'}
yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
for terminal_line in iter_handler_terminal_sse(
relay_stream_ctx,
payload,
emitted_keys=emitted_handler_state_keys,
):
yield terminal_line
# 返回 SSE 响应,mimetype 设为 text/event-stream
return Response(
+169 -98
View File
@@ -2,8 +2,11 @@
api/shipping_notice_tools.py
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url。
逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError。
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url、
batch_legacy_removed(create_batch 410)。
逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError;
`_payload()` 剥离 body 中的操作人伪造字段,禁止集成密钥冒充用户写审计;
co8 后 /tools/create_batch 固定 410,改走 order-extraction-submissions。
"""
from __future__ import annotations
@@ -23,17 +26,11 @@ from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
from app.services.shipping_notice.query_service import (
EXPORT_MIME_TYPE,
get_batch_by_no,
get_focus_task_for_batch,
get_task_by_ref,
get_task_in_batch,
list_batch_task_summaries,
resolve_task_export_download,
serialize_batch_summary,
serialize_task_summary,
task_export_error_message,
)
from app.services.shipping_notice.tool_common import switch_batch_focus
from app.services.shipping_notice.rpa_worker_heartbeat import record_rpa_worker_heartbeat
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
@@ -106,7 +103,32 @@ def _dify_openapi_spec() -> dict:
return build_dify_openapi_spec(_tool_api_base_url())
def _payload() -> dict:
return request.get_json(silent=True) or {}
"""
读取 Tool API JSON 请求体,并剥离不可信的操作人身份字段。
核心逻辑:集成密钥调用方不得通过 body 伪造 `_trusted_user_id` /
`operator_id` / `actor_id`;真实用户身份仅允许工作台/会话层鉴权后注入。
"""
raw = request.get_json(silent=True) or {}
if not isinstance(raw, dict):
return {}
payload = dict(raw)
for key in ('_trusted_user_id', 'operator_id', 'actor_id'):
payload.pop(key, None)
return payload
def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = None, batch_no: str | None = None) -> None:
"""Chatflow 只读查询必须携带短效会话能力令牌,不能仅依赖全局集成密钥。"""
from app.models import ShippingAuditEvent
from app.services.shipping_notice.chat_tool_capability import require_chat_capability
claims = require_chat_capability(token=payload.get('shipping_chat_capability_token'), scope=scope, task_no=task_no, batch_no=batch_no)
db.session.add(ShippingAuditEvent(
event_type='chatflow_tool_read', aggregate_type='chat_session', aggregate_id=str(claims['sid']),
task_no=task_no, actor_type='chatflow', actor_id=str(claims['uid']),
request_id=str(request.headers.get('X-Request-ID') or '')[:64] or None,
metadata_json={'tool': scope, 'token_nonce': str(claims['nonce'])[:16], 'success': True},
))
def _generate_batch_no() -> str:
from datetime import datetime
@@ -138,31 +160,56 @@ def tool_create_task():
"""
return jsonify(shipping_tools.create_task(_payload()))
@shipping_notice_bp.route('/tools/create_temporary_inventory_session', methods=['POST'])
def tool_create_temporary_inventory_session():
"""
创建对话上传库存候选会话。
【AI 触发时机】:用户明确说明 .xls、.xlsx 或 .csv 附件是库存文件时,在临时库存固定分支调用。
"""
return jsonify(shipping_tools.create_temporary_inventory_session(_payload()))
@shipping_notice_bp.route('/tools/get_temporary_inventory_session', methods=['POST'])
def tool_get_temporary_inventory_session():
"""
读取临时库存候选的脱敏分析结果。
【AI 触发时机】:创建临时会话后,需要决定采用已有方案还是请求映射建议时调用。
"""
return jsonify(shipping_tools.get_temporary_inventory_session(_payload()))
@shipping_notice_bp.route('/tools/submit_temporary_inventory_mapping_suggestion', methods=['POST'])
def tool_submit_temporary_inventory_mapping_suggestion():
"""
保存临时库存字段映射建议。
【AI 触发时机】:仅在临时库存 LLM 节点返回真实表头到库存字段目录的候选后调用。
"""
return jsonify(shipping_tools.submit_temporary_inventory_mapping_suggestion(_payload()))
@shipping_notice_bp.route('/tools/confirm_temporary_inventory_use', methods=['POST'])
def tool_confirm_temporary_inventory_use():
"""
确认本次对话临时库存文件的使用。
【AI 触发时机】:仅在用户明确确认当前文件和方案后调用,禁止模型自行确认。
"""
return jsonify(shipping_tools.confirm_temporary_inventory_use(_payload()))
@shipping_notice_bp.route('/tools/create_batch', methods=['POST'])
def tool_create_batch():
"""
创建或复用发货批次。
【AI 触发时机】:仅供 Hxops 内部建批链路调用;不是 Dify 画布正式入口。
"""
payload = _payload()
if isinstance(payload.get('notice_items'), list) and payload.get('notice_items'):
return jsonify(shipping_tools.create_batch_tasks(payload))
batch_no = str(payload.get('batch_no') or '').strip()
if batch_no:
batch = get_batch_by_no(batch_no)
if batch:
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已复用批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
batch, _created = shipping_tools.create_batch(payload)
db.session.commit()
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已创建批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
历史建批 Tool(已下线)。
【AI 触发时机】:禁止调用;shipping_batches 已物理删除,请改走 order-extraction-submissions。
@shipping_notice_bp.route('/tools/parse_notice', methods=['POST'])
def tool_parse_notice():
Raises:
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
"""
解析发货通知正文。
【AI 触发时机】:当用户上传、粘贴或修正发货通知内容后,需要把文本转成任务单头和订单行时调用。
"""
return jsonify(shipping_tools.parse_notice(_payload()))
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
raise_shipping_batches_removed(action='tools.create_batch')
@shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST'])
def tool_update_notice_fields():
@@ -196,47 +243,20 @@ def tool_remove_notice_line():
"""
return jsonify(shipping_tools.remove_notice_line(_payload()))
@shipping_notice_bp.route('/tools/parse_inventory', methods=['POST'])
def tool_parse_inventory():
"""
解析库存内容。
【AI 触发时机】:当用户提供库存文本或表格内容,需要把库存转成系统可匹配格式时调用。
"""
return jsonify(shipping_tools.parse_inventory(_payload()))
@shipping_notice_bp.route('/tools/upload_inventory_file', methods=['POST'])
def tool_upload_inventory_file():
"""
服务器侧接收库存 Excel 并解析。
【AI 触发时机】:当用户上传库存 Excel,且不希望把二进制文件内容经由 LLM 传输时调用。
"""
task_id = str(request.form.get('task_id') or request.args.get('task_id') or '').strip()
upload = request.files.get('file')
return jsonify(shipping_tools.upload_inventory_file(task_id, upload))
@shipping_notice_bp.route('/tools/get_inventory_schema_preview', methods=['POST'])
def tool_get_inventory_schema_preview():
"""
获取库存表头预览。
【AI 触发时机】:当 Agent 需要先看 Excel/表格列名,再决定 map_json 或提示用户确认映射时调用。
"""
return jsonify(shipping_tools.get_inventory_schema_preview(_payload()))
@shipping_notice_bp.route('/tools/apply_inventory_mapping', methods=['POST'])
def tool_apply_inventory_mapping():
"""
应用库存字段映射。
【AI 触发时机】:当用户或 Agent 已确认列名与系统字段的对应关系,需要提交 map_json 时调用。
"""
return jsonify(shipping_tools.apply_inventory_mapping(_payload()))
@shipping_notice_bp.route('/tools/ensure_inventory', methods=['POST'])
def tool_ensure_inventory():
"""
保证任务已取得库存数据。
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
"""
return jsonify(shipping_tools.ensure_inventory(_payload()))
payload = _payload()
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
return jsonify(run_task_auto_progress(
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
trigger='legacy_tool_ensure_inventory',
operator_id=payload.get('operator_id'),
resume_gate_code='inventory_preparation',
))
@shipping_notice_bp.route('/tools/auto_progress', methods=['POST'])
def tool_auto_progress():
@@ -252,7 +272,14 @@ def tool_match_inventory():
执行库存匹配。
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
"""
return jsonify(shipping_tools.match_inventory(_payload()))
payload = _payload()
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
return jsonify(run_task_auto_progress(
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
trigger='legacy_tool_match_inventory',
operator_id=payload.get('operator_id'),
resume_gate_code='inventory_matching',
))
@shipping_notice_bp.route('/tools/submit_decision', methods=['POST'])
def tool_submit_decision():
@@ -272,19 +299,36 @@ def tool_confirm_inventory_source():
return jsonify(shipping_tools.confirm_inventory_source(_payload()))
@shipping_notice_bp.route('/tools/confirm_customer', methods=['POST'])
def tool_confirm_customer():
"""
确认任务所属标准客户(仅提交 customer_id)。
【AI 触发时机】:用户在客户人工确认检查点选择正式客户后调用。
"""
return jsonify(shipping_tools.confirm_customer(_payload()))
@shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST'])
def tool_generate_shipment_excel():
"""
生成出货 Excel。
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
"""
return jsonify(shipping_tools.generate_excel(_payload()))
payload = _payload()
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
return jsonify(run_task_auto_progress(
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
trigger='legacy_tool_generate_excel',
operator_id=payload.get('operator_id'),
resume_gate_code='artifact_generation',
))
@shipping_notice_bp.route('/tools/upload_to_freight', methods=['POST'])
def tool_upload_to_freight():
"""
上传到货代系统或确认人工上传完成。
【AI 触发时机】:仅供后端主调度、内部恢复链路或人工上传收口调用;不是 Dify 画布正式入口。
Agent 应优先引导用户走工作台 mark-manual-uploaded,勿在自动链中调用。
"""
return jsonify(shipping_tools.upload_to_freight(_payload()))
@@ -294,48 +338,36 @@ def tool_get_task_status():
查询任务状态。
【AI 触发时机】:当 Agent 只拿到任务号/会话号,需要先确认当前卡点后再决定下一步时调用。
"""
return jsonify(shipping_tools.get_task_status(_payload()))
payload = _payload()
task_no = str(payload.get('task_id') or payload.get('task_no') or '').strip().upper()
_require_read_capability(payload, scope='get_shipping_status', task_no=task_no or None)
return jsonify(shipping_tools.get_task_status(payload))
@shipping_notice_bp.route('/tools/get_batch_status', methods=['POST'])
def tool_get_batch_status():
"""
查询批次状态。
【AI 触发时机】:当用户关注整批任务处理进度,或 Agent 需要查看当前 focus task 与批次摘要时调用。
历史批次状态查询(已下线)。
【AI 触发时机】:禁止调用;请改用 get_task_status 或 shipping-processing。
Raises:
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
"""
payload = _payload()
batch_no = str(payload.get('batch_no') or '').strip()
if not batch_no:
raise ValidationError("batch_no is required")
batch = get_batch_by_no(batch_no)
if not batch:
raise NotFoundError("batch not found")
focus_task = get_focus_task_for_batch(batch_no, batch.user_id or 0) if batch.user_id is not None else None
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已获取批次 {batch.batch_no} 状态', 'data': {**serialize_batch_summary(batch), 'focus_task': serialize_task_summary(focus_task) if focus_task else None, 'tasks': list_batch_task_summaries(batch)}})
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
raise_shipping_batches_removed(action='tools.get_batch_status')
@shipping_notice_bp.route('/tools/switch_focus_task', methods=['POST'])
def tool_switch_focus_task():
"""
切换批次当前焦点任务。
【AI 触发时机】:当前仅保留给 Hxops 内部切票能力;不属于 Dify 正式导出 Tool。
历史批次焦点切换(已下线)。
【AI 触发时机】:禁止调用;shipping_batches 已物理删除。
Raises:
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
"""
payload = _payload()
batch_no = str(payload.get('batch_no') or '').strip()
task_no = str(payload.get('task_no') or payload.get('target_task_no') or '').strip()
if not batch_no or not task_no:
raise ValidationError("batch_no and task_no are required")
batch = get_batch_by_no(batch_no)
if not batch:
raise NotFoundError("batch not found")
task = get_task_in_batch(batch_no, task_no)
if not task:
raise NotFoundError("task not found in batch")
switch_batch_focus(
batch,
task,
source="tool_api",
)
db.session.commit()
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'task_no': task.task_no, 'message': f'已切换当前任务到 {task.task_no}', 'data': {'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}})
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
raise_shipping_batches_removed(action='tools.switch_focus_task')
@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST'])
def rpa_worker_heartbeat():
@@ -363,6 +395,37 @@ def rpa_inventory_batch_ready():
"""RPA 批量库存导出回调:按 Warehouse 写入库存快照。"""
return jsonify(shipping_tools.rpa_report_inventory_batch(_payload()))
@shipping_notice_bp.route('/rpa/inventory-batch-claimed', methods=['POST'])
def rpa_inventory_batch_claimed():
"""v2 Worker 领取回调:仅记录 Attempt 执行阶段。"""
from app.services.shipping_notice.per_source_rpa_service import claim_inventory_batch
return jsonify({'success': True, 'data': claim_inventory_batch(_payload())})
@shipping_notice_bp.route('/rpa/inventory-configuration-test-ready', methods=['POST'])
def rpa_inventory_configuration_test_ready():
"""RPA 配置测试回调:仅分析文件结构,不创建生产库存快照或任务关联。"""
from app.services.shipping_notice import inventory_configuration_test
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_test_export(_payload())})
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-ready', methods=['POST'])
def rpa_inventory_configuration_test_batch_ready():
"""RPA 批量配置测试回调:按 validation_run_no 独立回写每个库存站点。"""
from app.services.shipping_notice import inventory_configuration_test
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_exports(_payload())})
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-progress', methods=['POST'])
def rpa_inventory_configuration_test_batch_progress():
"""RPA 批量配置测试进度:Worker 领取单个站点后立即回写执行阶段。"""
from app.services.shipping_notice import inventory_configuration_test
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_progress(_payload())})
@shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST'])
def repair_task_inventory_attachment(task_no: str):
"""
@@ -374,6 +437,14 @@ def repair_task_inventory_attachment(task_no: str):
payload.setdefault("task_id", task_no)
return jsonify(shipping_tools.repair_task_inventory_attachment(payload))
@shipping_notice_bp.route('/rpa/inventory-repair', methods=['POST'])
def rpa_inventory_repair():
"""受控库存回调修复:复用正式 v2 ingest 链路。"""
payload = _payload()
payload['repair'] = True
return jsonify(shipping_tools.rpa_report_inventory_batch(payload))
@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST'])
def rpa_upload_complete():
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
@@ -0,0 +1,69 @@
"""
backend/app/api/workspace/shipping_inventory_candidates.py
用途:正式 Task 库存候选只读详情 API。
依赖:workspace_shipping_notice_bp、query_service.get_task_for_user、inventory_candidate_projection。
逻辑:路由层仅做鉴权与查询参数校验;当前版本缺失返回 200 + current_set=null + blocking_reason,
不把可恢复业务阻断误报成 404。
"""
from __future__ import annotations
from flask import request
from app.api.workspace.shipping_notice import _ok, _require_user, workspace_shipping_notice_bp
from app.core.errors import ValidationError
from app.services.shipping_notice.inventory_candidate_projection import (
project_inventory_candidate_detail,
)
from app.services.shipping_notice.query_service import get_task_for_user
def _parse_version_arg() -> str | int:
"""解析 version 查询参数,仅允许 current 或正整数。"""
raw = str(request.args.get('version') or 'current').strip().lower()
if raw == 'current':
return 'current'
try:
value = int(raw)
except (TypeError, ValueError) as exc:
raise ValidationError('version must be "current" or an integer') from exc
if value <= 0:
raise ValidationError('version must be positive')
return value
def _parse_bool_arg(name: str, *, default: bool) -> bool:
"""解析布尔查询参数。"""
raw = request.args.get(name)
if raw is None:
return default
return str(raw).strip().lower() in {'1', 'true', 'yes', 'on'}
@workspace_shipping_notice_bp.route(
'/shipping-notice/tasks/<task_no>/inventory-candidates',
methods=['GET'],
)
def workspace_get_task_inventory_candidates(task_no: str):
"""返回正式 Task 当前候选版本、历史摘要与行级详情。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
version = _parse_version_arg()
include_history = _parse_bool_arg('include_history', default=True)
include_drafts = _parse_bool_arg('include_drafts', default=False)
payload = project_inventory_candidate_detail(
task,
version=version,
include_history=include_history,
include_drafts=include_drafts,
)
return _ok({
'task_no': task.task_no,
'current_set': payload.get('current_set'),
'sources': payload.get('sources') or [],
'lines': payload.get('lines') or [],
'history': payload.get('history') or [],
'blocking_reason': payload.get('blocking_reason'),
'primary_action': payload.get('primary_action'),
})
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,160 @@
"""
backend/app/api/workspace/shipping_process_gate.py
用途:货代全门禁恢复 Workspace API(Execution 读、Gate 列表、恢复动作、审计事件)。
依赖:workspace_shipping_notice_bp、process_gate_recovery_service、process_gate_api_service、
process_gate_access_service、AppError 全局 handler。
逻辑:薄路由鉴权与 POST 体 forbidden-key 校验;写动作委托 request_gate_action;
403 时 access_service 写入 process_gate_permission_denied 审计。
"""
from __future__ import annotations
from flask import g, request
from app import db
from app.api.workspace.shipping_notice import _ok, _require_user, workspace_shipping_notice_bp
from app.core.errors import ValidationError
from app.services.shipping_notice.process_gate_access_service import assert_execution_visible_to_user
from app.services.shipping_notice.process_gate_api_service import (
get_workspace_process_execution,
list_workspace_process_gate_audit_events,
list_workspace_process_gates,
)
from app.services.shipping_notice.process_gate_recovery_service import get_execution_by_no, request_gate_action
def _query_int(name: str, default: int) -> int:
"""读取可选整数查询参数。"""
raw = request.args.get(name)
if raw in (None, ''):
return default
try:
return int(raw)
except (TypeError, ValueError) as exc:
raise ValidationError(f'{name} must be an integer') from exc
def _parse_gate_action_body() -> dict:
"""
校验 POST 恢复动作请求体。
核心逻辑:仅允许 action_code / expected_gate_version / idempotency_key / payload;
顶层与 payload 均禁止 execution 控制字段。
Returns:
规范化后的 action 参数字典。
Raises:
ValidationError: 缺字段或含 forbidden keys。
"""
body = request.get_json(silent=True) or {}
if body and not isinstance(body, dict):
raise ValidationError('Request body must be an object')
forbidden = {'start_stage', 'target_status', 'worker_name', 'tool_name', 'next_node', 'sql', 'start_gate'}
if forbidden.intersection(set(body.keys())):
raise ValidationError(
'Client must not submit execution controls',
code='SHIPPING.PROCESS_GATE_ACTION_FORBIDDEN',
)
action_code = str(body.get('action_code') or '').strip()
if not action_code:
raise ValidationError('action_code is required', code='SHIPPING.PROCESS_GATE_ACTION_INVALID')
if body.get('expected_gate_version') is None:
raise ValidationError(
'expected_gate_version is required',
code='SHIPPING.PROCESS_GATE_ACTION_INVALID',
)
try:
expected_gate_version = int(body.get('expected_gate_version'))
except (TypeError, ValueError) as exc:
raise ValidationError(
'expected_gate_version must be an integer',
code='SHIPPING.PROCESS_GATE_ACTION_INVALID',
) from exc
idempotency_key = str(body.get('idempotency_key') or '').strip()
if not idempotency_key:
raise ValidationError('idempotency_key is required', code='SHIPPING.PROCESS_GATE_ACTION_INVALID')
payload = body.get('payload')
if payload is not None and not isinstance(payload, dict):
raise ValidationError('payload must be an object', code='SHIPPING.PROCESS_GATE_ACTION_INVALID')
if isinstance(payload, dict) and forbidden.intersection(set(payload.keys())):
raise ValidationError(
'Client must not submit execution controls',
code='SHIPPING.PROCESS_GATE_ACTION_FORBIDDEN',
)
return {
'action_code': action_code,
'expected_gate_version': expected_gate_version,
'idempotency_key': idempotency_key,
'payload': payload if isinstance(payload, dict) else None,
}
@workspace_shipping_notice_bp.route(
'/shipping-notice/process-executions/<execution_no>',
methods=['GET'],
)
def workspace_get_process_execution(execution_no: str):
"""读取当前用户可见的 Process Execution 工作台投影。"""
user = _require_user()
execution = get_execution_by_no(execution_no)
assert_execution_visible_to_user(user, execution)
return _ok(get_workspace_process_execution(execution))
@workspace_shipping_notice_bp.route(
'/shipping-notice/process-executions/<execution_no>/gates',
methods=['GET'],
)
def workspace_list_process_gates(execution_no: str):
"""列出 Execution 下全部 Gate 的用户安全投影。"""
user = _require_user()
execution = get_execution_by_no(execution_no)
assert_execution_visible_to_user(user, execution)
return _ok(list_workspace_process_gates(execution))
@workspace_shipping_notice_bp.route(
'/shipping-notice/process-executions/<execution_no>/gates/<gate_code>/actions',
methods=['POST'],
)
def workspace_post_process_gate_action(execution_no: str, gate_code: str):
"""
请求执行服务端下发的门禁恢复动作。
核心逻辑:校验权限与 POST 契约后调用 request_gate_action;同事务提交。
"""
user = _require_user()
execution = get_execution_by_no(execution_no)
assert_execution_visible_to_user(user, execution, write=True, gate_code=gate_code)
parsed = _parse_gate_action_body()
result = request_gate_action(
execution_no=execution.execution_no,
gate_code=gate_code,
action_code=parsed['action_code'],
expected_gate_version=parsed['expected_gate_version'],
idempotency_key=parsed['idempotency_key'],
actor_type='admin' if str(user.role or '').lower() == 'admin' else 'user',
actor_id=int(user.id),
payload=parsed['payload'],
)
db.session.commit()
return _ok(result)
@workspace_shipping_notice_bp.route(
'/shipping-notice/process-executions/<execution_no>/audit-events',
methods=['GET'],
)
def workspace_list_process_gate_audit_events(execution_no: str):
"""分页返回 Execution 关联的 PROCESS_GATE 审计事件(用户可见字段)。"""
user = _require_user()
execution = get_execution_by_no(execution_no)
assert_execution_visible_to_user(user, execution)
payload = list_workspace_process_gate_audit_events(
execution,
page=_query_int('page', 1),
page_size=_query_int('page_size', 50),
)
return _ok(payload)
+291 -28
View File
@@ -3,9 +3,11 @@ backend/app/core/config/settings.py
用途:Flask Config 类与环境文件加载(dev/test/prod)。
依赖:dotenv、app.path_utils。
逻辑:create_app 通过 config[config_name] 加载;旧路径 app.config 为兼容 shim。
逻辑:create_app 通过 config[config_name] 加载;含发货通知开关
(如 SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED);旧路径 app.config 为兼容 shim。
"""
import os
import warnings
from pathlib import Path
from dotenv import dotenv_values
@@ -13,6 +15,18 @@ from dotenv import dotenv_values
_BACKEND_DIR = Path(__file__).resolve().parents[3]
_ROOT_DIR = _BACKEND_DIR.parent
_WARNED_LEGACY_RPA_ENV: set[str] = set()
_RPA_LEGACY_TO_CANONICAL = {
'SHIPPING_RPA_CREDENTIAL_KEY': 'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY',
'FREIGHT_INVENTORY_DROP_DIR': 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR',
'FREIGHT_RPA_INVENTORY_TRIGGER_DIR': 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR',
'FREIGHT_UPLOAD_QUEUE_DIR': 'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR',
'FREIGHT_RPA_UPLOAD_TRIGGER_DIR': 'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR',
'FREIGHT_RPA_BROWSER_PROFILE_DIR': 'SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR',
'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR': 'SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR',
'FREIGHT_RPA_MOCK': 'SHIPPING_NOTICE_RPA_WORKER_MOCK',
}
def _normalize_env_name(raw: str | None) -> str:
@@ -75,6 +89,58 @@ def _backend_path(env_key: str, *parts: str) -> str:
return resolve_backend_relative_path(os.getenv(env_key), default)
def _rpa_env(canonical_name: str, default: str | None = None) -> str | None:
"""
读取 Shipping Notice RPA 配置,并在迁移期兼容历史环境变量名。
核心逻辑:优先读取 `SHIPPING_NOTICE_RPA_*`;仅在新变量缺失时读取映射的
历史变量,并按进程对每个旧名称最多发出一次弃用警告。
Args:
canonical_name: 统一后的规范环境变量名。
default: 新旧变量均未设置时返回的默认值。
Returns:
str | None: 环境变量值或默认值。
"""
value = os.getenv(canonical_name)
if value is not None:
return value
legacy_name = next(
(legacy for legacy, canonical in _RPA_LEGACY_TO_CANONICAL.items() if canonical == canonical_name),
None,
)
if legacy_name:
value = os.getenv(legacy_name)
if value is not None:
if legacy_name not in _WARNED_LEGACY_RPA_ENV:
warnings.warn(
f'{legacy_name} is deprecated; use {canonical_name}',
DeprecationWarning,
stacklevel=2,
)
_WARNED_LEGACY_RPA_ENV.add(legacy_name)
return value
return default
def _rpa_data_path(canonical_name: str, *parts: str) -> str:
"""
解析 RPA 数据目录,并兼容历史环境变量名称。
Args:
canonical_name: 统一后的 RPA 目录环境变量名。
*parts: 未配置时相对 `backend/data` 的默认路径片段。
Returns:
str: 解析后的绝对或后端相对兼容路径。
"""
from app.path_utils import resolve_backend_relative_path
default = _BACKEND_DIR.joinpath('data', *parts)
return resolve_backend_relative_path(_rpa_env(canonical_name), default)
class Config:
ENV_NAME = ACTIVE_ENV_NAME
SQLALCHEMY_TRACK_MODIFICATIONS = False
@@ -147,6 +213,10 @@ class Config:
)
# Redis 连接配置,默认使用本地 Redis + 密码
REDIS_URL = os.getenv('REDIS_URL')
# 订单文档模板预览默认要求 Redis;仅开发单进程 run.py 可显式放开进程内一次性令牌兜底。
ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK = False
# 默认禁止进程内 JTI;仅 Development/Testing 显式开启
XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = False
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
HR_WORKFLOW_IFRAME_URL = os.getenv('HR_WORKFLOW_IFRAME_URL')
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE')
@@ -170,6 +240,10 @@ class Config:
# 货代发货通知 Agent Tool API
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
# RPA Profile 凭据字段的 Fernet 主密钥;只允许由环境变量提供,禁止持久化到数据库。
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = _rpa_env('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY')
# 兼容仍从 Flask config 读取旧属性的扩展;新代码禁止继续使用该属性。
SHIPPING_RPA_CREDENTIAL_KEY = SHIPPING_NOTICE_RPA_CREDENTIAL_KEY
# 文件检核 Chatflow Tool API
FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY')
@@ -180,24 +254,126 @@ class Config:
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
)
# 建单后是否延后 parse_notice,交由 Dify 画布 LLM + Tool 解析(默认 true,符合 Dify 优先原则)
SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY = os.getenv('SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY', 'true').lower() == 'true'
SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED = (
os.getenv('SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY = int(
os.getenv('SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY') or '3'
)
SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS') or '180'
)
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
SHIPPING_NOTICE_WORKER_CONCURRENCY = int(os.getenv('SHIPPING_NOTICE_WORKER_CONCURRENCY', '2'))
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '300')
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420')
)
# 资格达标后 waiting_to_start 且仍无 STP Job 的超时;超时投影为 manual_fallback。
SHIPPING_NOTICE_STP_WAITING_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_STP_WAITING_TIMEOUT_SECONDS', '120') or '120'
)
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
SHIPPING_NOTICE_AUTO_PROGRESS_RECOVERY_MAX_AGE_HOURS = int(
os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_RECOVERY_MAX_AGE_HOURS', '72') or '72'
)
SHIPPING_NOTICE_WORKER_RECOVERY_TICK_SECONDS = float(
os.getenv('SHIPPING_NOTICE_WORKER_RECOVERY_TICK_SECONDS', '60') or '60'
)
SHIPPING_NOTICE_STP_QUEUED_UNCLAIMED_THRESHOLD_SECONDS = int(
os.getenv('SHIPPING_NOTICE_STP_QUEUED_UNCLAIMED_THRESHOLD_SECONDS', '300') or '300'
)
# OT 后行级自动履约总闸:关闭时仍投影 match_result/库存列,但禁止自动写决定与批量 wave。
SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED = (
os.getenv('SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED', 'false').lower() == 'true'
)
# 订单解析主链开关:通用确定性解析 / 分路径自动冻结 / 模板自动采用 / LLM 辅助复核 / 全局紧急停止。
# 主链不依赖 Dify;LLM 仅用于复核建议且默认关闭自动路径。
SHIPPING_NOTICE_GENERIC_EXTRACTION_ENABLED = (
os.getenv('SHIPPING_NOTICE_GENERIC_EXTRACTION_ENABLED', 'false').lower() == 'true'
)
SHIPPING_NOTICE_GENERIC_AUTO_FREEZE_ENABLED = (
os.getenv('SHIPPING_NOTICE_GENERIC_AUTO_FREEZE_ENABLED', 'false').lower() == 'true'
)
SHIPPING_NOTICE_PROFILE_AUTO_SELECTION_ENABLED = (
os.getenv('SHIPPING_NOTICE_PROFILE_AUTO_SELECTION_ENABLED', 'true').lower() == 'true'
)
# 阶段四:要求候选模板具备有效版面签名;默认 false,全量重签发布后开启。
SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED = (
os.getenv('SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED', 'false').lower() == 'true'
)
# XFA 数据路径 Profile:识别到 xfa_hybrid 即走 xfa_dataset。
# 独立自动建单总闸(阶段 5+);默认关。开启前须满足合成预览门禁 / CQ / 盲测 / 审计补偿。
SHIPPING_NOTICE_XFA_ENABLED = (
os.getenv('SHIPPING_NOTICE_XFA_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_XFA_AUTO_CREATE_ENABLED = (
os.getenv('SHIPPING_NOTICE_XFA_AUTO_CREATE_ENABLED', 'false').lower() == 'true'
)
# 离线完整 flatten 引擎是否已交付并可返回 ready;默认 false(禁 overlay/壳图)。
SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY = (
os.getenv('SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY', 'false').lower() == 'true'
)
# 自动建单硬前置:审计写失败补偿能力就绪前禁止开自动建单(阶段 6)。
SHIPPING_NOTICE_XFA_AUDIT_COMPENSATION_REQUIRED_FOR_AUTO_CREATE = (
os.getenv('SHIPPING_NOTICE_XFA_AUDIT_COMPENSATION_REQUIRED_FOR_AUTO_CREATE', 'true').lower()
== 'true'
)
SHIPPING_NOTICE_XFA_SHADOW_MODE = (
os.getenv('SHIPPING_NOTICE_XFA_SHADOW_MODE', 'false').lower() == 'true'
)
# 客户 / Profile checksum / 场景白名单:空客户或空 checksum 对自动建单 fail-closed。
SHIPPING_NOTICE_XFA_CUSTOMER_ALLOWLIST = os.getenv('SHIPPING_NOTICE_XFA_CUSTOMER_ALLOWLIST') or ''
SHIPPING_NOTICE_XFA_PROFILE_CHECKSUM_ALLOWLIST = (
os.getenv('SHIPPING_NOTICE_XFA_PROFILE_CHECKSUM_ALLOWLIST') or ''
)
SHIPPING_NOTICE_XFA_SCENARIO_ALLOWLIST = (
os.getenv('SHIPPING_NOTICE_XFA_SCENARIO_ALLOWLIST') or 'shipping_notice_order'
)
SHIPPING_NOTICE_XFA_MAX_PDF_BYTES = int(
os.getenv('SHIPPING_NOTICE_XFA_MAX_PDF_BYTES') or str(20 * 1024 * 1024)
)
SHIPPING_NOTICE_XFA_MAX_PACKET_BYTES = int(
os.getenv('SHIPPING_NOTICE_XFA_MAX_PACKET_BYTES') or str(10 * 1024 * 1024)
)
SHIPPING_NOTICE_XFA_MAX_XML_DEPTH = int(os.getenv('SHIPPING_NOTICE_XFA_MAX_XML_DEPTH') or '64')
SHIPPING_NOTICE_XFA_MAX_XML_NODES = int(os.getenv('SHIPPING_NOTICE_XFA_MAX_XML_NODES') or '100000')
SHIPPING_NOTICE_XFA_MAX_LINE_ROWS = int(os.getenv('SHIPPING_NOTICE_XFA_MAX_LINE_ROWS') or '2000')
SHIPPING_NOTICE_XFA_PARSE_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_XFA_PARSE_TIMEOUT_SECONDS') or '30'
)
SHIPPING_NOTICE_XFA_MAX_RETRIES = int(os.getenv('SHIPPING_NOTICE_XFA_MAX_RETRIES') or '2')
SHIPPING_NOTICE_LLM_REVIEW_ENABLED = (
os.getenv('SHIPPING_NOTICE_LLM_REVIEW_ENABLED', 'false').lower() == 'true'
)
SHIPPING_NOTICE_EXTRACTION_EMERGENCY_STOP = (
os.getenv('SHIPPING_NOTICE_EXTRACTION_EMERGENCY_STOP', 'false').lower() == 'true'
)
# 进度细化 / 取消 / 审计导出灰度开关(阶段 5);默认 true,回滚 UI 时按需关闭,不删除审计事实。
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED = (
os.getenv('SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED = (
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED = (
os.getenv('SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS = int(
os.getenv('SHIPPING_NOTICE_AUDIT_RETENTION_DAYS') or '1095'
)
# 保留任务是否抽样校验审计哈希链;默认开启,可按环境关闭以免遗留无 hash 行刷屏。
SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED = (
os.getenv('SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED = (
os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED', 'true').lower() == 'true'
)
# 自动确认必须同时满足人工标注样本量和准确率门禁,避免仅凭开关放大解析误识别。
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES = int(
os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES') or '20'
)
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY = float(
os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY') or '0.98'
)
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
)
@@ -225,7 +401,7 @@ class Config:
or '.hxops_rpa_shared_mount'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED', 'true').lower() == 'true'
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED', 'false').lower() == 'true'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800'
@@ -248,7 +424,10 @@ class Config:
'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN',
'shipment_{task_no}_{ts}.xlsx',
)
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'false').lower() == 'true'
# 货代上传 RPA:默认关闭(生产安全);须环境变量显式 true 才自动触发上传。
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = (
os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'false').lower() == 'true'
)
# Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true'
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
@@ -258,9 +437,6 @@ class Config:
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
)
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG = _backend_path(
'SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG', 'config', 'shipping_inventory_sources.yaml'
)
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int(
os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24'
)
@@ -272,27 +448,33 @@ class Config:
)
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
FREIGHT_INVENTORY_DROP_DIR = _data_path(
"FREIGHT_INVENTORY_DROP_DIR", "shipping_notice", "freight_rpa", "inventory_drop"
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR', 'shipping_notice', 'freight_rpa', 'inventory_drop'
)
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = _data_path(
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "shipping_notice", "freight_rpa", "inventory_triggers"
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'shipping_notice', 'freight_rpa', 'inventory_triggers'
)
FREIGHT_UPLOAD_QUEUE_DIR = _data_path(
"FREIGHT_UPLOAD_QUEUE_DIR", "shipping_notice", "freight_rpa", "upload_queue"
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR', 'shipping_notice', 'freight_rpa', 'upload_queue'
)
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = _data_path(
"FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "shipping_notice", "freight_rpa", "upload_triggers"
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'shipping_notice', 'freight_rpa', 'upload_triggers'
)
FREIGHT_RPA_BROWSER_PROFILE_DIR = _data_path(
"FREIGHT_RPA_BROWSER_PROFILE_DIR", "shipping_notice", "freight_rpa", "browser_profile"
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR', 'shipping_notice', 'freight_rpa', 'browser_profile'
)
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _data_path(
"FREIGHT_RPA_INVENTORY_ARCHIVE_DIR", "shipping_notice", "freight_rpa", "inventory_archives"
)
FREIGHT_SHIPMENT_TEMPLATE_PATH = _backend_path(
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR', 'shipping_notice', 'freight_rpa', 'inventory_archives'
)
SHIPPING_NOTICE_RPA_WORKER_MOCK = _rpa_env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false')
# 旧 Flask config 属性仅用于过渡期测试和外部扩展兼容。
FREIGHT_INVENTORY_DROP_DIR = SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR
FREIGHT_UPLOAD_QUEUE_DIR = SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR
FREIGHT_RPA_BROWSER_PROFILE_DIR = SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR
FREIGHT_RPA_MOCK = SHIPPING_NOTICE_RPA_WORKER_MOCK
# WeCom (企业微信) 登录配置
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
@@ -444,11 +626,77 @@ class Config:
SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', '300')
)
# 订单抽取发送后选择计划预算:首轮只挑最相关附件,后续批次按固定预算待扩展。
SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_ATTACHMENTS = int(
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_ATTACHMENTS', '2')
)
SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_CONCURRENCY = int(
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_CONCURRENCY', '2')
)
SHIPPING_NOTICE_ORDER_EXTRACTION_EXPANSION_BATCH_SIZE = int(
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_EXPANSION_BATCH_SIZE', '2')
)
SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS = int(
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS', '6')
)
SHIPPING_NOTICE_PARSER_VERSION = os.getenv('SHIPPING_NOTICE_PARSER_VERSION', 'v6')
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED = os.getenv(
'SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED', 'false'
).lower() == 'true'
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL = os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL', '').strip()
SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS', '10')
)
SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS', '300')
)
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE = int(
os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', '10')
)
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY = int(
os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY', '2')
)
SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS = int(
os.getenv('SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS', str(1_000_000))
)
SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES = int(
os.getenv('SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', str(2_000_000))
)
SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS = int(
os.getenv('SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS', '3')
)
SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS', '360')
)
# PR-1:同 Job 内整页 OCR 结果复用;生产默认关,dev/test 由环境文件开启。
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED = os.getenv(
'SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED', 'false'
).lower() == 'true'
# PR-2:复用 MinerU 前 PDFium 字符预读,仅按需补齐页面渲染图。
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED = os.getenv(
'SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED', 'false'
).lower() == 'true'
# PR-3:表格 cell 候选使用裁剪 OCR;订单级 page_glyphs 仍整页 OCR。
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED = os.getenv(
'SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED', 'false'
).lower() == 'true'
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO = float(
os.getenv('SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO', '0.03')
)
# XFA 字段拆分规则资源上限(阶段 1:matcher 引擎与 RE2 安全执行)
XFA_SPLIT_MAX_RULES_PER_SET = int(os.getenv('XFA_SPLIT_MAX_RULES_PER_SET', '32'))
XFA_SPLIT_MAX_RULE_SETS = int(os.getenv('XFA_SPLIT_MAX_RULE_SETS', '64'))
XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH = int(os.getenv('XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH', '128'))
XFA_SPLIT_MAX_REGEX_GROUPS = int(os.getenv('XFA_SPLIT_MAX_REGEX_GROUPS', '5'))
XFA_SPLIT_MAX_PREFIX_LENGTH = int(os.getenv('XFA_SPLIT_MAX_PREFIX_LENGTH', '64'))
XFA_SPLIT_MAX_INPUT_LENGTH = int(os.getenv('XFA_SPLIT_MAX_INPUT_LENGTH', '32768'))
XFA_SPLIT_REGEX_TIMEOUT_MS = int(os.getenv('XFA_SPLIT_REGEX_TIMEOUT_MS', '50'))
# EML 附件提取安全上限(阶段一对齐:只抽取文本,不执行宏/脚本)
# parser v6:阶段二附件派生 FileAsset + Document/Candidate;相对 v5 须强制重解析
# parser v5:mixed 保留独立 HTML 段 + 附件型 alternative 可提取正文
SHIPPING_NOTICE_EML_MAX_ATTACHMENTS = int(os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENTS', '20'))
# 单次批量上传通知文件上限;与 EML 内附件上限独立,防止请求级资源耗尽。
SHIPPING_NOTICE_BATCH_MAX_FILES = int(os.getenv('SHIPPING_NOTICE_BATCH_MAX_FILES', '20'))
SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES = int(
os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES', str(20 * 1024 * 1024))
)
@@ -460,16 +708,30 @@ class Config:
SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS = int(
os.getenv('SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS', str(500_000))
)
# 订单抽取 Worker 的全 Run 资源门槛;超出时停止扩批并进入可复核终态。
SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_BYTES = int(
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_BYTES', str(30 * 1024 * 1024))
)
SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_RUNTIME_SECONDS = int(
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_RUNTIME_SECONDS', '300')
)
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK = True
# 本机常无 Redis:不强制 Redis,允许进程内存兜底心跳(单进程 run.py 可用)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
# XFA 拆分确认 JTI:仅单进程 development 允许内存消费;test/prod 多 Worker 必须 Redis
XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = True
class ProductionConfig(Config):
DEBUG = False
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = False
class TestingConfig(Config):
@@ -483,6 +745,8 @@ class TestingConfig(Config):
ENV_NAME = 'dev'
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
# pytest 单进程:允许内存 JTI;生产语义由 ProductionConfig 关闭
XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = True
config = {
@@ -494,4 +758,3 @@ config = {
'production': ProductionConfig,
'default': DevelopmentConfig,
}
@@ -0,0 +1,27 @@
"""
jobs/handlers/shipping_auto_progress.py
用途:终态化历史 APX AutoProgress Job。
依赖:JobContext、auto_progress_controller。
逻辑:Job 已由通用队列领取为 running;本 Handler 仅委托控制器取消遗留 APX
Job 并保留审计。正式 20-Gate 只能由 shipping_process_gate Handler 执行。
"""
from __future__ import annotations
from app.jobs.context import JobContext
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.services.shipping_notice.auto_progress_controller import run_auto_progress_job
@register_handler(JobType.SHIPPING_AUTO_PROGRESS)
def run_shipping_auto_progress(ctx: JobContext, payload: dict) -> None:
"""终态化历史 APX Job;payload 必须含队列注入的 job_id。"""
raw_job_id = payload.get('job_id')
if not raw_job_id:
raise RuntimeError('missing_job_id_for_shipping_auto_progress')
run_auto_progress_job(
job_id=int(raw_job_id),
worker_id=str(ctx.extras.get('worker_label') or f'shipping-auto-progress-{raw_job_id}'),
)
@@ -0,0 +1,296 @@
"""
backend/app/jobs/handlers/shipping_document_layout.py
用途:独立执行单份 ShippingOrderDocument 的 MinerU 布局解析任务。
依赖:Layout lifecycle/runtime、layout_diagnostics、FileAsset、通用 Job queue、audit_service、
workflow_ledger(尽力引用)。
逻辑:按 job attempt 领取版本 lease,读取对象存储调用 MinerU;收口时旧 lease 无权覆盖新版本;
起止与异常轻量写统一审计(若能定位 WorkflowItem 则带软引用);
PR-0 将脱敏 timings/counts 写入 Job result 与 worker 日志,不进 layout snapshot。
"""
from __future__ import annotations
from time import perf_counter
from app.extensions import db
from app.jobs.context import JobContext
from app.jobs.queue import fail_job, finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import FileAsset, Job, ShippingDocumentLayoutVersion
from app.services.file_assets.service import read_asset_bytes
from app.services.shipping_notice.document_layout.layout_diagnostics import (
empty_layout_counts,
empty_layout_timings,
freeze_layout_diagnostics,
ocr_engine_is_warm,
)
from app.services.shipping_notice.document_layout.lifecycle import (
claim_layout_version,
complete_layout_version,
sync_layout_after_job_failure,
)
from app.services.shipping_notice.document_layout.runtime import build_mineru_table_snapshot
LAYOUT_JOB_ERROR = 'shipping_document_layout_provider_failed'
def _layout_job_audit(
*,
event_type: str,
job: Job,
version: ShippingDocumentLayoutVersion | None,
result: str = 'success',
error_code: str | None = None,
metadata: dict | None = None,
) -> None:
"""
版面 Job 起止/异常轻量审计;能定位 Item 时写入 workflow 软引用。
Args:
event_type: 审计事件类型。
job: 当前 Job。
version: 布局版本(可空)。
result/error_code/metadata: 结果与脱敏元数据。
"""
try:
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.document_layout.lifecycle import _conversation_id_for_document
from app.services.shipping_notice.workflow_ledger_service import find_item_by_root
document_id = int(version.document_id) if version is not None else None
workflow_id = None
workflow_item_id = None
conversation_id = None
owner_user_id = None
if document_id:
conversation_id = _conversation_id_for_document(document_id)
if conversation_id:
item = find_item_by_root(
conversation_id=conversation_id,
root_document_id=document_id,
)
if item is not None:
workflow_id = str(item.workflow_no)
workflow_item_id = str(item.item_no)
owner_user_id = item.owner_user_id
append_shipping_audit_event(
event_type=event_type,
aggregate_type='shipping_document_layout_version',
aggregate_id=str(getattr(version, 'id', None) or job.id),
actor_type='system',
actor_id=f'job:{job.id}',
conversation_id=conversation_id,
document_id=document_id,
workflow_id=workflow_id,
workflow_item_id=workflow_item_id,
owner_user_id=owner_user_id,
result=result,
error_code=error_code,
source='shipping_document_layout',
metadata={
'job_id': int(job.id),
'attempt': int(job.attempts or 0),
**(metadata or {}),
},
)
except Exception:
pass
@register_handler(JobType.SHIPPING_DOCUMENT_LAYOUT)
def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
"""
执行单文档布局任务;Job 和版本均使用相同 attempt 代次条件收口。
Args:
ctx: Worker 上下文,用于记录仅运维可见的异常堆栈。
payload: 通用队列载荷,只读取 job_id;布局版本 ID 从冻结 Job 载荷读取。
Returns:
None。成功时同时完成布局版本与 Job;失败时按通用重试策略重新排队。
"""
raw_job_id = payload.get('job_id')
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
if job is None:
return
owned_attempt = int(job.attempts or 0)
version_id = int((job.payload_json or {}).get('layout_version_id') or 0)
version = db.session.get(ShippingDocumentLayoutVersion, version_id) if version_id else None
if version is None:
fail_job(job.id, error='layout version not found', retryable=False, owned_attempt=owned_attempt)
return
if version.status in {'ready', 'needs_review', 'failed', 'unsupported'}:
finish_job(job.id, result={'status': version.status, 'skipped': True}, owned_attempt=owned_attempt)
return
claimed = claim_layout_version(version.id, job_id=job.id, owned_attempt=owned_attempt)
if claimed is None:
finish_job(job.id, result={'status': 'stale', 'skipped': True}, owned_attempt=owned_attempt)
return
version, lease = claimed
_layout_job_audit(
event_type='document_layout_job_started',
job=job,
version=version,
metadata={'lease': True},
)
from app.services.shipping_notice.order_extraction_progress import record_layout_document_progress
record_layout_document_progress(document_id=int(version.document_id), event_code='layout_parsing_started')
try:
document = version.document
asset = db.session.get(FileAsset, int(document.asset_id or 0))
if asset is None:
raise ValueError('layout document asset is unavailable')
total_started = perf_counter()
asset_started = perf_counter()
content = read_asset_bytes(asset)
# [STEP 1] 初始化全量诊断键;ocr_engine_warm 在任何 OCR 之前读取进程状态。
timings = empty_layout_timings()
counts = empty_layout_counts()
counts['ocr_engine_warm'] = ocr_engine_is_warm()
timings['queue_wait_ms'] = max(
round((job.started_at - job.created_at).total_seconds() * 1000), 0,
) if job.started_at and job.created_at else 0
timings['asset_read_ms'] = round((perf_counter() - asset_started) * 1000)
from app.services.shipping_notice.document_layout.xfa_analysis import (
analyze_xfa_pdf,
persist_xfa_structure_analysis,
)
from app.services.shipping_notice.document_layout.xfa_contract import default_xfa_resource_limits
xfa_started = perf_counter()
xfa_outcome = None
if str(document.filename or '').lower().endswith('.pdf') and content.startswith(b'%PDF'):
_layout_job_audit(
event_type='xfa_parse_started',
job=job,
version=version,
metadata={'document_id': int(document.id)},
)
xfa_outcome = analyze_xfa_pdf(content, limits=default_xfa_resource_limits())
timings['xfa_analysis_ms'] = round((perf_counter() - xfa_started) * 1000)
snapshot = None
if (
xfa_outcome is not None
and xfa_outcome.packet_result is not None
and xfa_outcome.packet_result.document_kind not in {'plain_pdf', 'acroform'}
):
snapshot = dict(xfa_outcome.snapshot)
capability = snapshot.get('xfa_capability') if isinstance(snapshot.get('xfa_capability'), dict) else {}
try:
counts['page_count'] = int(capability.get('page_count') or 0)
except (TypeError, ValueError):
counts['page_count'] = 0
persist_xfa_structure_analysis(
document_id=int(document.id),
layout_version_id=int(version.id),
source_content_hash=str(document.content_hash or ''),
outcome=xfa_outcome,
)
if xfa_outcome.error_code == 'XFA_UNSAFE_XML':
_layout_job_audit(
event_type='xfa_parse_rejected_unsafe',
job=job,
version=version,
result='failure',
error_code=xfa_outcome.error_code,
)
elif snapshot.get('status') == 'ready':
_layout_job_audit(
event_type='xfa_structure_analysis_ready',
job=job,
version=version,
metadata={
'document_kind': snapshot.get('document_kind'),
'structure_analysis_id': (
(snapshot.get('xfa_capability') or {}).get('structure_analysis_id')
),
},
)
_layout_job_audit(event_type='xfa_parse_completed', job=job, version=version)
else:
_layout_job_audit(
event_type='xfa_parse_failed',
job=job,
version=version,
result='failure',
error_code=xfa_outcome.error_code,
metadata={'route_reason': xfa_outcome.route_reason},
)
if snapshot is None:
snapshot = build_mineru_table_snapshot(
filename=str(document.filename or asset.original_filename or 'document.pdf'),
content=content,
document_id=document.id,
content_hash=document.content_hash,
timings=timings,
counts=counts,
)
timings['snapshot_build_ms'] = round((perf_counter() - total_started) * 1000)
if snapshot is None:
snapshot = {
'snapshot_version': version.contract_version,
'provider': version.parser_name, 'backend': version.backend,
'status': 'unsupported', 'tables': [],
'issues': ['shipping_document_layout_input_unsupported'],
}
if complete_layout_version(version.id, lease_token=lease, snapshot=snapshot):
final_status = str(db.session.get(ShippingDocumentLayoutVersion, version.id).status or 'failed')
record_layout_document_progress(document_id=int(document.id), event_code='layout_parsing_completed')
_layout_job_audit(
event_type='document_layout_job_completed',
job=job,
version=version,
metadata={'status': str(snapshot.get('status') or 'failed')},
)
timings['total_handler_ms'] = round((perf_counter() - total_started) * 1000)
frozen_timings, frozen_counts = freeze_layout_diagnostics(timings, counts)
finish_job(
job.id, result={
'status': final_status,
'provider_status': str(snapshot.get('status') or 'failed'),
'timings': frozen_timings,
'counts': frozen_counts,
},
message=(
'文档版面解析完成' if final_status in {'ready', 'needs_review'}
else '文档版面解析失败'
), owned_attempt=owned_attempt,
)
from app.services.shipping_notice.order_extraction_run_service import resume_runs_waiting_for_layout
resume_runs_waiting_for_layout(document_id=int(document.id))
else:
timings['total_handler_ms'] = round((perf_counter() - total_started) * 1000)
if ctx.logger is not None:
frozen_timings, frozen_counts = freeze_layout_diagnostics(timings, counts)
ctx.logger.info(
'shipping_document_layout_timing job_id=%s version_id=%s document_id=%s timings=%s counts=%s',
job.id, version.id, document.id, frozen_timings, frozen_counts,
)
except Exception as exc:
db.session.rollback()
if ctx.logger is not None:
ctx.logger.exception(
'shipping_document_layout_failed job_id=%s version_id=%s', job.id, version.id,
)
_layout_job_audit(
event_type='document_layout_job_failed',
job=job,
version=version,
result='failure',
error_code=LAYOUT_JOB_ERROR,
metadata={'error': str(exc)[:200]},
)
fail_job(job.id, error=LAYOUT_JOB_ERROR, retryable=True, owned_attempt=owned_attempt)
sync_layout_after_job_failure(job.id)
# 仅当重试已耗尽时版本才会转 failed;此时需要唤醒等待中的 Run,
# 让用户看到“附件解析失败”而不是永久停留在“正在解析”。
from app.services.shipping_notice.order_extraction_run_service import resume_runs_waiting_for_layout
resume_runs_waiting_for_layout(document_id=int(version.document_id))
raise
@@ -0,0 +1,80 @@
"""
backend/app/jobs/handlers/shipping_line_auto_fulfill.py
用途:消费 OT 后行级自动履约协调 Job。
依赖:JobContext、line_auto_fulfill_coordinator、query_service.get_task_by_ref。
逻辑:shipping worker 领取;flag 关闭或无 eligible 时 finish 为 skipped;失败可重试。
"""
from __future__ import annotations
from app.extensions import db
from app.jobs.context import JobContext
from app.jobs.queue import fail_job, finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
coordinate_post_ot_auto_fulfill,
)
from app.services.shipping_notice.query_service import get_task_by_ref
@register_handler(JobType.SHIPPING_LINE_AUTO_FULFILL)
def handle_shipping_line_auto_fulfill(ctx: JobContext, payload: dict) -> None:
"""
执行 OT 后行级自动履约协调。
Args:
ctx: Worker 上下文。
payload: 须含 job_id;业务字段以 Job.payload_json 为准(task_no/trigger)。
"""
_ = ctx
raw_job_id = payload.get('job_id') if isinstance(payload, dict) else None
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
if job is None:
raise RuntimeError('missing_line_auto_fulfill_job_id')
job_id = int(job.id)
owned_attempt = int(job.attempts or 0)
frozen = dict(job.payload_json or {})
task_no = str(frozen.get('task_no') or '').strip()
trigger = str(frozen.get('trigger') or 'inventory_ready').strip()
task = get_task_by_ref(task_no) if task_no else None
if task is None:
fail_job(
job_id,
error='task_not_found',
result={'status': 'failed', 'error_code': 'SHIPPING.TASK_NOT_FOUND'},
retryable=False,
owned_attempt=owned_attempt,
)
return
try:
result = coordinate_post_ot_auto_fulfill(task=task, trigger=trigger)
db.session.commit()
if result.get('status') == 'failed':
fail_job(
job_id,
error=str(result.get('error') or 'auto_fulfill_failed'),
result=result,
retryable=True,
owned_attempt=owned_attempt,
)
return
finish_job(
job_id,
result=result,
message=str(result.get('status') or 'ok'),
owned_attempt=owned_attempt,
)
except Exception as exc: # noqa: BLE001
db.session.rollback()
fail_job(
job_id,
error=str(exc)[:500],
result={'status': 'failed'},
retryable=True,
owned_attempt=owned_attempt,
)
raise
@@ -21,7 +21,7 @@ from app.jobs.context import JobContext
from app.jobs.queue import fail_job, finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import FileAsset, Job, ShippingNoticeIntake
from app.models import FileAsset, Job, ShippingOrderIntake
from app.services.shipping_notice.intake_parse_workflow import (
fail_intake_with_stage2_cleanup,
run_intake_parse,
@@ -69,7 +69,7 @@ def _claim_intake_for_parsing(
*,
job_id: int | None,
owned_attempt: int | None,
) -> tuple[ShippingNoticeIntake, str] | None:
) -> tuple[ShippingOrderIntake, str] | None:
"""
原子领取 Intake 并轮转 parse_lease。
@@ -81,13 +81,13 @@ def _claim_intake_for_parsing(
"""
now = datetime.utcnow()
lease = _build_parse_lease(job_id=job_id, owned_attempt=owned_attempt)
claim_predicate = ShippingNoticeIntake.parse_status.in_(tuple(_CLAIMABLE_STATUSES))
claim_predicate = ShippingOrderIntake.parse_status.in_(tuple(_CLAIMABLE_STATUSES))
if job_id is not None:
claim_predicate = or_(
claim_predicate,
and_(
ShippingNoticeIntake.parse_status == 'parsing',
ShippingNoticeIntake.parse_job_id == int(job_id),
ShippingOrderIntake.parse_status == 'parsing',
ShippingOrderIntake.parse_job_id == int(job_id),
),
)
values: dict = {
@@ -98,9 +98,9 @@ def _claim_intake_for_parsing(
if job_id is not None:
values['parse_job_id'] = int(job_id)
stmt = (
update(ShippingNoticeIntake)
update(ShippingOrderIntake)
.where(
ShippingNoticeIntake.intake_no == intake_no,
ShippingOrderIntake.intake_no == intake_no,
claim_predicate,
)
.values(**values)
@@ -111,7 +111,7 @@ def _claim_intake_for_parsing(
return None
db.session.commit()
intake = (
db.session.query(ShippingNoticeIntake)
db.session.query(ShippingOrderIntake)
.filter_by(intake_no=intake_no)
.first()
)
@@ -156,7 +156,7 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
)
return
intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first()
intake = db.session.query(ShippingOrderIntake).filter_by(intake_no=intake_no).first()
if not intake:
if job_id is not None:
fail_job(
@@ -198,7 +198,7 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
intake_no, job_id=job_id, owned_attempt=owned_attempt
)
if claimed is None:
current = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first()
current = db.session.query(ShippingOrderIntake).filter_by(intake_no=intake_no).first()
if job_id is not None:
finish_job(
job_id,
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,121 @@
"""
backend/app/jobs/handlers/shipping_post_ot_wave_progress.py
用途:消费 post-OT wave 专用 Excel/RPA 推进 Job。
依赖:JobContext、post_ot_wave_progress_service、fulfillment_workflow.generate_excel。
逻辑:按 task_no+wave_no 推进;失败只标记 progress_failed,不回滚已提交 wave。
"""
from __future__ import annotations
from app.extensions import db
from app.jobs.context import JobContext
from app.jobs.queue import fail_job, finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.post_ot_wave_progress_service import (
mark_post_ot_wave_progress_result,
)
from app.services.shipping_notice.query_service import get_task_by_ref
@register_handler(JobType.SHIPPING_POST_OT_WAVE_PROGRESS)
def handle_shipping_post_ot_wave_progress(ctx: JobContext, payload: dict) -> None:
"""
执行本 wave 的 Excel 生成推进(RPA 链路由 generate_excel 后续状态机承接)。
Args:
ctx: Worker 上下文。
payload: 须含 job_id;业务字段以 Job.payload_json 为准。
"""
_ = ctx
raw_job_id = payload.get('job_id') if isinstance(payload, dict) else None
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
if job is None:
raise RuntimeError('missing_post_ot_wave_progress_job_id')
job_id = int(job.id)
owned_attempt = int(job.attempts or 0)
frozen = dict(job.payload_json or {})
task_no = str(frozen.get('task_no') or '').strip()
wave_no = frozen.get('wave_no')
idem_row_id = frozen.get('idempotency_row_id')
progress_key = frozen.get('progress_idempotency_key')
task = get_task_by_ref(task_no) if task_no else None
if task is None:
mark_post_ot_wave_progress_result(
idempotency_row_id=idem_row_id,
progress_idempotency_key=progress_key,
ok=False,
error='task_not_found',
)
db.session.commit()
fail_job(
job_id,
error='task_not_found',
result={'status': 'failed', 'wave_no': wave_no},
retryable=False,
owned_attempt=owned_attempt,
)
return
try:
from app.services.shipping_notice.fulfillment_workflow import generate_excel
# [STEP] 为本 OT 生成/刷新发货 Excel;wave_no 写入上下文供审计与后续过滤。
gen = generate_excel({
'task_id': task.task_no,
'wave_no': wave_no,
'line_keys': list(frozen.get('line_keys') or []),
'post_ot_wave': True,
})
status = str((gen or {}).get('status') or '').strip().lower()
if status in {'failed', 'error'}:
err = str((gen or {}).get('message') or (gen or {}).get('error') or 'excel_failed')
mark_post_ot_wave_progress_result(
idempotency_row_id=idem_row_id,
progress_idempotency_key=progress_key,
ok=False,
error=err,
)
db.session.commit()
fail_job(
job_id,
error=err[:500],
result={'status': 'failed', 'wave_no': wave_no, 'generate_excel': gen},
retryable=True,
owned_attempt=owned_attempt,
)
return
mark_post_ot_wave_progress_result(
idempotency_row_id=idem_row_id,
progress_idempotency_key=progress_key,
ok=True,
)
db.session.commit()
finish_job(
job_id,
result={'status': 'ok', 'wave_no': wave_no, 'generate_excel': gen},
message='post_ot_wave_progress_ok',
owned_attempt=owned_attempt,
)
except Exception as exc: # noqa: BLE001
db.session.rollback()
# [STEP] 下游失败:重新打开会话标记 progress_failed,wave 业务事实保留。
mark_post_ot_wave_progress_result(
idempotency_row_id=idem_row_id,
progress_idempotency_key=progress_key,
ok=False,
error=str(exc)[:1000],
)
db.session.commit()
fail_job(
job_id,
error=str(exc)[:500],
result={'status': 'failed', 'wave_no': wave_no},
retryable=True,
owned_attempt=owned_attempt,
)
raise
@@ -0,0 +1,130 @@
"""
backend/app/jobs/handlers/shipping_process_gate.py
用途:消费门禁恢复 Attempt Job,领取租约并执行 process_gate_executor。
依赖:JobContext、process_gate_job_service、process_gate_service、jobs.queue finish/fail、
process_gate_error_sanitizer。
逻辑:由 shipping worker 领取;技术失败按该 Attempt 下 failed Job 累计次数 + 5s/30s/120s 退避重新入队;
次数耗尽时 fail_job 并 complete_gate_attempt(blocked_retryable),保留人工恢复入口;
不修改 input_snapshot_json,以保持 input_snapshot_hash 与正文一致;
waiting_external 先结束当前 Job 再延迟入队新 Job;
healthcheck_probe 载荷用于部署探针,不依赖真实 Attempt。
"""
from __future__ import annotations
from flask import current_app
from app import db
from app.jobs.context import JobContext
from app.jobs.queue import fail_job, finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import Job, ShippingProcessGate, ShippingProcessGateAttempt
from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text
from app.services.shipping_notice.process_gate_job_service import (
SHIPPING_PROCESS_GATE_JOB_DOMAIN,
claim_and_run_gate_attempt,
enqueue_gate_attempt_job,
)
from app.services.shipping_notice.process_gate_service import complete_gate_attempt
def _finalize_attempt_after_failure(
*,
attempt: ShippingProcessGateAttempt,
exc: BaseException,
) -> None:
"""
单次门禁执行失败:结束当前 Attempt,并将 Gate 收口为可人工恢复阻断。
核心逻辑:调用 complete_gate_attempt,避免 Job=failed 而 Gate 仍 running。
"""
safe = sanitize_gate_error_text(exc, max_len=500) or 'technical_failure'
if attempt.status == 'queued':
attempt.status = 'running'
db.session.flush()
complete_gate_attempt(
attempt_id=int(attempt.id),
outcome='blocked_retryable',
# 与 error_explainability_contract / PROCESS_GATE_BLOCKING 对齐,禁止写未登记的 technical_failure
blocking_reason_code='technical_failure_present',
blocking_reason_json={
'reason_code': 'technical_failure_present',
'message': safe,
},
effective_result_json={'findings': [], 'error': 'technical_failure'},
output_snapshot={'error': safe},
error_code='TECHNICAL_FAILURE',
error_summary=safe,
)
@register_handler(JobType.SHIPPING_PROCESS_GATE)
def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
"""
执行门禁 Attempt;支持部署健康检查探针载荷。
Args:
ctx: Worker 上下文。
payload: 须含 attempt_id 与 job_id;healthcheck_probe=True 时仅证明领取能力。
"""
# [STEP] 部署探针:Worker 领取后立即成功结束,不触碰业务 Attempt。
if bool(payload.get('healthcheck_probe')):
raw_job_id = payload.get('job_id')
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
if job is None:
raise RuntimeError('missing_job_id_for_healthcheck_probe')
finish_job(
job.id,
result={'status': 'healthcheck_probe_ok'},
owned_attempt=int(job.attempts or 0),
)
return
attempt_id = int(payload.get('attempt_id') or 0)
raw_job_id = payload.get('job_id')
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
if attempt_id <= 0 or job is None:
raise RuntimeError('missing_attempt_id_or_job_id')
owned_attempt = int(job.attempts or 0)
worker_id = str(ctx.extras.get('worker_label') or f'shipping-gate-{job.id}')
try:
result = claim_and_run_gate_attempt(attempt_id=attempt_id, worker_id=worker_id)
except Exception as exc:
# claim/execute 可能已经让 SQLAlchemy 事务进入 aborted 状态(例如死锁)。
# 任何失败收口前必须先回滚,避免把 Job 标记失败后留下 queued Attempt/Gate。
db.session.rollback()
attempt = db.session.get(ShippingProcessGateAttempt, attempt_id)
gate = None
gate_status = None
if attempt is not None:
gate = db.session.get(ShippingProcessGate, int(attempt.gate_id))
gate_status = gate.status if gate else None
# [STEP] 外部等待:先结束当前 Job,再清空 job_id 并延迟入队,避免复用 running Job。
if gate_status == 'waiting_external':
poll = max(int(current_app.config.get('SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS', 30) or 30), 5)
finish_job(job.id, result={'status': 'waiting_external_requeued'}, owned_attempt=owned_attempt)
if attempt is not None:
attempt.job_id = None
db.session.flush()
enqueue_gate_attempt_job(
attempt_id=attempt_id,
delay_seconds=poll,
force_new=True,
)
db.session.commit()
return
safe_error = sanitize_gate_error_text(exc, max_len=1000) or 'technical_failure'
# 先把 Attempt/Gate/Execution 收口,再独立结束 Job;即使 Runner 随后兜底标记
# Job failed,也不会再留下 failed Job + queued Attempt 的非法组合。
if attempt is not None:
fresh_attempt = db.session.get(ShippingProcessGateAttempt, attempt_id)
if fresh_attempt is not None and fresh_attempt.status in {'queued', 'running'}:
_finalize_attempt_after_failure(attempt=fresh_attempt, exc=exc)
db.session.commit()
fail_job(job.id, error=safe_error, retryable=False, owned_attempt=owned_attempt)
return
finish_job(job.id, result=result if isinstance(result, dict) else {'status': 'ok'}, owned_attempt=owned_attempt)
@@ -0,0 +1,300 @@
"""
backend/app/jobs/handlers/shipping_review_revalidate_progress.py
用途:消费 Review Revalidate Job,在 Case 字段变更后异步刷新校验、
重跑 STP 资格判定、推进自动入队协调。
依赖:JobContext、order_review_auto_progress_coordinator.reconcile_single_case_for_auto_progress、
jobs.queue finish/fail、recovery_contract.is_tech_retryable_error。
逻辑:由 shipping worker 领取;按 business_ref(case_no)+ 部分唯一索引保证同 Case 不重复入队;
成功 finish 写 result_json(包含 enqueue_status / customer_step_status / validate_status);
失败统一走错误分类:
- AppError.is_tech_retryable_error 命中 → fail_job(retryable=True)
- 其它 AppError 业务阻断 → fail_job(retryable=False)
- 非预期 Exception → category_hint=temporary_storage_error,默认 retryable=True
"""
from __future__ import annotations
import logging
from typing import Any
from app.core.errors import AppError
from app.extensions import db
from app.jobs.context import JobContext
from app.jobs.queue import fail_job, finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.recovery_contract import is_tech_retryable_error
logger = logging.getLogger(__name__)
_SUCCESS_ENQUEUE_STATUSES: frozenset[str] = frozenset({
'queued',
'already_queued',
'already_running',
'reused',
'enqueued',
'already_confirmed_or_terminal',
})
def _classify_revalidate_error(
*,
error_code: str,
message: str,
category_hint: str | None = None,
) -> tuple[bool, dict[str, Any]]:
"""
将 Revalidate Job 执行失败按 recovery_contract 统一分类,输出 retryable、合并后的 result。
【AI 触发时机】:Handler 的两条 fail 路径(AppError 兜底、非预期 Exception 兜底)
统一调用,确保 Job.result_json schema 一致。
核心逻辑(fail-closed):
[STEP 1] is_tech_retryable_error(error_code, category_hint) 命中白名单或前缀
→ result.status=failed_transient,retryable=True。
[STEP 2] 否则 result.status=blocked_manual,retryable=False。
[STEP 3] 返回二元组(retryable, normalized_result_dict)。
Args:
error_code: 业务错误码(SHIPPING.* 或顶层 reason_code)。
message: 人类可读描述。
category_hint: 可选;调用方已知的技术分类(temporary_storage_error 等)。
Returns:
(retryable: bool, normalized_result: dict)。
"""
tech = is_tech_retryable_error(error_code, category_hint=category_hint)
result_status = 'failed_transient' if tech else 'blocked_manual'
normalized: dict[str, Any] = {
'contract_version': 'shipping-recovery-v1-phase1',
'status': result_status,
'error_code': str(error_code or ''),
'message': str(message or ''),
'retryable': bool(tech),
'decision_trace': {
'contract_version': 'shipping-recovery-v1-phase1',
'stage': 'revalidate_classify_error',
'retryable': bool(tech),
'matched_rule': 'tech_retryable_whitelist' if tech else 'business_blocking_default',
'category_hint': category_hint,
},
}
return bool(tech), normalized
@register_handler(JobType.SHIPPING_REVIEW_REVALIDATE_PROGRESS)
def handle_shipping_review_revalidate_progress(ctx: JobContext, payload: dict) -> None:
"""
执行 Review Revalidate Job(字段变更后异步协调)。
核心逻辑:
[STEP 0] 读取 Job 记录,冻结 payload,解析 case_no / draft_version / operation_id。
[STEP 1] 加行锁加载 Case,Case 不存在或已终态 → finish_job(status='skipped')。
[STEP 2] Draft 版本冲突检测:冻结版本与 Case.current_draft 不一致 →
result.draft_version_superseded,finish_job(status='skipped')。
[STEP 3] 调用 reconcile_single_case_for_auto_progress(case, trigger='review_revalidate_job', refresh_validation=True)。
[STEP 4] 按 enqueue_status / customer_step_status / validate_status 分类:
- 全部成功 → finish_job,写 result_json。
[STEP 5] AppError:is_tech_retryable_error 命中 → fail_job(retryable=True),否则 retryable=False。
[STEP 6] 非预期 Exception:category_hint=temporary_storage_error,retryable=True,最终 re-raise 保持 Worker 心跳。
Args:
ctx: Worker 上下文;当前执行体不依赖请求上下文。
payload: Worker 载荷,必须含 job_id;业务字段以 Job.payload_json 为准。
Returns:
None。
"""
_ = ctx
raw_job_id = payload.get('job_id') if isinstance(payload, dict) else None
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
if job is None:
raise RuntimeError('missing_review_revalidate_job_id')
job_id = int(job.id)
owned_attempt = int(job.attempts or 0)
frozen = dict(job.payload_json or {})
frozen.setdefault('job_id', job_id)
try:
case_no = str(frozen.get('case_no') or '').strip() or None
draft_version_raw = frozen.get('draft_version')
draft_version = int(draft_version_raw) if draft_version_raw is not None else None
operation_id = frozen.get('operation_id')
if operation_id is not None:
operation_id = str(operation_id).strip() or None
if not case_no:
fail_job(
job_id,
error='missing_case_no_in_payload',
result={
'status': 'payload_invalid',
'error_code': 'SHIPPING.REVALIDATE_MISSING_CASE_NO',
'message': 'payload 缺少 case_no',
'retryable': False,
},
retryable=False,
owned_attempt=owned_attempt,
)
return
from app.models.shipping_order_review import ShippingOrderReviewCase
case = (
ShippingOrderReviewCase.query
.filter_by(case_no=case_no)
.with_for_update()
.first()
)
TERMINAL_CASE_STATUSES = frozenset({
'confirmed',
'non_order',
'quality_issue',
'superseded',
})
if case is None or case.status in TERMINAL_CASE_STATUSES:
finish_job(
job_id,
result={
'status': 'skipped',
'reason': 'case_not_found_or_terminal',
'case_no': case_no,
'case_status': case.status if case is not None else None,
'operation_id': operation_id,
},
message='Case 不存在或已终态,跳过 Review Revalidate',
owned_attempt=owned_attempt,
)
return
if case.current_draft is None or (
draft_version is not None
and int(case.current_draft.draft_version) != int(draft_version)
):
current_draft_version = (
int(case.current_draft.draft_version)
if case.current_draft is not None
else None
)
finish_job(
job_id,
result={
'status': 'draft_version_superseded',
'reason': 'newer_draft_version_exists',
'frozen_draft_version': draft_version,
'current_draft_version': current_draft_version,
'case_no': case_no,
'operation_id': operation_id,
},
message='Draft 版本已被更新,新版本将有自己的 Revalidate Job',
owned_attempt=owned_attempt,
)
return
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
reconcile_single_case_for_auto_progress,
)
result = reconcile_single_case_for_auto_progress(
case=case,
trigger='review_revalidate_job',
refresh_validation=True,
)
enqueue_status = str(result.get('enqueue_status') or '').strip() or None
step_status = str(result.get('customer_step_status') or '').strip() or None
validate_status = str(result.get('validate_status') or '').strip() or None
all_ok = (
enqueue_status in _SUCCESS_ENQUEUE_STATUSES
or enqueue_status == 'skipped'
or enqueue_status == 'not_scheduled'
)
extra: dict[str, Any] = {
'contract_version': 'shipping-recovery-v1-phase1',
'status': 'ok' if all_ok else 'partial_or_failed',
'enqueue_status': enqueue_status,
'customer_step_status': step_status,
'validate_status': validate_status,
'case_no': case_no,
'draft_version': draft_version,
'operation_id': operation_id,
}
if isinstance(result, dict):
for pass_key in {
'task_no',
'stp_job_id',
'auto_progress_job_id',
'validation_summary',
'can_auto_create',
'can_build',
}:
if pass_key in result:
extra[pass_key] = result[pass_key]
finish_job(
job_id,
result={**dict(result or {}), **extra},
message=str(
result.get('message')
or (
f'Review Revalidate 协调完成(enqueue={enqueue_status}, validate={validate_status}'
)
)[:2000],
owned_attempt=owned_attempt,
)
return
except AppError as exc:
raw_code = str(getattr(exc, 'code', '') or 'SHIPPING.REVALIDATE_APP_ERROR')
raw_message = str(getattr(exc, 'message', str(exc) or '') or 'Revalidate 执行失败')[:1500]
details: dict[str, Any] = {
'case_no': str(frozen.get('case_no') or ''),
'draft_version': frozen.get('draft_version'),
'operation_id': frozen.get('operation_id'),
'error_details': dict(getattr(exc, 'details', None) or {}),
}
retryable, normalized = _classify_revalidate_error(
error_code=raw_code,
message=raw_message,
)
if details:
normalized['blocking_reason_details'] = {
**dict(normalized.get('blocking_reason_details') or {}),
**details,
}
fail_job(
job_id,
error=str(normalized.get('message') or raw_message)[:2000],
result=normalized,
retryable=retryable,
owned_attempt=owned_attempt,
)
return
except Exception as exc: # noqa: BLE001
raw_message = str(exc)[:1500]
raw_code = 'SHIPPING.REVALIDATE_UNEXPECTED'
details = {
'exception_type': type(exc).__name__,
'case_no': str(frozen.get('case_no') or ''),
'draft_version': frozen.get('draft_version'),
'operation_id': frozen.get('operation_id'),
}
category_hint = 'temporary_storage_error'
retryable, normalized = _classify_revalidate_error(
error_code=raw_code,
message=raw_message,
category_hint=category_hint,
)
if details:
normalized['blocking_reason_details'] = {
**dict(normalized.get('blocking_reason_details') or {}),
**details,
}
fail_job(
job_id,
error=str(normalized.get('message') or raw_message)[:2000],
result=normalized,
retryable=retryable,
owned_attempt=owned_attempt,
)
raise
@@ -0,0 +1,291 @@
"""
backend/app/jobs/handlers/shipping_stp_auto_create.py
用途:消费 STP 自动建单 Job,执行 confirm_review_case 与确认后自动推进入队;
按 recovery_contract 统一错误分类,业务阻断(如 NOTICE_EXACT_DUPLICATE)
retryable=false + blocked_manual,技术失败白名单 retryable=true。
依赖:JobContext、order_stp_auto_create_service.execute_stp_auto_create_job、
jobs.queue finish/fail、recovery_contract(is_tech_retryable_error、
build_stp_job_blocked_manual_result / build_stp_job_failed_transient_result、
derive_blocking_next_actions)、fulfillment_audit.emit_stp_auto_create_blocked_manual_audit。
逻辑:由 shipping worker 领取;幂等键保证同一 Case/draft 不重复建单;
成功 finish,附加 task_no / idempotent_replay;
失败统一走 _classify_stp_result:
- 技术白名单 → retryable=true(failed_transient)
- 业务阻断 → retryable=false(blocked_manual + 注入 next_action + 写阻断审计)
"""
from __future__ import annotations
import logging
from typing import Any
from app.extensions import db
from app.jobs.context import JobContext
from app.jobs.queue import fail_job, finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.order_stp_auto_create_service import (
execute_stp_auto_create_job,
)
from app.services.shipping_notice.recovery_contract import (
build_stp_job_blocked_manual_result,
build_stp_job_failed_transient_result,
derive_blocking_next_actions,
is_tech_retryable_error,
)
logger = logging.getLogger(__name__)
def _classify_stp_job_result(
*,
error_code: str,
message: str,
details: dict[str, Any] | None = None,
category_hint: str | None = None,
) -> tuple[bool, dict[str, Any], str | None]:
"""
将 STP 执行失败按 recovery_contract 统一分类,输出 retryable、合并后的 result、next_action。
【AI 触发时机】:Handler 的三条 fail 路径(业务拒绝 ok=False、AppError 兜底、
非预期 Exception 兜底)统一调用,确保 Job.result_json schema 一致。
核心逻辑(fail-closed):
[STEP 1] is_tech_retryable_error(error_code, category_hint) 命中白名单或前缀
→ build_stp_job_failed_transient_result,retryable=True。
[STEP 2] 否则 build_stp_job_blocked_manual_result:
derive_blocking_next_actions 取第一个动作作 next_action,默认 open_order_review;
details 合并至 blocking_reason_details。
[STEP 3] 返回三元组(retryable, normalized_result_dict, next_action)。
Args:
error_code: 业务错误码(SHIPPING.* 或顶层 reason_code)。
message: 人类可读描述。
details: 业务上下文(case_no、existing_task_no、idempotency_key 等),
合并至 blocking_reason_details。
category_hint: 可选;调用方已知的技术分类(worker_timeout 等)。
Returns:
(retryable: bool, normalized_result: dict, next_action: str | None)。
"""
tech = is_tech_retryable_error(error_code, category_hint=category_hint)
if tech:
transient: dict[str, Any] = build_stp_job_failed_transient_result(
error_code=error_code,
message=message,
category_hint=category_hint,
)
if details:
transient['blocking_reason_details'] = {
**dict(transient.get('blocking_reason_details') or {}),
**dict(details),
}
return True, transient, transient.get('next_action')
actions = derive_blocking_next_actions(blocking_reason=error_code)
next_action = actions[0] if actions else 'open_order_review'
blocked: dict[str, Any] = build_stp_job_blocked_manual_result(
error_code=error_code,
message=message,
next_action=next_action,
details=details,
)
return False, blocked, next_action
def _emit_blocked_manual_audit_if_needed(
*,
job_id: int,
retryable: bool,
error_code: str,
next_action: str | None,
payload: dict[str, Any],
details: dict[str, Any] | None,
) -> None:
"""
Phase 1-5:业务阻断时写入 stp_auto_create_blocked_manual 顶层审计。
审计失败只告警,不阻断 Job fail。
"""
if retryable:
return
if not error_code:
return
case_no = str(payload.get('case_no') or '').strip() or None
try:
from app.services.shipping_notice.fulfillment_audit import (
emit_stp_auto_create_blocked_manual_audit,
)
from app.models import ShippingOrderReviewCase
case = None
if case_no:
case = (
ShippingOrderReviewCase.query
.filter_by(case_no=case_no)
.order_by(ShippingOrderReviewCase.id.desc())
.with_entities(ShippingOrderReviewCase)
.first()
)
emit_stp_auto_create_blocked_manual_audit(
case=case,
job_id=int(job_id),
error_code=str(error_code or ''),
next_action=str(next_action or ''),
details={
'payload_case_no': case_no,
**(dict(details) if details else {}),
},
)
db.session.commit()
except Exception: # noqa: BLE001
logger.warning(
'stp_blocked_manual_audit_failed|job_id=%s|case_no=%s|error_code=%s',
int(job_id),
case_no,
str(error_code or ''),
exc_info=True,
)
try:
db.session.rollback()
except Exception:
pass
@register_handler(JobType.SHIPPING_STP_AUTO_CREATE)
def handle_shipping_stp_auto_create(ctx: JobContext, payload: dict) -> None:
"""
执行 STP 自动建单 Job。
核心逻辑:
[STEP 1] 按 job_id 读取冻结 payload 与执行代次(owned_attempt)。
[STEP 2] 委托 execute_stp_auto_create_job 执行业务确认。
[STEP 3] 成功:finish_job,保留 task_no / idempotent_replay / contract_version。
[STEP 4] 业务拒绝 ok=False:_classify_stp_job_result 分类 → 阻断审计 → fail_job。
[STEP 5] AppError 兜底:同上分类 + 审计。
[STEP 6] 非预期 Exception:category_hint=temporary_storage_error(fail-open 倾向重试),
同上分类后 fail_job;最终 re-raise 保持 Worker 心跳。
Args:
ctx: Worker 上下文;当前执行体不依赖请求上下文。
payload: Worker 载荷,必须含 job_id;业务字段以 Job.payload_json 为准。
Returns:
None。
"""
_ = ctx
raw_job_id = payload.get('job_id') if isinstance(payload, dict) else None
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
if job is None:
raise RuntimeError('missing_stp_auto_create_job_id')
job_id = int(job.id)
owned_attempt = int(job.attempts or 0)
frozen = dict(job.payload_json or {})
frozen.setdefault('job_id', job_id)
try:
result = execute_stp_auto_create_job(payload=frozen, job_id=job_id)
if result.get('ok'):
extra: dict[str, Any] = {
'contract_version': 'shipping-recovery-v1-phase1',
'status': 'ok',
}
if result.get('task_no'):
extra['task_no'] = str(result.get('task_no') or '')
if result.get('idempotent_replay'):
extra['idempotent_replay'] = True
if result.get('auto_progress_status'):
extra['auto_progress_status'] = str(result.get('auto_progress_status') or '')
finish_job(
job_id,
result={**dict(result), **extra},
message=str(result.get('message') or 'STP 自动建单完成'),
owned_attempt=owned_attempt,
)
return
message = str(
result.get('message')
or result.get('error')
or result.get('error_code')
or 'STP 自动建单失败'
) or 'STP 自动建单失败'
error_code = str(
result.get('error_code')
or result.get('code')
or 'SHIPPING.STP_AUTO_CREATE_FAILED'
) or 'SHIPPING.STP_AUTO_CREATE_FAILED'
details: dict[str, Any] = {
k: v for k, v in result.items() if k in {
'task_no',
'existing_task_no',
'existing_notice_no',
'source_content_hash',
'duplicate_of',
'confirmation_mode',
'reused_task_id',
'reused_notice_id',
'idempotency_key',
'case_no',
'run_no',
'details',
}
}
details.setdefault('payload_case_no', str(frozen.get('case_no') or ''))
details.setdefault('payload_run_no', str(frozen.get('run_no') or ''))
retryable, normalized, next_action = _classify_stp_job_result(
error_code=error_code,
message=message,
details=details,
)
_emit_blocked_manual_audit_if_needed(
job_id=job_id,
retryable=retryable,
error_code=error_code,
next_action=next_action,
payload=frozen,
details=details,
)
fail_job(
job_id,
error=str(normalized.get('message') or message)[:2000],
result=normalized,
retryable=retryable,
owned_attempt=owned_attempt,
)
return
except Exception as exc: # noqa: BLE001
raw_message = str(exc)[:1500]
raw_code = 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED'
details = {
'exception_type': type(exc).__name__,
'payload_case_no': str(frozen.get('case_no') or ''),
'payload_run_no': str(frozen.get('run_no') or ''),
}
# [PARAM_TUNING] 非预期异常默认归类为临时存储/基础设施失败,
# 倾向可重试;若是业务阻断性异常(如 IntegrityError 唯一冲突),
# 真实错误码已在业务层捕获并走 ok=False 路径,不会流入此兜底。
category_hint = 'temporary_storage_error'
retryable, normalized, next_action = _classify_stp_job_result(
error_code=raw_code,
message=raw_message,
details=details,
category_hint=category_hint,
)
_emit_blocked_manual_audit_if_needed(
job_id=job_id,
retryable=retryable,
error_code=raw_code,
next_action=next_action,
payload=frozen,
details=details,
)
fail_job(
job_id,
error=str(normalized.get('message') or raw_message)[:2000],
result=normalized,
retryable=retryable,
owned_attempt=owned_attempt,
)
raise
@@ -0,0 +1,82 @@
"""
backend/app/jobs/handlers/shipping_xfa_ocr_automark.py
用途:异步执行 XFA OCR 自动标记(原生 PDF/PDFium 页图),产出 suggested visual_bindings(不自动 confirmed)。
依赖:Job queue、order_document_profile_xfa_automark_service(执行体)、JobType。
逻辑:由 shipping worker 领取;payload 含 profile_id/document_id/preview_render_checksum;
不再依赖 /xfa/preview synthetic;空白壳返回空建议成功;OCR 不可用时 fail_job。
"""
from __future__ import annotations
from app.extensions import db
from app.jobs.context import JobContext
from app.jobs.queue import fail_job, finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import Job
@register_handler(JobType.SHIPPING_XFA_OCR_AUTOMARK)
def run_shipping_xfa_ocr_automark(ctx: JobContext, payload: dict) -> None:
"""
执行 XFA OCR 自动标记 Job。
核心逻辑:读取冻结 Job 载荷 → 委托 automark_service.execute_xfa_ocr_automark_job →
finish/fail。OCR 引擎不可用时不可重试(明确业务码)。
Args:
ctx: Worker 上下文(堆栈仅运维可见)。
payload: 须含 job_id;业务字段在 Job.payload_json。
Returns:
None。
"""
_ = ctx
raw_job_id = payload.get('job_id')
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
if job is None:
return
owned_attempt = int(job.attempts or 0)
frozen = dict(job.payload_json or {})
frozen.setdefault('job_id', int(job.id))
from app.services.shipping_notice import order_document_profile_xfa_automark_service as automark_service
try:
result = automark_service.execute_xfa_ocr_automark_job(frozen)
except automark_service.XfaOcrAutomarkError as exc:
fail_job(
job.id,
error=str(exc.message or exc)[:500],
result={
'status': 'failed',
'error_code': exc.error_code,
'preview_render_checksum': frozen.get('preview_render_checksum'),
'details': dict(exc.details or {}),
},
retryable=bool(exc.retryable),
owned_attempt=owned_attempt,
)
return
except Exception as exc: # noqa: BLE001 — 未知异常走可重试失败
fail_job(
job.id,
error=str(exc)[:500],
result={
'status': 'failed',
'error_code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_AUTOMARK_FAILED',
'preview_render_checksum': frozen.get('preview_render_checksum'),
},
retryable=True,
owned_attempt=owned_attempt,
)
return
finish_job(
job.id,
result=result,
message='XFA OCR automark completed',
owned_attempt=owned_attempt,
)
+50 -6
View File
@@ -143,7 +143,7 @@ def _is_safe_supersede_target(sibling: Job, *, cancelled_job: Job) -> bool:
if status != "running":
return False
from app.models import ShippingNoticeIntake
from app.models import ShippingOrderIntake
intake_no = str(
(cancelled_job.payload_json or {}).get("intake_no")
@@ -154,8 +154,8 @@ def _is_safe_supersede_target(sibling: Job, *, cancelled_job: Job) -> bool:
if not intake_no:
return False
locked = (
db.session.query(ShippingNoticeIntake)
.filter(ShippingNoticeIntake.intake_no == intake_no)
db.session.query(ShippingOrderIntake)
.filter(ShippingOrderIntake.intake_no == intake_no)
.execution_options(populate_existing=True)
.with_for_update()
.first()
@@ -210,7 +210,7 @@ def _retarget_intake_parse_job_after_supersede(
"""
if not _subject_to_parse_queued_unique(str(cancelled_job.job_type or "")):
return
from app.models import ShippingNoticeIntake
from app.models import ShippingOrderIntake
intake_no = str(
(cancelled_job.payload_json or {}).get("intake_no")
@@ -227,8 +227,8 @@ def _retarget_intake_parse_job_after_supersede(
return
locked = (
db.session.query(ShippingNoticeIntake)
.filter(ShippingNoticeIntake.intake_no == intake_no)
db.session.query(ShippingOrderIntake)
.filter(ShippingOrderIntake.intake_no == intake_no)
.execution_options(populate_existing=True)
.with_for_update()
.first()
@@ -387,6 +387,11 @@ def enqueue(
commit: bool = True,
correlation_id: str | None = None,
scheduled_at: Any = None,
task_id: int | None = None,
execution_id: int | None = None,
gate_id: int | None = None,
candidate_set_id: int | None = None,
fencing_token: str | None = None,
) -> int:
"""
将任务写入通用 jobs 队列并返回 job id。
@@ -411,6 +416,9 @@ def enqueue(
commit: False 时仅 flush,由调用方与业务行同一事务提交。
correlation_id: 兼容旧接口;business_ref 为空时作为业务锚点。
scheduled_at: 未来时间则延迟到该时间后才可被 worker 领取。
task_id / execution_id / gate_id / candidate_set_id: 正式业务作用域;AutoProgress
使用这些列实施 Task 级活动唯一与版本围栏。
fencing_token: Worker 领取前写入的代次围栏;迟到副作用必须比对。
"""
normalized_type = _normalize_job_type(job_type)
if normalized_type in {JobType.KB_CLEAN.value, JobType.KB_DIFY_SYNC.value}:
@@ -464,6 +472,11 @@ def enqueue(
attempts=0,
max_attempts=max(1, int(max_attempts or 1)),
created_by_id=created_by_id,
task_id=task_id,
execution_id=execution_id,
gate_id=gate_id,
candidate_set_id=candidate_set_id,
fencing_token=fencing_token,
created_at=queue_at,
updated_at=now,
)
@@ -727,6 +740,23 @@ def _sync_parse_intake_after_job_mutation(job_id: int) -> None:
sync_intake_after_parse_job_recovery(job)
def _sync_shipping_order_extraction_run_after_job_failure(job_id: int) -> None:
"""将最终失败的订单抽取 Job 收口到对应 Run,避免用户界面永久轮询。"""
job = db.session.get(Job, int(job_id))
if job is None or str(job.job_type or '') != JobType.SHIPPING_ORDER_EXTRACTION.value:
return
db.session.expire(job)
db.session.refresh(job)
if str(job.status or '') != 'failed':
return
from app.services.shipping_notice.order_extraction_run_service import (
sync_order_extraction_run_after_job_failure,
)
sync_order_extraction_run_after_job_failure(job)
def finish_job(
job: Job | int,
*,
@@ -934,6 +964,8 @@ def fail_job(
rowcount = int(db.session.execute(fail_stmt).rowcount or 0)
if rowcount == 1:
_sync_parse_intake_after_job_mutation(job_id)
# 订单抽取的用户态以 Run 为准;Job 耗尽重试后必须同事务收口。
_sync_shipping_order_extraction_run_after_job_failure(job_id)
db.session.commit()
_expire_cached()
return rowcount == 1
@@ -977,6 +1009,18 @@ def process_next_job(
)
on_recovered = sync_intake_after_parse_job_recovery
elif normalized_type == JobType.SHIPPING_ORDER_EXTRACTION.value:
from app.services.shipping_notice.order_extraction_run_service import (
sync_order_extraction_run_after_job_recovery,
)
on_recovered = sync_order_extraction_run_after_job_recovery
elif normalized_type == JobType.SHIPPING_DOCUMENT_LAYOUT.value:
from app.services.shipping_notice.document_layout.lifecycle import (
sync_layout_after_job_recovery,
)
on_recovered = sync_layout_after_job_recovery
recover_stale_jobs(
domain=domain,
timeout_seconds=timeout_seconds,
+58 -3
View File
@@ -7,7 +7,7 @@ backend/app/jobs/runner.py
from __future__ import annotations
import time
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Callable
from app.jobs import store
from app.jobs.registry import get_handler
@@ -26,21 +26,49 @@ def _resolve_poll_seconds(ctx: JobContext) -> float:
return float(ctx.config.get('KB_WORKER_POLL_SECONDS', 2))
def run_forever(ctx: JobContext, *, poll_interval_seconds: float | None = None) -> None:
def run_forever(
ctx: JobContext,
*,
poll_interval_seconds: float | None = None,
recovery_callback: Callable[[], int] | None = None,
recovery_interval_seconds: float = 60.0,
) -> None:
"""
持续轮询并执行任务。
核心逻辑:claim_next → get_handler → handler(ctx, payload);异常时 mark_failed。
支持 recovery_callback:启动立即执行一次,空闲睡眠和 claim 后检查 tick。
Args:
ctx: Worker 上下文(extras.queues 指定消费队列)。
poll_interval_seconds: 无任务时的休眠秒数;默认按队列读 config。
recovery_callback: 恢复回调函数,返回本轮处理计数;默认 None 关闭。
recovery_interval_seconds: 两次 recovery tick 的最小间隔秒数;默认 60。
"""
queues = ctx.extras.get('queues') or ['kb']
poll = poll_interval_seconds if poll_interval_seconds is not None else _resolve_poll_seconds(ctx)
ctx.logger.info('Job runner started queues=%s poll_seconds=%s', queues, poll)
ctx.logger.info('Job runner started queues=%s poll_seconds=%s recovery=%s',
queues, poll, recovery_callback is not None)
if recovery_callback is not None:
try:
recovery_callback()
except Exception:
ctx.logger.exception('Recovery callback failed on BOOT')
finally:
last_recovery_ts = time.monotonic()
else:
last_recovery_ts = time.monotonic()
while True:
job = store.claim_next(queues=queues)
if not job:
current_ts = time.monotonic()
if recovery_callback is not None and (current_ts - last_recovery_ts) >= recovery_interval_seconds:
try:
recovery_callback()
except Exception:
ctx.logger.exception('Recovery callback failed during idle poll')
finally:
last_recovery_ts = current_ts
time.sleep(poll)
continue
@@ -54,14 +82,41 @@ def run_forever(ctx: JobContext, *, poll_interval_seconds: float | None = None)
message=f'no handler for {job.get("job_type")}',
owned_attempt=owned_attempt_int,
)
if recovery_callback is not None:
current_ts = time.monotonic()
if (current_ts - last_recovery_ts) >= recovery_interval_seconds:
try:
recovery_callback()
except Exception:
ctx.logger.exception('Recovery callback failed after no-handler job')
finally:
last_recovery_ts = current_ts
continue
try:
handler(ctx, job.get('payload') or {})
except Exception as exc:
ctx.logger.exception('Handler failed job_id=%s', job.get('id'))
# Handler 可能在 flush/写库失败后留下 aborted transaction;先回滚,
# 再查询并收口 Job,否则 mark_failed 自身会被 InFailedSqlTransaction 阻断。
try:
from app import db
db.session.rollback()
except Exception:
ctx.logger.exception('Session rollback failed after handler job_id=%s', job.get('id'))
store.mark_failed(
job['id'],
message=str(exc),
owned_attempt=owned_attempt_int,
)
finally:
if recovery_callback is not None:
current_ts = time.monotonic()
if (current_ts - last_recovery_ts) >= recovery_interval_seconds:
try:
recovery_callback()
except Exception:
ctx.logger.exception('Recovery callback failed after job execution')
finally:
last_recovery_ts = current_ts
+1 -1
View File
@@ -75,7 +75,7 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
from app.services.knowledge_cleaning.queue_service import recover_stale_running_jobs
recover_stale_running_jobs()
if 'shipping_notice_run' in allowed_types or 'shipping_notice_parse' in allowed_types:
if allowed_types & QUEUE_KB_JOB_TYPES['shipping']:
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
recover_stale_shipping_notice_jobs()
+6 -1
View File
@@ -11,7 +11,7 @@ from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, Index, JSON, String, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base, user_agent_permissions
@@ -25,6 +25,11 @@ class Agent(Base):
"""
__tablename__ = 'agents'
__table_args__ = (
Index('uq_agents_one_active_shipping_notice', 'agent_code', unique=True,
postgresql_where=text("agent_code = 'shipping_notice' AND is_active = true"),
sqlite_where=text("agent_code = 'shipping_notice' AND is_active = 1")),
)
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100))
+1 -1
View File
@@ -3,7 +3,7 @@ backend/app/models/file_asset.py
用途:平台级通用文件资产模型,承载私有 MinIO 存储元数据与生命周期。
依赖:models.base.Base。
逻辑:由 file_assets.service 创建与更新;ShippingNoticeIntake 经 asset_id 引用上传根资产;
逻辑:由 file_assets.service 创建与更新;ShippingOrderIntake 经 asset_id 引用上传根资产;
EML 解析后的订单附件以 parent_asset_id 挂为 derived 子资产(阶段二);
派生资产对 (parent_asset_id, content_hash) 使用未删除行的部分唯一索引。
"""
+107
View File
@@ -29,6 +29,26 @@ class Job(Base):
Index('ix_jobs_type_status_created', 'job_type', 'status', 'created_at'),
Index('ix_jobs_business_ref', 'domain', 'job_type', 'business_ref'),
Index('ix_jobs_locked_at', 'locked_at'),
Index('ix_jobs_retry_of_job_id', 'retry_of_job_id'),
# P0-3:同一 Task 同时只允许一个正式 AutoProgress 决策 Job。库存源 RPA
# Attempt 不使用该索引,因此可以按 source 并行执行。
Index(
'uq_jobs_shipping_auto_progress_one_active_task',
'task_id',
unique=True,
postgresql_where=text(
"domain = 'shipping_notice' "
"AND job_type = 'shipping_auto_progress' "
"AND status IN ('queued', 'running') "
"AND task_id IS NOT NULL"
),
sqlite_where=text(
"domain = 'shipping_notice' "
"AND job_type = 'shipping_auto_progress' "
"AND status IN ('queued', 'running') "
"AND task_id IS NOT NULL"
),
),
# 仅预解析 Job:同业务锚点同时只允许一条 queued
# (不含 running:retry 可在旧 running 残留时另建 queued;RUN 复查也不受限)
Index(
@@ -48,6 +68,78 @@ class Job(Base):
"AND business_ref IS NOT NULL"
),
),
Index(
'uq_jobs_shipping_order_extraction_active_ref',
'domain',
'job_type',
'business_ref',
unique=True,
postgresql_where=text(
"job_type = 'shipping_order_extraction' "
"AND status IN ('queued', 'running') "
"AND business_ref IS NOT NULL"
),
sqlite_where=text(
"job_type = 'shipping_order_extraction' "
"AND status IN ('queued', 'running') "
"AND business_ref IS NOT NULL"
),
),
Index(
'uq_jobs_shipping_document_layout_active_ref',
'domain',
'job_type',
'business_ref',
unique=True,
postgresql_where=text(
"job_type = 'shipping_document_layout' "
"AND status IN ('queued', 'running') "
"AND business_ref IS NOT NULL"
),
sqlite_where=text(
"job_type = 'shipping_document_layout' "
"AND status IN ('queued', 'running') "
"AND business_ref IS NOT NULL"
),
),
# STP 自动建单:同幂等键同时只允许一条 queued/running(failed 可保留审计并新建重试 Job)
Index(
'uq_jobs_shipping_stp_auto_create_active_ref',
'domain',
'job_type',
'business_ref',
unique=True,
postgresql_where=text(
"job_type = 'shipping_stp_auto_create' "
"AND status IN ('queued', 'running') "
"AND business_ref IS NOT NULL"
),
sqlite_where=text(
"job_type = 'shipping_stp_auto_create' "
"AND status IN ('queued', 'running') "
"AND business_ref IS NOT NULL"
),
),
# Review Revalidate Job:同 Case 同时只允许一条 queued/running(failed 可新建重试 Job)
Index(
'uq_jobs_shipping_review_revalidate_progress_active_ref',
'domain',
'job_type',
'business_ref',
unique=True,
postgresql_where=text(
"domain = 'shipping_notice' "
"AND job_type = 'shipping_review_revalidate_progress' "
"AND status IN ('queued', 'running') "
"AND business_ref IS NOT NULL"
),
sqlite_where=text(
"domain = 'shipping_notice' "
"AND job_type = 'shipping_review_revalidate_progress' "
"AND status IN ('queued', 'running') "
"AND business_ref IS NOT NULL"
),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -65,6 +157,20 @@ class Job(Base):
max_attempts: Mapped[int] = mapped_column(Integer, default=3)
locked_by: Mapped[Optional[str]] = mapped_column(String(128))
locked_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
# 重试链:新 Job 指向被替换的 failed/dead Job,保留旧行审计。
retry_of_job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True)
# 正式编排作用域。payload 仍保留相同 identity,列用于数据库唯一约束、恢复扫描和审计查询。
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True, index=True)
execution_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_process_executions.id'), nullable=True, index=True,
)
gate_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_process_gates.id'), nullable=True, index=True,
)
candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id'), nullable=True, index=True,
)
fencing_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
@@ -72,3 +178,4 @@ class Job(Base):
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
created_by: Mapped[Optional['User']] = relationship('User', foreign_keys=[created_by_id])
retry_of_job: Mapped[Optional['Job']] = relationship('Job', remote_side=[id], foreign_keys=[retry_of_job_id])
+336 -156
View File
@@ -1,22 +1,30 @@
"""
backend/app/models/shipping.py
用途:货代发货通知批次、任务、事件、库存文件、接入记录、文档/候选与库存映射模型。
依赖:models.base.Base。
逻辑:ShippingBatch.create_idempotency_key 为建单幂等;ShippingTask.idempotency_key 为货代上传幂等;
用途:货代发货通知正式 Notice(shipping_notices)、事件、库存文件、接入记录、文档/候选与库存映射模型。
依赖:models.base.Base;规范订单行见 shipping_task_line;建单前 OT 见 shipping_order_task。
逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列;
Intake 消费绑定仅保留 consumed_task_id / consumed_at;upload_batch_id 为上传边界批次(非 shipping_batches);
ShippingNotice.idempotency_key 为货代上传幂等;
Intake.create_idempotency_key 承载混合/open_existing 确认请求重放;
Intake/Task/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离;
Document/Candidate 承载阶段二「一邮件多订单」识别;ShippingTask.source_candidate_id 预留给建单;
ShippingTask.supersedes_task_id 唯一约束保证修订链线性。
Intake/Notice/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离;
Document/Candidate 承载「一邮件多订单」识别;ShippingNotice.source_candidate_id 记录正式建单来源;
ShippingNotice.order_task_id 挂接建单前 OT(shipping_order_tasks);ShippingNotice.supersedes_task_id 唯一约束保证修订链线性;
order_data_version 为冻结前 Candidate/Extraction 纠错的乐观锁版本;
current_order_extraction_id 追溯解析事实,order_snapshot_id 指向不可变履约事实;
阶段 1:Intake.source_type / order_submission_id 挂接 shipping_order_submissions;
建单前接入层表名为 shipping_order_intakes / documents / candidates(类名 ShippingOrder*)。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import List, Optional
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
Float,
ForeignKey,
@@ -34,70 +42,40 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingBatch(Base):
"""货代发货通知批次(一次多文件上传的聚合容器)"""
class ShippingNotice(Base):
"""
正式发货通知(Candidate 建单后的履约实体)。
__tablename__ = 'shipping_batches'
核心逻辑:Chatflow Tool 编排状态机;建单前 OT 聚合根见 ShippingOrderTask(shipping_order_tasks)。
"""
__tablename__ = 'shipping_notices'
__table_args__ = (
Index('ix_shipping_batches_user_created', 'user_id', 'created_at'),
Index('ix_shipping_batches_conversation', 'conversation_id'),
UniqueConstraint(
'user_id',
'create_idempotency_key',
name='uq_shipping_batches_user_create_idempotency',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
batch_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
current_focus_task_no: Mapped[Optional[str]] = mapped_column(
String(64),
ForeignKey(
'shipping_tasks.task_no',
name='fk_shipping_batches_current_focus_task_no_shipping_tasks',
use_alter=True,
),
nullable=True,
)
file_count: Mapped[int] = mapped_column(Integer, default=1)
create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
process_summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
tasks: Mapped[List['ShippingTask']] = relationship(
'ShippingTask',
back_populates='batch',
foreign_keys='ShippingTask.batch_id',
)
class ShippingTask(Base):
"""货代发货通知 task(Chatflow Tool 编排状态机)"""
__tablename__ = 'shipping_tasks'
__table_args__ = (
Index('ix_shipping_tasks_user_status', 'user_id', 'process_status'),
Index('ix_shipping_tasks_conversation', 'conversation_id'),
Index('ix_shipping_tasks_batch_step', 'batch_id', 'current_step'),
Index('ix_shipping_tasks_upload_status', 'upload_status'),
Index('ix_shipping_tasks_inventory_source_code', 'inventory_source_code'),
Index('ix_shipping_tasks_inventory_site_id', 'inventory_site_id'),
Index('ix_shipping_tasks_inventory_source_status', 'inventory_source_status'),
Index('ix_shipping_tasks_inventory_routing_fingerprint', 'inventory_routing_fingerprint'),
Index('ix_shipping_tasks_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'),
Index('ix_shipping_tasks_user_source_content_hash', 'user_id', 'source_content_hash'),
Index('ix_shipping_tasks_user_business_fingerprint', 'user_id', 'business_fingerprint'),
Index('ix_shipping_notices_user_status', 'user_id', 'process_status'),
Index('ix_shipping_notices_conversation', 'conversation_id'),
Index('ix_shipping_notices_current_step', 'current_step'),
Index('ix_shipping_notices_upload_status', 'upload_status'),
Index('ix_shipping_notices_inventory_source_code', 'inventory_source_code'),
Index('ix_shipping_notices_inventory_source_status', 'inventory_source_status'),
Index('ix_shipping_notices_inventory_routing_fingerprint', 'inventory_routing_fingerprint'),
Index('ix_shipping_notices_active_inventory_candidate_set_id', 'active_inventory_candidate_set_id'),
Index('ix_shipping_notices_active_process_execution_id', 'active_process_execution_id'),
Index('ix_shipping_notices_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'),
Index('ix_shipping_notices_user_source_content_hash', 'user_id', 'source_content_hash'),
Index('ix_shipping_notices_user_business_fingerprint', 'user_id', 'business_fingerprint'),
Index('ix_shipping_notices_user_content_fingerprint', 'user_id', 'content_fingerprint'),
# 线性版本链:同一父任务至多一个后继(NULL 不冲突)
UniqueConstraint('supersedes_task_id', name='uq_shipping_tasks_supersedes_task_id'),
Index('ix_shipping_tasks_duplicate_source_task_id', 'duplicate_source_task_id'),
UniqueConstraint('supersedes_task_id', name='uq_shipping_notices_supersedes_task_id'),
Index('ix_shipping_notices_duplicate_source_task_id', 'duplicate_source_task_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), index=True, nullable=True)
shipping_case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_cases.id'),
index=True,
nullable=True,
)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
source_type: Mapped[str] = mapped_column(String(32), default='manual')
@@ -106,29 +84,40 @@ class ShippingTask(Base):
source_content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=True)
source_intake_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notice_intakes.id'),
ForeignKey('shipping_order_intakes.id'),
index=True,
nullable=True,
)
# 阶段二:由 Candidate 正式建单时回填;与 Candidate.consumed_task_id 对向引用,用 use_alter
source_candidate_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_notice_candidates.id',
name='fk_shipping_tasks_source_candidate_id',
'shipping_order_candidates.id',
name='fk_shipping_notices_source_candidate_id',
use_alter=True,
),
index=True,
nullable=True,
)
order_task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_order_tasks.id',
name='fk_shipping_notices_order_task_id',
use_alter=True,
),
nullable=True,
index=True,
)
business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
content_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
content_fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
document_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
supersedes_task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_tasks.id'),
ForeignKey('shipping_notices.id'),
nullable=True,
)
duplicate_source_task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_tasks.id'),
ForeignKey('shipping_notices.id'),
nullable=True,
)
duplicate_override_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
@@ -137,16 +126,17 @@ class ShippingTask(Base):
batch_total: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
raw_content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
customer_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
customer_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
ship_to: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
customer_resolution_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
customer_resolution_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
customer_identity_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
customer_confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
customer_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
destination_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
destination_city: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
destination_country: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
warehouse_hint: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
inventory_site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_connector_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_source_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
inventory_source_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
@@ -154,11 +144,52 @@ class ShippingTask(Base):
inventory_source_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
inventory_source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
inventory_routing_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
active_inventory_candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_inventory_candidate_sets.id',
name='fk_shipping_notices_active_inventory_candidate_set_id',
use_alter=True,
),
nullable=True,
)
# P0-3:当前业务真相只由此 Execution 的六个正式 Gate 决定;历史 Execution 保留审计。
active_process_execution_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_process_executions.id',
name='fk_shipping_notices_active_process_execution_id',
use_alter=True,
),
nullable=True,
)
inventory_rpa_consumed_run_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
required_date: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
lines_json: Mapped[Optional[list]] = mapped_column(JSON, default=list)
parse_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
# 动态订单 FieldValue 编辑的乐观锁版本。
order_data_version: Mapped[int] = mapped_column(
Integer,
default=1,
server_default=text('1'),
nullable=False,
)
current_order_extraction_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_order_extractions.id',
name='fk_shipping_notices_current_order_extraction_id',
use_alter=True,
),
nullable=True,
index=True,
)
# 阶段 1:库存、导出和上传必须通过此指针读取冻结订单快照。
order_snapshot_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_order_snapshots.id',
name='fk_shipping_notices_order_snapshot_id',
use_alter=True,
),
nullable=True,
unique=True,
index=True,
)
process_status: Mapped[str] = mapped_column(String(32), default='created', index=True)
current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
@@ -186,19 +217,40 @@ class ShippingTask(Base):
pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
# 任务处置与流程状态正交:process_status 继续驱动履约工作流,生命周期负责作废/归档。
lifecycle_status: Mapped[str] = mapped_column(
String(16),
nullable=False,
default='active',
server_default=text("'active'"),
index=True,
)
deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
deleted_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
deletion_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
voided_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
voided_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
void_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
archived_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
archived_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
batch: Mapped[Optional['ShippingBatch']] = relationship(
'ShippingBatch',
shipping_case: Mapped[Optional['ShippingCase']] = relationship(
'ShippingCase',
back_populates='tasks',
foreign_keys=[batch_id],
lazy='joined',
)
events: Mapped[List['ShippingTaskEvent']] = relationship(
'ShippingTaskEvent',
back_populates='task',
cascade='all, delete-orphan',
)
field_conflicts: Mapped[List['ShippingTaskFieldConflict']] = relationship(
'ShippingTaskFieldConflict',
back_populates='task',
cascade='all, delete-orphan',
)
class ShippingTaskEvent(Base):
@@ -207,12 +259,32 @@ class ShippingTaskEvent(Base):
__tablename__ = 'shipping_task_events'
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), index=True)
event_type: Mapped[str] = mapped_column(String(64), index=True)
detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
before_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
after_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True, index=True)
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
task: Mapped['ShippingTask'] = relationship('ShippingTask', back_populates='events')
task: Mapped['ShippingNotice'] = relationship('ShippingNotice', back_populates='events')
class ShippingTaskPurgeAudit(Base):
"""任务永久删除后的独立快照审计;不保留 task 外键以允许物理清除。"""
__tablename__ = 'shipping_task_purge_audits'
__table_args__ = (Index('ix_shipping_task_purge_audits_task_no_created', 'task_no_snapshot', 'created_at'),)
id: Mapped[int] = mapped_column(primary_key=True)
task_no_snapshot: Mapped[str] = mapped_column(String(64), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
reason: Mapped[str] = mapped_column(Text, nullable=False)
snapshot_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
class ShippingInventoryFile(Base):
@@ -220,7 +292,6 @@ class ShippingInventoryFile(Base):
__tablename__ = 'shipping_inventory_files'
__table_args__ = (
Index('ix_shipping_inventory_files_batch_created', 'batch_id', 'created_at'),
Index('ix_shipping_inventory_files_user_created', 'user_id', 'created_at'),
Index(
'ix_shipping_inventory_files_source_snapshot',
@@ -230,32 +301,44 @@ class ShippingInventoryFile(Base):
'exported_at',
),
Index(
'ix_shipping_inventory_files_source_site_wh',
'ix_shipping_inventory_files_source_warehouse',
'source_code',
'site_id',
'warehouse_id',
),
Index(
'uq_shipping_inventory_files_rpa_identity_ready',
'rpa_run_no',
'source_code',
'site_id',
'warehouse_id',
unique=True,
postgresql_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND site_id IS NOT NULL AND warehouse_id IS NOT NULL"
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
),
sqlite_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND site_id IS NOT NULL AND warehouse_id IS NOT NULL"
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
),
),
# 动态多仓文件没有单一 Warehouse;按 RPA run + Source 保证回调重放幂等。
Index(
'uq_shipping_inventory_files_rpa_dynamic_source_ready',
'rpa_run_no',
'source_code',
unique=True,
postgresql_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
),
sqlite_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
inventory_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), index=True, nullable=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
storage_path: Mapped[str] = mapped_column(String(500), nullable=False)
@@ -268,7 +351,6 @@ class ShippingInventoryFile(Base):
share_mode: Mapped[str] = mapped_column(String(32), default='task_only')
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
@@ -279,10 +361,18 @@ class ShippingInventoryFile(Base):
rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True)
source_query_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
batch: Mapped[Optional['ShippingBatch']] = relationship('ShippingBatch', foreign_keys=[batch_id])
links: Mapped[List['ShippingTaskInventoryLink']] = relationship(
'ShippingTaskInventoryLink',
back_populates='inventory_file',
@@ -301,12 +391,11 @@ class ShippingTaskInventoryLink(Base):
'ix_shipping_task_inventory_links_task_source',
'task_id',
'matched_source_code',
'matched_site_id',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), index=True)
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id'), index=True)
link_role: Mapped[str] = mapped_column(String(32), default='member')
access_mode: Mapped[str] = mapped_column(String(32), default='readonly')
@@ -314,15 +403,20 @@ class ShippingTaskInventoryLink(Base):
link_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
matched_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
matched_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
matched_site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
identity_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', use_alter=True), nullable=True, index=True)
source_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_source_attempts.id', use_alter=True), nullable=True, index=True)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
audit_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
linked_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
task: Mapped['ShippingTask'] = relationship('ShippingTask', foreign_keys=[task_id])
task: Mapped['ShippingNotice'] = relationship('ShippingNotice', foreign_keys=[task_id])
inventory_file: Mapped['ShippingInventoryFile'] = relationship(
'ShippingInventoryFile',
back_populates='links',
@@ -330,25 +424,41 @@ class ShippingTaskInventoryLink(Base):
)
class ShippingNoticeIntake(Base):
"""发货通知预解析接入记录(上传成功至正式建单前的异步解析阶段)。"""
class ShippingOrderIntake(Base):
"""
发货通知接入记录:分别跟踪文件预处理与订单抽取状态。
__tablename__ = 'shipping_notice_intakes'
阶段 1:source_type=eml|direct_pdf 标识裁决边界;order_submission_id 挂接上传 Submission。
表名 shipping_order_intakes(建单前接入层)。
"""
__tablename__ = 'shipping_order_intakes'
__table_args__ = (
UniqueConstraint('intake_no', name='uq_shipping_notice_intakes_intake_no'),
CheckConstraint(
"purpose IN ('shipping_notice', 'order_document_profile_sample')",
name='ck_shipping_order_intakes_purpose',
),
CheckConstraint(
"source_type IS NULL OR source_type IN ('eml', 'direct_pdf')",
name='ck_shipping_order_intakes_source_type',
),
UniqueConstraint('intake_no', name='uq_shipping_order_intakes_intake_no'),
UniqueConstraint(
'asset_id',
'purpose',
'parser_version',
name='uq_shipping_notice_intakes_asset_purpose_parser',
name='uq_shipping_order_intakes_asset_purpose_parser',
),
Index('ix_shipping_notice_intakes_user_conversation_created', 'user_id', 'conversation_id', 'created_at'),
Index('ix_shipping_notice_intakes_parse_status_created', 'parse_status', 'created_at'),
Index('ix_shipping_notice_intakes_expires', 'expires_at'),
Index('ix_shipping_notice_intakes_user_business_fingerprint', 'user_id', 'business_fingerprint'),
Index('ix_shipping_notice_intakes_duplicate_status_created', 'duplicate_status', 'created_at'),
Index('ix_shipping_notice_intakes_fp_version_fingerprint', 'fingerprint_version', 'business_fingerprint'),
Index('ix_shipping_notice_intakes_user_create_idempotency', 'user_id', 'create_idempotency_key'),
Index('ix_shipping_order_intakes_user_conversation_created', 'user_id', 'conversation_id', 'created_at'),
Index('ix_shipping_order_intakes_user_upload_batch_created', 'user_id', 'upload_batch_id', 'created_at'),
Index('ix_shipping_order_intakes_parse_status_created', 'parse_status', 'created_at'),
Index('ix_shipping_order_intakes_expires', 'expires_at'),
Index('ix_shipping_order_intakes_user_business_fingerprint', 'user_id', 'business_fingerprint'),
Index('ix_shipping_order_intakes_duplicate_status_created', 'duplicate_status', 'created_at'),
Index('ix_shipping_order_intakes_fp_version_fingerprint', 'fingerprint_version', 'business_fingerprint'),
Index('ix_shipping_order_intakes_user_create_idempotency', 'user_id', 'create_idempotency_key'),
Index('ix_shipping_order_intakes_source_type', 'source_type'),
Index('ix_shipping_order_intakes_order_submission_id', 'order_submission_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -356,8 +466,26 @@ class ShippingNoticeIntake(Base):
asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=False)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True, nullable=False)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
# 同一输入框一次选取的上传批次;发送端只能冻结同一批次的 Intake。
upload_batch_id: Mapped[str] = mapped_column(String(36), nullable=False, default=lambda: str(uuid.uuid4()))
# 上传边界 Submission(阶段 1);与 OT 发送决策 submission 分离。
order_submission_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_submissions.id'),
nullable=True,
)
# eml = 一份邮件裁决边界;direct_pdf = 一份直接 PDF;其它类型暂 NULL。
source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
purpose: Mapped[str] = mapped_column(String(32), default='shipping_notice', nullable=False)
parse_status: Mapped[str] = mapped_column(String(32), default='created', nullable=False, index=True)
order_extraction_status: Mapped[str] = mapped_column(
String(32),
default='not_started',
server_default=text("'not_started'"),
nullable=False,
index=True,
)
order_extraction_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
order_extraction_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
extracted_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
structured_result_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
parse_warnings_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
@@ -384,39 +512,37 @@ class ShippingNoticeIntake(Base):
duplicate_resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
consumed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
consumed_batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), nullable=True)
consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True)
# co8e9f0a1b2c 已 DROP shipping_batches 与 consumed_batch_id;消费绑定仅保留任务侧。
consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True)
create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
class ShippingNoticeDocument(Base):
class ShippingOrderDocument(Base):
"""
发货通知文档单元:邮件正文或单个附件(阶段二)。
核心逻辑:Intake 解析后按 attachment_key 幂等 upsert;附件型 Document 可挂 derived FileAsset。
"""
__tablename__ = 'shipping_notice_documents'
__tablename__ = 'shipping_order_documents'
__table_args__ = (
UniqueConstraint(
'intake_id',
'attachment_key',
name='uq_shipping_notice_documents_intake_attachment_key',
name='uq_shipping_order_documents_intake_attachment_key',
),
# 支撑 Candidate (primary_document_id, intake_id) 复合外键
UniqueConstraint('id', 'intake_id', name='uq_shipping_notice_documents_id_intake'),
Index('ix_shipping_notice_documents_intake_id', 'intake_id'),
Index('ix_shipping_notice_documents_asset_id', 'asset_id'),
Index('ix_shipping_notice_documents_content_hash', 'content_hash'),
Index('ix_shipping_notice_documents_parse_status', 'parse_status'),
UniqueConstraint('id', 'intake_id', name='uq_shipping_order_documents_id_intake'),
Index('ix_shipping_order_documents_intake_id', 'intake_id'),
Index('ix_shipping_order_documents_asset_id', 'asset_id'),
Index('ix_shipping_order_documents_content_hash', 'content_hash'),
Index('ix_shipping_order_documents_parse_status', 'parse_status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
intake_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_intakes.id'),
ForeignKey('shipping_order_intakes.id'),
nullable=False,
)
asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True)
@@ -428,48 +554,108 @@ class ShippingNoticeDocument(Base):
parse_status: Mapped[str] = mapped_column(String(32), default='pending', nullable=False)
extracted_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
parse_warnings_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
current_layout_version_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_order_document_layout_versions.id',
name='fk_shipping_order_documents_current_layout_version',
ondelete='SET NULL',
use_alter=True,
),
nullable=True,
)
order_extraction_status: Mapped[str] = mapped_column(
String(32),
default='not_started',
server_default=text("'not_started'"),
nullable=False,
index=True,
)
order_extraction_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
order_extraction_result_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
order_extraction_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
order_extraction_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
current_layout_version = relationship(
'ShippingDocumentLayoutVersion',
foreign_keys=[current_layout_version_id],
post_update=True,
)
layout_versions = relationship(
'ShippingDocumentLayoutVersion',
foreign_keys='ShippingDocumentLayoutVersion.document_id',
back_populates='document',
cascade='all, delete-orphan',
)
class ShippingNoticeCandidate(Base):
class ShippingOrderCandidate(Base):
"""
订单候选:一封邮件中识别出的独立发货通知(阶段二,尚未创建 Task)。
核心逻辑:通常 1 Document → 1 Candidate;重复检测与决策落在 Candidate 级,互不影响。
核心逻辑:一个 Document 可抽取多个 Candidate;candidate_key 保证重提取幂等,
重复检测、自动建单与待补字段状态均落在 Candidate 级。
"""
__tablename__ = 'shipping_notice_candidates'
__tablename__ = 'shipping_order_candidates'
__table_args__ = (
UniqueConstraint('candidate_no', name='uq_shipping_notice_candidates_candidate_no'),
CheckConstraint(
"candidate_status IN ('provisional', 'accepted', 'rejected', 'expired')",
name='ck_shipping_order_candidates_status',
),
CheckConstraint(
"acceptance_mode IS NULL OR acceptance_mode IN ('automatic', 'manual', 'legacy')",
name='ck_shipping_order_candidates_acceptance_mode',
),
UniqueConstraint('candidate_no', name='uq_shipping_order_candidates_candidate_no'),
UniqueConstraint(
'intake_id',
'primary_document_id',
name='uq_shipping_notice_candidates_intake_primary_document',
'intake_id', 'candidate_key', 'order_extraction_run_id',
name='uq_shipping_order_candidates_intake_key_run',
),
# 保证主文档与 Candidate 同属一 Intake,禁止跨 Intake 挂接
ForeignKeyConstraint(
['primary_document_id', 'intake_id'],
['shipping_notice_documents.id', 'shipping_notice_documents.intake_id'],
name='fk_shipping_notice_candidates_document_intake',
['shipping_order_documents.id', 'shipping_order_documents.intake_id'],
name='fk_shipping_order_candidates_document_intake',
),
Index('ix_shipping_notice_candidates_intake_id', 'intake_id'),
Index('ix_shipping_notice_candidates_primary_document_id', 'primary_document_id'),
Index('ix_shipping_notice_candidates_po_number', 'po_number'),
Index('ix_shipping_order_candidates_intake_id', 'intake_id'),
Index('ix_shipping_order_candidates_primary_document_id', 'primary_document_id'),
Index('ix_shipping_order_candidates_po_number', 'po_number'),
Index(
'ix_shipping_notice_candidates_user_fingerprint',
'ix_shipping_order_candidates_user_fingerprint',
'business_fingerprint',
),
Index('ix_shipping_notice_candidates_duplicate_status', 'duplicate_status'),
Index('ix_shipping_order_candidates_duplicate_status', 'duplicate_status'),
Index('ix_shipping_order_candidates_fulfillment_gate', 'candidate_status', 'is_current_version'),
)
id: Mapped[int] = mapped_column(primary_key=True)
candidate_no: Mapped[str] = mapped_column(String(64), nullable=False)
intake_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_intakes.id'),
ForeignKey('shipping_order_intakes.id'),
nullable=False,
)
primary_document_id: Mapped[int] = mapped_column(Integer, nullable=False)
candidate_key: Mapped[str] = mapped_column(String(128), nullable=False)
source_order_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
# 当前 Candidate 对应的受控订单抽取真相;识别运行时不得再从 LLM 摘要 JSON 反查该关联。
order_extraction_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_extractions.id'), nullable=True, index=True,
)
order_extraction_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id'), nullable=True, index=True,
)
# 仅当前版本候选可进入建单;旧版本保留为只读审计和重新识别失败时的回退依据。
is_current_version: Mapped[bool] = mapped_column(
Boolean, default=True, server_default=text('true'), nullable=False, index=True,
)
selected_before_superseded: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)
candidate_status_before_superseded: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
extraction_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
classification_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
field_confidence_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
missing_fields_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
evidence_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
structured_result_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
@@ -480,10 +666,21 @@ class ShippingNoticeCandidate(Base):
nullable=False,
)
conflicts_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
selected: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), nullable=False)
# `selected` is a legacy UI projection. Fulfillment must use candidate_status.
candidate_status: Mapped[str] = mapped_column(
String(32), default='provisional', server_default=text("'provisional'"), nullable=False, index=True,
)
acceptance_mode: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
accepted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
accepted_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
acceptance_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
acceptance_policy_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
selected: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'), nullable=False)
business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
fingerprint_strength: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
content_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
content_fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
duplicate_status: Mapped[str] = mapped_column(
String(32),
default='unchecked',
@@ -495,28 +692,11 @@ class ShippingNoticeCandidate(Base):
duplicate_resolution_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
duplicate_target_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
duplicate_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
duplicate_resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
consumed_task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_tasks.id'),
ForeignKey('shipping_notices.id'),
nullable=True,
)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
class ShippingInventoryMapping(Base):
"""客户库存 Excel 表头 → 标准字段的列映射缓存(按 customer_code + header_hash 去重)。"""
__tablename__ = 'shipping_inventory_mappings'
__table_args__ = (
UniqueConstraint('customer_code', 'header_hash', name='uq_shipping_inventory_mappings_customer_header'),
Index('ix_shipping_inventory_mappings_customer_code', 'customer_code'),
)
id: Mapped[int] = mapped_column(primary_key=True)
customer_code: Mapped[str] = mapped_column(String(64), nullable=False)
header_hash: Mapped[str] = mapped_column(String(64), nullable=False)
headers_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
field_mapping_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
last_used_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, index=True)
+124
View File
@@ -0,0 +1,124 @@
"""
backend/app/models/shipping_audit_event.py
用途:定义货代领域统一、仅追加的审计事件。
依赖:SQLAlchemy Base;Workflow / Run / Task / Intake 等稳定业务编号(软引用)。
逻辑:各业务服务通过 audit_service 追加事件;actor_type 含 worker(门禁 Job);
事件不依赖可级联删除的业务外键,保留跨生命周期追溯事实。
进度审计阶段扩展 operation_id、对象关联、白名单前后快照、证据引用、结果与保留到期时间;
Workflow 阶段以 workflow_id / workflow_item_id / workflow_item_version_id 软引用批次与 PDF 项,
并写入 previous_event_hash / event_hash 哈希链与 diff_json;另含 owner_user_id 与脱敏
client_ip_hash/user_agent_hash;
项次派生阶段使用 LINE_DERIVATION_AUDIT_EVENT_TYPES(FIELD_DERIVED / LINE_NO_OVERRIDDEN /
DERIVATION_SIMULATED / EXPORT_GENERATED 等),元数据仅存脱敏摘要与规则校验和;
禁止存储 PDF/邮件正文、模型原文、对象存储 URL、原始 IP/UA 或密钥。
ORM before_update/before_delete 拒绝改删;PostgreSQL 另有 append-only 触发器
(迁移 a0e1f2b3c4d5);到期清理须 set_config('hxops.shipping_audit_purge','1')。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, Index, Integer, JSON, String, Text, event
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
from app.core.errors import ValidationError
class ShippingAuditEvent(Base):
"""货代领域的不可变审计事件;禁止业务代码更新或删除既有记录。"""
__tablename__ = 'shipping_audit_events'
__table_args__ = (
CheckConstraint(
"actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin', 'worker')",
name='ck_shipping_audit_events_actor_type',
),
CheckConstraint(
"result IS NULL OR result IN ('success', 'failure', 'rejected', 'ignored')",
name='ck_shipping_audit_events_result',
),
Index('ix_shipping_audit_events_aggregate_created', 'aggregate_type', 'aggregate_id', 'created_at'),
Index('ix_shipping_audit_events_run_created', 'run_no', 'created_at'),
Index('ix_shipping_audit_events_task_created', 'task_no', 'created_at'),
Index('ix_shipping_audit_events_operation_created', 'operation_id', 'created_at'),
Index('ix_shipping_audit_events_request_created', 'request_id', 'created_at'),
Index('ix_shipping_audit_events_conversation_created', 'conversation_id', 'created_at'),
Index('ix_shipping_audit_events_document_created', 'document_id', 'created_at'),
Index('ix_shipping_audit_events_unit_created', 'unit_id', 'created_at'),
Index('ix_shipping_audit_events_actor_created', 'actor_type', 'actor_id', 'created_at'),
Index('ix_shipping_audit_events_event_type_created', 'event_type', 'created_at'),
Index('ix_shipping_audit_events_retention_expires', 'retention_expires_at', 'id'),
Index('ix_shipping_audit_events_workflow_created', 'workflow_id', 'created_at'),
Index('ix_shipping_audit_events_workflow_item_created', 'workflow_item_id', 'created_at'),
Index('ix_shipping_audit_events_event_hash', 'event_hash'),
Index('ix_shipping_audit_events_owner_created', 'owner_user_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
event_type: Mapped[str] = mapped_column(String(64), nullable=False)
aggregate_type: Mapped[str] = mapped_column(String(64), nullable=False)
aggregate_id: Mapped[str] = mapped_column(String(128), nullable=False)
run_no: Mapped[str | None] = mapped_column(String(64), nullable=True)
task_no: Mapped[str | None] = mapped_column(String(64), nullable=True)
intake_no: Mapped[str | None] = mapped_column(String(64), nullable=True)
actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system')
actor_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
actor_role: Mapped[str | None] = mapped_column(String(64), nullable=True)
# 操作者展示名(可选);与 actor_id 并存,禁止写入敏感联系方式。
actor_display: Mapped[str | None] = mapped_column(String(128), nullable=True)
request_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
operation_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
correlation_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
source: Mapped[str | None] = mapped_column(String(32), nullable=True)
result: Mapped[str | None] = mapped_column(String(16), nullable=True)
error_code: Mapped[str | None] = mapped_column(String(64), nullable=True)
conversation_id: Mapped[str | None] = mapped_column(String(100), nullable=True)
unit_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
document_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
review_case_no: Mapped[str | None] = mapped_column(String(64), nullable=True)
# Workflow 软引用:workflow_no / item_no / version id(字符串),避免级联删除抹除审计。
workflow_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
workflow_item_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
workflow_item_version_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
version_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
# 业务属主(非操作者);代操作场景与 actor_id 区分。
owner_user_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
# 仅存哈希,禁止写入原始 IP / User-Agent。
client_ip_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
user_agent_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
attempt_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
action: Mapped[str | None] = mapped_column(String(64), nullable=True)
reason_code: Mapped[str | None] = mapped_column(String(128), nullable=True)
reason: Mapped[str | None] = mapped_column(Text, nullable=True)
before_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
after_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
before_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
after_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
# 白名单前后快照差异;与哈希链一并支撑离线校验。
diff_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
previous_event_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
event_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
# 敏感等级:normal | sensitive;用于查询脱敏与访问审计分级。
sensitivity_level: Mapped[str | None] = mapped_column(String(16), nullable=True)
evidence_refs_json: Mapped[Optional[list[dict[str, Any]]]] = mapped_column(JSON, nullable=True)
artifact_refs_json: Mapped[Optional[list[dict[str, Any]]]] = mapped_column(JSON, nullable=True)
context_refs_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
metadata_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
retention_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@event.listens_for(ShippingAuditEvent, 'before_update')
def _reject_shipping_audit_update(_mapper, _connection, _target) -> None:
"""拒绝 ORM 更新,确保即使未调用审计服务也不能改写历史事件。"""
raise ValidationError('Shipping audit event is append-only', code='SHIPPING_NOTICE.AUDIT_IMMUTABLE')
@event.listens_for(ShippingAuditEvent, 'before_delete')
def _reject_shipping_audit_delete(_mapper, _connection, _target) -> None:
"""拒绝 ORM 删除,避免业务清理或级联关系抹除审计事实。"""
raise ValidationError('Shipping audit event is append-only', code='SHIPPING_NOTICE.AUDIT_IMMUTABLE')
@@ -0,0 +1,75 @@
"""
backend/app/models/shipping_context_provider.py
用途:定义订单通用上下文字段可选择的确定性来源目录及受控选项。
依赖:models.base.Base、SQLAlchemy。
逻辑:数据库维护来源展示与启停状态;代码注册表校验 provider_key/option_key 是否具有真实采集实现。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import CheckConstraint, ForeignKey, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingContextProvider(Base):
"""确定性上下文来源族;只允许绑定代码注册的 provider_key。"""
__tablename__ = 'shipping_context_providers'
__table_args__ = (
CheckConstraint("status IN ('active', 'disabled')", name='ck_shipping_context_providers_status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
provider_key: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
options: Mapped[list['ShippingContextProviderOption']] = relationship(
back_populates='provider', cascade='all, delete-orphan', order_by='ShippingContextProviderOption.id'
)
class ShippingContextProviderOption(Base):
"""来源族下的受控值选项;option_key 必须与代码注册表中的能力一致。"""
__tablename__ = 'shipping_context_provider_options'
__table_args__ = (
UniqueConstraint('provider_id', 'option_key', name='uq_shipping_context_provider_options_key'),
CheckConstraint("value_type IN ('string')", name='ck_shipping_context_provider_options_value_type'),
CheckConstraint(
"sensitivity_level IN ('low', 'personal', 'confidential')",
name='ck_shipping_context_provider_options_sensitivity',
),
CheckConstraint(
"default_dify_exposure_policy IN ('never', 'redacted', 'confirmed_readonly')",
name='ck_shipping_context_provider_options_dify_policy',
),
CheckConstraint("status IN ('active', 'disabled')", name='ck_shipping_context_provider_options_status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
provider_id: Mapped[int] = mapped_column(
ForeignKey('shipping_context_providers.id', ondelete='CASCADE'), nullable=False
)
option_key: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
value_type: Mapped[str] = mapped_column(String(16), nullable=False, default='string', server_default='string')
sensitivity_level: Mapped[str] = mapped_column(String(16), nullable=False)
default_dify_exposure_policy: Mapped[str] = mapped_column(
String(32), nullable=False, default='never', server_default='never'
)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
provider: Mapped[ShippingContextProvider] = relationship(back_populates='options')
+296
View File
@@ -0,0 +1,296 @@
"""
backend/app/models/shipping_customer.py
用途:货代标准客户、客户识别证据、业务单聚合与业务编号流水模型。
依赖:models.base.Base、users、shipping_notices。
逻辑:客户主数据提供稳定身份;ShippingCase 聚合 Notice 修订链;流水表供后续编号服务原子递增。
"""
from __future__ import annotations
from datetime import date, datetime
from typing import List, Optional
from sqlalchemy import Boolean, CheckConstraint, Date, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingCustomer(Base):
"""货代标准客户主数据;简码由管理员维护并用于业务编号前缀。"""
__tablename__ = 'shipping_customers'
__table_args__ = (
CheckConstraint(
"length(short_code) BETWEEN 2 AND 6 "
"AND short_code = upper(short_code) "
"AND short_code NOT GLOB '*[^A-Z]*'",
name='ck_shipping_customers_short_code_shape',
).ddl_if(dialect='sqlite'),
CheckConstraint(
"short_code ~ '^[A-Z]{2,6}$'",
name='ck_shipping_customers_short_code_shape',
).ddl_if(dialect='postgresql'),
Index('ix_shipping_customers_status_name', 'status', 'standard_name'),
)
id: Mapped[int] = mapped_column(primary_key=True)
standard_name: Mapped[str] = mapped_column(String(200), nullable=False, index=True)
short_code: Mapped[str] = mapped_column(String(6), nullable=False, unique=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
merged_into_customer_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_customers.id'),
nullable=True,
index=True,
)
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
identifiers: Mapped[List['ShippingCustomerIdentifier']] = relationship(
'ShippingCustomerIdentifier',
back_populates='customer',
cascade='all, delete-orphan',
)
cases: Mapped[List['ShippingCase']] = relationship('ShippingCase', back_populates='customer')
merged_into_customer: Mapped[Optional['ShippingCustomer']] = relationship(
'ShippingCustomer',
remote_side='ShippingCustomer.id',
back_populates='merged_source_customers',
)
external_refs: Mapped[List['ShippingCustomerExternalRef']] = relationship(
'ShippingCustomerExternalRef', back_populates='customer', cascade='all, delete-orphan',
)
sites: Mapped[List['ShippingCustomerSite']] = relationship(
'ShippingCustomerSite', back_populates='customer', cascade='all, delete-orphan',
)
merged_source_customers: Mapped[List['ShippingCustomer']] = relationship(
'ShippingCustomer',
back_populates='merged_into_customer',
)
class ShippingCustomerIdentifier(Base):
"""标准客户的可审核识别证据;同一别名可属于多个客户以表达歧义。"""
__tablename__ = 'shipping_customer_identifiers'
__table_args__ = (
UniqueConstraint(
'customer_id',
'identifier_type',
'normalized_value',
name='uq_shipping_customer_identifiers_customer_type_value',
),
Index(
'ix_shipping_customer_identifiers_lookup',
'identifier_type',
'normalized_value',
'status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
customer_id: Mapped[int] = mapped_column(ForeignKey('shipping_customers.id'), nullable=False, index=True)
identifier_type: Mapped[str] = mapped_column(String(32), nullable=False)
raw_value: Mapped[str] = mapped_column(String(500), nullable=False)
normalized_value: Mapped[str] = mapped_column(String(500), nullable=False)
auto_match_allowed: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false'))
status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
source: Mapped[str] = mapped_column(String(32), nullable=False, default='manual', server_default='manual')
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
confirmed_at: Mapped[Optional[datetime]] = mapped_column(nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
customer: Mapped['ShippingCustomer'] = relationship('ShippingCustomer', back_populates='identifiers')
class ShippingCustomerExternalRef(Base):
"""客户在期初文件或外部系统中的稳定来源键,用于重复导入幂等。"""
__tablename__ = 'shipping_customer_external_refs'
__table_args__ = (
UniqueConstraint(
'source_system',
'legacy_customer_key',
name='uq_shipping_customer_external_refs_source_key',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
customer_id: Mapped[int] = mapped_column(ForeignKey('shipping_customers.id'), nullable=False, index=True)
source_system: Mapped[str] = mapped_column(String(64), nullable=False)
legacy_customer_key: Mapped[str] = mapped_column(String(128), nullable=False)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
customer: Mapped['ShippingCustomer'] = relationship('ShippingCustomer', back_populates='external_refs')
class ShippingCustomerSite(Base):
"""标准客户下的送货/收货站点;Ship-to 匹配指向站点而不是复制一条账款客户。"""
__tablename__ = 'shipping_customer_sites'
__table_args__ = (
UniqueConstraint('customer_id', 'site_code', name='uq_shipping_customer_sites_customer_code'),
Index('ix_shipping_customer_sites_status_name', 'status', 'site_name'),
)
id: Mapped[int] = mapped_column(primary_key=True)
customer_id: Mapped[int] = mapped_column(ForeignKey('shipping_customers.id'), nullable=False, index=True)
site_name: Mapped[str] = mapped_column(String(200), nullable=False)
site_code: Mapped[str] = mapped_column(String(64), nullable=False)
address: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
city: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
country: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
customer: Mapped['ShippingCustomer'] = relationship('ShippingCustomer', back_populates='sites')
identifiers: Mapped[List['ShippingCustomerSiteIdentifier']] = relationship(
'ShippingCustomerSiteIdentifier', back_populates='site', cascade='all, delete-orphan',
)
class ShippingCustomerSiteIdentifier(Base):
"""送货站点的名称、外部站点编码或地址别名,用于 Ship-to 确定性匹配。"""
__tablename__ = 'shipping_customer_site_identifiers'
__table_args__ = (
UniqueConstraint(
'site_id', 'identifier_type', 'source_system', 'normalized_value',
name='uq_shipping_customer_site_identifiers_value',
),
Index(
'ix_shipping_customer_site_identifiers_lookup',
'identifier_type', 'source_system', 'normalized_value', 'status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
site_id: Mapped[int] = mapped_column(ForeignKey('shipping_customer_sites.id'), nullable=False, index=True)
identifier_type: Mapped[str] = mapped_column(String(32), nullable=False)
source_system: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
raw_value: Mapped[str] = mapped_column(String(500), nullable=False)
normalized_value: Mapped[str] = mapped_column(String(500), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='approved', server_default='approved')
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
site: Mapped['ShippingCustomerSite'] = relationship('ShippingCustomerSite', back_populates='identifiers')
class ShippingCase(Base):
"""一票发货业务聚合;多个线性任务修订版本共享同一业务单。"""
__tablename__ = 'shipping_cases'
__table_args__ = (
Index('ix_shipping_cases_customer_created', 'customer_id', 'created_at'),
Index('ix_shipping_cases_status_created', 'status', 'created_at'),
UniqueConstraint('replaces_case_id', name='uq_shipping_cases_replaces_case_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
case_no: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True, index=True)
business_no: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, unique=True)
customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True)
business_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
sequence_value: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
numbering_rule_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
numbering_status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
status: Mapped[str] = mapped_column(String(32), nullable=False, default='open', server_default='open')
replaces_case_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_cases.id'), nullable=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
customer: Mapped[Optional['ShippingCustomer']] = relationship('ShippingCustomer', back_populates='cases')
tasks: Mapped[List['ShippingNotice']] = relationship(
'ShippingNotice',
back_populates='shipping_case',
lazy='selectin',
)
class ShippingBusinessSequence(Base):
"""按业务类型、客户和 Asia/Shanghai 业务日期保存当前流水值。"""
__tablename__ = 'shipping_business_sequences'
__table_args__ = (
CheckConstraint(
'current_value BETWEEN 0 AND 99',
name='ck_shipping_business_sequences_current_value',
),
UniqueConstraint(
'business_type',
'customer_id',
'business_date',
name='uq_shipping_business_sequences_type_customer_date',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
business_type: Mapped[str] = mapped_column(
String(32),
nullable=False,
default='shipping_notice',
server_default='shipping_notice',
)
customer_id: Mapped[int] = mapped_column(ForeignKey('shipping_customers.id'), nullable=False, index=True)
business_date: Mapped[date] = mapped_column(Date, nullable=False, index=True)
current_value: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
class ShippingCustomerLifecycleEvent(Base):
"""客户生命周期审计;只保存客户快照,不能反向阻断受控删除。"""
__tablename__ = 'shipping_customer_lifecycle_events'
__table_args__ = (
Index('ix_shipping_customer_lifecycle_events_customer_created', 'customer_id_snapshot', 'created_at'),
Index('ix_shipping_customer_lifecycle_events_event_created', 'event_type', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
event_type: Mapped[str] = mapped_column(String(32), nullable=False)
customer_id_snapshot: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
detail_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
class ShippingCustomerMerge(Base):
"""客户身份归并审计;仅存快照,不给历史审计链增加客户外键依赖。"""
__tablename__ = 'shipping_customer_merges'
__table_args__ = (
UniqueConstraint('source_customer_id_snapshot', name='uq_shipping_customer_merges_source_snapshot'),
Index('ix_shipping_customer_merges_target_created', 'target_customer_id_snapshot', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
source_customer_id_snapshot: Mapped[int] = mapped_column(Integer, nullable=False)
source_name_snapshot: Mapped[str] = mapped_column(String(200), nullable=False)
source_short_code_snapshot: Mapped[str] = mapped_column(String(6), nullable=False)
target_customer_id_snapshot: Mapped[int] = mapped_column(Integer, nullable=False)
target_name_snapshot: Mapped[str] = mapped_column(String(200), nullable=False)
target_short_code_snapshot: Mapped[str] = mapped_column(String(6), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
reason: Mapped[str] = mapped_column(Text, nullable=False)
detail_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
@@ -0,0 +1,86 @@
"""
backend/app/models/shipping_customer_import.py
用途:保存货代期初客户导入批次、原始文件与逐行预检/发布结果。
依赖:models.base.Base、users、shipping_customers。
逻辑:上传仅写暂存批次与行;管理员解决冲突后由发布服务单事务写入正式客户主数据。
"""
from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from sqlalchemy import ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingCustomerImportBatch(Base):
"""期初客户导入批次,保存文件哈希、原始内容、统计和发布审计。"""
__tablename__ = 'shipping_customer_import_batches'
__table_args__ = (
UniqueConstraint('file_hash', 'source_system', name='uq_shipping_customer_import_batches_hash_source'),
Index('ix_shipping_customer_import_batches_status_created', 'status', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
batch_no: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
file_hash: Mapped[str] = mapped_column(String(64), nullable=False)
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
source_system: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='validated', server_default='validated')
total_rows: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
valid_rows: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
warning_rows: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
error_rows: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
published_rows: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
uploaded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_at: Mapped[Optional[datetime]] = mapped_column(nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
rows: Mapped[List['ShippingCustomerImportRow']] = relationship(
'ShippingCustomerImportRow',
back_populates='batch',
cascade='all, delete-orphan',
order_by='ShippingCustomerImportRow.row_order',
)
class ShippingCustomerImportRow(Base):
"""导入文件逐行暂存、校验、人工决定与正式发布结果。"""
__tablename__ = 'shipping_customer_import_rows'
__table_args__ = (
UniqueConstraint('batch_id', 'sheet_name', 'row_no', name='uq_shipping_customer_import_rows_location'),
Index('ix_shipping_customer_import_rows_batch_status', 'batch_id', 'validation_status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
batch_id: Mapped[int] = mapped_column(ForeignKey('shipping_customer_import_batches.id'), nullable=False, index=True)
sheet_name: Mapped[str] = mapped_column(String(32), nullable=False)
row_no: Mapped[int] = mapped_column(Integer, nullable=False)
row_order: Mapped[int] = mapped_column(Integer, nullable=False)
row_type: Mapped[str] = mapped_column(String(32), nullable=False)
legacy_customer_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
raw_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
normalized_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
validation_status: Mapped[str] = mapped_column(String(32), nullable=False, default='valid')
errors_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
warnings_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
suggested_action: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
decision_action: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
target_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
decision_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
result_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
result_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
result_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
batch: Mapped['ShippingCustomerImportBatch'] = relationship('ShippingCustomerImportBatch', back_populates='rows')
@@ -0,0 +1,100 @@
"""
backend/app/models/shipping_customer_resolution.py
用途:保存订单候选的客户影子识别结果与人工标签。
依赖:ShippingOrderCandidate、ShippingOrderIntake、ShippingCustomer、User。
逻辑:订单候选抽取后幂等刷新本表;阶段 3 仅用于质量观测,禁止据此绑定业务单或生成编号。
"""
from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from sqlalchemy import CheckConstraint, Float, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingCustomerShadowResolution(Base):
"""每个订单候选唯一一条影子识别快照,可追加管理员真值标签。"""
__tablename__ = 'shipping_customer_shadow_resolutions'
__table_args__ = (
CheckConstraint(
"status IN ('unique_candidate', 'ambiguous', 'unmatched', 'failed')",
name='ck_shipping_customer_shadow_status',
),
Index('ix_shipping_customer_shadow_status_created', 'status', 'created_at'),
Index('ix_shipping_customer_shadow_labeled_created', 'manual_customer_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
candidate_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_candidates.id', ondelete='CASCADE'),
nullable=False,
unique=True,
)
intake_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_intakes.id', ondelete='CASCADE'),
nullable=False,
index=True,
)
identity_rule_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_identity_rule_sets.id'), nullable=True, index=True,
)
identity_rule_set_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
identity_rule_set_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
order_schema_version_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_schema_versions.id'), nullable=True,
)
resolution_version: Mapped[str] = mapped_column(String(32), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
evidence_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
candidate_matches_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
resolution_context_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
top_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
top_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
manual_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
labeled_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
labeled_at: Mapped[Optional[datetime]] = mapped_column(nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
matches: Mapped[List['ShippingCustomerShadowMatch']] = relationship(
'ShippingCustomerShadowMatch',
back_populates='resolution',
cascade='all, delete-orphan',
order_by='ShippingCustomerShadowMatch.match_rank',
)
class ShippingCustomerShadowMatch(Base):
"""影子识别候选的规范化关联,供删除资格与合并可靠反查。"""
__tablename__ = 'shipping_customer_shadow_matches'
__table_args__ = (
UniqueConstraint('resolution_id', 'customer_id', name='uq_shipping_customer_shadow_matches_resolution_customer'),
Index('ix_shipping_customer_shadow_matches_customer', 'customer_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
resolution_id: Mapped[int] = mapped_column(
ForeignKey('shipping_customer_shadow_resolutions.id', ondelete='CASCADE'),
nullable=False,
index=True,
)
customer_id: Mapped[int] = mapped_column(ForeignKey('shipping_customers.id'), nullable=False)
match_rank: Mapped[int] = mapped_column(Integer, nullable=False)
score: Mapped[float] = mapped_column(Float, nullable=False)
standard_name_snapshot: Mapped[str] = mapped_column(String(200), nullable=False)
short_code_snapshot: Mapped[str] = mapped_column(String(6), nullable=False)
reasons_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
resolution: Mapped['ShippingCustomerShadowResolution'] = relationship(
'ShippingCustomerShadowResolution',
back_populates='matches',
)
@@ -0,0 +1,71 @@
"""
backend/app/models/shipping_document_layout.py
用途:持久化每份发货通知 Document 的版本化版面解析生命周期、冻结快照和质量结果。
依赖:shipping_order_documents、jobs、SQLAlchemy Base。
逻辑:同一 Document 版本递增;运行租约隔离旧 Worker,只有成功版本可成为 Document 当前布局。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingDocumentLayoutVersion(Base):
"""单文档版面解析版本;payload/checksum 一旦完成即不可原地改写。"""
__tablename__ = 'shipping_order_document_layout_versions'
__table_args__ = (
UniqueConstraint('document_id', 'version', name='uq_shipping_order_document_layout_document_version'),
CheckConstraint(
"status IN ('queued', 'running', 'ready', 'needs_review', 'failed', 'unsupported')",
name='ck_shipping_order_document_layout_status',
),
Index('ix_shipping_order_document_layout_document_status', 'document_id', 'status'),
Index('ix_shipping_order_document_layout_content_parser', 'source_content_hash', 'parser_key'),
Index(
'uq_shipping_order_document_layout_one_active',
'document_id',
unique=True,
postgresql_where=text("status IN ('queued', 'running')"),
sqlite_where=text("status IN ('queued', 'running')"),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
document_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_documents.id', ondelete='CASCADE'), nullable=False,
)
version: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(24), default='queued', server_default='queued', nullable=False)
source_content_hash: Mapped[str] = mapped_column(String(64), nullable=False)
parser_key: Mapped[str] = mapped_column(String(128), nullable=False)
parser_name: Mapped[str] = mapped_column(String(32), nullable=False)
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
backend: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
contract_version: Mapped[str] = mapped_column(String(64), nullable=False)
payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
payload_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
payload_size_bytes: Mapped[int] = mapped_column(Integer, default=0, server_default='0', nullable=False)
quality_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
issues_json: Mapped[list] = mapped_column(JSON, default=list, nullable=False)
job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True, index=True)
lease_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
attempt_count: Mapped[int] = mapped_column(Integer, default=0, server_default='0', nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
document = relationship(
'ShippingOrderDocument', foreign_keys=[document_id], back_populates='layout_versions',
)
job = relationship('Job', foreign_keys=[job_id])
@@ -0,0 +1,66 @@
"""
订单模板自动冻结资格的版本化发布凭证。
用途:把模板可发布状态与自动冻结资格分离,并冻结 Profile、Schema、解析器和质量凭证身份。
依赖:订单 Profile、Schema 版本、盲测套件、用户和 SQLAlchemy Base。
逻辑:每个已发布模板版本独立持有一条资格记录;首版只能是人工确认,后续自动冻结须显式批准。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingDocumentProfileAutoFreezeQualification(Base):
"""模板版本的自动冻结资格;发布、暂停和撤销均保留独立审计身份。"""
__tablename__ = 'shipping_document_profile_auto_freeze_qualifications'
__table_args__ = (
UniqueConstraint(
'profile_id', 'profile_version', 'profile_checksum',
name='uq_shipping_document_profile_auto_freeze_qualification_version',
),
CheckConstraint(
"status IN ('manual_confirmation', 'auto_freeze_approved', 'auto_freeze_suspended')",
name='ck_shipping_document_profile_auto_freeze_qualification_status',
),
Index(
'ix_shipping_document_profile_auto_freeze_qualification_profile_status',
'profile_id', 'status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id'), nullable=False)
profile_version: Mapped[int] = mapped_column(Integer, nullable=False)
profile_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
parser_version: Mapped[str] = mapped_column(String(64), nullable=False)
quality_suite_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_document_profile_test_suites.id'), nullable=True,
)
customer_ids_json: Mapped[Optional[list[int]]] = mapped_column(JSON, nullable=True)
business_scenarios_json: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)
requires_customer_confirmation: Mapped[bool] = mapped_column(
Boolean, nullable=False, default=True, server_default=text('true'),
)
scope_updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
scope_updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
status: Mapped[str] = mapped_column(
String(32), nullable=False, default='manual_confirmation', server_default='manual_confirmation',
)
approved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
suspended_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
suspended_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
suspension_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
@@ -0,0 +1,92 @@
"""
backend/app/models/shipping_document_profile_quality.py
用途:保存订单文档 Profile 的独立盲测集、样本期望值和不可变执行结果。
依赖:订单 Profile、订单文档、用户和 SQLAlchemy Base。
逻辑:每个 Profile 版本以冻结 checksum 绑定至少三个盲测样本;全部通过并经管理员批准后,才可用于确定性自动建单。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingDocumentProfileTestSuite(Base):
"""一个发布 Profile 版本的盲测集;批准状态是确定性自动建单的发布凭证。"""
__tablename__ = 'shipping_document_profile_test_suites'
__table_args__ = (
UniqueConstraint('profile_id', 'profile_checksum', name='uq_shipping_document_profile_test_suites_profile_checksum'),
CheckConstraint("status IN ('draft', 'approved', 'superseded')", name='ck_shipping_document_profile_test_suites_status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id'), nullable=False, index=True)
profile_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
approved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
samples: Mapped[list['ShippingDocumentProfileTestSample']] = relationship(
back_populates='suite', cascade='all, delete-orphan', order_by='ShippingDocumentProfileTestSample.id',
)
runs: Mapped[list['ShippingDocumentProfileTestRun']] = relationship(
back_populates='suite', cascade='all, delete-orphan', order_by='ShippingDocumentProfileTestRun.id',
)
class ShippingDocumentProfileTestSample(Base):
"""盲测真值及确认时冻结的规范化 Layout 身份;不与建模样本自动复用。"""
__tablename__ = 'shipping_document_profile_test_samples'
__table_args__ = (
UniqueConstraint('suite_id', 'document_id', 'table_id', name='uq_shipping_document_profile_test_samples_source'),
)
id: Mapped[int] = mapped_column(primary_key=True)
suite_id: Mapped[int] = mapped_column(ForeignKey('shipping_document_profile_test_suites.id', ondelete='CASCADE'), nullable=False)
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_documents.id'), nullable=False)
table_id: Mapped[str] = mapped_column(String(128), nullable=False)
layout_version_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_document_layout_versions.id'), nullable=True,
)
layout_payload_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
layout_parser_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
layout_parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
expected_rows_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
expected_order_fields_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
suite: Mapped['ShippingDocumentProfileTestSuite'] = relationship(back_populates='samples')
class ShippingDocumentProfileTestRun(Base):
"""一次可审计盲测执行;只存计数和失败码,避免把订单正文复制到测试日志。"""
__tablename__ = 'shipping_document_profile_test_runs'
__table_args__ = (
CheckConstraint("status IN ('passed', 'failed')", name='ck_shipping_document_profile_test_runs_status'),
Index('ix_shipping_document_profile_test_runs_suite_created', 'suite_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
suite_id: Mapped[int] = mapped_column(ForeignKey('shipping_document_profile_test_suites.id', ondelete='CASCADE'), nullable=False)
profile_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False)
sample_count: Mapped[int] = mapped_column(Integer, nullable=False)
passed_sample_count: Mapped[int] = mapped_column(Integer, nullable=False)
failure_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
executed_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
suite: Mapped['ShippingDocumentProfileTestSuite'] = relationship(back_populates='runs')
@@ -0,0 +1,76 @@
"""
models/shipping_excel_template.py
用途:定义版本化发货 Excel 模板及不可变 Notice 导出产物。
依赖:models.base.Base、库存源、订单 Schema、ShippingNotice 与库存快照模型。
逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和;
co8e9f0a1b2c 已删除 export artifact 的 batch_id 列。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingExcelTemplate(Base):
"""可跨库存源复用的发货 Excel 模板版本。"""
__tablename__ = 'shipping_excel_templates'
__table_args__ = (
UniqueConstraint('template_code', 'version', name='uq_shipping_excel_templates_code_version'),
Index('ix_shipping_excel_templates_status', 'status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
template_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
storage_provider: Mapped[str] = mapped_column(String(32), nullable=False, default='minio', server_default='minio')
storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
storage_key: Mapped[str] = mapped_column(String(512), nullable=False)
original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
file_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
definition_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='excel_template')
class ShippingExportArtifact(Base):
"""一次 Notice 导出的不可变产物及生成输入快照。"""
__tablename__ = 'shipping_notice_export_artifacts'
__table_args__ = (
UniqueConstraint('artifact_no', name='uq_shipping_notice_export_artifacts_no'),
Index('ix_shipping_notice_export_artifacts_task_created', 'task_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
artifact_no: Mapped[str] = mapped_column(String(64), nullable=False)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False, index=True)
template_id: Mapped[int] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=False)
order_schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
order_extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
inventory_parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
input_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
file_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='ready', server_default='ready')
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
template: Mapped[ShippingExcelTemplate] = relationship()
task: Mapped['ShippingNotice'] = relationship()
@@ -0,0 +1,34 @@
"""货代上传后版本替代的外部撤销审计事实。"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingFreightCancellation(Base):
"""已上传旧 Notice 的撤销申请与货代回执;成功前新版本不得履约。"""
__tablename__ = 'shipping_notice_freight_cancellations'
__table_args__ = (
UniqueConstraint('old_task_id', 'new_task_id', name='uq_shipping_notice_freight_cancellations_version_pair'),
Index('ix_shipping_notice_freight_cancellations_old_status', 'old_task_id', 'status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
old_task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
new_task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='cancellation_required')
requested_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
requested_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
completed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
freight_receipt_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
receipt_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True)
reason: Mapped[str] = mapped_column(Text, nullable=False)
failure_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
+163
View File
@@ -0,0 +1,163 @@
"""
backend/app/models/shipping_fulfillment.py
用途:保存预约单全局注册、每轮库存核验和 Excel 对预约单的不可重叠归属。
依赖:冻结订单 Snapshot、库存文件、导出 Artifact 与 SQLAlchemy Base;Notice 主表 shipping_notices。
逻辑:Snapshot 行可保留历史预约号;全局 Reservation 决定当前有效行和履约状态,核验与 Artifact 行均追加保存。
"""
from __future__ import annotations
from datetime import datetime
from decimal import Decimal
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, Numeric, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingReservation(Base):
"""预约单当前履约注册表;Reservation ID 全局只能归属一个采购单。"""
__tablename__ = 'shipping_notice_reservations'
__table_args__ = (
UniqueConstraint('reservation_id', name='uq_shipping_notice_reservations_reservation_id'),
CheckConstraint(
"status IN ('pending', 'available', 'artifact_reserved', 'uploaded', 'external_change_required')",
name='ck_shipping_notice_reservations_status',
),
Index('ix_shipping_notice_reservations_task_status', 'task_id', 'status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
snapshot_line_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_snapshot_lines.id'), nullable=False)
reservation_id: Mapped[str] = mapped_column(String(64), nullable=False)
po_number_normalized: Mapped[str] = mapped_column(String(255), nullable=False)
part_number: Mapped[str] = mapped_column(String(255), nullable=False)
required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
current_artifact_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notice_export_artifacts.id'), nullable=True,
)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
class ShippingInventoryVerification(Base):
"""一次任务库存核验的不可变轮次,绑定当时有效库存快照。"""
__tablename__ = 'shipping_notice_inventory_verifications'
__table_args__ = (
CheckConstraint(
"status IN ('completed', 'expired', 'superseded')",
name='ck_shipping_notice_inventory_verifications_status',
),
Index('ix_shipping_notice_inventory_verifications_task_created', 'task_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True)
matching_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True, index=True)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id'), nullable=True)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='completed', server_default='completed')
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
lines: Mapped[list['ShippingInventoryVerificationLine']] = relationship(
back_populates='verification', cascade='all, delete-orphan', order_by='ShippingInventoryVerificationLine.id',
)
class ShippingInventoryVerificationLine(Base):
"""一个预约单在一轮库存中的需求、可用数量和确定性结果。"""
__tablename__ = 'shipping_notice_inventory_verification_lines'
__table_args__ = (
UniqueConstraint(
'verification_id', 'reservation_id',
name='uq_shipping_notice_inventory_verification_lines_reservation',
),
CheckConstraint(
"status IN ('available', 'shortage', 'invalid')",
name='ck_shipping_notice_inventory_verification_lines_status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
verification_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_inventory_verifications.id', ondelete='CASCADE'), nullable=False,
)
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
available_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False)
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
verification: Mapped['ShippingInventoryVerification'] = relationship(back_populates='lines')
class ShippingExportArtifactLine(Base):
"""将本轮 Excel 与预约单一对一绑定,防止同一预约单进入两个有效 Artifact。"""
__tablename__ = 'shipping_notice_export_artifact_lines'
__table_args__ = (
UniqueConstraint(
'artifact_id', 'reservation_id',
name='uq_shipping_notice_export_artifact_lines_artifact_reservation',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
artifact_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_export_artifacts.id', ondelete='CASCADE'), nullable=False,
)
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
verification_line_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_inventory_verification_lines.id'), nullable=False,
)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingUploadAttempt(Base):
"""一次 Artifact 上传尝试;回调幂等键和人工回执均在此处归档。"""
__tablename__ = 'shipping_notice_upload_attempts'
__table_args__ = (
UniqueConstraint('artifact_id', 'attempt_no', name='uq_shipping_notice_upload_attempts_artifact_attempt'),
UniqueConstraint('idempotency_key', name='uq_shipping_notice_upload_attempts_idempotency'),
UniqueConstraint('callback_id', name='uq_shipping_notice_upload_attempts_callback'),
CheckConstraint("mode IN ('rpa', 'manual')", name='ck_shipping_notice_upload_attempts_mode'),
CheckConstraint(
"status IN ('pending', 'running', 'succeeded', 'failed', 'timed_out', 'unknown')",
name='ck_shipping_notice_upload_attempts_status',
),
Index('ix_shipping_notice_upload_attempts_artifact_created', 'artifact_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
artifact_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_export_artifacts.id'), nullable=False)
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
mode: Mapped[str] = mapped_column(String(16), nullable=False)
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
callback_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
superseded_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_upload_attempts.id'), nullable=True)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='pending', server_default='pending')
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
evidence_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True)
# [BE-05] RPA 成功时持久化绿色 DOM 证据(kind/selector/observed_at/filename 等)。
success_evidence_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
operator_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -0,0 +1,139 @@
"""
backend/app/models/shipping_identity_rule.py
用途:定义货代客户/送货站点的可配置识别定义、发布规则集和追加式审计。
依赖:订单字段目录、客户/站点主数据、users。
逻辑:定义只引用已发布订单上下文字段;规则集冻结字段配置;证据值绑定定义。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import Boolean, CheckConstraint, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
def _uuid() -> str:
"""生成跨 PostgreSQL/SQLite 通用的字符串 UUID 主键。"""
return str(uuid.uuid4())
class ShippingIdentityDefinition(Base):
"""管理员维护的稳定识别定义;取值规则唯一来自已发布订单 Schema 字段。"""
__tablename__ = 'shipping_identity_definitions'
__table_args__ = (
UniqueConstraint('definition_code', name='uq_shipping_identity_definitions_code'),
CheckConstraint("target_type IN ('customer', 'site')", name='ck_shipping_identity_definitions_target'),
CheckConstraint("max_automation IN ('none', 'conditional')", name='ck_shipping_identity_definitions_automation'),
CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_identity_definitions_status'),
Index('ix_shipping_identity_definitions_target_status', 'target_type', 'status'),
Index('ix_shipping_identity_definitions_context_field', 'context_field_id'),
)
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_uuid)
definition_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False, default='', server_default='')
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
evidence_label: Mapped[str] = mapped_column(String(128), nullable=False, default='', server_default='')
target_type: Mapped[str] = mapped_column(String(16), nullable=False)
context_field_id: Mapped[str] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=False)
default_weight: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
max_automation: Mapped[str] = mapped_column(String(16), nullable=False, default='none', server_default='none')
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
class ShippingIdentityRuleSet(Base):
"""全局客户识别规则集版本;发布后定义快照不可修改。"""
__tablename__ = 'shipping_identity_rule_sets'
__table_args__ = (
UniqueConstraint('version', name='uq_shipping_identity_rule_sets_version'),
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_identity_rule_sets_status'),
Index('ix_shipping_identity_rule_sets_status_version', 'status', 'version'),
)
id: Mapped[int] = mapped_column(primary_key=True)
version: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
change_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
source_rule_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_identity_rule_sets.id'), nullable=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_at: Mapped[Optional[datetime]] = mapped_column(nullable=True)
retired_at: Mapped[Optional[datetime]] = mapped_column(nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
class ShippingIdentityRuleAuditEvent(Base):
"""识别定义和规则集变更的只追加审计;快照避免后续配置污染历史。"""
__tablename__ = 'shipping_identity_rule_audit_events'
__table_args__ = (
CheckConstraint(
"event_type IN ('definition_created', 'definition_updated', 'definition_retired', "
"'rule_set_created', 'rule_set_saved', 'rule_set_published')",
name='ck_shipping_identity_rule_audits_event',
),
Index('ix_shipping_identity_rule_audits_rule_created', 'rule_set_id', 'created_at'),
Index('ix_shipping_identity_rule_audits_definition_created', 'definition_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
event_type: Mapped[str] = mapped_column(String(32), nullable=False)
definition_id: Mapped[Optional[str]] = mapped_column(ForeignKey('shipping_identity_definitions.id'), nullable=True)
rule_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_identity_rule_sets.id'), nullable=True)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
before_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
after_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False)
class ShippingIdentityEvidence(Base):
"""客户或站点的审核识别证据值;必须且只能归属一个目标对象。"""
__tablename__ = 'shipping_identity_evidences'
__table_args__ = (
CheckConstraint(
'(customer_id IS NOT NULL AND site_id IS NULL) OR (customer_id IS NULL AND site_id IS NOT NULL)',
name='ck_shipping_identity_evidences_one_target',
),
CheckConstraint("status IN ('pending', 'approved', 'disabled')", name='ck_shipping_identity_evidences_status'),
Index(
'uq_shipping_identity_evidence_customer', 'definition_id', 'customer_id', 'normalized_value', unique=True,
postgresql_where=text('customer_id IS NOT NULL'), sqlite_where=text('customer_id IS NOT NULL'),
),
Index(
'uq_shipping_identity_evidence_site', 'definition_id', 'site_id', 'normalized_value', unique=True,
postgresql_where=text('site_id IS NOT NULL'), sqlite_where=text('site_id IS NOT NULL'),
),
Index('ix_shipping_identity_evidences_lookup', 'definition_id', 'normalized_value', 'status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
definition_id: Mapped[str] = mapped_column(ForeignKey('shipping_identity_definitions.id'), nullable=False)
customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
site_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customer_sites.id'), nullable=True)
raw_value: Mapped[str] = mapped_column(String(500), nullable=False)
normalized_value: Mapped[str] = mapped_column(String(500), nullable=False)
auto_match_allowed: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false'))
status: Mapped[str] = mapped_column(String(16), nullable=False, default='pending', server_default='pending')
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
confirmed_at: Mapped[Optional[datetime]] = mapped_column(nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
@@ -0,0 +1,220 @@
"""
models/shipping_inventory_candidates.py
用途:库存候选冻结的结构化持久化——决策 C1 的正式业务真相。
InventoryCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源),
同时 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze'] 保存
同一时刻的完整不可变副本,用于审计与回滚。
依赖:Base、ShippingNotice、ShippingProcessExecution、ShippingOrderReviewCase、users、
ShippingInventoryRoutingRule(可选外键,路由规则版本)。
逻辑:建单前复核阶段(review_case 绑定)或建单后正式推进阶段(task 绑定)都可冻结;
input_fingerprint 相同的重复 freeze 直接返回旧 set_id(幂等);
source_codes_json 为有序列表(路由优先级信息不能丢),禁止用 SET 类型。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import (
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
def _utc_now() -> datetime:
"""返回 naive UTC 时间,与仓库其他模型一致。"""
return datetime.utcnow()
class ShippingInventoryCandidateSet(Base):
"""
库存候选集合(冻结真相根)。
核心逻辑:一次候选冻结对应一个 Set;input_fingerprint 相同 + 绑定对象相同则幂等复用;
同时支持绑定 task_id(建单后)和 review_case_id(建单前草稿复核)两种场景,
二者至少一个非空(CheckConstraint 强制)。
"""
__tablename__ = 'shipping_inventory_candidate_sets'
__table_args__ = (
CheckConstraint(
'task_id IS NOT NULL OR review_case_id IS NOT NULL',
name='ck_shipping_inv_cand_sets_binding',
),
CheckConstraint('set_version >= 1', name='ck_shipping_inv_cand_sets_version'),
CheckConstraint(
"lifecycle_status IN ('draft', 'frozen', 'superseded', 'invalidated')",
name='ck_shipping_inv_cand_sets_lifecycle',
),
Index(
'uq_shipping_inv_cand_sets_task_fp',
'task_id', 'input_fingerprint',
unique=True,
postgresql_where=text('task_id IS NOT NULL'),
sqlite_where=text('task_id IS NOT NULL'),
),
UniqueConstraint('task_id', 'set_version', name='uq_shipping_inv_cand_sets_task_version'),
Index(
'uq_shipping_inv_cand_sets_review_fp',
'review_case_id', 'input_fingerprint',
unique=True,
postgresql_where=text('review_case_id IS NOT NULL'),
sqlite_where=text('review_case_id IS NOT NULL'),
),
Index('ix_shipping_inv_cand_sets_task_frozen', 'task_id', 'frozen_at'),
Index('ix_shipping_inv_cand_sets_review_frozen', 'review_case_id', 'frozen_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
set_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=True,
)
review_case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=True,
)
execution_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_process_executions.id', ondelete='SET NULL'), nullable=True,
)
lifecycle_status: Mapped[str] = mapped_column(
String(32), nullable=False, default='frozen', server_default='frozen',
)
frozen_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
frozen_by_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('users.id'), nullable=True,
)
superseded_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
superseded_by_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), nullable=True,
)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
input_fingerprint: Mapped[str] = mapped_column(String(64), nullable=False)
routing_rule_version_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
manifest_snapshot_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
)
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
sources: Mapped[list['ShippingInventoryCandidateSource']] = relationship(
back_populates='candidate_set',
cascade='all, delete-orphan',
order_by='ShippingInventoryCandidateSource.candidate_order',
)
lines: Mapped[list['ShippingInventoryCandidateLine']] = relationship(
back_populates='candidate_set',
cascade='all, delete-orphan',
order_by='ShippingInventoryCandidateLine.line_no',
)
class ShippingInventoryCandidateSource(Base):
"""
任务级候选库存源(Set 的子级)。
核心逻辑:多源 RPA 按 (set_id, source_code) 唯一创建 Trigger / Attempt,
candidate_order 本身就是路由优先级(不能丢),不能用 SET 无序存储。
candidate_origin ∈ {rule, manual_override},区分是规则算出来还是人工强制指定。
"""
__tablename__ = 'shipping_inventory_candidate_sources'
__table_args__ = (
UniqueConstraint(
'candidate_set_id', 'source_code',
name='uq_shipping_inv_cand_sources_set_source',
),
CheckConstraint(
"candidate_origin IN ('rule', 'manual_override')",
name='ck_shipping_inv_cand_sources_origin',
),
CheckConstraint('candidate_order >= 1', name='ck_shipping_inv_cand_sources_order'),
Index(
'ix_shipping_inv_cand_sources_set_order',
'candidate_set_id', 'candidate_order',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
candidate_set_id: Mapped[int] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), nullable=False,
)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
candidate_order: Mapped[int] = mapped_column(Integer, nullable=False)
candidate_origin: Mapped[str] = mapped_column(String(32), nullable=False, default='rule')
routing_rule_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_routing_rules.id', ondelete='SET NULL'), nullable=True,
)
routing_rule_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
override_by_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('users.id'), nullable=True,
)
override_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
)
candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship(
back_populates='sources',
)
class ShippingInventoryCandidateLine(Base):
"""
行级候选库存源(Set 的子级,按稳定 line_no 对齐订单行)。
核心逻辑:source_codes_json 是**有序列表**(不是 set),顺序即行级路由优先级;
line_no 始终使用任务快照内稳定顺序号,source_line_no 只保存原始单据行号做审计;
跨源匹配需要按行读取候选集合,所以结构化存 line_no + source_line_no +
part_number + reservation_id,不能只依赖 Snapshot JSON 做高频查询。
"""
__tablename__ = 'shipping_inventory_candidate_lines'
__table_args__ = (
UniqueConstraint(
'candidate_set_id', 'line_no',
name='uq_shipping_inv_cand_lines_set_line',
),
Index(
'ix_shipping_inv_cand_lines_set_pn_resv',
'candidate_set_id', 'part_number', 'reservation_id',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
candidate_set_id: Mapped[int] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), nullable=False,
)
line_no: Mapped[int] = mapped_column(Integer, nullable=False)
source_line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
source_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
override_by_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('users.id'), nullable=True,
)
override_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
)
candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship(
back_populates='lines',
)
@@ -0,0 +1,378 @@
"""
models/shipping_inventory_config.py
用途:定义货代库存源、RPA Profile、通用路由规则及外部系统仓库映射主数据。
依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 shipping_notice.credential_crypto 读写。
逻辑:库存运行链路以 ShippingInventorySource.source_code 为业务主键;RPA Profile 仅提供登录连接配置,
外部系统映射仅供后端内部复用,不承载调拨决策。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingInventoryField(Base):
"""用户维护的库存业务字段目录;程序仅依据字段 ID 和业务用途运行。"""
__tablename__ = 'shipping_inventory_fields'
__table_args__ = (
UniqueConstraint('field_code', name='uq_shipping_inventory_fields_code'),
UniqueConstraint('display_name', name='uq_shipping_inventory_fields_display_name'),
CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_inventory_fields_status'),
CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_shipping_inventory_fields_value_type'),
CheckConstraint(
"usage_type IN ('match_identity', 'inventory_quantity', 'warehouse_identity', 'general')",
name='ck_shipping_inventory_fields_usage_type',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
# Internal stable code supports runtime contracts; it is deliberately not exposed in the business UI.
field_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
value_type: Mapped[str] = mapped_column(String(16), nullable=False, default='text', server_default='text')
usage_type: Mapped[str] = mapped_column(String(32), nullable=False, default='general', server_default='general')
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=100, server_default='100')
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
class ShippingRpaProfile(Base):
"""货代库存登录连接配置;凭据字段始终保存密文。"""
__tablename__ = 'shipping_rpa_profiles'
__table_args__ = (
UniqueConstraint('profile_code', name='uq_shipping_rpa_profiles_profile_code'),
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_rpa_profiles_connector_type'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
login_url: Mapped[str] = mapped_column(String(500), nullable=False)
username_ciphertext: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
password_ciphertext: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
login_config_json: Mapped[dict[str, Any]] = mapped_column(
JSON, default=lambda: {'auth_mode': 'password'}, nullable=False,
)
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
credential_updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='rpa_profile')
class ShippingInventorySource(Base):
"""库存业务来源;固定仓或库存行动态解析 Warehouse。"""
__tablename__ = 'shipping_inventory_sources'
__table_args__ = (
UniqueConstraint('source_code', name='uq_shipping_inventory_sources_source_code'),
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_inventory_sources_connector_type'),
CheckConstraint(
"(warehouse_resolution_mode = 'fixed' AND fixed_warehouse_id IS NOT NULL) "
"OR (warehouse_resolution_mode = 'inventory_match' AND fixed_warehouse_id IS NULL)",
name='ck_shipping_inventory_sources_warehouse_mode',
),
CheckConstraint(
"enabled = false OR (parsing_profile_id IS NOT NULL AND excel_template_id IS NOT NULL)",
name='ck_shipping_inventory_sources_enabled_bindings',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
rpa_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_rpa_profiles.id'), nullable=False, index=True)
parsing_profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True)
excel_template_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=True, index=True)
warehouse_resolution_mode: Mapped[str] = mapped_column(String(32), nullable=False)
fixed_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 业务报表定义属于 Source;Driver 的 selector、等待与下载实现不进入数据库配置。
report_path_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, server_default=text("'{}'"), nullable=False)
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, default=list, server_default=text("'[]'"), nullable=False)
snapshot_ttl_seconds: Mapped[int] = mapped_column(Integer, default=86400, server_default=text('86400'), nullable=False)
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
rpa_profile: Mapped[ShippingRpaProfile] = relationship(back_populates='sources')
parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship(back_populates='sources')
excel_template: Mapped[Optional['ShippingExcelTemplate']] = relationship(back_populates='sources')
external_mappings: Mapped[list['ShippingInventoryExternalMapping']] = relationship(
back_populates='inventory_source', cascade='all, delete-orphan'
)
class ShippingInventorySourceParsingBindingAudit(Base):
"""库存站点解析方案绑定的只追加审计;保存绑定前后快照以支持上线追溯。"""
__tablename__ = 'shipping_inventory_source_parsing_binding_audits'
__table_args__ = (
Index('ix_inventory_source_parsing_binding_audit_source_created', 'inventory_source_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False)
previous_parsing_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True,
)
parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False)
operation: Mapped[str] = mapped_column(String(32), nullable=False)
reason: Mapped[str] = mapped_column(String(500), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
source_config_version_before: Mapped[int] = mapped_column(Integer, nullable=False)
source_config_version_after: Mapped[int] = mapped_column(Integer, nullable=False)
before_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
after_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingInventoryParsingProfile(Base):
"""可跨库存源复用的库存文件结构、样本证据与订单匹配配置。"""
__tablename__ = 'shipping_inventory_parsing_profiles'
__table_args__ = (
UniqueConstraint('profile_code', 'version', name='uq_inventory_parsing_profiles_code_version'),
Index('ix_inv_parse_profile_exact_fp', 'exact_structure_fingerprint'),
Index('ix_inv_parse_profile_compat_fp', 'compatibility_fingerprint'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
file_format: Mapped[str] = mapped_column(String(16), nullable=False, default='xlsx', server_default='xlsx')
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
structure_definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
exact_structure_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
compatibility_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
# Draft and published definitions keep their analysed sample evidence without retaining the full uploaded workbook.
sample_analysis_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True,
)
# Preserve every confirmed evidence switch so a draft remains explainable after samples change.
sample_evidence_history_json: Mapped[list[dict[str, Any]]] = mapped_column(
JSON, nullable=False, default=list, server_default=text("'[]'"),
)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='parsing_profile')
sample_analysis: Mapped[Optional['ShippingInventoryStructureAnalysis']] = relationship(
foreign_keys=[sample_analysis_id],
)
class ShippingInventoryStructureAnalysis(Base):
"""库存文件结构分析记录;保存脱敏结构证据,不承载正式库存快照。"""
__tablename__ = 'shipping_inventory_structure_analyses'
__table_args__ = (
Index('ix_inv_structure_analysis_file_hash', 'file_checksum'),
Index('ix_inv_structure_analysis_created', 'created_at'),
Index('ix_inv_structure_analysis_exact_fp', 'exact_structure_fingerprint'),
Index('ix_inv_structure_analysis_compat_fp', 'compatibility_fingerprint'),
)
id: Mapped[int] = mapped_column(primary_key=True)
source_kind: Mapped[str] = mapped_column(String(32), nullable=False, default='sample_upload', server_default='sample_upload')
source_file_name: Mapped[str] = mapped_column(String(255), nullable=False)
# Only temporary conversation sessions retain a short-lived source file for confirmation.
storage_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
file_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
file_format: Mapped[str] = mapped_column(String(16), nullable=False)
analysis_status: Mapped[str] = mapped_column(String(32), nullable=False, default='ready', server_default='ready')
structure_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
suggested_mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
validation_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
sample_rows_json: Mapped[list[list[Any]]] = mapped_column(JSON, nullable=False, default=list)
warning_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
exact_structure_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
compatibility_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
match_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingInventoryConfigurationTestRun(Base):
"""库存站点配置测试的异步 RPA 运行;锁定站点和连接配置版本且不进入生产库存池。"""
__tablename__ = 'shipping_inventory_configuration_test_runs'
__table_args__ = (UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),)
id: Mapped[int] = mapped_column(primary_key=True)
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
validation_batch_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_validation_batches.id'), nullable=True, index=True,
)
rpa_batch_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
source_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
rpa_profile_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='awaiting_rpa', server_default='awaiting_rpa')
stage: Mapped[str] = mapped_column(String(32), nullable=False, default='waiting_worker', server_default='waiting_worker')
analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True)
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
class ShippingInventoryValidationBatch(Base):
"""库存站点批量验证的聚合运行;逐站点结果仍由 ConfigurationTestRun 保存。"""
__tablename__ = 'shipping_inventory_validation_batches'
__table_args__ = (UniqueConstraint('batch_no', name='uq_inventory_validation_batches_batch_no'),)
id: Mapped[int] = mapped_column(primary_key=True)
batch_no: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
total_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
success_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
empty_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
failed_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
stale_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
retry_of_batch_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_validation_batches.id'), nullable=True,
)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
class ShippingInventoryRoutingRule(Base):
"""可版本化的库存源路由决策表;仅产出受控 Source 候选。"""
__tablename__ = 'shipping_inventory_routing_rules'
__table_args__ = (
UniqueConstraint('rule_code', 'version', name='uq_shipping_inventory_routing_rules_code_version'),
CheckConstraint("scope IN ('task', 'line')", name='ck_shipping_inventory_routing_rules_scope'),
CheckConstraint("match_mode IN ('all', 'any')", name='ck_shipping_inventory_routing_rules_match_mode'),
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_inventory_routing_rules_status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
rule_code: Mapped[str] = mapped_column(String(64), nullable=False)
rule_name: Mapped[str] = mapped_column(String(128), nullable=False)
scope: Mapped[str] = mapped_column(String(16), nullable=False)
priority: Mapped[int] = mapped_column(Integer, default=0, server_default=text('0'), nullable=False)
match_mode: Mapped[str] = mapped_column(String(16), default='all', server_default=text("'all'"), nullable=False)
status: Mapped[str] = mapped_column(String(16), default='draft', server_default=text("'draft'"), nullable=False)
action_type: Mapped[str] = mapped_column(String(64), nullable=False)
action_payload_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, nullable=False)
version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
effective_from: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
effective_to: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
conditions: Mapped[list['ShippingInventoryRoutingRuleCondition']] = relationship(
back_populates='rule', cascade='all, delete-orphan', order_by='ShippingInventoryRoutingRuleCondition.sequence'
)
class ShippingInventoryRoutingRuleCondition(Base):
"""库存源路由条件;仅引用已发布订单 Schema 的稳定 field_id。"""
__tablename__ = 'shipping_inventory_routing_rule_conditions'
__table_args__ = (
UniqueConstraint('rule_id', 'sequence', name='uq_shipping_inventory_routing_rule_conditions_sequence'),
CheckConstraint(
"source_kind = 'order_field' AND order_field_id IS NOT NULL",
name='ck_inventory_routing_condition_source',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True)
condition_group: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
source_kind: Mapped[str] = mapped_column(String(16), nullable=False, default='order_field')
order_field_id: Mapped[Optional[str]] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=True)
operator: Mapped[str] = mapped_column(String(32), nullable=False)
expected_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
sequence: Mapped[int] = mapped_column(Integer, nullable=False)
rule: Mapped[ShippingInventoryRoutingRule] = relationship(back_populates='conditions')
class ShippingInventoryRoutingRuleVersion(Base):
"""已发布路由规则的不可变定义快照,供任务审计回放使用。"""
__tablename__ = 'shipping_inventory_routing_rule_versions'
__table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_shipping_inventory_routing_rule_versions_rule_version'),)
id: Mapped[int] = mapped_column(primary_key=True)
rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True)
version: Mapped[int] = mapped_column(Integer, nullable=False)
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False)
published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingInventoryExternalMapping(Base):
"""货代库存身份到外部系统仓库的单向映射;不承载调拨规则。"""
__tablename__ = 'shipping_inventory_external_mappings'
__table_args__ = (
Index(
'uq_shipping_inv_ext_map_src_default_enabled',
'inventory_source_id',
unique=True,
postgresql_where=text('freight_warehouse_id IS NULL AND enabled = true'),
sqlite_where=text('freight_warehouse_id IS NULL AND enabled = 1'),
),
Index(
'uq_shipping_inv_ext_map_src_wh_enabled',
'inventory_source_id',
'freight_warehouse_id',
unique=True,
postgresql_where=text('freight_warehouse_id IS NOT NULL AND enabled = true'),
sqlite_where=text('freight_warehouse_id IS NOT NULL AND enabled = 1'),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
freight_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
external_system_code: Mapped[str] = mapped_column(String(32), nullable=False)
external_organization_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
external_site_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
external_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False)
external_warehouse_name: Mapped[str] = mapped_column(String(128), nullable=False)
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
inventory_source: Mapped[ShippingInventorySource] = relationship(back_populates='external_mappings')
@@ -0,0 +1,40 @@
"""
models/shipping_inventory_mapping.py
用途:保存不可变库存字段映射版本。
依赖:ShippingInventoryFile、ShippingInventoryParsingProfile、Base。
逻辑:每次确认/重跑创建新版本,匹配 Attempt 通过 mapping_id 精确引用。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingInventoryMapping(Base):
"""库存文件的不可变字段映射版本。"""
__tablename__ = 'shipping_inventory_mappings'
__table_args__ = (
UniqueConstraint('inventory_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'),
CheckConstraint("status IN ('active','superseded','invalidated')", name='ck_shipping_inventory_mapping_status'),
Index('ix_shipping_inventory_mapping_file_status', 'inventory_file_id', 'status'),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='CASCADE'), nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id', ondelete='SET NULL'), nullable=True)
mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id'), nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -0,0 +1,79 @@
"""
models/shipping_inventory_preparation.py
用途:表达一次任务级库存准备轮次及逐库存源状态。
依赖:ShippingNotice、RecoveryPlan、RPA Attempt、InventoryFile、TaskInventoryLink、Base。
逻辑:PreparationAttempt 聚合多个 SourceAttempt,支持有效源复用和问题源单独重拉。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingInventoryPreparationAttempt(Base):
"""一次任务级库存准备恢复轮次。"""
__tablename__ = 'shipping_inventory_preparation_attempts'
__table_args__ = (
UniqueConstraint('task_id', 'attempt_no', name='uq_shipping_inventory_preparation_task_attempt'),
CheckConstraint(
"status IN ('queued','running','waiting_external','waiting_manual','succeeded','failed','cancelled','superseded')",
name='ck_shipping_inventory_preparation_status',
),
Index('ix_shipping_inventory_preparation_task_status', 'task_id', 'status', 'created_at'),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=False)
execution_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_executions.id', ondelete='SET NULL'), nullable=True)
gate_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', ondelete='SET NULL'), nullable=True, index=True)
recovery_plan_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_recovery_plans.id', ondelete='SET NULL'), nullable=True)
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
candidate_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), nullable=True)
input_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
output_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
source_attempts = relationship('ShippingInventoryPreparationSourceAttempt', back_populates='preparation_attempt', cascade='all, delete-orphan')
class ShippingInventoryPreparationSourceAttempt(Base):
"""准备轮次中某个库存源的业务状态。"""
__tablename__ = 'shipping_inventory_preparation_source_attempts'
__table_args__ = (
UniqueConstraint('preparation_attempt_id', 'source_code', name='uq_shipping_inventory_preparation_source_attempt'),
CheckConstraint(
"status IN ('ready','reusable','skipped','failed','waiting','queued','running')",
name='ck_shipping_inventory_preparation_source_status',
),
Index('ix_shipping_inventory_preparation_source_status', 'source_code', 'status', 'created_at'),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
preparation_attempt_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='CASCADE'), nullable=False)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
skip_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
rpa_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_rpa_attempts.id', ondelete='SET NULL'), nullable=True)
inventory_file_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True)
task_inventory_link_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_links.id', ondelete='SET NULL'), nullable=True)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
preparation_attempt = relationship('ShippingInventoryPreparationAttempt', back_populates='source_attempts')
@@ -0,0 +1,46 @@
"""
backend/app/models/shipping_notice_line.py
用途:正式发货通知行(shipping_notice_lines),对齐蓝图建单后命名空间。
依赖:shipping_notices、shipping_order_snapshot_lines、SQLAlchemy Base。
逻辑:冻结 Snapshot 时双写;履约仍以 Snapshot 为权威,本表供 Notice 域查询与 1:N 扩展。
"""
from __future__ import annotations
from datetime import datetime
from decimal import Decimal
from typing import Any, Optional
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, Numeric, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingNoticeLine(Base):
"""
正式发货通知行投影。
核心逻辑:由 Snapshot 冻结路径幂等写入;position 在同一 Notice 内唯一。
"""
__tablename__ = 'shipping_notice_lines'
__table_args__ = (
UniqueConstraint('notice_id', 'position', name='uq_shipping_notice_lines_position'),
Index('ix_shipping_notice_lines_notice_id', 'notice_id'),
Index('ix_shipping_notice_lines_snapshot_line_id', 'snapshot_line_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
notice_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=False)
snapshot_line_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_snapshot_lines.id', ondelete='SET NULL'), nullable=True,
)
position: Mapped[int] = mapped_column(Integer, nullable=False)
line_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
required_qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
field_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -0,0 +1,142 @@
"""
models/shipping_notice_line_inventory_match.py
用途:正式 OT(ShippingNotice)行级库存匹配事实持久化——可用数量/短缺/match_result 的真相源。
依赖:shipping_notices、shipping_inventory_files、shipping_order_review_cases(可选关联)。
逻辑:由 inventory_matching 完成后写入;同一 OT+行+快照唯一;新快照新增行不覆盖历史;
is_current 标记投影用的当前事实;禁止用 Job payload / line_projections 充当正式真相。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingNoticeLineInventoryMatch(Base):
"""一条 OT 明细在某库存快照下的匹配事实(不可原地覆盖历史快照结果)。"""
__tablename__ = 'shipping_notice_line_inventory_matches'
__table_args__ = (
UniqueConstraint(
'task_id',
'line_key',
'inventory_snapshot_id',
name='uq_shipping_notice_line_inv_match_task_line_snap',
),
# 同一 OT 行同一时刻仅一条当前事实(PostgreSQL partial unique)。
Index(
'uq_shipping_notice_line_inv_match_current',
'task_id',
'line_key',
unique=True,
postgresql_where=text('is_current IS TRUE'),
),
Index('ix_shipping_notice_line_inv_match_task', 'task_id'),
Index('ix_shipping_notice_line_inv_match_case', 'review_case_id'),
Index('ix_shipping_notice_line_inv_match_snapshot', 'inventory_snapshot_id'),
CheckConstraint(
"match_result IN ("
"'matched', 'not_found', 'result_missing', 'preparing', "
"'source_conflict', 'invalid_key', 'mapping_failed', 'unavailable', 'invalid'"
")",
name='ck_shipping_notice_line_inv_match_result',
),
CheckConstraint(
"inventory_status IN ("
"'ready', 'preparing', 'mapping_failed', 'source_conflict', "
"'unavailable', 'invalid_key', 'invalid'"
")",
name='ck_shipping_notice_line_inv_match_status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notices.id', ondelete='CASCADE'),
nullable=False,
)
review_case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='SET NULL'),
nullable=True,
)
line_key: Mapped[str] = mapped_column(String(64), nullable=False)
line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'),
nullable=True,
index=True,
)
candidate_set_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
candidate_line_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_lines.id', ondelete='SET NULL'),
nullable=True,
index=True,
)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'),
nullable=True,
)
match_result: Mapped[str] = mapped_column(String(32), nullable=False)
inventory_status: Mapped[str] = mapped_column(String(32), nullable=False)
required_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
shortage_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
matching_rule_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
is_current: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default='true')
matched_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
# BE-7:自动履约失败独立存储(非 decision_code 枚举)
auto_fulfill_failed: Mapped[bool] = mapped_column(
Boolean, nullable=False, default=False, server_default='false',
)
auto_fulfill_error_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
auto_fulfill_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
auto_fulfill_failed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime,
default=datetime.utcnow,
onupdate=datetime.utcnow,
nullable=False,
)
# T6: 行级实际源证据(决策 E1 硬约束)——用于幂等保护与跨源匹配审计。
matched_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
matched_row_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
evidence_ref: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
allowed_source_codes_snapshot: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)
matched_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
evidence_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
match_attempt_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_process_gate_attempts.id', ondelete='SET NULL'),
nullable=True,
index=True,
)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
superseded_by_match_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_line_inventory_matches.id'), nullable=True)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
mapping_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id', ondelete='SET NULL'), nullable=True, index=True)
verification_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id', ondelete='SET NULL'), nullable=True, index=True)
@@ -0,0 +1,55 @@
"""
backend/app/models/shipping_order_candidate_evidence.py
用途:Candidate 主证据/辅助证据/冲突证据的可查询关系表(蓝图 §六)。
依赖:shipping_order_candidates、shipping_order_documents、SQLAlchemy Base。
逻辑:替代仅落在 Candidate.evidence_json 的不可查询结构;PDF 优先裁决审计可按字段检索。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, text
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingOrderCandidateEvidence(Base):
"""
Candidate 与文档证据的角色化关联。
核心逻辑:primary_pdf 标识主证据;conflict 记录跨证据冲突;payload_json 存轻量引用非全文。
"""
__tablename__ = 'shipping_order_candidate_evidences'
__table_args__ = (
CheckConstraint(
"evidence_role IN ('primary_pdf', 'auxiliary', 'conflict', 'context')",
name='ck_shipping_order_candidate_evidences_role',
),
CheckConstraint(
"evidence_kind IN ('pdf', 'email_body', 'excel', 'word', 'image', 'ocr', 'model', 'other')",
name='ck_shipping_order_candidate_evidences_kind',
),
Index('ix_shipping_order_candidate_evidences_candidate', 'candidate_id'),
Index('ix_shipping_order_candidate_evidences_document', 'document_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
candidate_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_candidates.id', ondelete='CASCADE'), nullable=False,
)
document_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_documents.id', ondelete='SET NULL'), nullable=True,
)
evidence_role: Mapped[str] = mapped_column(String(32), nullable=False)
evidence_kind: Mapped[str] = mapped_column(String(32), nullable=False)
is_primary: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false'))
field_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
value_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
decision_rule_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -0,0 +1,70 @@
"""
models/shipping_order_candidate_qualification.py
用途:持久化 Candidate 级统一自动建单资格评估快照(追加式历史)。
依赖:SQLAlchemy Base、shipping_order_candidates / shipping_order_processing_runs / users。
逻辑:每次评估追加一行;is_current 标记最新;模板质量信息仅出现在 parser_trace_json。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import Boolean, CheckConstraint, DateTime, Float, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingOrderCandidateQualification(Base):
"""Candidate 自动建单资格快照;同一 Candidate 可有多条历史评估。"""
__tablename__ = 'shipping_order_candidate_qualifications'
__table_args__ = (
UniqueConstraint(
'candidate_id',
'evaluation_seq',
name='ix_ship_order_cand_qual_candidate_seq',
),
CheckConstraint(
"status IN ('eligible', 'review_required', 'blocked', 'rejected')",
name='ck_shipping_order_candidate_qualifications_status',
),
Index(
'ix_ship_order_cand_qual_status_evaluated',
'status', 'evaluated_at',
),
Index(
'ix_ship_order_cand_qual_candidate_current',
'candidate_id', 'is_current',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
candidate_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_candidates.id'),
nullable=False,
index=True,
)
run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id'),
nullable=True,
index=True,
)
evaluation_seq: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
is_current: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
qualification_score: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)
gate_results_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
blocking_reason_codes_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
parser_trace_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
evidence_snapshot_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
evaluator_version: Mapped[str] = mapped_column(String(64), nullable=False)
evaluated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
evaluated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
@@ -0,0 +1,63 @@
"""
backend/app/models/shipping_order_customer_match.py
用途:保存订单解析中账款客户、送货客户与货代客户主数据的角色化匹配结果。
依赖:ShippingOrderExtraction、ShippingCustomer、users。
逻辑:动态订单字段保留原文客户名称;本表按角色保存规则版本化身份指纹、候选、确认客户及名称/简称快照,供冻结和导出读取。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderCustomerMatch(Base):
"""一次订单解析中的角色化客户匹配;每个解析记录的每种客户角色仅保留一条当前结果。"""
__tablename__ = 'shipping_order_customer_matches'
__table_args__ = (
UniqueConstraint('extraction_id', 'role', name='uq_shipping_order_customer_matches_extraction_role'),
CheckConstraint("role IN ('bill_to', 'ship_to')", name='ck_shipping_order_customer_matches_role'),
CheckConstraint(
"status IN ('unmatched', 'unique_candidate', 'ambiguous', 'confirmed')",
name='ck_shipping_order_customer_matches_status',
),
Index('ix_shipping_order_customer_matches_customer_role', 'customer_id', 'role'),
)
id: Mapped[int] = mapped_column(primary_key=True)
extraction_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False, index=True,
)
role: Mapped[str] = mapped_column(String(16), nullable=False)
raw_name: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
normalized_name: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
source_system: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
external_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
identity_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
identity_rule_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
identity_components_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='unmatched', server_default='unmatched')
customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
site_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customer_sites.id'), nullable=True)
customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True)
candidates_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
resolution_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
confirmation_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
extraction = relationship('ShippingOrderExtraction')
customer = relationship('ShippingCustomer')
site = relationship('ShippingCustomerSite')
@@ -0,0 +1,304 @@
"""
backend/app/models/shipping_order_document_profile.py
用途:保存订单坐标 Profile 的版本、样本绑定、可选客户范围、版面签名引用与追加式配置审计。
依赖:订单 Schema、订单文档、用户和 SQLAlchemy Base。
逻辑:Profile 主表保存可索引摘要、scoring_policy_version 与当前有效版面签名轻量引用;
完整签名存 ValidationRun.result_snapshot_json;完整 v2 定义仍在 definition_json。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderDocumentProfile(Base):
"""版本化订单文档模板解析配置;published/retired 行不可原地修改。"""
__tablename__ = 'shipping_order_document_profiles'
__table_args__ = (
UniqueConstraint('profile_code', 'version', name='uq_shipping_order_document_profiles_code_version'),
CheckConstraint(
"status IN ('draft', 'published', 'retired')",
name='ck_shipping_order_document_profiles_status',
),
Index('ix_shipping_order_document_profiles_schema_status', 'schema_version_id', 'status'),
Index('ix_shipping_order_document_profiles_fingerprint', 'structure_fingerprint'),
Index('ix_shipping_order_document_profiles_mode_status', 'template_mode', 'status'),
Index(
'uq_shipping_order_document_profiles_one_published',
'profile_code',
unique=True,
postgresql_where=text("status = 'published'"),
sqlite_where=text("status = 'published'"),
),
Index('ix_shipping_order_document_profiles_matching_signature_run', 'matching_signature_run_id'),
Index('ix_shipping_order_document_profiles_matching_signature_checksum', 'matching_signature_checksum'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
schema_version_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_schema_versions.id'), nullable=False,
)
structure_fingerprint: Mapped[str] = mapped_column(String(64), nullable=False)
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
template_mode: Mapped[str] = mapped_column(String(32), nullable=False, default='coordinate', server_default='coordinate')
training_sample_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
match_strategy_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
customer_ids_json: Mapped[Optional[list[int]]] = mapped_column(JSON, nullable=True)
scoring_policy_version: Mapped[str] = mapped_column(
String(64), nullable=False, default='order-profile-scoring.v1', server_default='order-profile-scoring.v1',
)
# 当前有效版面签名轻量引用;完整签名仅存在于 ValidationRun.result_snapshot_json。
matching_signature_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_order_document_profile_validation_runs.id',
ondelete='SET NULL',
use_alter=True,
name='fk_sodp_matching_signature_run',
),
nullable=True,
)
matching_signature_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
matching_signature_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
change_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
source_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_document_profiles.id'), nullable=True,
)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
retired_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
schema_version = relationship('ShippingOrderSchemaVersion')
source_profile: Mapped[Optional['ShippingOrderDocumentProfile']] = relationship(
remote_side='ShippingOrderDocumentProfile.id', foreign_keys=[source_profile_id],
)
matching_signature_run: Mapped[Optional['ShippingOrderDocumentProfileValidationRun']] = relationship(
'ShippingOrderDocumentProfileValidationRun',
foreign_keys=[matching_signature_run_id],
post_update=True,
)
class ShippingOrderDocumentProfileSample(Base):
"""绑定 Profile 与建模/盲测样本文档;不复制正文、PDF 或对象存储地址。"""
__tablename__ = 'shipping_order_document_profile_samples'
__table_args__ = (
CheckConstraint("sample_role IN ('annotation', 'training', 'blind_test')", name='ck_shipping_order_document_profile_samples_role'),
UniqueConstraint('profile_id', 'document_id', 'table_id', 'sample_role', name='uq_shipping_order_document_profile_samples_source_role'),
Index('ix_shipping_order_document_profile_samples_document', 'document_id'),
Index('ix_shipping_order_document_profile_samples_layout_version', 'layout_version_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_documents.id'), nullable=False)
table_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
sample_role: Mapped[str] = mapped_column(String(16), nullable=False, default='annotation', server_default='annotation')
layout_version_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_document_layout_versions.id'), nullable=True,
)
source_content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
layout_payload_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
layout_contract_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
parser_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
parser_name: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
evidence_frozen_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
source_filename_snapshot: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
page_count_snapshot: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
table_identity_snapshot: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingOrderDocumentProfileAudit(Base):
"""追加式 Profile 操作审计;详情只保存无敏感值的结构摘要和对象身份。"""
__tablename__ = 'shipping_order_document_profile_audits'
__table_args__ = (
Index('ix_shipping_order_document_profile_audits_profile_created', 'profile_id', 'created_at'),
Index('ix_shipping_order_document_profile_audits_profile_request', 'profile_id', 'request_id', 'id'),
Index('ix_shipping_order_document_profile_audits_operation', 'operation_id', 'id'),
Index('ix_shipping_order_document_profile_audits_document', 'document_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='SET NULL'), nullable=True)
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_documents.id', ondelete='SET NULL'), nullable=True)
event_type: Mapped[str] = mapped_column(String(48), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
browser_session_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
revision_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingOrderDocumentProfileDraftRevision(Base):
"""草稿每次有效保存的不可变定义快照;同 checksum 重试只能复用同一修订。"""
__tablename__ = 'shipping_order_document_profile_draft_revisions'
__table_args__ = (
UniqueConstraint('profile_id', 'revision_no', name='uq_shipping_order_document_profile_draft_revisions_number'),
UniqueConstraint('profile_id', 'operation_id', name='uq_shipping_order_document_profile_draft_revisions_operation'),
Index('ix_shipping_order_document_profile_draft_revisions_operation', 'operation_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
revision_no: Mapped[int] = mapped_column(Integer, nullable=False)
base_lock_version: Mapped[int] = mapped_column(Integer, nullable=False)
result_lock_version: Mapped[int] = mapped_column(Integer, nullable=False)
definition_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
change_source: Mapped[str] = mapped_column(String(32), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
browser_session_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
operation_id: Mapped[str] = mapped_column(String(64), nullable=False)
change_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
definition_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingOrderDocumentProfileEditLease(Base):
"""Profile 单写者编辑租约;令牌仅保存 SHA-256 哈希,不能从数据库还原。"""
__tablename__ = 'shipping_order_document_profile_edit_leases'
__table_args__ = (
UniqueConstraint('profile_id', name='uq_shipping_order_document_profile_edit_leases_profile'),
Index('ix_shipping_order_document_profile_edit_leases_expires', 'expires_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
lease_token_hash: Mapped[str] = mapped_column(String(64), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
browser_session_id: Mapped[str] = mapped_column(String(128), nullable=False)
expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
last_renewed_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
taken_over_from_actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
lock_version: Mapped[int] = mapped_column(Integer, nullable=False)
class ShippingOrderDocumentProfileSuggestionDecision(Base):
"""冻结算法建议及管理员决定;建议永不直接覆盖已保存或人工画布配置。"""
__tablename__ = 'shipping_order_document_profile_suggestion_decisions'
__table_args__ = (
CheckConstraint("decision IN ('accepted', 'accepted_adjusted', 'rejected')", name='ck_shipping_order_document_profile_suggestion_decisions_decision'),
UniqueConstraint('profile_id', 'suggestion_id', name='uq_shipping_order_document_profile_suggestion_decisions_suggestion'),
Index('ix_shipping_order_document_profile_suggestion_decisions_profile_revision', 'profile_id', 'revision_no'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
revision_no: Mapped[int] = mapped_column(Integer, nullable=False)
sample_binding_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profile_samples.id', ondelete='SET NULL'), nullable=True)
layout_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_layout_versions.id'), nullable=True)
parser_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
algorithm_version: Mapped[str] = mapped_column(String(64), nullable=False)
suggestion_id: Mapped[str] = mapped_column(String(64), nullable=False)
suggestion_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
decision: Mapped[str] = mapped_column(String(24), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
operation_id: Mapped[str] = mapped_column(String(64), nullable=False)
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingOrderDocumentProfileValidationRun(Base):
"""不可变验证运行;输出绑定精确草稿 checksum,草稿变化后只能标记 stale 而不重写历史。"""
__tablename__ = 'shipping_order_document_profile_validation_runs'
__table_args__ = (
CheckConstraint(
"run_type IN ('instant_check', 'current_sample', 'blind_test', 'scenario_coverage', "
"'schema_compatibility', 'layout_signature', 'cross_template_overlap', 'xfa_structure_signature')",
name='ck_shipping_order_document_profile_validation_runs_type',
),
CheckConstraint("status IN ('pending', 'running', 'passed', 'failed')", name='ck_shipping_order_document_profile_validation_runs_status'),
Index('ix_shipping_order_document_profile_validation_runs_profile_created', 'profile_id', 'created_at'),
Index('ix_shipping_order_document_profile_validation_runs_checksum', 'profile_id', 'definition_checksum'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
revision_no: Mapped[int] = mapped_column(Integer, nullable=False)
definition_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
schema_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
sample_binding_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profile_samples.id', ondelete='SET NULL'), nullable=True)
layout_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_layout_versions.id'), nullable=True)
layout_payload_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
parser_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
run_type: Mapped[str] = mapped_column(String(32), nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False)
summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
result_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
operation_id: Mapped[str] = mapped_column(String(64), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
class ShippingOrderDocumentProfilePublishCheckReport(Base):
"""不可变发布检查报告;只能由与冻结草稿完全一致的一次原子发布消费。"""
__tablename__ = 'shipping_order_document_profile_publish_check_reports'
__table_args__ = (
CheckConstraint("status IN ('valid', 'invalidated', 'consumed')", name='ck_shipping_order_document_profile_publish_check_reports_status'),
UniqueConstraint('profile_id', 'operation_id', name='uq_shipping_order_document_profile_publish_check_reports_operation'),
Index('ix_shipping_order_document_profile_publish_check_reports_profile_created', 'profile_id', 'created_at'),
Index('ix_shipping_order_document_profile_publish_check_reports_report_no', 'report_no', unique=True),
)
id: Mapped[int] = mapped_column(primary_key=True)
report_no: Mapped[str] = mapped_column(String(64), nullable=False)
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
revision_no: Mapped[int] = mapped_column(Integer, nullable=False)
definition_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
lock_version: Mapped[int] = mapped_column(Integer, nullable=False)
validation_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profile_validation_runs.id', ondelete='SET NULL'), nullable=True)
matching_signature_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_document_profile_validation_runs.id', ondelete='SET NULL'),
nullable=True,
)
matching_signature_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
overlap_validation_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_document_profile_validation_runs.id', ondelete='SET NULL'),
nullable=True,
)
matcher_policy_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
base_published_profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='SET NULL'), nullable=True)
semantic_diff_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
blocking_items_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
warning_items_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
confirmed_warning_keys_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='valid')
expires_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[str] = mapped_column(String(64), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
consumed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
@@ -0,0 +1,40 @@
"""
backend/app/models/shipping_order_document_version.py
用途:OT 文档/重识别版本台账(shipping_order_document_versions),对齐蓝图。
依赖:shipping_order_tasks、shipping_order_processing_runs、SQLAlchemy Base。
逻辑:每次新建/重识别 Run 挂到同一 OT 时追加版本;替代仅靠 Notice.document_version 的弱模型。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingOrderDocumentVersion(Base):
"""
OT 下的文档识别版本。
核心逻辑:(order_task_id, version) 唯一;extraction_run_id 追溯本次识别。
"""
__tablename__ = 'shipping_order_document_versions'
__table_args__ = (
UniqueConstraint('order_task_id', 'version', name='uq_shipping_order_document_versions_task_version'),
Index('ix_shipping_order_document_versions_run', 'extraction_run_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
order_task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False)
extraction_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id', ondelete='SET NULL'), nullable=True,
)
content_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -0,0 +1,83 @@
"""
backend/app/models/shipping_order_extraction_quality.py
用途:保存订单抽取 L7 影子验收批次、双人匿名标签和双角色批准事实。
依赖:Agent、User、ShippingOrderSchemaVersion、ShippingOrderProcessingRun。
逻辑:批次锁定 owner/schema/阈值;同 Run 两名管理员标签一致后计入指标,达标后双人批准供 Runtime Binding 门禁引用。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderExtractionQualityBatch(Base):
"""L7 影子验收批次;批准后成为不可变自动建单发布凭证。"""
__tablename__ = 'shipping_order_extraction_quality_batches'
__table_args__ = (
UniqueConstraint('batch_no', name='uq_shipping_order_extraction_quality_batches_no'),
CheckConstraint(
"status IN ('collecting', 'ready', 'approved', 'rejected')",
name='ck_shipping_order_extraction_quality_batches_status',
),
Index('ix_shipping_order_extraction_quality_batches_owner_created', 'owner_agent_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
batch_no: Mapped[str] = mapped_column(String(64), nullable=False)
owner_agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), nullable=False, index=True)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
threshold_version: Mapped[str] = mapped_column(String(32), nullable=False, default='l7.v1', server_default='l7.v1')
status: Mapped[str] = mapped_column(String(32), nullable=False, default='collecting', server_default='collecting')
created_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
business_approved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
business_approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
technical_approved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
technical_approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
rejected_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
rejected_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
rejection_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
labels: Mapped[list['ShippingOrderExtractionQualityLabel']] = relationship(
back_populates='batch', cascade='all, delete-orphan', order_by='ShippingOrderExtractionQualityLabel.id',
)
class ShippingOrderExtractionQualityLabel(Base):
"""单个管理员对真实 Run 提交的匿名质量计数;不保存订单字段值或正文。"""
__tablename__ = 'shipping_order_extraction_quality_labels'
__table_args__ = (
UniqueConstraint('batch_id', 'run_id', 'reviewer_id', name='uq_shipping_order_quality_label_reviewer'),
CheckConstraint('core_expected_count >= 0', name='ck_shipping_order_quality_expected_nonnegative'),
CheckConstraint('core_extracted_count >= 0', name='ck_shipping_order_quality_extracted_nonnegative'),
CheckConstraint('core_correct_count >= 0', name='ck_shipping_order_quality_correct_nonnegative'),
Index('ix_shipping_order_quality_labels_batch_run', 'batch_id', 'run_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
batch_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_extraction_quality_batches.id', ondelete='CASCADE'), nullable=False,
)
run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_processing_runs.id'), nullable=False)
reviewer_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
core_expected_count: Mapped[int] = mapped_column(Integer, nullable=False)
core_extracted_count: Mapped[int] = mapped_column(Integer, nullable=False)
core_correct_count: Mapped[int] = mapped_column(Integer, nullable=False)
wrong_merge: Mapped[bool] = mapped_column(nullable=False, default=False, server_default='false')
wrong_split: Mapped[bool] = mapped_column(nullable=False, default=False, server_default='false')
wrong_auto_create: Mapped[bool] = mapped_column(nullable=False, default=False, server_default='false')
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
batch: Mapped['ShippingOrderExtractionQualityBatch'] = relationship(back_populates='labels')
@@ -0,0 +1,499 @@
"""
backend/app/models/shipping_order_extraction_run.py
用途:定义建单前订单 Processing Run 的领域运行记录及其冻结 Intake 集合。
物理表名:shipping_order_processing_runs / _run_intakes / _plans / _units /
shipping_order_route_decisions(本文件名保留以减少 import 变更)。
依赖:agents、users、jobs、shipping_order_intakes、shipping_order_schema_versions。
逻辑:Run 保存用户可见生命周期和不可变输入快照;自动建单策略随 Schema 快照冻结。
取消为请求语义:cancellation_* 元数据记录请求与生效;Worker 在安全点收口,
progress_version 作为最后活动版本供轮询与乐观协作。
会话多任务聚合(2026-08-03 阶段 1):用户可见任务(OT-…)与内部 Run(WF-/SNER-…)分层;
已移除 uq_*_active_conversation,同会话允许多个 queued|processing Run;
统一提交靠 can_append / composer_context / focused_user_task 裁决追加或新建。
upload_batch_id 仅隔离 Intake 选择,不得充当 user_task_no;
user_task_no 延迟至 Candidate/OT 形成后分配(nullable);reparse/后继 Run 继承谱系 OT。
client_submission_id 为客户端幂等键(与 user_id 部分唯一);
根任务 submission_ordinal 在 (user_id, conversation_id) 上部分唯一。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import (
CheckConstraint,
DateTime,
ForeignKey,
ForeignKeyConstraint,
Index,
Integer,
JSON,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
def _default_user_task_no() -> str:
"""生成默认用户可见任务号;正式创建路径会覆盖为与 Run 对齐的 OT- 编号。"""
return f"OT-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
class ShippingOrderProcessingRun(Base):
"""一次建单前订单 Processing 业务运行;状态只允许按领域状态机单调推进。"""
__tablename__ = 'shipping_order_processing_runs'
__table_args__ = (
UniqueConstraint('run_no', name='uq_shipping_order_processing_runs_no'),
UniqueConstraint('idempotency_key', name='uq_shipping_order_processing_runs_idempotency'),
CheckConstraint(
"status IN ('queued', 'processing', 'completed', "
"'partially_completed', 'review_required', 'failed', 'cancelled')",
name='ck_shipping_order_processing_runs_status',
),
CheckConstraint(
"input_lifecycle IN ('open', 'freezing', 'frozen', 'closed')",
name='ck_shipping_order_processing_runs_input_lifecycle',
),
Index('ix_shipping_order_processing_runs_user_created', 'user_id', 'created_at'),
Index('ix_shipping_order_processing_runs_conversation_created', 'conversation_id', 'created_at'),
Index('ix_shipping_order_processing_runs_status_created', 'status', 'created_at'),
# 阶段 1:非唯一查询索引,替代原 partial unique(同会话多活跃 Run)。
Index(
'ix_shipping_order_processing_runs_conversation_status',
'user_id',
'owner_agent_id',
'conversation_id',
'status',
),
Index(
'ix_shipping_order_processing_runs_user_task_no',
'user_task_no',
),
Index(
'uq_shipping_order_processing_runs_client_submission',
'user_id',
'client_submission_id',
unique=True,
postgresql_where=text('client_submission_id IS NOT NULL'),
sqlite_where=text('client_submission_id IS NOT NULL'),
),
# 根任务(非 reparse/后继)会话内提交序号唯一;后继 Run 可继承同一序号。
Index(
'uq_shipping_order_processing_runs_submission_ordinal',
'user_id',
'conversation_id',
'submission_ordinal',
unique=True,
postgresql_where=text(
'reparse_of_run_id IS NULL AND submission_ordinal IS NOT NULL'
),
sqlite_where=text(
'reparse_of_run_id IS NULL AND submission_ordinal IS NOT NULL'
),
),
Index(
'ix_shipping_order_processing_runs_cancel_requested',
'cancellation_requested_at',
'status',
),
CheckConstraint(
"cancellation_actor_type IS NULL OR cancellation_actor_type IN "
"('user', 'admin', 'system')",
name='ck_shipping_order_processing_runs_cancel_actor',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
# 用户可见任务号(OT-…);Candidate/OT 形成前为 NULL;reparse 继承源号。
user_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
owner_agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), nullable=False, index=True)
parser_engine_version: Mapped[str] = mapped_column(String(64), nullable=False, default='deterministic-order-parser.v1')
parser_policy_version: Mapped[str] = mapped_column(String(64), nullable=False, default='deterministic-order-policy.v1')
auto_freeze_policy_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
# 重新识别创建新 Run;谱系字段保留旧结果,禁止用原地覆盖破坏审计事实。
reparse_of_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id'), nullable=True, index=True,
)
superseded_by_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id'), nullable=True, index=True,
)
reparse_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
reparse_comment: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
superseded_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
schema_version_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_schema_versions.id'), nullable=False,
)
# 请求快照是发送时的审计与幂等锚点;Worker 后续可物化 input_snapshot_* 作为执行快照。
request_snapshot_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
request_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False)
input_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False)
idempotency_key: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
phase: Mapped[str] = mapped_column(String(64), nullable=False, default='queued', server_default='queued')
# 用户可见任务输入生命周期;前端只消费 can_append,不展示原文案。
input_lifecycle: Mapped[str] = mapped_column(
String(16), nullable=False, default='open', server_default='open',
)
input_frozen_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
composer_context_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
submission_ordinal: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
# 客户端提交幂等键;与 user_id 组成部分唯一索引。
client_submission_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
current_job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True, index=True)
execution_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
extraction_completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
attempt_count: Mapped[int] = mapped_column(Integer, default=0, server_default='0', nullable=False)
result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
# 当前投影只包含用户安全的阶段事实;高频原始事件写入独立明细表。
progress_version: Mapped[int] = mapped_column(Integer, default=1, server_default='1', nullable=False)
current_stage_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
active_stage_codes_json: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)
completed_stage_codes_json: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)
progress_message_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
progress_health: Mapped[str] = mapped_column(String(32), default='normal', server_default='normal', nullable=False)
last_activity_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
progress_summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
progress_mapping_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
attention_generated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
seen_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
# 取消请求元数据:请求不等于生效;排队 Unit 可立即 cancelled,执行中须等安全检查点。
cancellation_requested_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
cancellation_actor_type: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
cancellation_actor_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
cancellation_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
cancellation_reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
cancellation_completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
lock_version: Mapped[int] = mapped_column(Integer, default=1, server_default='1', nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
result_persisted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
intakes: Mapped[list['ShippingOrderProcessingRunIntake']] = relationship(
back_populates='run', cascade='all, delete-orphan', order_by='ShippingOrderProcessingRunIntake.position',
)
reparse_source: Mapped[Optional['ShippingOrderProcessingRun']] = relationship(
'ShippingOrderProcessingRun', foreign_keys=[reparse_of_run_id], remote_side='ShippingOrderProcessingRun.id',
)
superseding_run: Mapped[Optional['ShippingOrderProcessingRun']] = relationship(
'ShippingOrderProcessingRun', foreign_keys=[superseded_by_run_id], remote_side='ShippingOrderProcessingRun.id',
)
extraction_plan: Mapped[Optional['ShippingOrderProcessingPlan']] = relationship(
back_populates='run', cascade='all, delete-orphan', uselist=False,
)
route_decisions: Mapped[list['ShippingOrderRouteDecision']] = relationship(
back_populates='run', cascade='all, delete-orphan', order_by='ShippingOrderRouteDecision.id',
)
review_cases: Mapped[list['ShippingOrderReviewCase']] = relationship(
'ShippingOrderReviewCase', back_populates='run', cascade='all, delete-orphan',
order_by='ShippingOrderReviewCase.id',
)
class ShippingOrderProcessingRunIntake(Base):
"""Run 冻结的 Intake 成员;position 保证输入集合顺序稳定且可审计。"""
__tablename__ = 'shipping_order_processing_run_intakes'
__table_args__ = (
UniqueConstraint('run_id', 'intake_id', name='uq_shipping_order_processing_run_intake'),
UniqueConstraint('run_id', 'position', name='uq_shipping_order_processing_run_position'),
Index('ix_shipping_order_processing_run_intakes_intake', 'intake_id'),
Index(
'uq_shipping_order_processing_run_intakes_active_intake',
'intake_id',
unique=True,
postgresql_where=text('released_at IS NULL'),
sqlite_where=text('released_at IS NULL'),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'), nullable=False,
)
intake_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False)
released_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
run: Mapped['ShippingOrderProcessingRun'] = relationship(back_populates='intakes')
class ShippingOrderProcessingPlan(Base):
"""Run 的不可变抽取计划;计划版本和快照哈希共同锚定冻结输入。"""
__tablename__ = 'shipping_order_processing_plans'
__table_args__ = (
UniqueConstraint('run_id', name='uq_shipping_order_processing_plans_run'),
CheckConstraint(
"status IN ('planned', 'running', 'completed', 'partial_failed', 'failed')",
name='ck_shipping_order_processing_plans_status',
),
Index('ix_shipping_order_processing_plans_status_created', 'status', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'), nullable=False,
)
# 版本标识是稳定的可读契约,须容纳带业务命名空间的版本号。
plan_version: Mapped[str] = mapped_column(String(64), nullable=False)
input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='planned', server_default='planned')
unit_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
run: Mapped['ShippingOrderProcessingRun'] = relationship(back_populates='extraction_plan')
units: Mapped[list['ShippingOrderProcessingUnit']] = relationship(
back_populates='plan', cascade='all, delete-orphan', order_by='ShippingOrderProcessingUnit.position',
)
class ShippingOrderProcessingUnit(Base):
"""计划内单个冻结附件抽取单元;状态、选择事实和错误相互隔离。"""
__tablename__ = 'shipping_order_processing_units'
__table_args__ = (
UniqueConstraint('plan_id', 'document_id', name='uq_shipping_order_processing_units_document'),
UniqueConstraint('plan_id', 'position', name='uq_shipping_order_processing_units_position'),
CheckConstraint(
"unit_type IN ('document_extraction', 'email_relation')",
name='ck_shipping_order_processing_units_type',
),
CheckConstraint(
"status IN ('pending', 'routing', 'matching_profile', 'extracting', "
"'merging_supplement', 'candidate_ready', 'review_required', 'failed', 'cancelled')",
name='ck_shipping_order_processing_units_status',
),
ForeignKeyConstraint(
['document_id', 'intake_id'],
['shipping_order_documents.id', 'shipping_order_documents.intake_id'],
name='fk_shipping_order_processing_units_document_intake',
),
Index('ix_shipping_order_processing_units_plan_status', 'plan_id', 'status'),
Index('ix_shipping_order_processing_units_document', 'document_id'),
Index(
'ix_shipping_order_processing_units_cancel_requested',
'cancellation_requested_at',
'status',
),
CheckConstraint(
"cancellation_actor_type IS NULL OR cancellation_actor_type IN "
"('user', 'admin', 'system')",
name='ck_shipping_order_processing_units_cancel_actor',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
plan_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_processing_plans.id', ondelete='CASCADE'), nullable=False,
)
intake_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=False)
document_id: Mapped[int] = mapped_column(nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False)
unit_type: Mapped[str] = mapped_column(String(32), nullable=False)
document_type: Mapped[str] = mapped_column(String(32), nullable=False)
content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
selection_batch: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
selection_reason_codes_json: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)
group_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
budget_cost_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
retry_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
technical_failure_reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
attempt_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
last_activity_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
# 单 Unit 活动版本;取消/重试与状态迁移同事务递增,供乐观协作与投影。
activity_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
cancellation_requested_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
cancellation_actor_type: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
cancellation_actor_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
cancellation_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
cancellation_reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
cancellation_completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
plan: Mapped['ShippingOrderProcessingPlan'] = relationship(back_populates='units')
route_decisions: Mapped[list['ShippingOrderRouteDecision']] = relationship(
back_populates='unit', cascade='all, delete-orphan', order_by='ShippingOrderRouteDecision.id',
)
review_case: Mapped[Optional['ShippingOrderReviewCase']] = relationship(
'ShippingOrderReviewCase', back_populates='unit', uselist=False,
)
class ShippingOrderRouteDecision(Base):
"""Unit 每次模板分流的不可变脱敏审计;禁止存储文档、字段值和 Provider 输入。"""
__tablename__ = 'shipping_order_route_decisions'
__table_args__ = (
UniqueConstraint('unit_id', 'job_id', 'attempt_no', name='uq_shipping_order_route_decision_attempt'),
CheckConstraint(
"decision IN ('deterministic', 'review_required', 'skipped')",
name='ck_shipping_order_route_decision',
),
CheckConstraint(
"match_status IN ("
"'unique_match', 'selected_by_score', 'no_special_profile_feature', "
"'no_match', 'ambiguous', 'layout_drift', 'evidence_insufficient'"
")",
name='ck_shipping_order_route_match_status',
),
Index('ix_shipping_order_route_decisions_run_unit', 'run_id', 'unit_id', 'id'),
Index('ix_shipping_order_route_decisions_unit_created', 'unit_id', 'created_at'),
Index('ix_shipping_order_route_decisions_profile_id', 'selected_profile_id', 'id'),
Index(
'ix_shipping_order_route_decisions_profile_snapshot',
'selected_profile_code', 'selected_profile_version', 'selected_profile_checksum', 'id',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'), nullable=False)
unit_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_processing_units.id', ondelete='CASCADE'), nullable=False)
job_id: Mapped[int] = mapped_column(ForeignKey('jobs.id'), nullable=False)
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
decision: Mapped[str] = mapped_column(String(16), nullable=False)
match_status: Mapped[str] = mapped_column(String(32), nullable=False)
selected_profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profiles.id'), nullable=True)
selected_profile_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
selected_profile_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
selected_profile_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
auto_create_approved: Mapped[Optional[bool]] = mapped_column(nullable=True)
candidate_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
document_table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
business_table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
matched_table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
parsed_table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
approved_table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
candidate_summary_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
fallback_reason_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
run: Mapped['ShippingOrderProcessingRun'] = relationship(back_populates='route_decisions')
unit: Mapped['ShippingOrderProcessingUnit'] = relationship(back_populates='route_decisions')
class ShippingOrderExtractionProgressEvent(Base):
"""订单抽取的可恢复业务事件;用户态与管理员态通过 visibility 隔离。"""
__tablename__ = 'shipping_order_extraction_progress_events'
__table_args__ = (
UniqueConstraint('idempotency_key', name='uq_shipping_order_extraction_progress_event_key'),
UniqueConstraint('run_id', 'sequence_no', name='uq_shipping_order_extraction_progress_event_sequence'),
Index('ix_shipping_order_extraction_progress_events_run_sequence', 'run_id', 'sequence_no'),
Index('ix_shipping_order_extraction_progress_events_expires_id', 'expires_at', 'id'),
Index('ix_shipping_order_extraction_progress_events_run_visibility', 'run_id', 'visibility', 'sequence_no'),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'), nullable=False)
unit_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_processing_units.id', ondelete='CASCADE'), nullable=True)
document_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True)
attempt_count: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
sequence_no: Mapped[int] = mapped_column(Integer, nullable=False)
visibility: Mapped[str] = mapped_column(String(32), nullable=False, default='workspace', server_default='workspace')
event_code: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='completed', server_default='completed')
occurred_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
received_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
mapping_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingOrderExtractionSubmission(Base):
"""
统一提交幂等记录:每次用户发送独立一行,禁止用 Run.client_submission_id 覆盖历史键。
用途:submission_id 重放只返回原决策;追加不会破坏更早的 submission 幂等。
"""
__tablename__ = 'shipping_order_extraction_submissions'
__table_args__ = (
UniqueConstraint(
'user_id', 'submission_id',
name='uq_shipping_order_extraction_submissions_user_submission',
),
Index(
'ix_shipping_order_extraction_submissions_run',
'run_id',
),
Index(
'ix_shipping_order_extraction_submissions_conversation',
'user_id',
'conversation_id',
'created_at',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
submission_id: Mapped[str] = mapped_column(String(64), nullable=False)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False)
user_task_no: Mapped[str] = mapped_column(String(64), nullable=False)
run_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'),
nullable=False,
)
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
decision: Mapped[str] = mapped_column(String(32), nullable=False)
reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
composer_context_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
intake_nos_json: Mapped[list[Any]] = mapped_column(JSON, nullable=False, default=list)
appended_intake_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingOrderExtractionDiagnosticAudit(Base):
"""管理员订单抽取诊断访问审计;不记录Run业务正文或原始筛选参数。"""
__tablename__ = 'shipping_order_extraction_diagnostic_audits'
__table_args__ = (
Index('ix_shipping_order_extraction_diagnostic_audits_run_created', 'run_id', 'created_at'),
Index('ix_shipping_order_extraction_diagnostic_audits_admin_created', 'admin_user_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
admin_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_processing_runs.id'), nullable=True)
action: Mapped[str] = mapped_column(String(64), nullable=False)
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
query_summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
+161
View File
@@ -0,0 +1,161 @@
"""
建单前订单人工复核领域模型。
依赖:订单抽取 Run/Unit、候选 Candidate、用户和后续 ShippingNotice、
ShippingOrderReviewLineDecision(行级履约决定)、
ShippingOrderReviewWaveLine(波次行不可变归属)。
逻辑:Case 以 PDF Unit 为唯一复核对象,Draft 保存独立人工版本;机器 Candidate
始终只读,后续确认服务将以 Case/Draft 生成不可变确认版本和 Task;
行级决定支持完整明细先行履约波次,禁止拆分数量;
wave_lines 保证同一 (case, line_key) 最多关联一个 task_id。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderReviewCase(Base):
"""一份 PDF 的建单前复核生命周期;终态 Case 不允许后续草稿写入。"""
__tablename__ = 'shipping_order_review_cases'
__table_args__ = (
UniqueConstraint('case_no', name='uq_shipping_order_review_cases_no'),
UniqueConstraint('unit_id', name='uq_shipping_order_review_cases_unit'),
UniqueConstraint('confirmed_task_id', name='uq_shipping_order_review_cases_confirmed_task'),
CheckConstraint(
"status IN ('unreviewed', 'draft', 'ready', 'confirming', 'confirmed', "
"'non_order', 'quality_issue', 'reparse_pending', 'superseded')",
name='ck_shipping_order_review_cases_status',
),
Index('ix_shipping_order_review_cases_run_status', 'run_id', 'status'),
Index('ix_shipping_order_review_cases_owner_updated', 'owner_user_id', 'updated_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
case_no: Mapped[str] = mapped_column(String(64), nullable=False)
run_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_processing_runs.id', ondelete='CASCADE'), nullable=False,
)
unit_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_processing_units.id', ondelete='CASCADE'), nullable=False,
)
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_documents.id'), nullable=False)
candidate_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_candidates.id'), nullable=True)
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='unreviewed', server_default='unreviewed')
disposition: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
current_draft_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_drafts.id', use_alter=True, name='fk_shipping_order_review_cases_current_draft'),
nullable=True,
)
confirmed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True)
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
run: Mapped['ShippingOrderProcessingRun'] = relationship('ShippingOrderProcessingRun', back_populates='review_cases')
unit: Mapped['ShippingOrderProcessingUnit'] = relationship('ShippingOrderProcessingUnit', back_populates='review_case')
current_draft: Mapped[Optional['ShippingOrderReviewDraft']] = relationship(
'ShippingOrderReviewDraft', foreign_keys=[current_draft_id], post_update=True,
)
drafts: Mapped[list['ShippingOrderReviewDraft']] = relationship(
'ShippingOrderReviewDraft', back_populates='case', foreign_keys='ShippingOrderReviewDraft.case_id',
cascade='all, delete-orphan', order_by='ShippingOrderReviewDraft.draft_version',
)
llm_suggestions: Mapped[list['ShippingOrderReviewSuggestion']] = relationship(
'ShippingOrderReviewSuggestion', back_populates='case', cascade='all, delete-orphan',
order_by='ShippingOrderReviewSuggestion.created_at.desc()',
)
line_decisions: Mapped[list['ShippingOrderReviewLineDecision']] = relationship(
'ShippingOrderReviewLineDecision',
back_populates='case',
cascade='all, delete-orphan',
order_by='ShippingOrderReviewLineDecision.line_key, ShippingOrderReviewLineDecision.decision_version',
)
wave_lines: Mapped[list['ShippingOrderReviewWaveLine']] = relationship(
'ShippingOrderReviewWaveLine',
back_populates='case',
cascade='all, delete-orphan',
order_by='ShippingOrderReviewWaveLine.wave_no, ShippingOrderReviewWaveLine.line_key',
)
class ShippingOrderReviewDraft(Base):
"""当前人工草稿;阶段 1 只初始化和投影,阶段 3 才允许写入。"""
__tablename__ = 'shipping_order_review_drafts'
__table_args__ = (
UniqueConstraint('case_id', 'draft_version', name='uq_shipping_order_review_drafts_case_version'),
CheckConstraint('draft_version >= 1', name='ck_shipping_order_review_drafts_version'),
Index('ix_shipping_order_review_drafts_case_updated', 'case_id', 'updated_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
case_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False,
)
draft_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
lines_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
issue_summary_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
validation_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
change_reason_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
case: Mapped['ShippingOrderReviewCase'] = relationship(
'ShippingOrderReviewCase', back_populates='drafts', foreign_keys=[case_id],
)
class ShippingOrderReviewCaseEvent(Base):
"""复核域追加审计事件;阶段 3 起记录每项草稿变更,阶段 1 记录初始化事实。"""
__tablename__ = 'shipping_order_review_case_events'
__table_args__ = (
Index('ix_shipping_order_review_case_events_case_occurred', 'case_id', 'occurred_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
case_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False)
event_type: Mapped[str] = mapped_column(String(64), nullable=False)
draft_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
actor_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
operation_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
occurred_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingOrderReviewConfirmedRevision(Base):
"""一次不可变建单确认快照;同一 Case 可对应多个履约波次 Task。"""
__tablename__ = 'shipping_order_review_confirmed_revisions'
__table_args__ = (
UniqueConstraint('case_id', 'task_id', name='uq_shipping_order_review_confirmed_revisions_case_task'),
UniqueConstraint('idempotency_key', name='uq_shipping_order_review_confirmed_revisions_idempotency'),
Index('ix_shipping_order_review_confirmed_revisions_task', 'task_id'),
Index('ix_shipping_order_review_confirmed_revisions_case', 'case_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
case_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False,
)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
draft_version: Mapped[int] = mapped_column(Integer, nullable=False)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
lines_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
validation_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
warning_acknowledgements_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
confirmed_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
confirmed_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -0,0 +1,87 @@
"""
models/shipping_order_review_line_decision.py
用途:复核 Case 的行级履约决定(版本化、可追溯);含 OT 后系统/人工来源。
依赖:ShippingOrderReviewCase、ShippingNotice、users。
逻辑:由 order_review_fulfillment_decision_service 写入;同一 (case, line_key, version) 唯一;
活动决定不可覆盖,重开生成新版本;Task 波次通过 task_id 关联;
decision_source 区分 system/user(历史可空)。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderReviewLineDecision(Base):
"""一条订单明细的履约决定版本;禁止拆分数量。"""
__tablename__ = 'shipping_order_review_line_decisions'
__table_args__ = (
UniqueConstraint(
'review_case_id',
'line_key',
'decision_version',
name='uq_shipping_review_line_decisions_case_line_ver',
),
CheckConstraint(
"decision_code IN ("
"'wait_inventory', 'use_new_inventory_file', 'change_inventory_source', "
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen'"
")",
name='ck_shipping_review_line_decisions_code',
),
CheckConstraint(
"line_status IN ("
"'pending_decision', 'waiting_inventory', 'ready_to_fulfill', "
"'task_created', 'fulfilled', 'closed_unfulfillable', 'reopened'"
")",
name='ck_shipping_review_line_decisions_status',
),
CheckConstraint(
"decision_source IS NULL OR decision_source IN ('system', 'user', 'unknown')",
name='ck_shipping_review_line_decisions_source',
),
CheckConstraint('decision_version >= 1', name='ck_shipping_review_line_decisions_version'),
Index('ix_shipping_review_line_decisions_case_line', 'review_case_id', 'line_key'),
Index('ix_shipping_review_line_decisions_case_active', 'review_case_id', 'is_active'),
Index('ix_shipping_review_line_decisions_task', 'task_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
review_case_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'),
nullable=False,
)
line_key: Mapped[str] = mapped_column(String(64), nullable=False)
line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
decision_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
decision_code: Mapped[str] = mapped_column(String(48), nullable=False)
line_status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending_decision')
is_active: Mapped[bool] = mapped_column(nullable=False, default=True, server_default='true')
reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
required_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True)
wave_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
# system=自动履约;user=人工异常/显式履约;unknown=历史无法判定。
decision_source: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
actor_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
case: Mapped['ShippingOrderReviewCase'] = relationship(
'ShippingOrderReviewCase',
back_populates='line_decisions',
)
@@ -0,0 +1,105 @@
"""
backend/app/models/shipping_order_review_suggestion.py
用途:持久化订单复核 LLM 建议请求、验证结果与人工裁决。
依赖:SQLAlchemy Base、Review Case / Document 外键。
逻辑:
- 建议只能预填草稿;accept/modify/reject 写入裁决字段;不得自动冻结。
- v2:新增 status=gated_failed;evidence_level 扩展新枚举;
新增 8 个 provider & trace 独立列;旧数据不 backfill。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderReviewSuggestion(Base):
"""一次最小证据 LLM 建议及其人工裁决记录。"""
__tablename__ = 'shipping_order_review_suggestions'
__table_args__ = (
UniqueConstraint('suggestion_no', name='uq_shipping_order_review_suggestions_no'),
CheckConstraint(
"status IN ('pending', 'gated_failed', 'validated', 'validation_failed', "
"'accepted', 'modified', 'rejected', 'failed', 'provider_unavailable')",
name='ck_shipping_order_review_suggestions_status',
),
CheckConstraint(
"evidence_level IN ("
"'L1_field', 'L2_table', 'L3_page', 'L4_pdf', "
"'L2_row', 'L3_table', 'L4_page', 'L5_document')",
name='ck_shipping_order_review_suggestions_evidence_level',
),
CheckConstraint(
"decision IS NULL OR decision IN ('accept', 'modify', 'reject')",
name='ck_shipping_order_review_suggestions_decision',
),
Index('ix_shipping_order_review_suggestions_case', 'review_case_id', 'created_at'),
Index('ix_shipping_order_review_suggestions_document', 'document_id', 'id'),
Index(
'ix_shipping_order_review_suggestions_provider_conversation',
'provider_conversation_id',
),
Index(
'ix_shipping_order_review_suggestions_context_hash',
'context_hash',
),
Index(
'ix_shipping_order_review_suggestions_status_created',
'status', 'created_at',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
suggestion_no: Mapped[str] = mapped_column(String(64), nullable=False)
review_case_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False,
)
document_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_documents.id'), nullable=False,
)
run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id'), nullable=True,
)
field_id: Mapped[str] = mapped_column(String(64), nullable=False)
line_key: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
scope: Mapped[str] = mapped_column(String(16), nullable=False, default='header', server_default='header')
evidence_level: Mapped[str] = mapped_column(String(16), nullable=False, default='L1_field')
status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
contract_version: Mapped[str] = mapped_column(String(64), nullable=False)
draft_version_at_request: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
request_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
response_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
validated_suggestions_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
validation_issues_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
suggested_value_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
decision: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
decision_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
decision_note: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
decided_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
decided_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
requested_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
# —— v2 新增列:provider & trace 独立列;历史数据保持 NULL/默认值,不回填
provider: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
provider_conversation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
provider_message_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
latency_ms: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
context_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
evidence_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
context_truncated: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default='false')
auto_upgrade_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
case = relationship('ShippingOrderReviewCase', back_populates='llm_suggestions')
@@ -0,0 +1,67 @@
"""
models/shipping_order_review_wave_idempotency.py
用途:post-OT 履约 wave 请求幂等表(idempotency_key → wave 身份),无 wave 主表时提供强约束。
依赖:shipping_order_review_cases、shipping_notices。
逻辑:create_post_ot_fulfillment_wave 写入/回放;同 key 参数不一致 → 409;
progress_* 记录本 wave Excel/RPA 推进状态(失败不回滚已提交 wave)。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingOrderReviewWaveIdempotency(Base):
"""一次 post-OT wave 创建请求的幂等记录。"""
__tablename__ = 'shipping_order_review_wave_idempotency'
__table_args__ = (
UniqueConstraint(
'idempotency_key',
name='uq_shipping_review_wave_idempotency_key',
),
Index('ix_shipping_review_wave_idempotency_case', 'review_case_id'),
Index('ix_shipping_review_wave_idempotency_task', 'task_id'),
Index('ix_shipping_review_wave_idempotency_wave', 'review_case_id', 'wave_no'),
)
id: Mapped[int] = mapped_column(primary_key=True)
idempotency_key: Mapped[str] = mapped_column(String(191), nullable=False)
review_case_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'),
nullable=False,
)
task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notices.id', ondelete='CASCADE'),
nullable=False,
)
task_no: Mapped[str] = mapped_column(String(64), nullable=False)
wave_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
decision_source: Mapped[str] = mapped_column(String(16), nullable=False)
# 稳定排序后的 line_key JSON 数组字符串指纹(冲突比对)。
line_keys_json: Mapped[list[Any]] = mapped_column(JSON, nullable=False, default=list)
line_keys_hash: Mapped[str] = mapped_column(String(64), nullable=False)
# 行集合共享快照 ID;多快照时为空,靠 fingerprint 比对。
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
inventory_snapshot_fingerprint: Mapped[str] = mapped_column(String(256), nullable=False, default='')
status: Mapped[str] = mapped_column(String(32), nullable=False, default='succeeded')
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
# 本 wave 下游推进(Excel/RPA);失败不回滚 wave 创建事实。
progress_status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending')
progress_job_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
progress_error: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
progress_idempotency_key: Mapped[Optional[str]] = mapped_column(String(191), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime,
default=datetime.utcnow,
onupdate=datetime.utcnow,
nullable=False,
)
@@ -0,0 +1,52 @@
"""
models/shipping_order_review_wave_line.py
用途:复核 Case 履约波次行归属(不可变),保证同一明细行最多进入一个 Task。
依赖:ShippingOrderReviewCase、ShippingNotice、ShippingOrderReviewConfirmedRevision。
逻辑:由 order_review_confirmation_service 在建波次/整单确认时写入;
(review_case_id, line_key) 数据库唯一约束防并发重复入波次。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderReviewWaveLine(Base):
"""一条复核明细行与履约 Task 的不可变归属记录。"""
__tablename__ = 'shipping_order_review_wave_lines'
__table_args__ = (
UniqueConstraint(
'review_case_id',
'line_key',
name='uq_shipping_review_wave_lines_case_line',
),
Index('ix_shipping_review_wave_lines_task', 'task_id'),
Index('ix_shipping_review_wave_lines_case_wave', 'review_case_id', 'wave_no'),
)
id: Mapped[int] = mapped_column(primary_key=True)
review_case_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'),
nullable=False,
)
line_key: Mapped[str] = mapped_column(String(64), nullable=False)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
wave_no: Mapped[int] = mapped_column(Integer, nullable=False)
confirmed_revision_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_confirmed_revisions.id', ondelete='SET NULL'),
nullable=True,
)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
case: Mapped['ShippingOrderReviewCase'] = relationship(
'ShippingOrderReviewCase',
back_populates='wave_lines',
)
+368
View File
@@ -0,0 +1,368 @@
"""
backend/app/models/shipping_order_schema.py
用途:定义货代字段资产、Schema 族/不可变版本、配置审计及动态订单解析结果。
依赖:models.base.Base、shipping_notices、shipping_order_intakes、users。
逻辑:字段资产全局存活(标准只读、扩展可弃用);Schema 族版本仅采用资产并冻结 definition_json;
definition_json 含 fields / auto_creation_policy / derivation_rules(及 checksum);
写操作追加审计;解析链锁定发布版本。表名保留历史命名以降低迁移耦合。
"""
from __future__ import annotations
import uuid
from datetime import date, datetime
from decimal import Decimal
from typing import Any, Optional
from sqlalchemy import (
Boolean,
CheckConstraint,
Date,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
Numeric,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
def _uuid() -> str:
"""生成跨 PostgreSQL/SQLite 通用的 UUID 字符串主键。"""
return str(uuid.uuid4())
def _default_field_category(context: Any) -> str:
"""为未显式分类的既有 ORM 创建路径按 scope 生成订单字段分类。"""
return 'order_line' if context.get_current_parameters().get('scope') == 'line' else 'order_header'
class ShippingOrderSchema(Base):
"""Schema 族容器;本轮默认族编码 STANDARD_SHIPPING_NOTICE,模型允许多族。"""
__tablename__ = 'shipping_order_schemas'
id: Mapped[int] = mapped_column(primary_key=True)
schema_code: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
auto_creation_policy_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
versions: Mapped[list['ShippingOrderSchemaVersion']] = relationship(
back_populates='schema', cascade='all, delete-orphan', order_by='ShippingOrderSchemaVersion.version'
)
ShippingSchemaFamily = ShippingOrderSchema
class ShippingOrderField(Base):
"""全局字段资产(系统标准或扩展)。标准不可弃用/删除;扩展仅 active⇄retired。"""
__tablename__ = 'shipping_order_fields'
__table_args__ = (
# Header/Line may intentionally share a business code (for example
# reservation_id); scope is part of the asset identity.
UniqueConstraint('field_code', 'scope', name='uq_shipping_order_fields_code_scope'),
CheckConstraint("scope IN ('header', 'line')", name='ck_shipping_order_fields_scope'),
CheckConstraint(
"field_category IN ('general_context', 'order_header', 'order_line')",
name='ck_shipping_order_fields_category',
),
CheckConstraint(
"collection_mode IN ('deterministic_context', 'llm_extraction')",
name='ck_shipping_order_fields_collection_mode',
),
CheckConstraint(
"value_type IN ('string', 'decimal', 'integer', 'date', 'boolean', 'enum')",
name='ck_shipping_order_fields_value_type',
),
CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_order_fields_status'),
CheckConstraint(
"asset_kind IN ('system_standard', 'extension')",
name='ck_shipping_order_fields_asset_kind',
),
CheckConstraint(
"storage_mode IN ('typed_column', 'json_only')",
name='ck_shipping_order_fields_storage_mode',
),
Index('ix_shipping_order_fields_scope_status', 'scope', 'status'),
Index('ix_shipping_order_fields_asset_kind', 'asset_kind'),
)
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_uuid)
field_code: Mapped[str] = mapped_column(String(64), nullable=False)
scope: Mapped[str] = mapped_column(String(16), nullable=False)
value_type: Mapped[str] = mapped_column(String(16), nullable=False)
field_category: Mapped[str] = mapped_column(String(32), nullable=False, default=_default_field_category)
collection_mode: Mapped[str] = mapped_column(String(32), nullable=False, default='llm_extraction')
asset_kind: Mapped[str] = mapped_column(String(32), nullable=False, default='extension', server_default='extension')
storage_mode: Mapped[str] = mapped_column(String(32), nullable=False, default='json_only', server_default='json_only')
storage_column: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
semantic_description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
display_name_default: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
fulfillment_role: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
display_sequence: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
published_once: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false'))
retired_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
retired_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
retired_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
restored_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
restored_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
ShippingFieldAsset = ShippingOrderField
class ShippingOrderSchemaVersion(Base):
"""
订单 Schema 版本;草稿与发布版本统一以完整 definition_json 为配置真相。
definition_json 契约要点:
- fields[]:字段采用与识别规则
- auto_creation_policy:自动建单策略
- derivation_rules[]:同行明细字段派生(首期 copy_if_empty → line_no)
- derivation_rules_checksum:派生规则稳定校验和
"""
__tablename__ = 'shipping_order_schema_versions'
__table_args__ = (
UniqueConstraint('schema_id', 'version', name='uq_shipping_order_schema_versions_schema_version'),
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_order_schema_versions_status'),
Index(
'uq_shipping_order_schema_one_published',
'schema_id',
unique=True,
postgresql_where=text("status = 'published'"),
sqlite_where=text("status = 'published'"),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
schema_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
change_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
source_version_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_schema_versions.id'), nullable=True
)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
retired_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
schema: Mapped['ShippingOrderSchema'] = relationship(back_populates='versions')
source_version: Mapped[Optional['ShippingOrderSchemaVersion']] = relationship(
remote_side='ShippingOrderSchemaVersion.id', foreign_keys=[source_version_id]
)
class ShippingOrderSchemaAuditEvent(Base):
"""字段资产与 Schema 配置的追加式审计事件;不提供修改入口。"""
__tablename__ = 'shipping_order_schema_audit_events'
__table_args__ = (
CheckConstraint(
"event_type IN ("
"'draft_created', 'draft_saved', 'published', 'draft_deleted', 'cloned', "
"'field_saved', 'field_retired', 'field_restored', "
"'extension_created', 'extension_updated', 'extension_retired', 'extension_restored', "
"'family_created', 'field_adopted', 'field_unadopted', 'publish_blocked'"
")",
name='ck_shipping_order_schema_audit_event_type',
),
Index('ix_shipping_order_schema_audit_version_created', 'version_id', 'created_at'),
Index('ix_shipping_order_schema_audit_schema_created', 'schema_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
schema_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=True)
field_id: Mapped[Optional[str]] = mapped_column(String(36), nullable=True)
version_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_schema_versions.id', ondelete='SET NULL'), nullable=True
)
event_type: Mapped[str] = mapped_column(String(32), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
before_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
after_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
change_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingOrderExtraction(Base):
"""一次订单解析审计;锁定 Schema 和输入快照,承载 LLM 原始结果及最终状态。"""
__tablename__ = 'shipping_order_extractions'
__table_args__ = (
Index('ix_shipping_order_extractions_task_created', 'task_id', 'created_at'),
Index('ix_shipping_order_extractions_intake_created', 'intake_id', 'created_at'),
# Version history pages aggregate and paginate the runtime records that used a Schema snapshot.
Index('ix_shipping_order_extractions_schema_version_created', 'schema_version_id', 'created_at'),
CheckConstraint(
"status IN ('created', 'extracting', 'needs_review', 'accepted', 'failed', 'superseded')",
name='ck_shipping_order_extractions_status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id'), nullable=True, index=True,
)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True)
intake_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=True)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False)
input_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='created', server_default='created')
raw_llm_output_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
normalized_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
validation_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
schema_version: Mapped['ShippingOrderSchemaVersion'] = relationship()
lines: Mapped[list['ShippingOrderLine']] = relationship(
back_populates='extraction', cascade='all, delete-orphan', order_by='ShippingOrderLine.position'
)
observations: Mapped[list['ShippingOrderFieldObservation']] = relationship(
back_populates='extraction', cascade='all, delete-orphan'
)
decisions: Mapped[list['ShippingOrderFieldDecision']] = relationship(
back_populates='extraction', cascade='all, delete-orphan'
)
values: Mapped[list['ShippingOrderFieldValue']] = relationship(
back_populates='extraction', cascade='all, delete-orphan'
)
class ShippingOrderLine(Base):
"""动态订单解析中的行身份;业务值全部位于 FieldValue。"""
__tablename__ = 'shipping_order_lines'
__table_args__ = (UniqueConstraint('extraction_id', 'position', name='uq_shipping_order_lines_position'),)
id: Mapped[int] = mapped_column(primary_key=True)
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False)
line_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='lines')
class ShippingOrderFieldObservation(Base):
"""某字段来自某 Document/解析器的原始观察及可回查文本或版面证据。"""
__tablename__ = 'shipping_order_field_observations'
__table_args__ = (Index('ix_shipping_order_observations_extraction_field', 'extraction_id', 'field_id'),)
id: Mapped[int] = mapped_column(primary_key=True)
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False)
line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True)
field_id: Mapped[str] = mapped_column(String(36), nullable=False) # 软引用:历史 Run 可保留孤儿 field_id
source_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_documents.id'), nullable=True)
source_type: Mapped[str] = mapped_column(String(32), nullable=False)
extractor: Mapped[str] = mapped_column(String(32), nullable=False)
raw_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
normalized_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
evidence_quote: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
evidence_ref: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
evidence_metadata_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
confidence: Mapped[Optional[Decimal]] = mapped_column(Numeric(5, 4), nullable=True)
evidence_verified: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false'))
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='observations')
class ShippingOrderFieldDecision(Base):
"""后端对字段观察集合的最终裁决;下游只能消费 accepted 决定。"""
__tablename__ = 'shipping_order_field_decisions'
__table_args__ = (
Index(
'uq_shipping_order_decisions_header_field', 'extraction_id', 'field_id', unique=True,
postgresql_where=text('line_id IS NULL'), sqlite_where=text('line_id IS NULL'),
),
Index(
'uq_shipping_order_decisions_line_field', 'extraction_id', 'line_id', 'field_id', unique=True,
postgresql_where=text('line_id IS NOT NULL'), sqlite_where=text('line_id IS NOT NULL'),
),
CheckConstraint(
"decision_status IN ('accepted', 'corroborated', 'needs_review', 'blocked', 'missing')",
name='ck_shipping_order_decisions_status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False)
line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True)
field_id: Mapped[str] = mapped_column(String(36), nullable=False) # 软引用:历史 Run 可保留孤儿 field_id
decision_status: Mapped[str] = mapped_column(String(32), nullable=False)
selected_observation_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_field_observations.id'), nullable=True
)
supporting_observation_ids_json: Mapped[list[int]] = mapped_column(JSON, nullable=False, default=list)
resolved_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
decided_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='decisions')
class ShippingOrderFieldValue(Base):
"""已接受订单字段的类型化查询投影,供路由、匹配和 Excel 模板稳定引用。"""
__tablename__ = 'shipping_order_field_values'
__table_args__ = (
Index(
'uq_shipping_order_field_values_header_field', 'extraction_id', 'field_id', unique=True,
postgresql_where=text('line_id IS NULL'), sqlite_where=text('line_id IS NULL'),
),
Index(
'uq_shipping_order_field_values_line_field', 'extraction_id', 'line_id', 'field_id', unique=True,
postgresql_where=text('line_id IS NOT NULL'), sqlite_where=text('line_id IS NOT NULL'),
),
Index('ix_shipping_order_field_values_field_text', 'field_id', 'value_text'),
Index('ix_shipping_order_field_values_field_decimal', 'field_id', 'value_decimal'),
)
id: Mapped[int] = mapped_column(primary_key=True)
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False)
line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True)
field_id: Mapped[str] = mapped_column(String(36), nullable=False) # 软引用:历史 Run 可保留孤儿 field_id
value_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
value_decimal: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
value_integer: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
value_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
value_boolean: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)
value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
decision_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_field_decisions.id'), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='values')
@@ -0,0 +1,127 @@
"""
backend/app/models/shipping_order_snapshot.py
用途:保存从订单解析候选冻结而来的不可变履约订单快照及人工复核审计。
依赖:shipping_order_schema 的 Extraction、shipping_notices、shipping_customers 与 users。
逻辑:order_freeze_service 将已接受 Extraction 的字段按稳定 field_id 冻结为 Snapshot;库存、导出和上传阶段只消费本模块的快照。
Phase 0+ 扩展约定:rule_versions_json 可含 derivation_rules_snapshot / derivation_rules_checksum;
source_manifest_json 可含 field_lineage(值来源、规则引用、覆盖原因、证据引用)。
"""
from __future__ import annotations
from datetime import date, datetime
from decimal import Decimal
from typing import Any, Optional
from sqlalchemy import CheckConstraint, Date, DateTime, ForeignKey, Index, Integer, JSON, Numeric, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderSnapshot(Base):
"""不可变的订单单头履约事实;一个已接受 Extraction 最多冻结一次。"""
__tablename__ = 'shipping_order_snapshots'
__table_args__ = (
UniqueConstraint('task_id', name='uq_shipping_order_snapshots_task'),
UniqueConstraint('extraction_id', name='uq_shipping_order_snapshots_extraction'),
Index('ix_shipping_order_snapshots_customer_created', 'customer_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False, index=True)
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True, index=True)
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
order_data_version: Mapped[int] = mapped_column(Integer, nullable=False)
# 可含 derivation_rules_snapshot / derivation_rules_checksum 等规则版本投影。
rule_versions_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
# 冻结时固化字段裁决、文档哈希、页码坐标及人工复核,避免下游回读可变解析事实;
# 可含 field_lineage(按 field_code 记录 value_source / rule_id / override_reason / evidence_refs)。
source_manifest_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
# 保留所有已发布 Header 字段;核心字段同时写入下方强类型列,扩展字段由业务配置按 field_id 消费。
header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
customer_po_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
customer_code: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
customer_name: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
bill_to_customer: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
bill_to_address: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
ship_to_customer: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
ship_to_address: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
destination: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
currency: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
incoterm: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
required_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
order_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
payment_term: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
frozen_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
frozen_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
lines: Mapped[list['ShippingOrderSnapshotLine']] = relationship(
back_populates='snapshot', cascade='all, delete-orphan', order_by='ShippingOrderSnapshotLine.position',
)
review_events: Mapped[list['ShippingOrderReviewEvent']] = relationship(
back_populates='snapshot', cascade='all, delete-orphan', order_by='ShippingOrderReviewEvent.created_at',
)
schema_version = relationship('ShippingOrderSchemaVersion')
class ShippingOrderSnapshotLine(Base):
"""不可变订单单身履约事实;料号和预约单始终保存为字符串以保留前导零。"""
__tablename__ = 'shipping_order_snapshot_lines'
__table_args__ = (
UniqueConstraint('snapshot_id', 'position', name='uq_shipping_order_snapshot_lines_position'),
CheckConstraint('qty IS NULL OR qty > 0', name='ck_shipping_order_snapshot_lines_positive_qty'),
)
id: Mapped[int] = mapped_column(primary_key=True)
snapshot_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_snapshots.id', ondelete='CASCADE'), nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False)
line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
customer_part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
uom: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
unit_price: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
amount: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
warehouse: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
inventory_source_hint: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
# 与 Header 同理:以 field_id 为键,避免后续字段重命名改变已冻结履约事实。
field_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
snapshot: Mapped['ShippingOrderSnapshot'] = relationship(back_populates='lines')
class ShippingOrderReviewEvent(Base):
"""冻结前人工纠错的追加式审计;每项变更必须保留原值、新值、证据和原因。"""
__tablename__ = 'shipping_order_review_events'
__table_args__ = (
CheckConstraint("scope IN ('header', 'line')", name='ck_shipping_order_review_events_scope'),
Index('ix_shipping_order_review_events_task_created', 'task_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_snapshots.id', ondelete='CASCADE'), nullable=True)
scope: Mapped[str] = mapped_column(String(16), nullable=False)
line_position: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
field_code: Mapped[str] = mapped_column(String(64), nullable=False)
old_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
new_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
evidence_ref: Mapped[str] = mapped_column(String(512), nullable=False)
reason: Mapped[str] = mapped_column(Text, nullable=False)
reviewed_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
snapshot: Mapped[Optional['ShippingOrderSnapshot']] = relationship(back_populates='review_events')
@@ -0,0 +1,96 @@
"""
models/shipping_order_submission.py
用途:一次文件选择/上传批次的订单材料 Submission 边界(多 EML / 直接 PDF 阶段 1)。
依赖:users、agents、shipping_order_intakes(反向关联)。
逻辑:同一 (user_id, upload_batch_id) 唯一;仅承载幂等、文件集合汇总与会话关联,
不拥有端到端业务进度。由 order_submission_service 创建;Intake 通过
order_submission_id 挂接。与 shipping_order_extraction_submissions(OT 发送决策)
概念分离。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import (
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
def generate_order_submission_no() -> str:
"""
生成上传 Submission 业务编号。
核心逻辑:SOS-日期-短 UUID,保证可读且碰撞概率极低。
Returns:
形如 SOS-YYYYMMDD-XXXXXXXX 的编号。
"""
return f"SOS-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
class ShippingOrderSubmission(Base):
"""一次上传提交:聚合同 upload_batch 下的多个 Intake。"""
__tablename__ = 'shipping_order_submissions'
__table_args__ = (
UniqueConstraint('submission_no', name='uq_shipping_order_submissions_submission_no'),
UniqueConstraint(
'user_id',
'upload_batch_id',
name='uq_shipping_order_submissions_user_upload_batch',
),
CheckConstraint(
"status IN ('accepted', 'processing', 'completed', 'failed', 'cancelled')",
name='ck_shipping_order_submissions_status',
),
Index(
'ix_shipping_order_submissions_user_conversation_created',
'user_id',
'conversation_id',
'created_at',
),
Index('ix_shipping_order_submissions_status_created', 'status', 'created_at'),
Index(
'ix_shipping_order_submissions_client_submission',
'user_id',
'client_submission_id',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
submission_no: Mapped[str] = mapped_column(String(64), nullable=False)
client_submission_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
owner_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
upload_batch_id: Mapped[str] = mapped_column(String(36), nullable=False)
status: Mapped[str] = mapped_column(
String(32),
nullable=False,
default='accepted',
server_default=text("'accepted'"),
)
intake_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
eml_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
direct_pdf_count: Mapped[int] = mapped_column(
Integer, nullable=False, default=0, server_default=text('0')
)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
+96
View File
@@ -0,0 +1,96 @@
"""
backend/app/models/shipping_order_task.py
用途:正式发货通知创建前的 OT(shipping_order_tasks)聚合根,对齐多 EML/PDF 蓝图。
依赖:users、agents、shipping_order_submissions/intakes/candidates、extraction_runs、shipping_notices。
逻辑:由 Extraction Run 的 user_task_no 双写/回填;建单成功后挂 shipping_notice_id。
页面链路以 task_no(OT-…)为根身份;1 OT 可对应 0..N Notice。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import (
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
def _default_order_task_no() -> str:
"""生成默认 OT 编号;正式路径由 Run 派生覆盖。"""
return f"OT-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
class ShippingOrderTask(Base):
"""
建单前订单任务(OT)聚合根。
核心逻辑:与 Extraction Run.user_task_no 对齐;进度由领域服务单调推进并 bump progress_version。
"""
__tablename__ = 'shipping_order_tasks'
__table_args__ = (
UniqueConstraint('task_no', name='uq_shipping_order_tasks_task_no'),
CheckConstraint(
"source_type IS NULL OR source_type IN ('eml', 'direct_pdf')",
name='ck_shipping_order_tasks_source_type',
),
Index('ix_shipping_order_tasks_user_created', 'user_id', 'created_at'),
Index('ix_shipping_order_tasks_conversation', 'conversation_id'),
Index('ix_shipping_order_tasks_status', 'status'),
Index('ix_shipping_order_tasks_extraction_run_id', 'extraction_run_id'),
Index('ix_shipping_order_tasks_shipping_notice_id', 'shipping_notice_id'),
# 一 Candidate 一 OT;NULL candidate_id 仅遗留行,新创建路径禁止。
Index(
'uq_shipping_order_tasks_candidate_id',
'candidate_id',
unique=True,
postgresql_where=text('candidate_id IS NOT NULL'),
sqlite_where=text('candidate_id IS NOT NULL'),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_no: Mapped[str] = mapped_column(String(64), nullable=False, default=_default_order_task_no)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
owner_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
submission_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_submissions.id'), nullable=True,
)
intake_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=True)
candidate_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_candidates.id'), nullable=True,
)
extraction_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id'), nullable=True,
)
shipping_notice_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notices.id', name='fk_shipping_order_tasks_shipping_notice_id', use_alter=True),
nullable=True,
)
source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='processing')
stage: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
progress_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
+273
View File
@@ -0,0 +1,273 @@
"""
models/shipping_process_gate.py
用途:门禁级中断恢复的持久化模型——Execution / Gate / Attempt。
依赖:SQLAlchemy Base、ReviewCase、ShippingNotice、Job;状态枚举与 process_gate_contract 对齐。
逻辑:Execution 为业务恢复真相;Gate 保存当前门禁状态;Attempt 不可变执行尝试并承载租约。
由领域服务独占写入;Job 仅调度。
co8e9f0a1b2c:已移除对 shipping_notice_workflow_* 的硬外键(无历史兼容)。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import (
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
def _utc_now() -> datetime:
"""返回 naive UTC 时间,与仓库现有模型一致。"""
return datetime.utcnow()
class ShippingProcessExecution(Base):
"""业务执行实例;门禁恢复状态唯一真相,不保存大体量订单原文。"""
__tablename__ = 'shipping_process_executions'
__table_args__ = (
UniqueConstraint('execution_no', name='uq_shipping_process_executions_no'),
CheckConstraint(
"status IN ('active', 'blocked', 'waiting_external', 'completed', 'cancelled', 'failed', 'superseded')",
name='ck_shipping_process_executions_status',
),
CheckConstraint('lock_version >= 1', name='ck_shipping_process_executions_lock_version'),
Index(
'ix_shipping_process_executions_status_updated',
'status',
'updated_at',
),
Index(
'ix_shipping_process_executions_current_gate',
'current_gate_code',
'status',
'updated_at',
),
Index(
'ix_shipping_process_executions_review_case',
'review_case_id',
),
Index(
'ix_shipping_process_executions_task',
'task_id',
),
Index('ix_shipping_process_executions_candidate_set', 'candidate_set_id', 'status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
execution_no: Mapped[str] = mapped_column(String(64), nullable=False)
review_case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_cases.id'), nullable=True,
)
task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notices.id'), nullable=True,
)
# 绑定候选版本,防止旧 callback/job 写入新候选链。
candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id'), nullable=True,
)
execution_revision: Mapped[int] = mapped_column(
Integer, nullable=False, default=1, server_default='1',
)
status: Mapped[str] = mapped_column(
String(32), nullable=False, default='active', server_default='active',
)
current_gate_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
last_passed_gate_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
primary_next_action_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
responsible_party: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
)
gates: Mapped[list['ShippingProcessGate']] = relationship(
back_populates='execution',
cascade='all, delete-orphan',
order_by='ShippingProcessGate.sequence_no',
)
class ShippingProcessGate(Base):
"""单门禁实例;保存状态、输入指纹、阻断原因与最新 Attempt 指针。"""
__tablename__ = 'shipping_process_gates'
__table_args__ = (
UniqueConstraint(
'execution_id',
'gate_code',
name='uq_shipping_process_gates_execution_code',
),
UniqueConstraint(
'execution_id',
'sequence_no',
name='uq_shipping_process_gates_execution_sequence',
),
CheckConstraint(
"status IN ("
"'pending', 'queued', 'running', 'passed', 'blocked_retryable', "
"'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated', 'skipped', 'cancelled'"
")",
name='ck_shipping_process_gates_status',
),
CheckConstraint('sequence_no >= 1', name='ck_shipping_process_gates_sequence'),
CheckConstraint('evaluation_version >= 1', name='ck_shipping_process_gates_eval_version'),
CheckConstraint('lock_version >= 1', name='ck_shipping_process_gates_lock_version'),
Index(
'ix_shipping_process_gates_execution_status',
'execution_id',
'status',
'updated_at',
),
Index(
'ix_shipping_process_gates_code_status',
'gate_code',
'status',
'updated_at',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
execution_id: Mapped[int] = mapped_column(
ForeignKey('shipping_process_executions.id', ondelete='CASCADE'), nullable=False,
)
gate_code: Mapped[str] = mapped_column(String(64), nullable=False)
sequence_no: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(
String(32), nullable=False, default='pending', server_default='pending',
)
evaluation_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
blocking_reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
blocking_reason_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
recommendation_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
effective_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
next_action_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
# 软指针:避免与 Attempt.gate_id 循环外键;由领域服务保证一致性。
latest_attempt_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
passed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
)
execution: Mapped[ShippingProcessExecution] = relationship(back_populates='gates')
attempts: Mapped[list['ShippingProcessGateAttempt']] = relationship(
back_populates='gate',
cascade='all, delete-orphan',
order_by='ShippingProcessGateAttempt.attempt_no',
foreign_keys='ShippingProcessGateAttempt.gate_id',
)
class ShippingProcessGateAttempt(Base):
"""不可变门禁执行尝试;成功或失败后业务结果不得被后续重试覆盖。"""
__tablename__ = 'shipping_process_gate_attempts'
__table_args__ = (
UniqueConstraint(
'gate_id',
'attempt_no',
name='uq_shipping_process_gate_attempts_gate_no',
),
UniqueConstraint(
'idempotency_key',
name='uq_shipping_process_gate_attempts_idempotency',
),
CheckConstraint(
"status IN ('queued', 'running', 'succeeded', 'failed', 'cancelled', 'superseded')",
name='ck_shipping_process_gate_attempts_status',
),
CheckConstraint('attempt_no >= 1', name='ck_shipping_process_gate_attempts_no'),
CheckConstraint(
"trigger_type IN ("
"'auto', 'user_retry', 'user_manual', 'worker_takeover', "
"'upstream_invalidation', 'system_requeue'"
")",
name='ck_shipping_process_gate_attempts_trigger',
),
CheckConstraint(
"actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin', 'worker')",
name='ck_shipping_process_gate_attempts_actor_type',
),
# 同一 Gate 同时最多一个 queued/running Attempt。
Index(
'uq_shipping_process_gate_attempts_one_active',
'gate_id',
unique=True,
postgresql_where=text("status IN ('queued', 'running')"),
sqlite_where=text("status IN ('queued', 'running')"),
),
Index(
'ix_shipping_process_gate_attempts_lease',
'lease_token',
'lease_expires_at',
),
Index(
'ix_shipping_process_gate_attempts_job',
'job_id',
),
Index(
'ix_shipping_process_gate_attempts_gate_status',
'gate_id',
'status',
'created_at',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
gate_id: Mapped[int] = mapped_column(
ForeignKey('shipping_process_gates.id', ondelete='CASCADE'), nullable=False,
)
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(
String(32), nullable=False, default='queued', server_default='queued',
)
trigger_type: Mapped[str] = mapped_column(String(32), nullable=False, default='auto', server_default='auto')
actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system')
actor_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
input_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
input_snapshot_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
rule_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
rule_snapshot_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
output_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
output_snapshot_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True)
worker_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
lease_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
lease_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
heartbeat_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_summary: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
recovery_plan_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_process_recovery_plans.id', use_alter=True), nullable=True, index=True,
)
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False)
gate: Mapped[ShippingProcessGate] = relationship(
back_populates='attempts',
foreign_keys=[gate_id],
)
recovery_plan = relationship(
'ShippingProcessRecoveryPlan', back_populates='attempts', foreign_keys=[recovery_plan_id],
)
@@ -0,0 +1,64 @@
"""
models/shipping_process_recovery_plan.py
用途:持久化一次跨阶段门禁恢复业务意图及其生命周期。
依赖:ShippingProcessExecution、ShippingProcessGateAttempt、User、Base。
逻辑:RecoveryPlan 记录目标 Gate、失效计划、幂等键和最终结果;一个计划可关联多个 Gate Attempt。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
RECOVERY_PLAN_STATUSES = (
'planned', 'invalidating', 'queued', 'running', 'waiting_external',
'waiting_manual', 'succeeded', 'failed', 'conflicted', 'cancelled',
)
class ShippingProcessRecoveryPlan(Base):
"""一次跨阶段恢复意图;不可用 Gate Attempt JSON 替代。"""
__tablename__ = 'shipping_process_recovery_plans'
__table_args__ = (
UniqueConstraint('plan_no', name='uq_shipping_process_recovery_plans_no'),
UniqueConstraint('execution_id', 'idempotency_key', name='uq_shipping_process_recovery_plans_execution_idempotency'),
CheckConstraint(
"status IN ('planned','invalidating','queued','running','waiting_external','waiting_manual','succeeded','failed','conflicted','cancelled')",
name='ck_shipping_process_recovery_plans_status',
),
Index('ix_shipping_process_recovery_plans_execution_status', 'execution_id', 'status', 'created_at'),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
plan_no: Mapped[str] = mapped_column(String(64), nullable=False)
execution_id: Mapped[int] = mapped_column(ForeignKey('shipping_process_executions.id', ondelete='CASCADE'), nullable=False)
current_gate: Mapped[str] = mapped_column(String(64), nullable=False)
action_code: Mapped[str] = mapped_column(String(64), nullable=False)
target_gate: Mapped[str] = mapped_column(String(64), nullable=False)
resume_after_gate: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='planned', server_default='planned')
invalidation_plan_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
recovery_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
expected_gate_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system')
actor_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
failure_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
failure_detail_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
superseded_by_plan_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_recovery_plans.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
execution = relationship('ShippingProcessExecution', foreign_keys=[execution_id])
attempts = relationship('ShippingProcessGateAttempt', back_populates='recovery_plan', foreign_keys='ShippingProcessGateAttempt.recovery_plan_id')
@@ -0,0 +1,122 @@
"""
models/shipping_task_inventory_rpa_attempts.py
用途:逐库存源的 RPA 导出 Attempt 结构化记录(决策 D1/D2 三元组幂等)。
依赖:Base、ShippingNotice(task_no FK 可选直连 id 先保留 task_no 字符串关联)、users。
逻辑:每个库存源(task_no, source_code)独立计数 attempt_no / run_no;
Trigger 文件名格式 SN-<task_no>__<SOURCE_CODE>.trigger.json;回调按三元组
(task_no, source_code, run_no) 定位 Attempt;迟到回调(run_no < 当前 consumed)
标记 superseded 不写快照,保证幂等。
"""
from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING, Any, Optional
from sqlalchemy import (
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
Text,
UniqueConstraint,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship, synonym
from app.models.base import Base
_JSON_FOR_SQLITE = JSON().with_variant(JSONB(), "postgresql")
if TYPE_CHECKING:
pass
PER_SOURCE_RPA_ATTEMPT_STATUSES = (
'queued', # 已写 trigger 文件,等待 RPA Worker 领取
'running', # RPA Worker 已领取(租约写入 lease_token)
'succeeded', # 回调成功,快照已 ingest 并校验通过
'failed', # 回调返回失败或超时判定失败
'consumed', # 业务侧已消费该快照(推进到下一 Gate)
'superseded', # 迟到回调:run_no 早于已 consumed 的 run_no,忽略不写业务
'exhausted', # 当前 (task, source) 对已达最大 attempt 且未成功
)
class ShippingTaskInventoryRpaAttempt(Base):
"""逐 (task_no, source_code) 的库存 RPA 导出 Attempt 记录。"""
__tablename__ = 'shipping_task_inventory_rpa_attempts'
__table_args__ = (
# 三元组唯一:同一运行号同一源只允许一条记录
UniqueConstraint('task_no', 'source_code', 'source_run_no', name='uq_shipping_task_inv_rpa_triplet'),
# PostgreSQL 部分唯一索引:每个 (task, source) 同时只允许 1 条活动(queued/running)Attempt
Index(
'uq_shipping_task_inv_rpa_active_per_source',
'task_no', 'source_code',
unique=True,
postgresql_where="status IN ('queued','running')",
),
# 扫描超时 & 最新 Attempt 常用查询维度
Index('ix_shipping_task_inv_rpa_task_source', 'task_no', 'source_code', 'attempt_no'),
Index('ix_shipping_task_inv_rpa_status_updated', 'status', 'updated_at'),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in PER_SOURCE_RPA_ATTEMPT_STATUSES)})",
name='ck_shipping_task_inv_rpa_status_enum',
),
CheckConstraint('attempt_no >= 1', name='ck_shipping_task_inv_rpa_attempt_positive'),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
task_no: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
source_code: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
source_run_no: Mapped[str] = mapped_column(String(128), nullable=False)
# 仅为历史调用方提供 Python 层读取兼容;数据库正式事实只有 source_run_no。
run_no = synonym('source_run_no')
callback_id: Mapped[str | None] = mapped_column(String(256), nullable=True, unique=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', index=True)
trigger_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
callback_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
inventory_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
lease_token: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
leased_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True)
lease_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True)
callback_payload_json: Mapped[dict[str, Any]] = mapped_column(_JSON_FOR_SQLITE, nullable=False, default=dict)
extra_json: Mapped[dict[str, Any]] = mapped_column(_JSON_FOR_SQLITE, nullable=False, default=dict)
triggered_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True)
callback_received_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True)
claimed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True)
worker_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
execution_phase: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
file_generated: Mapped[bool] = mapped_column(default=False, nullable=False)
file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
file_size: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
file_exists_at_callback: Mapped[Optional[bool]] = mapped_column(nullable=True)
transaction_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
transaction_error_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
transaction_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
consumed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=False), nullable=False, default=datetime.utcnow, index=True,
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=False), nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow, index=True,
)
+94
View File
@@ -0,0 +1,94 @@
"""
backend/app/models/shipping_task_line.py
用途:订单字段冲突审计(ShippingTaskFieldConflict)模型。
依赖:models.base.Base、shipping_notices、users。
逻辑:冲突按动态订单 Extraction 的行 position 定位,不保留固定订单行投影。
"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import (
CheckConstraint,
ForeignKey,
Index,
Integer,
JSON,
String,
Text,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingTaskFieldConflict(Base):
"""
订单字段级冲突审计;未解决冲突将在后续阶段阻断下游流程。
核心逻辑:独立于 Candidate/TaskLine,记录双方值、来源、证据与解决结果。
"""
__tablename__ = 'shipping_task_field_conflicts'
__table_args__ = (
CheckConstraint(
"status IN ('open', 'resolved', 'dismissed')",
name='ck_shipping_task_field_conflicts_status',
),
Index('ix_shipping_task_field_conflicts_task_status', 'task_id', 'status'),
Index(
'uq_shipping_task_field_conflicts_open_task_field',
'task_id',
'field_name',
unique=True,
postgresql_where=text("status = 'open' AND position IS NULL"),
sqlite_where=text("status = 'open' AND position IS NULL"),
),
Index(
'uq_shipping_task_field_conflicts_open_position_field',
'task_id',
'position',
'field_name',
unique=True,
postgresql_where=text("status = 'open' AND position IS NOT NULL"),
sqlite_where=text("status = 'open' AND position IS NOT NULL"),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notices.id', ondelete='CASCADE'),
nullable=False,
index=True,
)
position: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
field_name: Mapped[str] = mapped_column(String(64), nullable=False)
existing_value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
incoming_value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
existing_source: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
incoming_source: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
existing_evidence_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
incoming_evidence_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
status: Mapped[str] = mapped_column(
String(32),
nullable=False,
default='open',
server_default=text("'open'"),
)
resolved_value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
resolved_at: Mapped[Optional[datetime]] = mapped_column(nullable=True)
resolution_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
conflict_version: Mapped[int] = mapped_column(
Integer,
nullable=False,
default=1,
server_default=text('1'),
)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
task: Mapped['ShippingNotice'] = relationship('ShippingNotice', back_populates='field_conflicts')
@@ -0,0 +1,51 @@
"""
models/shipping_temporary_inventory.py
用途:定义对话上传库存文件的临时会话,隔离其分析、确认与后续任务挂接过程。
依赖:Base、FileAsset、ChatSession、ShippingNotice(shipping_notices)、库存结构分析记录。
逻辑:Dify Tool 与工作台均先创建本会话,再由后端对受控文件资产进行结构初检;
co8e9f0a1b2c 已删除 batch_id;会话仅可关联 task_id;
本表不代表库存站点配置,也不代表生产库存快照。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingTemporaryInventorySession(Base):
"""对话上传库存候选文件的短生命周期会话;禁止直接成为生产库存来源。"""
__tablename__ = 'shipping_temporary_inventory_sessions'
__table_args__ = (
UniqueConstraint('session_no', name='uq_shipping_temporary_inventory_sessions_no'),
Index('ix_shipping_temp_inventory_user_created', 'user_id', 'created_at'),
Index('ix_shipping_temp_inventory_conversation_created', 'conversation_id', 'created_at'),
Index('ix_shipping_temp_inventory_asset', 'asset_id'),
Index('ix_shipping_temp_inventory_status_expires', 'status', 'expires_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
session_no: Mapped[str] = mapped_column(String(64), nullable=False)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), nullable=False, index=True)
analysis_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True,
)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True, index=True)
declared_intent: Mapped[str] = mapped_column(String(32), nullable=False, default='inventory_candidate')
file_classification_status: Mapped[str] = mapped_column(String(32), nullable=False, default='created')
status: Mapped[str] = mapped_column(String(32), nullable=False, default='created')
classification_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
candidate_source_ids_json: Mapped[list[int]] = mapped_column(JSON, nullable=False, default=list)
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, index=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False, index=True)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
@@ -0,0 +1,81 @@
"""
backend/app/models/shipping_xfa_audit_snapshot.py
用途:持久化 XFA 审计完整快照密文(不可变、可校验、默认保留 3 年)。
依赖:SQLAlchemy Base;由 audit_snapshot_service 写入/只读解密;禁止业务层直接改删。
逻辑:普通 ShippingAuditEvent 仅保存脱敏 diff 与 snapshot_ref;完整请求/definition/
受控原值经 envelope encryption 落入本表。ORM before_update/before_delete 与
PostgreSQL 触发器共同保证 append-only;到期清理须 set_config
('hxops.shipping_xfa_audit_purge','1')。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import JSON, CheckConstraint, DateTime, Index, Integer, String, Text, event
from sqlalchemy.orm import Mapped, mapped_column
from app.core.errors import ValidationError
from app.models.base import Base
class ShippingXfaAuditSnapshot(Base):
"""XFA 审计完整快照密文行;禁止业务更新或删除。"""
__tablename__ = 'shipping_xfa_audit_snapshots'
__table_args__ = (
CheckConstraint(
"purpose IN ('before', 'after', 'request', 'full', 'sample_values')",
name='ck_shipping_xfa_audit_snapshots_purpose',
),
CheckConstraint(
"encryption_alg IN ('fernet-v1')",
name='ck_shipping_xfa_audit_snapshots_encryption_alg',
),
Index('ix_shipping_xfa_audit_snapshots_object', 'object_type', 'object_id', 'created_at'),
Index('ix_shipping_xfa_audit_snapshots_retention', 'retention_expires_at', 'id'),
Index('ix_shipping_xfa_audit_snapshots_operation', 'operation_id', 'created_at'),
Index('ix_shipping_xfa_audit_snapshots_request', 'request_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
# 对外稳定引用(写入审计事件 context_refs / evidence_refs),禁止猜测递增 id。
snapshot_ref: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
object_type: Mapped[str] = mapped_column(String(64), nullable=False)
object_id: Mapped[str] = mapped_column(String(128), nullable=False)
purpose: Mapped[str] = mapped_column(String(32), nullable=False)
schema_version: Mapped[str] = mapped_column(String(32), nullable=False, default='xfa_audit_v1')
encryption_alg: Mapped[str] = mapped_column(String(32), nullable=False, default='fernet-v1')
key_id: Mapped[str] = mapped_column(String(64), nullable=False, default='primary')
# Fernet 密文;静态不可读,仅敏感读 API 在权限校验后解密。
ciphertext: Mapped[str] = mapped_column(Text, nullable=False)
ciphertext_sha256: Mapped[str] = mapped_column(String(64), nullable=False)
plaintext_sha256: Mapped[str] = mapped_column(String(64), nullable=False)
# 脱敏摘要(可进普通导出);不得含明文订单值或 XML。
redacted_summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
actor_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
audit_event_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
retention_expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@event.listens_for(ShippingXfaAuditSnapshot, 'before_update')
def _reject_xfa_audit_snapshot_update(_mapper, _connection, _target) -> None:
"""拒绝 ORM 更新,保证完整快照不可篡改。"""
raise ValidationError(
'Shipping XFA audit snapshot is append-only',
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_IMMUTABLE',
)
@event.listens_for(ShippingXfaAuditSnapshot, 'before_delete')
def _reject_xfa_audit_snapshot_delete(_mapper, _connection, _target) -> None:
"""拒绝 ORM 删除,避免业务清理抹除加密审计事实。"""
raise ValidationError(
'Shipping XFA audit snapshot is append-only',
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_IMMUTABLE',
)
@@ -0,0 +1,64 @@
"""
backend/app/models/shipping_xfa_structure_analysis.py
用途:持久化 XFA 样本/文档的结构分析摘要(document_kind、packet checksum、结构指纹、统计与安全摘要)。
依赖:shipping_order_documents、shipping_order_document_layout_versions、SQLAlchemy Base。
逻辑:由 shipping_document_layout Job 在 XFA 分支写入;admin API 只读投影,不返回原始 XML/PDF。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingXfaStructureAnalysis(Base):
"""单文档 XFA 结构分析记录;保存脱敏结构证据,完整敏感值仅通过 encrypted_snapshot_ref 占位。"""
__tablename__ = 'shipping_xfa_structure_analyses'
__table_args__ = (
CheckConstraint(
"analysis_status IN ('ready', 'failed', 'rejected')",
name='ck_shipping_xfa_structure_analysis_status',
),
CheckConstraint(
"document_kind IN ('plain_pdf', 'acroform', 'xfa_hybrid', 'pure_xfa', 'unsupported')",
name='ck_shipping_xfa_structure_analysis_document_kind',
),
Index('ix_shipping_xfa_structure_analysis_document', 'document_id', 'created_at'),
Index('ix_shipping_xfa_structure_analysis_content_hash', 'source_content_hash'),
Index('ix_shipping_xfa_structure_analysis_fingerprint', 'dataset_structure_fingerprint'),
)
id: Mapped[int] = mapped_column(primary_key=True)
document_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_documents.id', ondelete='CASCADE'), nullable=False,
)
layout_version_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_document_layout_versions.id', ondelete='SET NULL'), nullable=True,
)
source_content_hash: Mapped[str] = mapped_column(String(64), nullable=False)
document_kind: Mapped[str] = mapped_column(String(32), nullable=False)
analysis_status: Mapped[str] = mapped_column(String(16), nullable=False, default='ready', server_default='ready')
template_packet_checksum: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
datasets_packet_checksum: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
dataset_structure_fingerprint: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
packet_checksums_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
stats_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
security_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
tree_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
route_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
encrypted_snapshot_ref: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
parser_identity: Mapped[str] = mapped_column(String(64), nullable=False)
contract_version: Mapped[str] = mapped_column(String(64), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
document = relationship('ShippingOrderDocument', foreign_keys=[document_id])
layout_version = relationship('ShippingDocumentLayoutVersion', foreign_keys=[layout_version_id])
+6
View File
@@ -91,6 +91,12 @@ class User(Base):
'training_hr_manage': self.role in {'admin', 'hr'},
# 发货通知强制新建重复单据:admin 默认开;其他角色默认关,可显式授予
'shipping_notice_force_create': self.role == 'admin',
# 货代审计敏感快照/前后 Diff 读取:admin 默认开;不新建角色,可显式关闭或授予
'shipping_notice.audit_sensitive_read': self.role == 'admin',
# XFA 字段拆分:编辑 / 预览 / 发布审核;admin 默认开,可显式收紧
'shipping_notice.xfa_split_rule_edit': self.role == 'admin',
'shipping_notice.xfa_split_rule_preview': self.role == 'admin',
'shipping_notice.xfa_split_rule_publish': self.role == 'admin',
}
def get_feature_permissions(self) -> dict[str, bool]:
+8
View File
@@ -15,6 +15,10 @@ from . import (
linked_service_service,
permission_service,
report_service,
shipping_customer_import_service,
shipping_customer_lifecycle_service,
shipping_customer_merge_service,
shipping_customer_service,
user_service,
wecom_admin_service,
)
@@ -30,6 +34,10 @@ __all__ = [
'linked_service_service',
'permission_service',
'report_service',
'shipping_customer_import_service',
'shipping_customer_lifecycle_service',
'shipping_customer_merge_service',
'shipping_customer_service',
'user_service',
'wecom_admin_service',
]
@@ -189,7 +189,6 @@ def promote_faq_candidate(data: dict[str, Any]) -> dict:
q_norm = normalize_faq_query(str(data.get('q_norm') or ''))
if not agent_id or not q_norm:
raise ValidationError('agent_id and q_norm are required')
candidate = HotFaqCandidateStore.get_candidate(int(agent_id), q_norm)
if not candidate:
raise NotFoundError('FAQ candidate not found')
@@ -130,10 +130,10 @@ def approve_permission_request(request_id: int) -> dict:
if not req:
raise NotFoundError('Not found')
req.status = 'approved'
req.reviewed_at = datetime.utcnow()
user = db.session.get(User, req.user_id)
agent = db.session.get(Agent, req.agent_id)
req.status = 'approved'
req.reviewed_at = datetime.utcnow()
if user and agent and (agent not in user.agents):
user.agents.append(agent)
if user and user.wecom_userid:
@@ -0,0 +1,711 @@
"""
services/admin/shipping_customer_import_service.py
用途:货代期初客户 Excel 模板、上传预检、行级决策、单事务发布与对账。
依赖:openpyxl、客户/导入模型、shipping_customer_service、customer_normalization。
逻辑:上传仅落暂存;发布前阻断错误与未决警告,正式客户及识别证据在一个事务内写入。
"""
from __future__ import annotations
import csv
import hashlib
import io
import uuid
from datetime import date, datetime, time
from typing import Any
from openpyxl import Workbook, load_workbook
from sqlalchemy.exc import IntegrityError
from app import db
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingCustomerImportBatch,
ShippingCustomerImportRow,
)
from app.services.admin.shipping_customer_service import serialize_customer
from app.services.shipping_notice.customer_normalization import (
clean_text,
is_public_email_domain,
normalize_customer_name,
normalize_identifier,
normalize_short_code,
)
MAX_IMPORT_BYTES = 5 * 1024 * 1024
MAX_IMPORT_ROWS = 10_000
CUSTOMER_HEADERS = ('legacy_customer_key', 'standard_name', 'short_code', 'status', 'source_system', 'remark')
IDENTIFIER_HEADERS = (
'legacy_customer_key',
'source_system',
'identifier_type',
'identifier_value',
'auto_match_allowed',
'remark',
)
ROW_DECISIONS = frozenset({'create', 'update', 'merge', 'skip'})
def generate_import_batch_no() -> str:
"""生成客户导入批次号。"""
return f"SCI-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
def build_import_template() -> bytes:
"""生成包含 customers/identifiers 两个 Sheet 的标准期初导入模板。"""
wb = Workbook()
customers = wb.active
customers.title = 'customers'
customers.append(CUSTOMER_HEADERS)
customers.append(('INIT-000001', '无锡宇辰有限公司', 'WYC', 'active', 'INITIAL_EXCEL', '示例行,可删除'))
identifiers = wb.create_sheet('identifiers')
identifiers.append(IDENTIFIER_HEADERS)
identifiers.append(('INIT-000001', 'INITIAL_EXCEL', 'name_alias', 'WUXI YUCHEN', False, '历史英文名称'))
output = io.BytesIO()
wb.save(output)
return output.getvalue()
def _cell_bool(value: Any) -> bool:
"""将 Excel 常见真假写法转换为 bool。"""
if isinstance(value, bool):
return value
return clean_text(value).lower() in {'1', 'true', 'yes', 'y', '是'}
def _json_safe_cell(value: Any) -> Any:
"""将 Excel 单元格转换为 JSON 可持久化值,日期时间使用 ISO 8601。"""
if value is None or isinstance(value, (str, int, float, bool)):
return value
if isinstance(value, (datetime, date, time)):
return value.isoformat()
return str(value)
def _sheet_rows(workbook, sheet_name: str, headers: tuple[str, ...]) -> list[tuple[int, dict[str, Any]]]:
"""校验 Sheet 表头并返回非空数据行。"""
if sheet_name not in workbook.sheetnames:
raise ValidationError(
f'Missing sheet: {sheet_name}',
code='SHIPPING.CUSTOMER_IMPORT_SHEET_MISSING',
details={'sheet': sheet_name},
)
sheet = workbook[sheet_name]
actual = tuple(clean_text(cell.value) for cell in sheet[1])
missing = [header for header in headers if header not in actual]
if missing:
raise ValidationError(
'Customer import columns missing',
code='SHIPPING.CUSTOMER_IMPORT_COLUMNS_MISSING',
details={'sheet': sheet_name, 'missing': missing},
)
positions = {header: actual.index(header) for header in headers}
result: list[tuple[int, dict[str, Any]]] = []
for row_no, values in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
if not any(value not in (None, '') for value in values):
continue
result.append((row_no, {header: values[index] if index < len(values) else None for header, index in positions.items()}))
if len(result) > MAX_IMPORT_ROWS:
raise ValidationError(
'Customer import contains too many rows',
code='SHIPPING.CUSTOMER_IMPORT_TOO_MANY_ROWS',
details={'sheet': sheet_name, 'max_rows': MAX_IMPORT_ROWS},
)
return result
def _existing_customer_by_ref(source_system: str, legacy_key: str) -> ShippingCustomer | None:
"""按外部来源稳定键查找已导入客户。"""
ref = db.session.query(ShippingCustomerExternalRef).filter_by(
source_system=source_system,
legacy_customer_key=legacy_key,
).first()
return db.session.get(ShippingCustomer, ref.customer_id) if ref else None
def _customer_row_validation(raw: dict[str, Any], *, default_source_system: str) -> dict[str, Any]:
"""预检单条 customers 行,返回标准化字段、错误、警告和建议动作。"""
errors: list[dict[str, Any]] = []
warnings: list[dict[str, Any]] = []
legacy_key = clean_text(raw.get('legacy_customer_key'))
name = clean_text(raw.get('standard_name'))
source_system = clean_text(raw.get('source_system') or default_source_system).upper()
status = clean_text(raw.get('status') or 'active').lower()
short_code = ''
if not legacy_key:
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_KEY_REQUIRED', 'field': 'legacy_customer_key'})
elif len(legacy_key) > 128:
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_KEY_INVALID', 'field': 'legacy_customer_key'})
if not name:
errors.append({'code': 'SHIPPING.CUSTOMER_NAME_REQUIRED', 'field': 'standard_name'})
elif len(name) > 200:
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_NAME_TOO_LONG', 'field': 'standard_name'})
if not source_system or len(source_system) > 64:
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_SOURCE_INVALID', 'field': 'source_system'})
try:
short_code = normalize_short_code(raw.get('short_code'))
except ValidationError as exc:
errors.append({'code': exc.code, 'field': 'short_code'})
if status not in {'active', 'inactive'}:
errors.append({'code': 'SHIPPING.CUSTOMER_STATUS_INVALID', 'field': 'status'})
existing_ref = _existing_customer_by_ref(source_system, legacy_key) if legacy_key and source_system else None
code_owner = db.session.query(ShippingCustomer).filter_by(short_code=short_code).first() if short_code else None
if code_owner and (not existing_ref or code_owner.id != existing_ref.id):
warnings.append({
'code': 'SHIPPING.CUSTOMER_IMPORT_SHORT_CODE_CONFLICT',
'customer_id': code_owner.id,
'short_code': short_code,
})
normalized_name = normalize_customer_name(name)
similar = [
item for item in db.session.query(ShippingCustomer).all()
if normalize_customer_name(item.standard_name) == normalized_name and (not existing_ref or item.id != existing_ref.id)
] if normalized_name else []
if similar:
warnings.append({
'code': 'SHIPPING.CUSTOMER_IMPORT_NAME_MATCH',
'candidate_customer_ids': [item.id for item in similar],
})
suggested_action = 'update' if existing_ref else 'create'
target_customer_id = existing_ref.id if existing_ref else None
validation_status = 'error' if errors else 'warning' if warnings else 'valid'
return {
'legacy_customer_key': legacy_key or None,
'normalized': {
'legacy_customer_key': legacy_key,
'standard_name': name,
'short_code': short_code,
'status': status,
'source_system': source_system,
'remark': clean_text(raw.get('remark')),
},
'errors': errors,
'warnings': warnings,
'validation_status': validation_status,
'suggested_action': suggested_action,
'target_customer_id': target_customer_id,
}
def _identifier_row_validation(raw: dict[str, Any], *, default_source_system: str) -> dict[str, Any]:
"""预检单条 identifiers 行,补齐来源系统并将公共邮箱证据降级为人工匹配。"""
errors: list[dict[str, Any]] = []
warnings: list[dict[str, Any]] = []
legacy_key = clean_text(raw.get('legacy_customer_key'))
source_system = clean_text(raw.get('source_system') or default_source_system).upper()
kind = clean_text(raw.get('identifier_type')).lower()
value = clean_text(raw.get('identifier_value'))
auto_allowed = _cell_bool(raw.get('auto_match_allowed'))
normalized = ''
if not legacy_key:
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_KEY_REQUIRED', 'field': 'legacy_customer_key'})
elif len(legacy_key) > 128:
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_KEY_INVALID', 'field': 'legacy_customer_key'})
if not source_system or len(source_system) > 64:
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_SOURCE_INVALID', 'field': 'source_system'})
try:
normalized = normalize_identifier(kind, value)
except ValidationError as exc:
errors.append({'code': exc.code, 'field': 'identifier_value'})
if kind in {'domain', 'email'} and normalized and is_public_email_domain(normalized):
if auto_allowed:
warnings.append({'code': 'SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN'})
auto_allowed = False
validation_status = 'error' if errors else 'warning' if warnings else 'valid'
return {
'legacy_customer_key': legacy_key or None,
'normalized': {
'legacy_customer_key': legacy_key,
'source_system': source_system,
'identifier_type': kind,
'identifier_value': value,
'normalized_value': normalized,
'auto_match_allowed': auto_allowed,
'remark': clean_text(raw.get('remark')),
},
'errors': errors,
'warnings': warnings,
'validation_status': validation_status,
'suggested_action': 'create',
'target_customer_id': None,
}
def serialize_import_row(row: ShippingCustomerImportRow) -> dict[str, Any]:
"""序列化导入暂存行。"""
return {
'id': row.id,
'sheet_name': row.sheet_name,
'row_no': row.row_no,
'row_type': row.row_type,
'legacy_customer_key': row.legacy_customer_key,
'raw': row.raw_json or {},
'normalized': row.normalized_json or {},
'validation_status': row.validation_status,
'errors': row.errors_json or [],
'warnings': row.warnings_json or [],
'suggested_action': row.suggested_action,
'decision_action': row.decision_action,
'target_customer_id': row.target_customer_id,
'decision_note': row.decision_note,
'result_customer_id': row.result_customer_id,
'result_status': row.result_status,
'result_message': row.result_message,
}
def serialize_import_batch(batch: ShippingCustomerImportBatch, *, include_rows: bool = True) -> dict[str, Any]:
"""序列化导入批次及统计。"""
payload: dict[str, Any] = {
'id': batch.id,
'batch_no': batch.batch_no,
'file_name': batch.file_name,
'file_hash': batch.file_hash,
'file_size': batch.file_size,
'source_system': batch.source_system,
'status': batch.status,
'total_rows': batch.total_rows,
'valid_rows': batch.valid_rows,
'warning_rows': batch.warning_rows,
'error_rows': batch.error_rows,
'published_rows': batch.published_rows,
'uploaded_by_id': batch.uploaded_by_id,
'published_by_id': batch.published_by_id,
'published_at': batch.published_at.isoformat() if batch.published_at else None,
'created_at': batch.created_at.isoformat() if batch.created_at else None,
}
if include_rows:
payload['rows'] = [serialize_import_row(row) for row in batch.rows]
return payload
def create_import_batch(upload: Any, *, source_system: str, actor_id: int | None) -> dict[str, Any]:
"""
上传并预检客户期初 Excel。
Args:
upload: Flask FileStorage,仅支持 .xlsx,最大 5 MB。
source_system: 默认来源系统;行内可覆盖。
actor_id: 上传管理员 ID。
Returns:
导入批次详情;同文件哈希重复上传返回原批次并标记 idempotent_replay。
"""
filename = clean_text(getattr(upload, 'filename', ''))
if not filename.lower().endswith('.xlsx'):
raise ValidationError('Only .xlsx customer import files are supported', code='SHIPPING.CUSTOMER_IMPORT_FILE_TYPE_INVALID')
content = upload.read() if hasattr(upload, 'read') else b''
if not content:
raise ValidationError('Customer import file is empty', code='SHIPPING.CUSTOMER_IMPORT_FILE_EMPTY')
if len(content) > MAX_IMPORT_BYTES:
raise ValidationError(
'Customer import file is too large',
code='SHIPPING.CUSTOMER_IMPORT_FILE_TOO_LARGE',
details={'max_bytes': MAX_IMPORT_BYTES},
)
normalized_source = clean_text(source_system).upper() or 'INITIAL_EXCEL'
if len(normalized_source) > 64:
raise ValidationError(
'Customer import source system is too long',
code='SHIPPING.CUSTOMER_IMPORT_SOURCE_INVALID',
details={'field': 'source_system', 'max_length': 64},
)
file_hash = hashlib.sha256(content).hexdigest()
existing = db.session.query(ShippingCustomerImportBatch).filter_by(
file_hash=file_hash,
source_system=normalized_source,
).first()
if existing:
result = serialize_import_batch(existing)
result['idempotent_replay'] = True
return result
try:
workbook = load_workbook(io.BytesIO(content), data_only=True, read_only=True)
except Exception as exc:
raise ValidationError(
'Invalid customer import Excel file',
code='SHIPPING.CUSTOMER_IMPORT_FILE_INVALID',
details={'error_type': type(exc).__name__},
) from exc
try:
customer_rows = _sheet_rows(workbook, 'customers', CUSTOMER_HEADERS)
identifier_rows = _sheet_rows(workbook, 'identifiers', IDENTIFIER_HEADERS)
finally:
workbook.close()
batch = ShippingCustomerImportBatch(
batch_no=generate_import_batch_no(),
file_name=filename,
file_hash=file_hash,
file_size=len(content),
source_system=normalized_source,
uploaded_by_id=actor_id,
status='validated',
)
db.session.add(batch)
staged: list[ShippingCustomerImportRow] = []
try:
db.session.flush()
seen_keys: set[tuple[str, str]] = set()
order = 0
for sheet_name, row_type, rows, validator in (
(
'customers',
'customer',
customer_rows,
lambda raw: _customer_row_validation(raw, default_source_system=normalized_source),
),
(
'identifiers',
'identifier',
identifier_rows,
lambda raw: _identifier_row_validation(raw, default_source_system=normalized_source),
),
):
for row_no, raw in rows:
order += 1
result = validator(raw)
errors = list(result['errors'])
normalized = result['normalized']
if row_type == 'customer':
key = (normalized.get('source_system') or '', normalized.get('legacy_customer_key') or '')
if key in seen_keys:
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_DUPLICATE_KEY'})
result['validation_status'] = 'error'
seen_keys.add(key)
staged.append(ShippingCustomerImportRow(
batch_id=batch.id,
sheet_name=sheet_name,
row_no=row_no,
row_order=order,
row_type=row_type,
legacy_customer_key=result['legacy_customer_key'],
raw_json={key: _json_safe_cell(value) for key, value in raw.items()},
normalized_json=normalized,
validation_status=result['validation_status'],
errors_json=errors,
warnings_json=result['warnings'],
suggested_action=result['suggested_action'],
target_customer_id=result['target_customer_id'],
))
customer_sources_by_key: dict[str, set[str]] = {}
for row in staged:
if row.row_type != 'customer' or not row.legacy_customer_key or row.validation_status == 'error':
continue
customer_sources_by_key.setdefault(row.legacy_customer_key, set()).add(
clean_text((row.normalized_json or {}).get('source_system')).upper()
)
for row in staged:
if row.row_type != 'identifier' or not row.legacy_customer_key:
continue
raw_source = clean_text((row.raw_json or {}).get('source_system')).upper()
candidate_sources = customer_sources_by_key.get(row.legacy_customer_key) or set()
if not raw_source and len(candidate_sources) == 1:
row.normalized_json = {
**(row.normalized_json or {}),
'source_system': next(iter(candidate_sources)),
}
customer_keys = {
(
clean_text((row.normalized_json or {}).get('source_system')).upper(),
row.legacy_customer_key,
)
for row in staged
if row.row_type == 'customer' and row.legacy_customer_key and row.validation_status != 'error'
}
for row in staged:
if row.row_type != 'identifier' or not row.legacy_customer_key:
continue
source_system = clean_text((row.normalized_json or {}).get('source_system')).upper()
if (source_system, row.legacy_customer_key) not in customer_keys:
existing_ref = db.session.query(ShippingCustomerExternalRef.id).filter_by(
source_system=source_system,
legacy_customer_key=row.legacy_customer_key,
).first()
if not existing_ref:
row.errors_json = [
*(row.errors_json or []),
{'code': 'SHIPPING.CUSTOMER_IMPORT_IDENTIFIER_CUSTOMER_MISSING'},
]
row.validation_status = 'error'
db.session.add_all(staged)
batch.total_rows = len(staged)
batch.valid_rows = sum(row.validation_status == 'valid' for row in staged)
batch.warning_rows = sum(row.validation_status == 'warning' for row in staged)
batch.error_rows = sum(row.validation_status == 'error' for row in staged)
db.session.commit()
except ValidationError:
db.session.rollback()
raise
except IntegrityError as exc:
db.session.rollback()
existing = db.session.query(ShippingCustomerImportBatch).filter_by(
file_hash=file_hash,
source_system=normalized_source,
).first()
if existing is not None:
result = serialize_import_batch(existing)
result['idempotent_replay'] = True
return result
raise ConflictError(
'Customer import upload conflict',
code='SHIPPING.CUSTOMER_IMPORT_UPLOAD_CONFLICT',
) from exc
except Exception:
db.session.rollback()
raise
return serialize_import_batch(batch)
def get_import_batch(batch_id: int) -> dict[str, Any]:
"""读取导入批次详情。"""
batch = db.session.get(ShippingCustomerImportBatch, batch_id)
if batch is None:
raise NotFoundError('Customer import batch not found', code='SHIPPING.CUSTOMER_IMPORT_NOT_FOUND')
return serialize_import_batch(batch)
def decide_import_row(row_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""保存警告行的新增、更新/合并或跳过决定。"""
row = db.session.get(ShippingCustomerImportRow, row_id)
if row is None:
raise NotFoundError('Customer import row not found', code='SHIPPING.CUSTOMER_IMPORT_ROW_NOT_FOUND')
if row.batch.status == 'published':
raise ConflictError('Published import rows cannot be changed', code='SHIPPING.CUSTOMER_IMPORT_ALREADY_PUBLISHED')
if row.validation_status == 'error':
raise ValidationError(
'Rows with validation errors cannot be decided',
code='SHIPPING.CUSTOMER_IMPORT_HAS_ERRORS',
details={'row_id': row.id},
)
action = clean_text(data.get('action')).lower()
if action not in ROW_DECISIONS:
raise ValidationError('Invalid import row decision', code='SHIPPING.CUSTOMER_IMPORT_DECISION_INVALID')
target_id = data.get('target_customer_id')
if row.row_type == 'identifier' and action not in {'create', 'skip'}:
raise ValidationError(
'Identifier warning rows only support create or skip',
code='SHIPPING.CUSTOMER_IMPORT_DECISION_INVALID',
)
if row.row_type == 'customer' and action in {'update', 'merge'}:
try:
target_id = int(target_id)
except (TypeError, ValueError) as exc:
raise ValidationError('Target customer is required', code='SHIPPING.CUSTOMER_IMPORT_TARGET_REQUIRED') from exc
target = db.session.get(ShippingCustomer, target_id)
if target is None:
raise NotFoundError('Target customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if target.status != 'active':
raise ValidationError('Target customer must be active', code='SHIPPING.CUSTOMER_MERGE_TARGET_INVALID')
else:
target_id = None
row.decision_action = action
row.target_customer_id = target_id
row.decision_note = clean_text(data.get('note')) or None
db.session.commit()
return serialize_import_row(row)
def _effective_action(row: ShippingCustomerImportRow) -> str:
"""返回发布时实际动作;警告行必须显式决策。"""
if row.validation_status == 'error':
return ''
if row.validation_status == 'warning':
return clean_text(row.decision_action).lower()
return clean_text(row.decision_action or row.suggested_action).lower()
def _upsert_external_ref(customer_id: int, *, source_system: str, legacy_key: str) -> None:
"""创建或校验客户外部来源键;禁止同一来源键静默改绑。"""
existing = db.session.query(ShippingCustomerExternalRef).filter_by(
source_system=source_system,
legacy_customer_key=legacy_key,
).first()
if existing:
if existing.customer_id != customer_id:
raise ConflictError(
'Customer external reference is already bound',
code='SHIPPING.CUSTOMER_EXTERNAL_REF_CONFLICT',
)
return
db.session.add(ShippingCustomerExternalRef(
customer_id=customer_id,
source_system=source_system,
legacy_customer_key=legacy_key,
))
def publish_import_batch(batch_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""
单事务发布已预检的客户导入批次。
Raises:
ValidationError: 存在错误行或未决警告。
ConflictError: 批次已发布或发布时唯一约束冲突。
"""
batch = (
db.session.query(ShippingCustomerImportBatch)
.filter(ShippingCustomerImportBatch.id == batch_id)
.with_for_update()
.one_or_none()
)
if batch is None:
raise NotFoundError('Customer import batch not found', code='SHIPPING.CUSTOMER_IMPORT_NOT_FOUND')
if batch.status == 'published':
result = serialize_import_batch(batch)
result['idempotent_replay'] = True
return result
if any(row.validation_status == 'error' for row in batch.rows):
raise ValidationError(
'Customer import contains blocking errors',
code='SHIPPING.CUSTOMER_IMPORT_HAS_ERRORS',
details={'error_rows': batch.error_rows},
)
unresolved = [row.id for row in batch.rows if row.validation_status == 'warning' and not row.decision_action]
if unresolved:
raise ValidationError(
'Customer import warnings require decisions',
code='SHIPPING.CUSTOMER_IMPORT_DECISIONS_REQUIRED',
details={'row_ids': unresolved},
)
customer_by_key: dict[tuple[str, str], ShippingCustomer] = {}
published = 0
try:
# [STEP 1] 先发布客户行并建立外部来源键,供 identifiers Sheet 稳定关联。
for row in [item for item in batch.rows if item.row_type == 'customer']:
action = _effective_action(row)
if action == 'skip':
row.result_status = 'skipped'
row.result_message = 'Skipped by administrator'
continue
data = row.normalized_json or {}
target: ShippingCustomer | None = None
if action in {'update', 'merge'}:
target = db.session.get(ShippingCustomer, row.target_customer_id)
if target is None:
raise NotFoundError('Target customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if target.status != 'active':
raise ValidationError('Target customer must be active', code='SHIPPING.CUSTOMER_MERGE_TARGET_INVALID')
if action == 'update':
target.standard_name = data['standard_name']
target.short_code = data['short_code']
target.status = data['status']
target.remark = data.get('remark') or None
target.updated_by_id = actor_id
elif action == 'create':
target = ShippingCustomer(
standard_name=data['standard_name'],
short_code=data['short_code'],
status=data['status'],
remark=data.get('remark') or None,
created_by_id=actor_id,
updated_by_id=actor_id,
)
db.session.add(target)
db.session.flush()
else:
raise ValidationError('Invalid import action', code='SHIPPING.CUSTOMER_IMPORT_DECISION_INVALID')
_upsert_external_ref(
target.id,
source_system=data['source_system'],
legacy_key=data['legacy_customer_key'],
)
customer_by_key[(data['source_system'], data['legacy_customer_key'])] = target
row.result_customer_id = target.id
row.result_status = 'published'
row.result_message = action
published += 1
# [STEP 2] 标识行只绑定已发布/既有客户;导入标识默认 approved,保留 source=imported。
for row in [item for item in batch.rows if item.row_type == 'identifier']:
action = _effective_action(row)
if action == 'skip':
row.result_status = 'skipped'
row.result_message = 'Skipped by administrator'
continue
data = row.normalized_json or {}
source_system = data.get('source_system') or batch.source_system
customer = customer_by_key.get((source_system, data.get('legacy_customer_key')))
if customer is None:
ref = db.session.query(ShippingCustomerExternalRef).filter_by(
source_system=source_system,
legacy_customer_key=data.get('legacy_customer_key'),
).first()
customer = db.session.get(ShippingCustomer, ref.customer_id) if ref else None
if customer is None:
raise ConflictError(
'Identifier customer mapping is missing',
code='SHIPPING.CUSTOMER_IMPORT_IDENTIFIER_CUSTOMER_MISSING',
)
existing_identifier = db.session.query(ShippingCustomerIdentifier).filter_by(
customer_id=customer.id,
identifier_type=data['identifier_type'],
normalized_value=data['normalized_value'],
).first()
if existing_identifier is None:
db.session.add(ShippingCustomerIdentifier(
customer_id=customer.id,
identifier_type=data['identifier_type'],
raw_value=data['identifier_value'],
normalized_value=data['normalized_value'],
auto_match_allowed=bool(data.get('auto_match_allowed')),
status='approved',
source='imported',
remark=data.get('remark') or None,
confirmed_by_id=actor_id,
confirmed_at=datetime.utcnow(),
))
row.result_customer_id = customer.id
row.result_status = 'published'
row.result_message = 'identifier_created' if existing_identifier is None else 'identifier_exists'
published += 1
batch.status = 'published'
batch.published_rows = published
batch.published_by_id = actor_id
batch.published_at = datetime.utcnow()
db.session.commit()
except AppError:
db.session.rollback()
raise
except (IntegrityError, ValueError) as exc:
db.session.rollback()
raise ConflictError(
'Customer import publish conflict',
code='SHIPPING.CUSTOMER_IMPORT_PUBLISH_CONFLICT',
) from exc
except Exception:
db.session.rollback()
raise
return serialize_import_batch(batch)
def build_reconciliation_csv(batch_id: int) -> tuple[bytes, str]:
"""从持久化导入行生成可重复下载的 UTF-8 BOM 对账 CSV。"""
batch = db.session.get(ShippingCustomerImportBatch, batch_id)
if batch is None:
raise NotFoundError('Customer import batch not found', code='SHIPPING.CUSTOMER_IMPORT_NOT_FOUND')
output = io.StringIO(newline='')
writer = csv.writer(output)
writer.writerow([
'sheet_name', 'row_no', 'legacy_customer_key', 'validation_status', 'decision_action',
'result_status', 'result_customer_id', 'result_message', 'errors', 'warnings',
])
for row in batch.rows:
writer.writerow([
row.sheet_name,
row.row_no,
row.legacy_customer_key or '',
row.validation_status,
row.decision_action or row.suggested_action or '',
row.result_status or '',
row.result_customer_id or '',
row.result_message or '',
';'.join(str(item.get('code') or item) for item in (row.errors_json or [])),
';'.join(str(item.get('code') or item) for item in (row.warnings_json or [])),
])
return ('\ufeff' + output.getvalue()).encode('utf-8'), f'{batch.batch_no}_reconciliation.csv'
@@ -0,0 +1,253 @@
"""
services/admin/shipping_customer_lifecycle_service.py
用途:统一计算货代客户生命周期影响和永久删除资格。
依赖:客户、业务单、流水、导入、影子识别模型及统一 AppError。
逻辑:所有删除入口先调用本服务;业务和识别审计引用均阻断删除,识别证据仅作为可级联配置数据。
"""
from __future__ import annotations
from typing import Any
from app import db
from sqlalchemy import select
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingBusinessSequence,
ShippingCase,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingIdentityEvidence,
ShippingCustomerImportRow,
ShippingCustomerLifecycleEvent,
ShippingCustomerSite,
ShippingOrderCustomerMatch,
ShippingCustomerShadowMatch,
ShippingCustomerShadowResolution,
)
def _legacy_shadow_json_match_count(customer_id: int, *, matched_resolution_ids: set[int]) -> int:
"""统计规范化迁移前 JSON 中仍未映射的候选,防止现存审计记录漏算。"""
count = 0
rows = db.session.query(
ShippingCustomerShadowResolution.id,
ShippingCustomerShadowResolution.candidate_matches_json,
).all()
for resolution_id, matches in rows:
if int(resolution_id) in matched_resolution_ids:
continue
for item in matches or []:
if not isinstance(item, dict):
continue
try:
if int(item.get('customer_id')) == customer_id:
count += 1
break
except (TypeError, ValueError):
continue
return count
def _build_customer_lifecycle_impact(customer: ShippingCustomer) -> dict[str, Any]:
"""按已锁定或已读取的客户对象统计删除资格,保证各删除入口使用同一口径。"""
matched_resolution_ids = {
int(row[0])
for row in db.session.query(ShippingCustomerShadowMatch.resolution_id)
.filter_by(customer_id=customer.id)
.all()
}
shadow_normalized = len(matched_resolution_ids)
blockers = {
'business_cases': db.session.query(ShippingCase.id).filter_by(customer_id=customer.id).count(),
'business_sequences': db.session.query(ShippingBusinessSequence.id).filter_by(customer_id=customer.id).count(),
'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=customer.id).count(),
'order_customer_matches': db.session.query(ShippingOrderCustomerMatch.id).filter_by(customer_id=customer.id).count(),
'import_target_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(target_customer_id=customer.id).count(),
'import_result_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(result_customer_id=customer.id).count(),
'shadow_top_candidates': db.session.query(ShippingCustomerShadowResolution.id).filter_by(top_customer_id=customer.id).count(),
'shadow_manual_labels': db.session.query(ShippingCustomerShadowResolution.id).filter_by(manual_customer_id=customer.id).count(),
'shadow_candidate_matches': shadow_normalized + _legacy_shadow_json_match_count(
customer.id,
matched_resolution_ids=matched_resolution_ids,
),
'merged_source_customers': db.session.query(ShippingCustomer.id).filter_by(
merged_into_customer_id=customer.id,
).count(),
'merged_into_customer': int(customer.merged_into_customer_id is not None),
}
return {
'customer': {
'id': customer.id,
'standard_name': customer.standard_name,
'short_code': customer.short_code,
'status': customer.status,
},
'can_delete': not any(blockers.values()),
'blockers': blockers,
'cascade': {
'identifiers': db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=customer.id).count(),
'identity_evidences': db.session.query(ShippingIdentityEvidence.id).filter_by(customer_id=customer.id).count(),
'sites': db.session.query(ShippingCustomerSite.id).filter_by(customer_id=customer.id).count(),
},
}
def get_customer_lifecycle_impact(customer_id: int) -> dict[str, Any]:
"""
返回客户永久删除前必须检查的全部引用和可级联配置数据。
Args:
customer_id: 标准客户主键。
Returns:
客户快照、can_delete、阻断引用计数和可级联识别证据数。
"""
customer = db.session.get(ShippingCustomer, customer_id)
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
return _build_customer_lifecycle_impact(customer)
def get_customer_lifecycle_timeline(customer_id: int, *, limit: int = 100) -> dict[str, Any]:
"""返回客户关键治理操作的倒序时间线,事件只含快照而不依赖客户外键。"""
customer = db.session.get(ShippingCustomer, customer_id)
rows = (
db.session.query(ShippingCustomerLifecycleEvent)
.filter_by(customer_id_snapshot=customer_id)
.order_by(ShippingCustomerLifecycleEvent.id.desc())
.limit(max(1, min(int(limit), 500)))
.all()
)
if customer is None and not rows:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
# 受控删除后主表已不存在;以最近生命周期快照继续提供审计回放。
customer_snapshot = _build_customer_lifecycle_impact(customer)['customer'] if customer is not None else {
'id': customer_id,
'standard_name': rows[0].customer_name_snapshot,
'short_code': rows[0].customer_short_code_snapshot,
'status': 'deleted',
}
return {
'customer': customer_snapshot,
'items': [{
'id': row.id,
'event_type': row.event_type,
'actor_id': row.actor_id,
'reason': row.reason,
'detail': row.detail_json or {},
'created_at': row.created_at.isoformat() if row.created_at else None,
} for row in rows],
}
def get_customer_governance_quality(*, limit: int = 100) -> dict[str, Any]:
"""汇总影子识别、自动确认门禁和生命周期事件,供管理端持续治理。"""
from app.services.shipping_notice.customer_shadow_resolution import get_shadow_quality_report
from app.services.shipping_notice.customer_auto_resolution import get_auto_resolution_metrics
report = get_shadow_quality_report(limit=limit)
report['auto_resolution'] = get_auto_resolution_metrics()
event_counts = dict(
db.session.query(ShippingCustomerLifecycleEvent.event_type, db.func.count())
.group_by(ShippingCustomerLifecycleEvent.event_type)
.all()
)
return {
'shadow_quality': report,
'lifecycle_event_counts': event_counts,
}
def delete_customer(
customer_id: int,
*,
confirmation_short_code: object,
reason: object,
actor_id: int | None,
) -> dict[str, Any]:
"""
受控永久删除未进入任何业务或审计链的误建客户。
Args:
customer_id: 待删除的标准客户主键。
confirmation_short_code: 管理员二次输入的客户简码,忽略首尾空格并按大写比对。
reason: 必填删除原因,写入不可反向引用客户的生命周期审计。
actor_id: 当前管理员主键。
Returns:
已删除客户的快照、级联删除证据数与审计事件主键。
Raises:
ValidationError: 删除原因或二次确认简码不合法。
ConflictError: 锁定后发现存在任一阻断引用。
NotFoundError: 客户不存在。
"""
confirmed_code = str(confirmation_short_code or '').strip().upper()
delete_reason = str(reason or '').strip()
if not delete_reason:
raise ValidationError(
'Customer deletion reason is required',
code='SHIPPING.CUSTOMER_DELETE_REASON_REQUIRED',
details={'field': 'reason'},
)
try:
# 锁住客户行后再统计引用,避免预检与提交之间出现可删除的错误判断。
customer = db.session.execute(
select(ShippingCustomer)
.where(ShippingCustomer.id == customer_id)
.with_for_update()
).scalar_one_or_none()
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if confirmed_code != customer.short_code:
raise ValidationError(
'Customer deletion confirmation short code is invalid',
code='SHIPPING.CUSTOMER_DELETE_CONFIRMATION_INVALID',
details={'field': 'confirmation_short_code'},
)
impact = _build_customer_lifecycle_impact(customer)
if not impact['can_delete']:
raise ConflictError(
'Customer deletion is blocked by lifecycle references',
code='SHIPPING.CUSTOMER_DELETE_BLOCKED',
details={'blockers': impact['blockers']},
)
event = ShippingCustomerLifecycleEvent(
event_type='deleted',
customer_id_snapshot=customer.id,
customer_name_snapshot=customer.standard_name,
customer_short_code_snapshot=customer.short_code,
actor_id=actor_id,
reason=delete_reason,
detail_json={
'cascade': impact['cascade'],
},
)
customer_snapshot = impact['customer']
db.session.add(event)
db.session.flush()
# 新模型未在 Customer ORM 上定义 relationship;显式清理可级联配置,避免删除误建客户时外键阻断。
db.session.query(ShippingIdentityEvidence).filter_by(customer_id=customer.id).delete(synchronize_session=False)
site_ids = [item.id for item in db.session.query(ShippingCustomerSite.id).filter_by(customer_id=customer.id).all()]
if site_ids:
db.session.query(ShippingIdentityEvidence).filter(ShippingIdentityEvidence.site_id.in_(site_ids)).delete(
synchronize_session=False,
)
db.session.delete(customer)
db.session.commit()
return {
'deleted_customer': customer_snapshot,
'cascade': impact['cascade'],
'lifecycle_event_id': event.id,
}
except (ConflictError, NotFoundError, ValidationError):
db.session.rollback()
raise
except Exception:
db.session.rollback()
raise
@@ -0,0 +1,257 @@
"""
services/admin/shipping_customer_merge_service.py
用途:执行货代标准客户的受控身份归并。
依赖:客户、识别证据、外部来源键、生命周期审计与统一业务异常。
逻辑:历史业务、编号、导入和影子审计保持指向源客户;仅将未来识别配置归并至目标客户。
"""
from __future__ import annotations
from typing import Any
from sqlalchemy import select
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingIdentityEvidence,
ShippingCustomerLifecycleEvent,
ShippingCustomerMerge,
ShippingCustomerSite,
)
from app.services.admin.shipping_customer_lifecycle_service import get_customer_lifecycle_impact
def _load_customers_for_merge(source_customer_id: int, target_customer_id: int) -> tuple[ShippingCustomer, ShippingCustomer]:
"""按主键固定顺序锁住源和目标客户,避免两个反向合并请求产生死锁。"""
if source_customer_id == target_customer_id:
raise ValidationError('Source and target customer must differ', code='SHIPPING.CUSTOMER_MERGE_SAME_CUSTOMER')
ids = sorted({int(source_customer_id), int(target_customer_id)})
records = db.session.execute(
select(ShippingCustomer)
.where(ShippingCustomer.id.in_(ids))
.order_by(ShippingCustomer.id.asc())
.with_for_update()
).scalars().all()
by_id = {int(record.id): record for record in records}
source = by_id.get(int(source_customer_id))
target = by_id.get(int(target_customer_id))
if source is None or target is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
return source, target
def _assert_merge_allowed(source: ShippingCustomer, target: ShippingCustomer) -> None:
"""校验合并两端均处于可操作状态,禁止链式或循环归并。"""
if source.status == 'merged' or source.merged_into_customer_id is not None:
raise ConflictError('Source customer has already been merged', code='SHIPPING.CUSTOMER_MERGE_SOURCE_ALREADY_MERGED')
if target.status != 'active' or target.merged_into_customer_id is not None:
raise ValidationError('Target customer must be active', code='SHIPPING.CUSTOMER_MERGE_TARGET_INVALID')
def get_customer_merge_impact(source_customer_id: int, target_customer_id: int) -> dict[str, Any]:
"""预览归并的历史保留引用与可迁移配置,不执行任何数据修改。"""
if source_customer_id == target_customer_id:
raise ValidationError('Source and target customer must differ', code='SHIPPING.CUSTOMER_MERGE_SAME_CUSTOMER')
source = db.session.get(ShippingCustomer, source_customer_id)
target = db.session.get(ShippingCustomer, target_customer_id)
if source is None or target is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
_assert_merge_allowed(source, target)
target_identifiers = {
(item.identifier_type, item.normalized_value)
for item in db.session.query(ShippingCustomerIdentifier)
.filter_by(customer_id=target.id)
.all()
}
source_identifiers = db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=source.id).all()
duplicate_identifiers = sum(
(item.identifier_type, item.normalized_value) in target_identifiers
for item in source_identifiers
)
target_evidence_keys = {
(item.definition_id, item.normalized_value)
for item in db.session.query(ShippingIdentityEvidence).filter_by(customer_id=target.id).all()
}
source_evidence = db.session.query(ShippingIdentityEvidence).filter_by(customer_id=source.id).all()
duplicate_evidence = sum((item.definition_id, item.normalized_value) in target_evidence_keys for item in source_evidence)
return {
'source': {
'id': source.id,
'standard_name': source.standard_name,
'short_code': source.short_code,
'status': source.status,
},
'target': {
'id': target.id,
'standard_name': target.standard_name,
'short_code': target.short_code,
'status': target.status,
},
'historical_references': get_customer_lifecycle_impact(source.id)['blockers'],
'migrate': {
'identifiers': len(source_identifiers) - duplicate_identifiers,
'duplicate_identifiers': duplicate_identifiers,
'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=source.id).count(),
'sites': db.session.query(ShippingCustomerSite.id).filter_by(customer_id=source.id).count(),
'identity_evidences': len(source_evidence) - duplicate_evidence,
'duplicate_identity_evidences': duplicate_evidence,
},
}
def merge_customer(
source_customer_id: int,
*,
target_customer_id: int,
confirmation_short_code: object,
reason: object,
actor_id: int | None,
) -> dict[str, Any]:
"""
原子归并重复客户,不改写历史业务号及其引用。
Args:
source_customer_id: 待归并的源客户。
target_customer_id: 承接未来识别配置的启用目标客户。
confirmation_short_code: 必须匹配源客户当前简码。
reason: 必填合并原因。
actor_id: 当前管理员主键。
Returns:
源/目标快照、迁移统计与合并审计主键。
"""
merge_reason = str(reason or '').strip()
confirmation = str(confirmation_short_code or '').strip().upper()
if not merge_reason:
raise ValidationError('Customer merge reason is required', code='SHIPPING.CUSTOMER_MERGE_REASON_REQUIRED')
try:
source, target = _load_customers_for_merge(source_customer_id, target_customer_id)
_assert_merge_allowed(source, target)
if confirmation != source.short_code:
raise ValidationError(
'Customer merge confirmation short code is invalid',
code='SHIPPING.CUSTOMER_MERGE_CONFIRMATION_INVALID',
details={'field': 'confirmation_short_code'},
)
impact = get_customer_merge_impact(source.id, target.id)
target_identifier_keys = {
(item.identifier_type, item.normalized_value)
for item in db.session.query(ShippingCustomerIdentifier)
.filter_by(customer_id=target.id)
.all()
}
moved_identifiers = 0
duplicates: list[ShippingCustomerIdentifier] = []
identifiers_to_move: list[ShippingCustomerIdentifier] = []
for identifier in db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=source.id).all():
key = (identifier.identifier_type, identifier.normalized_value)
if key in target_identifier_keys:
duplicates.append(identifier)
else:
identifiers_to_move.append(identifier)
target_identifier_keys.add(key)
# 先实际删除与目标重复的证据,再更新其余证据的外键,避免唯一约束瞬时冲突。
for identifier in duplicates:
db.session.delete(identifier)
db.session.flush()
for identifier in identifiers_to_move:
identifier.customer_id = target.id
moved_identifiers += 1
removed_duplicate_identifiers = len(duplicates)
target_evidence_keys = {
(item.definition_id, item.normalized_value)
for item in db.session.query(ShippingIdentityEvidence).filter_by(customer_id=target.id).all()
}
duplicate_evidences = []
evidences_to_move = []
for evidence in db.session.query(ShippingIdentityEvidence).filter_by(customer_id=source.id).all():
key = (evidence.definition_id, evidence.normalized_value)
if key in target_evidence_keys:
duplicate_evidences.append(evidence)
else:
evidences_to_move.append(evidence)
target_evidence_keys.add(key)
for evidence in duplicate_evidences:
db.session.delete(evidence)
db.session.flush()
for evidence in evidences_to_move:
evidence.customer_id = target.id
external_refs = db.session.query(ShippingCustomerExternalRef).filter_by(customer_id=source.id).all()
for external_ref in external_refs:
external_ref.customer_id = target.id
target_site_codes = {
item.site_code for item in db.session.query(ShippingCustomerSite).filter_by(customer_id=target.id).all()
}
source_sites = db.session.query(ShippingCustomerSite).filter_by(customer_id=source.id).all()
duplicate_site_codes = sorted({item.site_code for item in source_sites if item.site_code in target_site_codes})
if duplicate_site_codes:
raise ConflictError(
'Customer sites conflict during merge',
code='SHIPPING.CUSTOMER_MERGE_SITE_CONFLICT',
details={'site_codes': duplicate_site_codes},
)
for site in source_sites:
site.customer_id = target.id
source_snapshot = impact['source']
target_snapshot = impact['target']
merge = ShippingCustomerMerge(
source_customer_id_snapshot=source.id,
source_name_snapshot=source.standard_name,
source_short_code_snapshot=source.short_code,
target_customer_id_snapshot=target.id,
target_name_snapshot=target.standard_name,
target_short_code_snapshot=target.short_code,
actor_id=actor_id,
reason=merge_reason,
detail_json={
'historical_references': impact['historical_references'],
'migrate': {
'identifiers': moved_identifiers,
'duplicate_identifiers': removed_duplicate_identifiers,
'external_references': len(external_refs),
'sites': len(source_sites),
'identity_evidences': len(evidences_to_move),
'duplicate_identity_evidences': len(duplicate_evidences),
},
},
)
source.status = 'merged'
source.merged_into_customer_id = target.id
source.updated_by_id = actor_id
db.session.add_all([
merge,
ShippingCustomerLifecycleEvent(
event_type='merged_source', customer_id_snapshot=source.id,
customer_name_snapshot=source.standard_name, customer_short_code_snapshot=source.short_code,
actor_id=actor_id, reason=merge_reason,
detail_json={'target': target_snapshot},
),
ShippingCustomerLifecycleEvent(
event_type='merged_target', customer_id_snapshot=target.id,
customer_name_snapshot=target.standard_name, customer_short_code_snapshot=target.short_code,
actor_id=actor_id, reason=merge_reason,
detail_json={'source': source_snapshot},
),
])
db.session.commit()
return {
'source': source_snapshot,
'target': target_snapshot,
'migrate': merge.detail_json['migrate'],
'merge_id': merge.id,
}
except (ConflictError, NotFoundError, ValidationError):
db.session.rollback()
raise
except Exception:
db.session.rollback()
raise
@@ -0,0 +1,611 @@
"""
services/admin/shipping_customer_service.py
用途:管理货代标准客户与已审核识别证据。
依赖:db、ShippingCustomer* 模型、customer_normalization、统一 AppError。
逻辑:管理 API 委托本服务完成校验、唯一性检查、停用与序列化;不承载运行期客户裁决。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from sqlalchemy import asc, desc, func, or_
from sqlalchemy.exc import IntegrityError
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingCase,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingCustomerLifecycleEvent,
ShippingCustomerSite,
ShippingCustomerSiteIdentifier,
ShippingIdentityEvidence,
)
from app.services.shipping_notice.customer_normalization import (
clean_text,
is_public_email_domain,
normalize_identifier,
normalize_short_code,
)
CUSTOMER_STATUSES = frozenset({'active', 'inactive', 'merged'})
IDENTIFIER_STATUSES = frozenset({'pending', 'approved', 'disabled'})
def _record_lifecycle_event(
customer: ShippingCustomer,
*,
event_type: str,
actor_id: int | None,
reason: str | None = None,
detail: dict[str, Any] | None = None,
) -> None:
"""写入仅含客户快照的治理审计,避免生命周期日志反向阻断受控删除。"""
db.session.add(ShippingCustomerLifecycleEvent(
event_type=event_type,
customer_id_snapshot=customer.id,
customer_name_snapshot=customer.standard_name,
customer_short_code_snapshot=customer.short_code,
actor_id=actor_id,
reason=reason,
detail_json=detail or {},
))
def _required_change_reason(data: dict[str, Any]) -> str:
"""返回高风险客户变更的必填审计原因,缺失时拒绝提交。"""
reason = clean_text(data.get('reason'))
if not reason:
raise ValidationError(
'Customer change reason is required',
code='SHIPPING.CUSTOMER_CHANGE_REASON_REQUIRED',
details={'field': 'reason'},
)
return reason
def _identifier_snapshot(record: ShippingCustomerIdentifier) -> dict[str, Any]:
"""生成识别证据变更前后对比所需的最小审计快照。"""
return {
'identifier_id': record.id,
'identifier_type': record.identifier_type,
'normalized_value': record.normalized_value,
'status': record.status,
'auto_match_allowed': bool(record.auto_match_allowed),
'remark': record.remark,
}
def _strict_bool(value: Any, *, field: str) -> bool:
"""只接受 JSON 布尔值,避免字符串 ``false`` 被 Python 判定为真。"""
if isinstance(value, bool):
return value
if value is None:
return False
raise ValidationError(
f'{field} must be a boolean',
code='VALIDATION.INVALID_PARAM',
details={'field': field},
)
def serialize_identifier(record: ShippingCustomerIdentifier) -> dict[str, Any]:
"""序列化客户识别证据,供管理后台列表与详情共用。"""
return {
'id': record.id,
'customer_id': record.customer_id,
'identifier_type': record.identifier_type,
'raw_value': record.raw_value,
'normalized_value': record.normalized_value,
'auto_match_allowed': bool(record.auto_match_allowed),
'status': record.status,
'source': record.source,
'remark': record.remark,
'confirmed_by_id': record.confirmed_by_id,
'confirmed_at': record.confirmed_at.isoformat() if record.confirmed_at else None,
'created_at': record.created_at.isoformat() if record.created_at else None,
'updated_at': record.updated_at.isoformat() if record.updated_at else None,
}
def serialize_customer(
record: ShippingCustomer,
*,
include_identifiers: bool = False,
case_count: int | None = None,
identifier_count: int | None = None,
identity_evidence_count: int | None = None,
) -> dict[str, Any]:
"""
序列化标准客户,并可选附带识别证据和业务引用数量。
Args:
record: 标准客户 ORM 记录。
include_identifiers: 是否附带识别证据明细。
case_count: 列表查询预聚合的业务单数量;为空时现场查询。
identifier_count: 历史固定类型证据数量,仅供存量审计显示。
identity_evidence_count: 配置化客户主体证据数量;为空时现场查询。
Returns:
管理端客户 JSON 字典。
"""
payload: dict[str, Any] = {
'id': record.id,
'standard_name': record.standard_name,
'short_code': record.short_code,
'status': record.status,
'merged_into_customer_id': record.merged_into_customer_id,
'remark': record.remark,
'created_by_id': record.created_by_id,
'updated_by_id': record.updated_by_id,
'created_at': record.created_at.isoformat() if record.created_at else None,
'updated_at': record.updated_at.isoformat() if record.updated_at else None,
'case_count': case_count if case_count is not None else db.session.query(ShippingCase.id).filter_by(customer_id=record.id).count(),
'identifier_count': identifier_count if identifier_count is not None else db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=record.id).count(),
'identity_evidence_count': identity_evidence_count if identity_evidence_count is not None else db.session.query(
ShippingIdentityEvidence.id,
).filter_by(customer_id=record.id).count(),
}
if include_identifiers:
payload['identifiers'] = [serialize_identifier(item) for item in record.identifiers]
payload['identity_evidences'] = [
_serialize_identity_evidence(item)
for item in db.session.query(ShippingIdentityEvidence)
.filter_by(customer_id=record.id)
.order_by(ShippingIdentityEvidence.id.desc())
.all()
]
payload['external_refs'] = [serialize_external_ref(item) for item in record.external_refs]
payload['sites'] = [serialize_site(item) for item in record.sites]
return payload
def list_customers(params: dict[str, Any]) -> dict[str, Any]:
"""
分页列出标准客户。
Args:
params: 支持 q/status/page/page_size/sort/order。
Returns:
items、total、page、page_size、pages。
"""
case_counts = (
db.session.query(ShippingCase.customer_id.label('customer_id'), func.count(ShippingCase.id).label('case_count'))
.group_by(ShippingCase.customer_id)
.subquery()
)
identifier_counts = (
db.session.query(
ShippingCustomerIdentifier.customer_id.label('customer_id'),
func.count(ShippingCustomerIdentifier.id).label('identifier_count'),
)
.group_by(ShippingCustomerIdentifier.customer_id)
.subquery()
)
identity_evidence_counts = (
db.session.query(
ShippingIdentityEvidence.customer_id.label('customer_id'),
func.count(ShippingIdentityEvidence.id).label('identity_evidence_count'),
)
.filter(ShippingIdentityEvidence.customer_id.isnot(None))
.group_by(ShippingIdentityEvidence.customer_id)
.subquery()
)
site_identity_evidence_counts = (
db.session.query(
ShippingCustomerSite.customer_id.label('customer_id'),
func.count(ShippingIdentityEvidence.id).label('identity_evidence_count'),
)
.join(ShippingIdentityEvidence, ShippingIdentityEvidence.site_id == ShippingCustomerSite.id)
.group_by(ShippingCustomerSite.customer_id)
.subquery()
)
query = (
db.session.query(
ShippingCustomer,
func.coalesce(case_counts.c.case_count, 0),
func.coalesce(identifier_counts.c.identifier_count, 0),
func.coalesce(identity_evidence_counts.c.identity_evidence_count, 0)
+ func.coalesce(site_identity_evidence_counts.c.identity_evidence_count, 0),
)
.outerjoin(case_counts, case_counts.c.customer_id == ShippingCustomer.id)
.outerjoin(identifier_counts, identifier_counts.c.customer_id == ShippingCustomer.id)
.outerjoin(identity_evidence_counts, identity_evidence_counts.c.customer_id == ShippingCustomer.id)
.outerjoin(site_identity_evidence_counts, site_identity_evidence_counts.c.customer_id == ShippingCustomer.id)
)
keyword = clean_text(params.get('q'))
status = clean_text(params.get('status')).lower()
if keyword:
like = f'%{keyword}%'
query = query.filter(or_(ShippingCustomer.standard_name.ilike(like), ShippingCustomer.short_code.ilike(like)))
if status:
if status not in CUSTOMER_STATUSES:
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
query = query.filter(ShippingCustomer.status == status)
try:
page = max(1, int(params.get('page') or 1))
page_size = min(100, max(1, int(params.get('page_size') or 20)))
except (TypeError, ValueError) as exc:
raise ValidationError('Invalid pagination') from exc
sort_map = {
'standard_name': ShippingCustomer.standard_name,
'short_code': ShippingCustomer.short_code,
'created_at': ShippingCustomer.created_at,
'updated_at': ShippingCustomer.updated_at,
}
sort_col = sort_map.get(clean_text(params.get('sort')).lower(), ShippingCustomer.updated_at)
order = asc if clean_text(params.get('order')).lower() == 'asc' else desc
total = query.count()
items = query.order_by(order(sort_col), ShippingCustomer.id.desc()).offset((page - 1) * page_size).limit(page_size).all()
return {
'items': [
serialize_customer(
customer, case_count=int(case_count), identifier_count=int(identifier_count),
identity_evidence_count=int(identity_evidence_count),
)
for customer, case_count, identifier_count, identity_evidence_count in items
],
'total': total,
'page': page,
'page_size': page_size,
'pages': max(1, (total + page_size - 1) // page_size),
}
def get_customer(customer_id: int) -> dict[str, Any]:
"""读取客户详情;不存在时抛出统一 NotFoundError。"""
record = db.session.get(ShippingCustomer, customer_id)
if record is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
return serialize_customer(record, include_identifiers=True)
def _assert_short_code_available(short_code: str, *, exclude_customer_id: int | None = None) -> None:
"""校验客户简码全局唯一。"""
query = db.session.query(ShippingCustomer.id).filter(ShippingCustomer.short_code == short_code)
if exclude_customer_id is not None:
query = query.filter(ShippingCustomer.id != exclude_customer_id)
if query.first():
raise ConflictError(
'Customer short code already exists',
code='SHIPPING.CUSTOMER_SHORT_CODE_EXISTS',
details={'short_code': short_code},
)
def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""
创建标准客户。
Args:
data: standard_name、short_code、status、remark。
actor_id: 当前管理员 ID。
Returns:
新客户详情。
"""
standard_name = clean_text(data.get('standard_name'))
if not standard_name:
raise ValidationError(
'Customer standard name is required',
code='SHIPPING.CUSTOMER_NAME_REQUIRED',
details={'field': 'standard_name'},
)
short_code = normalize_short_code(data.get('short_code'))
_assert_short_code_available(short_code)
status = clean_text(data.get('status') or 'active').lower()
if status not in CUSTOMER_STATUSES - {'merged'}:
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
record = ShippingCustomer(
standard_name=standard_name,
short_code=short_code,
status=status,
remark=clean_text(data.get('remark')) or None,
created_by_id=actor_id,
updated_by_id=actor_id,
)
db.session.add(record)
db.session.flush()
_record_lifecycle_event(
record,
event_type='created',
actor_id=actor_id,
detail={'after': {'standard_name': standard_name, 'short_code': short_code, 'status': status}},
)
try:
db.session.commit()
except IntegrityError as exc:
db.session.rollback()
raise ConflictError('Customer already exists', code='SHIPPING.CUSTOMER_CONFLICT') from exc
return serialize_customer(record, include_identifiers=True)
def serialize_external_ref(record: ShippingCustomerExternalRef) -> dict[str, Any]:
"""序列化客户在外部系统中的稳定客户编码。"""
return {
'id': record.id, 'customer_id': record.customer_id,
'source_system': record.source_system, 'customer_code': record.legacy_customer_key,
}
def _serialize_identity_evidence(record: ShippingIdentityEvidence) -> dict[str, Any]:
"""序列化配置化身份识别证据及定义快照,供客户主数据页直接渲染。"""
from app.services.shipping_notice.identity_rules.service import serialize_evidence
return serialize_evidence(record)
def serialize_site(record: ShippingCustomerSite) -> dict[str, Any]:
"""序列化送货站点及其名称/外部编码标识。"""
return {
'id': record.id, 'customer_id': record.customer_id, 'site_name': record.site_name,
'site_code': record.site_code, 'address': record.address, 'city': record.city,
'country': record.country, 'status': record.status, 'remark': record.remark,
'identifiers': [{
'id': item.id, 'identifier_type': item.identifier_type,
'source_system': item.source_system, 'raw_value': item.raw_value,
'normalized_value': item.normalized_value, 'status': item.status,
} for item in record.identifiers],
'identity_evidences': [
_serialize_identity_evidence(item)
for item in db.session.query(ShippingIdentityEvidence)
.filter_by(site_id=record.id)
.order_by(ShippingIdentityEvidence.id.desc())
.all()
],
}
def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""更新标准客户;历史业务号使用快照,不受简码修改影响。"""
record = db.session.get(ShippingCustomer, customer_id)
if record is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if record.status == 'merged':
raise ConflictError('Merged customer cannot be edited', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
before = {
'standard_name': record.standard_name,
'short_code': record.short_code,
'status': record.status,
'remark': record.remark,
}
next_name = before['standard_name']
next_short_code = before['short_code']
next_status = before['status']
next_remark = before['remark']
if 'standard_name' in data:
name = clean_text(data.get('standard_name'))
if not name:
raise ValidationError('Customer standard name is required', code='SHIPPING.CUSTOMER_NAME_REQUIRED')
next_name = name
if 'short_code' in data:
next_short_code = normalize_short_code(data.get('short_code'))
_assert_short_code_available(next_short_code, exclude_customer_id=customer_id)
if 'status' in data:
next_status = clean_text(data.get('status')).lower()
if next_status not in CUSTOMER_STATUSES - {'merged'}:
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
if 'remark' in data:
next_remark = clean_text(data.get('remark')) or None
after = {
'standard_name': next_name,
'short_code': next_short_code,
'status': next_status,
'remark': next_remark,
}
changes = {key: {'before': before[key], 'after': after[key]} for key in before if before[key] != after[key]}
if changes:
high_risk_change = 'short_code' in changes or 'status' in changes
change_reason = _required_change_reason(data) if high_risk_change else clean_text(data.get('reason')) or None
record.standard_name = next_name
record.short_code = next_short_code
record.status = next_status
record.remark = next_remark
record.updated_by_id = actor_id
_record_lifecycle_event(
record,
event_type='updated',
actor_id=actor_id,
reason=change_reason,
detail={'changes': changes},
)
try:
db.session.commit()
except IntegrityError as exc:
db.session.rollback()
raise ConflictError('Customer update conflict', code='SHIPPING.CUSTOMER_CONFLICT') from exc
return serialize_customer(record, include_identifiers=True)
def deactivate_customer(customer_id: int, *, reason: object = None, actor_id: int | None) -> dict[str, Any]:
"""停用客户;不物理删除,以保留业务单和识别审计。"""
return update_customer(customer_id, {'status': 'inactive', 'reason': reason}, actor_id=actor_id)
def create_identifier(customer_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""
新增客户识别证据。
核心逻辑:公共邮箱域名不得开启自动匹配;approved 状态写入审核人和时间。
"""
customer = db.session.get(ShippingCustomer, customer_id)
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if customer.status == 'merged':
raise ConflictError('Merged customer cannot receive identifiers', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
identifier_type = clean_text(data.get('identifier_type')).lower()
raw_value = clean_text(data.get('raw_value') or data.get('identifier_value'))
normalized_value = normalize_identifier(identifier_type, raw_value)
status = clean_text(data.get('status') or 'pending').lower()
if status not in IDENTIFIER_STATUSES:
raise ValidationError('Invalid identifier status', code='SHIPPING.CUSTOMER_IDENTIFIER_STATUS_INVALID')
auto_match_allowed = _strict_bool(data.get('auto_match_allowed'), field='auto_match_allowed')
if identifier_type in {'domain', 'email'} and is_public_email_domain(normalized_value) and auto_match_allowed:
raise ValidationError(
'Public email domains cannot be used for automatic matching',
code='SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN',
)
if status != 'approved' and auto_match_allowed:
raise ValidationError(
'Only approved identifiers can enable automatic matching',
code='SHIPPING.CUSTOMER_IDENTIFIER_NOT_APPROVED',
)
record = ShippingCustomerIdentifier(
customer_id=customer.id,
identifier_type=identifier_type,
raw_value=raw_value,
normalized_value=normalized_value,
auto_match_allowed=auto_match_allowed,
status=status,
source=clean_text(data.get('source') or 'manual').lower(),
remark=clean_text(data.get('remark')) or None,
confirmed_by_id=actor_id if status == 'approved' else None,
confirmed_at=datetime.utcnow() if status == 'approved' else None,
)
db.session.add(record)
db.session.flush()
_record_lifecycle_event(
customer,
event_type='identifier_created',
actor_id=actor_id,
detail={'identifier': _identifier_snapshot(record)},
)
try:
db.session.commit()
except IntegrityError as exc:
db.session.rollback()
raise ConflictError(
'Customer identifier already exists',
code='SHIPPING.CUSTOMER_IDENTIFIER_EXISTS',
) from exc
return serialize_identifier(record)
def update_identifier(identifier_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""更新识别证据;先校验最终状态,再一次性修改 ORM,避免失败后残留脏状态。"""
record = db.session.get(ShippingCustomerIdentifier, identifier_id)
if record is None:
raise NotFoundError('Customer identifier not found', code='SHIPPING.CUSTOMER_IDENTIFIER_NOT_FOUND')
customer = db.session.get(ShippingCustomer, record.customer_id)
if customer is None or customer.status == 'merged':
raise ConflictError('Merged customer identifier cannot be edited', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
before = _identifier_snapshot(record)
next_status = record.status
if 'status' in data:
next_status = clean_text(data.get('status')).lower()
if next_status not in IDENTIFIER_STATUSES:
raise ValidationError('Invalid identifier status', code='SHIPPING.CUSTOMER_IDENTIFIER_STATUS_INVALID')
next_allowed = record.auto_match_allowed if next_status == 'approved' else False
if 'auto_match_allowed' in data:
next_allowed = _strict_bool(data.get('auto_match_allowed'), field='auto_match_allowed')
if record.identifier_type in {'domain', 'email'} and is_public_email_domain(record.normalized_value) and next_allowed:
raise ValidationError(
'Public email domains cannot be used for automatic matching',
code='SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN',
)
if next_status != 'approved' and next_allowed:
raise ValidationError(
'Only approved identifiers can enable automatic matching',
code='SHIPPING.CUSTOMER_IDENTIFIER_NOT_APPROVED',
)
next_remark = clean_text(data.get('remark')) or None if 'remark' in data else record.remark
after = {
**before,
'status': next_status,
'auto_match_allowed': bool(next_allowed),
'remark': next_remark,
}
changes = {key: {'before': before[key], 'after': after[key]} for key in before if before[key] != after[key]}
if changes:
requires_reason = 'status' in changes or 'auto_match_allowed' in changes
change_reason = _required_change_reason(data) if requires_reason else clean_text(data.get('reason')) or None
record.status = next_status
record.auto_match_allowed = next_allowed
if next_status == 'approved' and record.confirmed_at is None:
record.confirmed_by_id = actor_id
record.confirmed_at = datetime.utcnow()
record.remark = next_remark
_record_lifecycle_event(
customer,
event_type='identifier_updated',
actor_id=actor_id,
reason=change_reason,
detail={'identifier_id': record.id, 'changes': changes},
)
db.session.commit()
return serialize_identifier(record)
def create_external_ref(customer_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""新增来源系统客户编码;同一来源和编码只能绑定一个标准客户。"""
customer = db.session.get(ShippingCustomer, customer_id)
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
source_system = clean_text(data.get('source_system')).upper()
customer_code = clean_text(data.get('customer_code')).upper()
if not source_system or not customer_code:
raise ValidationError('Source system and customer code are required', code='SHIPPING.CUSTOMER_EXTERNAL_REF_INVALID')
record = ShippingCustomerExternalRef(
customer_id=customer.id, source_system=source_system, legacy_customer_key=customer_code,
)
db.session.add(record)
try:
db.session.commit()
except IntegrityError as exc:
db.session.rollback()
raise ConflictError('Customer external reference already exists', code='SHIPPING.CUSTOMER_EXTERNAL_REF_CONFLICT') from exc
return serialize_external_ref(record)
def create_site(customer_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""新增客户送货站点,站点编码在同一标准客户内唯一。"""
customer = db.session.get(ShippingCustomer, customer_id)
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
site_name = clean_text(data.get('site_name'))
site_code = clean_text(data.get('site_code')).upper()
if not site_name or not site_code:
raise ValidationError('Site name and code are required', code='SHIPPING.CUSTOMER_SITE_INVALID')
record = ShippingCustomerSite(
customer_id=customer.id, site_name=site_name, site_code=site_code,
address=clean_text(data.get('address')) or None, city=clean_text(data.get('city')) or None,
country=clean_text(data.get('country')) or None, status='active',
remark=clean_text(data.get('remark')) or None, created_by_id=actor_id, updated_by_id=actor_id,
)
db.session.add(record)
try:
db.session.commit()
except IntegrityError as exc:
db.session.rollback()
raise ConflictError('Customer site already exists', code='SHIPPING.CUSTOMER_SITE_CONFLICT') from exc
return serialize_site(record)
def create_site_identifier(site_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""为送货站点新增名称别名、地址或带来源系统的外部站点编码。"""
site = db.session.get(ShippingCustomerSite, site_id)
if site is None:
raise NotFoundError('Customer site not found', code='SHIPPING.CUSTOMER_SITE_NOT_FOUND')
identifier_type = clean_text(data.get('identifier_type')).lower()
if identifier_type not in {'name_alias', 'external_code', 'address'}:
raise ValidationError('Site identifier type is invalid', code='SHIPPING.CUSTOMER_SITE_IDENTIFIER_INVALID')
raw_value = clean_text(data.get('identifier_value'))
source_system = clean_text(data.get('source_system')).upper() if identifier_type == 'external_code' else ''
if not raw_value or (identifier_type == 'external_code' and not source_system):
raise ValidationError('Site identifier is incomplete', code='SHIPPING.CUSTOMER_SITE_IDENTIFIER_INVALID')
normalized = normalize_identifier('name_alias', raw_value) if identifier_type == 'name_alias' else raw_value.upper()
record = ShippingCustomerSiteIdentifier(
site_id=site.id, identifier_type=identifier_type, source_system=source_system,
raw_value=raw_value, normalized_value=normalized, status='approved',
remark=clean_text(data.get('remark')) or None,
)
db.session.add(record)
try:
db.session.commit()
except IntegrityError as exc:
db.session.rollback()
raise ConflictError('Site identifier already exists', code='SHIPPING.CUSTOMER_SITE_IDENTIFIER_CONFLICT') from exc
return serialize_site(site)
File diff suppressed because it is too large. Load diff
@@ -32,7 +32,6 @@ platform:
dify_required_providers:
- dify
- hybrid
agent_types:
generic:
label: 通用问答 / 知识库
@@ -54,8 +53,8 @@ agent_types:
conversation_mode_default: task_chat
runtime_provider_default: hybrid
models:
- ShippingBatch
- ShippingTask
- ShippingNotice
- ShippingOrderTask
- ShippingTaskEvent
required_fields: []
default_capabilities:
@@ -70,5 +70,9 @@ class AgentHandler:
ctx: ChatStreamContext,
event_data: dict[str, Any],
) -> Iterator[str]:
"""上游 message_end/workflow_finished 后追加的 SSE 行。"""
"""上游 error/message_end/workflow_finished 后执行领域收口并追加 SSE 行。"""
return iter(())
def should_recover_upstream_error(self, ctx: ChatStreamContext, event_data: dict[str, Any]) -> bool:
"""业务事实已持久化时,允许把上游 SSE error 收口为正常终态。"""
return False
@@ -1,9 +1,7 @@
"""
backend/app/services/agent_registry/handlers/shipping_notice.py
用途:货代发货通知 Hybrid Handler — 聊天流 UI State 与上下文准备。
依赖:shipping_notice.query_service、ui_state、agent_registry.handlers.registry。
逻辑:SSE relay 调用 build_ui_state_event;不替代 Dify 正文生成。
用途:货代发货通知 Hybrid Handler,负责普通聊天中的任务/批次 UI State。
依赖:shipping_notice.query_service/ui_state、agent_registry.handlers.registry。
逻辑:根据显式 task/batch 上下文构造并推送 UI State;订单抽取由后台 Run/Worker 独立执行。
"""
from __future__ import annotations
@@ -38,9 +36,17 @@ class ShippingNoticeHandler(AgentHandler):
"""
货代发货通知业务 Handler。
核心逻辑:按 adapter_hints / 请求 task_id、batch_no 构造 shipping_ui_state 事件供前端渲染步骤与按钮。
核心逻辑:按 adapter_hints / task_id / batch_no 构造 shipping_ui_state,供实时消息使用。
订单抽取状态卡由 Run API 和本地消息持久化恢复,不进入普通 Dify Chatflow 生命周期。
"""
@staticmethod
def _shipping_hints(ctx: ChatStreamContext) -> dict[str, Any]:
"""读取 shipping adapter_hints,非法或缺失时返回空字典。"""
hints = ctx.adapter_hints if isinstance(ctx.adapter_hints, dict) else {}
shipping_hints = hints.get('shipping_notice')
return shipping_hints if isinstance(shipping_hints, dict) else {}
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
"""
构造 shipping_ui_state SSE 事件。
@@ -49,12 +55,10 @@ class ShippingNoticeHandler(AgentHandler):
"""
if not _uses_shipping_ui_state_progress(ctx.agent):
return None
task_id = str(ctx.shipping_task_id or '').strip()
batch_no = str(ctx.shipping_batch_no or '').strip()
shipping_hints = self._shipping_hints(ctx)
if not task_id and not batch_no:
hints = ctx.adapter_hints if isinstance(ctx.adapter_hints, dict) else {}
shipping_hints = hints.get('shipping_notice') if isinstance(hints.get('shipping_notice'), dict) else {}
task_id = str(shipping_hints.get('task_id') or '').strip()
batch_no = str(shipping_hints.get('batch_no') or '').strip()
if not task_id and not batch_no:
@@ -66,27 +70,30 @@ class ShippingNoticeHandler(AgentHandler):
task = get_task_by_ref(task_id) if task_id else None
batch = get_batch_by_no(batch_no) if batch_no else None
if task is None and batch is not None:
focus_task_no = str(batch.current_focus_task_no or '').strip()
if focus_task_no:
candidate = get_task_by_ref(focus_task_no)
if candidate is not None and candidate.batch_id == batch.id:
task = candidate
session_id = str(getattr(ctx.session, 'session_id', '') or '')
if task is not None:
return {
'event': 'shipping_ui_state',
'conversation_id': session_id,
'task_no': task.task_no,
'batch_no': task.batch.batch_no if task.batch is not None else None,
'batch_no': None,
'ui_state': build_task_ui_state(task),
}
if batch is not None:
batch_ui_state = build_batch_ui_state(batch)
focus_task = batch_ui_state.get('focus_task') if isinstance(batch_ui_state.get('focus_task'), dict) else {}
focus_ui_state = (
batch_ui_state.get('focus_task_ui_state')
if isinstance(batch_ui_state.get('focus_task_ui_state'), dict)
else None
)
return {
'event': 'shipping_ui_state',
'conversation_id': session_id,
'batch_no': batch.batch_no,
'batch_ui_state': build_batch_ui_state(batch),
'task_no': focus_task.get('task_no'),
'batch_ui_state': batch_ui_state,
**({'ui_state': focus_ui_state} if focus_ui_state is not None else {}),
}
except Exception:
if current_app:
@@ -99,6 +106,9 @@ class ShippingNoticeHandler(AgentHandler):
return None
def iter_ui_state_dedupe_key(self, event: dict[str, Any]) -> str | None:
"""仅为 shipping_ui_state 构造去重键,其他领域事件保持独立生命周期。"""
if str(event.get('event') or '') != 'shipping_ui_state':
return None
ui_state = event.get('ui_state') if isinstance(event.get('ui_state'), dict) else {}
batch_ui_state = event.get('batch_ui_state') if isinstance(event.get('batch_ui_state'), dict) else {}
focus_state = (
@@ -114,10 +124,13 @@ class ShippingNoticeHandler(AgentHandler):
'updated_at': ui_state.get('updated_at') or batch_ui_state.get('updated_at'),
}, ensure_ascii=False, sort_keys=True)
def _format_sse(self, event: dict[str, Any]) -> str:
@staticmethod
def _format_sse(event: dict[str, Any]) -> str:
"""把领域事件编码为单条 SSE data frame。"""
return f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
def iter_preface_sse_lines(self, ctx: ChatStreamContext) -> Iterator[str]:
"""上游调用前补充已有任务 UI State。"""
event = self.build_ui_state_event(ctx)
if event:
yield self._format_sse(event)
@@ -127,8 +140,9 @@ class ShippingNoticeHandler(AgentHandler):
ctx: ChatStreamContext,
event_data: dict[str, Any],
) -> Iterator[str]:
"""上游终态后刷新显式任务或批次的 UI State。"""
event_name = str(event_data.get('event') or '').strip()
if event_name not in {'message_end', 'workflow_finished'}:
if event_name not in {'error', 'message_end', 'workflow_finished'}:
return iter(())
event = self.build_ui_state_event(ctx)
if event:
@@ -31,7 +31,11 @@ ALLOWED_PARSE_PATHS: frozenset[str] = frozenset(
"refs.batch_no",
"refs.task_no",
"refs.run_purpose",
"refs.capability",
"refs.intake_nos",
"refs.file_name",
"refs.temporary_inventory_asset_no",
"refs.temporary_inventory_session_no",
"refs.schedule_task_id",
"refs.hxops_turn_id",
"domain.type",
@@ -1,9 +1,9 @@
"""
backend/app/services/chat/executors/__init__.py
用途:RUNTIME_PROVIDER_REGISTRY 与聊天 Executor 解析入口。
用途:RUNTIME_PROVIDER_REGISTRY、聊天 Executor 解析及同步 Handler 前置准备入口。
依赖:dify_chat、hybrid、builtin executors;agent_registry.resolver。
逻辑:chat.py completions 默认 Dify 路径调用 stream_chat_via_executor。
逻辑:chat.py 先调用 stream_chat_via_executor 同步执行 prepare_stream,再下发 preface 并惰性迭代上游流。
"""
from __future__ import annotations
@@ -12,7 +12,11 @@ from typing import Iterator
from app.core.errors import ValidationError
from app.services.agent_registry.handlers.base import ChatStreamContext
from app.services.agent_registry.resolver import resolve_runtime_provider
from app.services.agent_registry.resolver import (
resolve_handler,
resolve_handler_for_agent_code,
resolve_runtime_provider,
)
from app.services.chat.executors.base import ChatExecutor
from app.services.chat.executors.builtin import BuiltinChatExecutor
from app.services.chat.executors.dify_chat import DifyChatExecutor
@@ -61,10 +65,19 @@ def stream_chat_via_executor(ctx: ChatStreamContext) -> Iterator[str]:
Args:
ctx: ChatStreamContext。
核心逻辑:必须在返回惰性生成器前同步调用 Handler.prepare_stream,确保 chat.py 随后的 preface
能读取到已登记的领域状态;Hybrid/Builtin 强制要求 Handler,Dify Chatflow 允许无 Handler。
Returns:
上游 SSE 行迭代器。
已完成 Handler 前置准备的上游 SSE 行迭代器。
"""
executor = resolve_chat_executor(ctx.agent)
if executor.provider_key in {'hybrid', 'builtin'}:
handler = resolve_handler(ctx.agent)
else:
handler = resolve_handler_for_agent_code(ctx.agent)
if handler is not None:
ctx = handler.prepare_stream(ctx)
return executor.stream(ctx)
@@ -3,7 +3,7 @@ backend/app/services/chat/executors/builtin.py
用途:runtime_provider=builtin 的聊天 Executor。
依赖:agent_registry.resolver.resolve_handler。
逻辑:必须存在 Handler;由 Handler 驱动内置流(v1 未实现完整 builtin 流时显式报错)。
逻辑:stream_chat_via_executor 已校验并准备 Handler;v1 未实现完整 builtin 流时显式报错。
"""
from __future__ import annotations
@@ -21,8 +21,8 @@ class BuiltinChatExecutor(ChatExecutor):
provider_key = 'builtin'
def stream(self, ctx: ChatStreamContext) -> Iterator[str]:
"""返回尚未实现的明确错误,并保留 Handler key 便于诊断。"""
handler = resolve_handler(ctx.agent)
ctx = handler.prepare_stream(ctx)
raise AppError(
code='AGENT.BUILTIN_NOT_IMPLEMENTED',
message='runtime_provider=builtin 的聊天流尚未实现,请使用 hybrid 或 dify',
@@ -2,15 +2,14 @@
backend/app/services/chat/executors/dify_chat.py
用途:runtime_provider=dify 的 Chatflow 聊天 Executor。
依赖:DifyService.stream_chat、executors.base、agent_registry.resolver。
逻辑:Handler.prepare_stream → build_chat_dify_inputs → DifyService.stream_chat。
依赖:DifyService.stream_chat、executors.base。
逻辑:stream_chat_via_executor 已完成 Handler 前置准备;本文件构造 inputs 并惰性转发 Dify SSE。
"""
from __future__ import annotations
from typing import Iterator
from app.services.agent_registry.resolver import resolve_handler_for_agent_code
from app.services.chat.executors.base import (
ChatExecutor,
ChatStreamContext,
@@ -25,9 +24,7 @@ class DifyChatExecutor(ChatExecutor):
provider_key = 'dify'
def stream(self, ctx: ChatStreamContext) -> Iterator[str]:
handler = resolve_handler_for_agent_code(ctx.agent)
if handler is not None:
ctx = handler.prepare_stream(ctx)
"""使用已经完成 Handler 前置准备的上下文调用 Dify Chatflow。"""
dify_inputs = build_dify_inputs_for_context(ctx)
yield from DifyService.stream_chat(
ctx.query,
@@ -1,16 +1,15 @@
"""
backend/app/services/chat/executors/hybrid.py
用途:runtime_provider=hybrid 的聊天 Executor(Handler 前置 + Dify 流)。
依赖:resolve_handler、DifyChatExecutor。
逻辑:resolve_handler 校验 → handler.prepare_stream → DifyChatExecutor.stream。
用途:runtime_provider=hybrid 的聊天 Executor(强制 Handler + Dify 流)。
依赖:DifyChatExecutor;Handler 校验与前置准备由 stream_chat_via_executor 统一完成。
逻辑:接收已准备上下文并委托 DifyChatExecutor.stream。
"""
from __future__ import annotations
from typing import Iterator
from app.services.agent_registry.resolver import resolve_handler
from app.services.chat.executors.base import ChatExecutor, ChatStreamContext
from app.services.chat.executors.dify_chat import DifyChatExecutor
@@ -24,6 +23,5 @@ class HybridChatExecutor(ChatExecutor):
self._dify = DifyChatExecutor()
def stream(self, ctx: ChatStreamContext) -> Iterator[str]:
handler = resolve_handler(ctx.agent)
ctx = handler.prepare_stream(ctx)
"""把已完成 Handler 准备的 Hybrid 上下文委托给 Dify Chatflow。"""
yield from self._dify.stream(ctx)
+60 -2
View File
@@ -1,9 +1,9 @@
"""
backend/app/services/chat/log_service.py
用途:Chat Turn 与对话历史的 ChatLog 统一写入。
用途:Chat Turn 与对话历史的 ChatLog 统一写入及结构化 payload 合并。
依赖:models.ChatLog、SQLAlchemy。
逻辑:turn_runtime 在 run.completed 时调用 save_turn_chat_log;api/chat 历史路由可逐步迁入。
逻辑:turn_runtime 在 run.completed 时调用 save_turn_chat_log;领域 Handler 可在上游终态后安全合并回放 payload。
"""
from __future__ import annotations
@@ -72,3 +72,61 @@ def save_turn_chat_log(
current_app.logger.exception("[chat-turn] failed to save chat log: %s", exc)
db.session.rollback()
return None
def merge_chat_log_payload(
*,
chat_log_id: int,
user_id: int,
agent_id: int,
session_id: str,
payload_patch: dict[str, Any],
) -> bool:
"""
在归属校验通过后幂等合并 ChatLog 结构化 payload。
核心逻辑:锁定指定消息并同时校验用户、Agent、本地会话,随后以顶层键覆盖方式合并领域终态;
该函数不修改正文,适合 SSE terminal 之后补写可回放的状态卡片数据。
Args:
chat_log_id: 已持久化的 ChatLog 主键,必须为正整数。
user_id: 当前请求用户主键。
agent_id: 当前请求 Agent 主键。
session_id: 当前 HXOPS 本地会话号。
payload_patch: 要合并的顶层结构化字段,不得为空。
Returns:
找到且成功写入时返回 True;身份不匹配、参数为空或写入失败时返回 False。
"""
if chat_log_id <= 0 or user_id <= 0 or agent_id <= 0 or not str(session_id or '').strip() or not payload_patch:
return False
try:
chat_log = (
db.session.query(ChatLog)
.filter(
ChatLog.id == int(chat_log_id),
ChatLog.user_id == int(user_id),
ChatLog.agent_id == int(agent_id),
ChatLog.session_id == str(session_id).strip(),
)
.with_for_update()
.one_or_none()
)
if chat_log is None:
db.session.rollback()
return False
chat_log.payload = {
**(chat_log.payload if isinstance(chat_log.payload, dict) else {}),
**payload_patch,
}
db.session.commit()
return True
except Exception as exc:
if current_app:
current_app.logger.exception(
"[chat-log] failed to merge payload chat_log_id=%s: %s",
chat_log_id,
exc,
)
db.session.rollback()
return False
+7 -1
View File
@@ -42,7 +42,7 @@ def iter_handler_terminal_sse(
*,
emitted_keys: set[str],
) -> Iterator[str]:
"""上游终态事件后追加 Handler SSE(如 shipping_ui_state 刷新)。"""
"""上游终态/error 事件后追加 Handler SSE(如订单抽取收口与 shipping_ui_state 刷新)。"""
handler = resolve_handler_for_agent_code(ctx.agent)
if handler is None:
return
@@ -58,6 +58,12 @@ def iter_handler_terminal_sse(
emitted_keys.add(dedupe_key)
def should_recover_upstream_error(ctx: ChatStreamContext, event_data: dict) -> bool:
"""委托领域 Handler 判断上游流错误是否可由已持久化业务事实恢复。"""
handler = resolve_handler_for_agent_code(ctx.agent)
return bool(handler and handler.should_recover_upstream_error(ctx, event_data))
def maybe_emit_handler_ui_state(ctx: ChatStreamContext, *, emitted_keys: set[str]) -> str | None:
"""
构造并格式化单次 UI State SSE;已 emit 的 dedupe 键则跳过。
+74 -171
View File
@@ -135,36 +135,21 @@ class DifyService:
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。"
@staticmethod
def _friendly_upstream_error_message(status_code: int, raw_body: str, agent_name: str | None = None) -> str:
"""将 Dify HTTP 错误转换为可执行的用户提示。
AI 触发时机:Dify 在建立 SSE 流前直接返回非 2xx 响应时调用。
核心逻辑:优先识别知识检索常用的 rerank 插件授权失败,避免把上游 403 误报为网络超时;
其余状态码则给出不泄露密钥和内部地址的通用排查方向。
def _friendly_stream_request_failure_message(error: requests.exceptions.RequestException) -> str:
"""
将对话连接异常转换成可安全展示的业务提示。
Args:
status_code: Dify HTTP 响应状态码。
raw_body: 已截断的 Dify 错误正文,仅用于分类,不向用户原样透传。
agent_name: 当前智能体名称。
error: requests 抛出的上游连接异常;原始内容只用于服务端日志。
Returns:
面向最终用户的安全错误提示。
不包含服务名称、地址、密钥或异常正文的用户提示。
"""
text = str(raw_body or "")
lower = text.lower()
resolved_agent_name = str(agent_name or "").strip() or "当前智能体"
if "rerank" in lower and ("403" in lower or "forbidden" in lower):
return (
f"{resolved_agent_name}的知识检索重排服务授权失败。"
"请联系管理员在 Dify 中更新 Rerank 模型供应商的 API Key 后重新发布应用。"
)
if status_code in (401, 403):
return f"{resolved_agent_name}暂时无法访问 Dify 服务,请联系管理员检查该应用的 API Key 与服务授权。"
if status_code == 404:
return f"{resolved_agent_name}的 Dify 应用地址或应用类型配置错误,请联系管理员检查 API Base URL。"
if status_code in (429, 502, 503, 504):
return f"{resolved_agent_name}的 Dify 服务暂时不可用或繁忙,请稍后重试。"
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试;如持续失败请联系管理员检查 Dify 工作流。"
if isinstance(error, requests.exceptions.ReadTimeout):
return "回答生成时间较长,本次请求未能完成,请稍后重试。"
if isinstance(error, requests.exceptions.ConnectTimeout):
return "当前服务连接超时,请稍后重试。"
return "当前服务暂时无法完成回答,请稍后重试。"
@staticmethod
def _merge_stream_answer_text(
@@ -551,6 +536,25 @@ class DifyService:
out["_workflow_error_type"] = error_type
return out
@staticmethod
def _observe_workflow_event(event_observer, event_type: str, event_data: dict[str, Any], state: dict[str, Any]) -> None:
"""向可选观察器发送脱敏 Workflow 生命周期字段;观察器错误不得中断Provider调用。"""
if event_observer is None:
return
node_data = event_data.get('node_data') if isinstance(event_data.get('node_data'), dict) else {}
try:
event_observer({
'event_type': str(event_type),
'workflow_run_id': event_data.get('workflow_run_id') or state.get('workflow_run_id'),
'node_execution_id': event_data.get('node_execution_id') or event_data.get('node_id'),
'node_type': event_data.get('node_type') or node_data.get('type'),
'node_title': event_data.get('title') or node_data.get('title'),
'event_status': event_data.get('status'),
})
except Exception:
if current_app:
current_app.logger.exception('[workflow-streaming] event observer failed')
@staticmethod
def _consume_workflow_stream(
*,
@@ -559,6 +563,7 @@ class DifyService:
payload: dict[str, Any],
timeout: tuple[int, int],
state: dict[str, Any],
event_observer=None,
) -> dict[str, Any]:
"""
执行一次 Workflow streaming POST 并消费 SSE 直至 workflow_finished。
@@ -590,6 +595,8 @@ class DifyService:
continue
event_type = evt.get("event", "")
event_data = evt.get('data') if isinstance(evt.get('data'), dict) else {}
DifyService._observe_workflow_event(event_observer, str(event_type), event_data, state)
if event_type == "workflow_started":
run_id = (evt.get("data") or {}).get("workflow_run_id")
@@ -628,6 +635,7 @@ class DifyService:
inputs: dict[str, Any] | None = None,
user: str = "system",
timeout: tuple[int, int] = (5, 300),
event_observer=None,
) -> dict[str, Any]:
"""
调用 Dify Workflow(streaming),并在断连/超时时优先 poll 补偿结果。
@@ -671,6 +679,7 @@ class DifyService:
payload=payload,
timeout=timeout,
state=stream_state,
event_observer=event_observer,
)
workflow_run_id = stream_state.get("workflow_run_id")
if workflow_run_id:
@@ -679,6 +688,9 @@ class DifyService:
# [STEP] 连接正常结束但未收到 workflow_finished 时,用 poll 补偿最终结果
if not result and workflow_run_id:
poll_used = True
DifyService._observe_workflow_event(
event_observer, 'poll_started', {'workflow_run_id': workflow_run_id}, stream_state,
)
if current_app:
current_app.logger.warning(
"[workflow-streaming] stream closed without finished event, polling run_id=%s",
@@ -689,6 +701,10 @@ class DifyService:
workflow_run_id=workflow_run_id,
max_wait=max_wait,
)
DifyService._observe_workflow_event(
event_observer, 'recovered' if result else 'stream_interrupted',
{'workflow_run_id': workflow_run_id, 'status': result.get('status') if result else 'timeout'}, stream_state,
)
poll_error_type = None if result else "poll_timeout"
return DifyService._attach_workflow_reliability_meta(
result,
@@ -745,6 +761,9 @@ class DifyService:
if workflow_run_id:
poll_used = True
DifyService._observe_workflow_event(
event_observer, 'stream_interrupted', {'workflow_run_id': workflow_run_id}, stream_state,
)
if current_app:
current_app.logger.warning(
"[workflow-streaming] polling after disconnect run_id=%s error_type=%s",
@@ -756,6 +775,10 @@ class DifyService:
workflow_run_id=workflow_run_id,
max_wait=max_wait,
)
DifyService._observe_workflow_event(
event_observer, 'recovered' if result else 'stream_interrupted',
{'workflow_run_id': workflow_run_id, 'status': result.get('status') if result else 'timeout'}, stream_state,
)
poll_error_type = None if result else "poll_timeout"
return DifyService._attach_workflow_reliability_meta(
result,
@@ -767,6 +790,9 @@ class DifyService:
if retryable and attempt < max_attempts - 1:
retry_count += 1
DifyService._observe_workflow_event(
event_observer, 'retry_started', {'workflow_run_id': workflow_run_id}, stream_state,
)
if current_app:
current_app.logger.info(
"[workflow-streaming] retrying attempt=%s error_type=%s",
@@ -894,7 +920,7 @@ class DifyService:
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
url = DifyService._build_chat_messages_url(base_url)
normalized_conversation_id = DifyService._normalize_dify_conversation_id(conversation_id)
visible_query = str(display_query or query or '').strip()
visible_query = str(query if display_query is None else display_query).strip()
headers = {
'Authorization': f'Bearer {agent.dify_api_key}',
@@ -1060,23 +1086,6 @@ class DifyService:
if retryable and attempt < max_retries:
time.sleep(attempt * 2)
continue
if not response.ok:
message = DifyService._friendly_upstream_error_message(
response.status_code,
response.text[:2000],
getattr(agent, 'name', None),
)
persist_stream_chat(
{
'event': 'error',
'conversation_id': normalized_conversation_id,
'answer': f"[Error: {message}]",
'metadata': {},
},
'error',
)
yield f"data: {json.dumps({'event': 'error', 'message': message}, ensure_ascii=False)}\n\n"
return
response.raise_for_status()
yield f"data: {json.dumps({'event': 'upstream_connected', 'message': 'Dify 已连接'}, ensure_ascii=False)}\n\n"
@@ -1177,141 +1186,35 @@ class DifyService:
if isinstance(e, requests.exceptions.ReadTimeout) and has_sent_answer:
if current_app:
current_app.logger.warning(
"[chat-stream] read timeout after answer request_id=%s attempt=%s; finish stream silently",
"[chat-stream] read timeout after answer request_id=%s attempt=%s; emit synthetic terminal",
request_id,
attempt,
)
persist_stream_chat(
{
'event': 'message_end',
'conversation_id': normalized_conversation_id,
'answer': ''.join(full_answer).strip(),
'metadata': {},
},
'message_end',
)
# [STEP 3] 已有正文时用合成 message_end 正常收口;persist 会把 chat_log_id 回写到同一事件,
# 领域 Handler 仍能在网络超时后完成状态持久化,而前端不会把本轮误判为永久处理中。
timeout_end_event = {
'event': 'message_end',
'conversation_id': normalized_conversation_id,
'answer': ''.join(full_answer).strip(),
'metadata': {},
}
persist_stream_chat(timeout_end_event, 'message_end')
yield f"data: {json.dumps(timeout_end_event, ensure_ascii=False)}\n\n"
break
if not is_timeout and attempt < max_retries:
time.sleep(attempt * 2)
continue
if isinstance(e, requests.exceptions.ReadTimeout):
message = (
f"Dify 在 {int(getattr(Config, 'DIFY_CHAT_READ_TIMEOUT_SECONDS', 30) or 30)} 秒内没有返回响应。"
"请检查 Dify 应用地址/API Key、Chatflow 是否发布,以及 Dify 服务是否能正常执行。"
)
elif isinstance(e, requests.exceptions.ConnectTimeout):
message = "连接 Dify 超时,请检查 Dify API Base URL 和网络连通性。"
else:
message = str(e)
persist_stream_chat(
{
'event': 'error',
'conversation_id': normalized_conversation_id,
'answer': f"[Error: {message}]",
'metadata': {},
},
'error',
)
error_msg = json.dumps({'event': 'error', 'message': message})
yield f"data: {error_msg}\n\n"
@staticmethod
def run_chatflow_once(
*,
agent,
query: str,
inputs: dict[str, Any] | None = None,
user: str = "system",
timeout: tuple[int, int] = (5, 120),
) -> dict[str, Any]:
"""
以单次、无持久会话方式调用 Dify Chatflow 并收集最终回答。
核心逻辑:复用 Chatflow 的 `/v1/chat-messages` 和 SSE 协议,但不写 chat_logs、
不传 conversation_id;适用于合同审核等后台结构化任务,返回 message_end 的 answer。
Args:
agent: 含 Dify API Key 的 Chatflow Agent。
query: 传给 Chatflow 的一次性任务提示。
inputs: Dify Start 节点声明的变量。
user: Dify 用户标识,不应使用真实业务用户 ID。
timeout: `(connect_seconds, read_seconds)`。
Returns:
包含 `answer`、`conversation_id`、`message_id` 的字典。
Raises:
RuntimeError: Dify 返回错误事件或未产出最终回答。
requests.RequestException: HTTP 连接、超时或状态码错误。
"""
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
url = DifyService._build_chat_messages_url(base_url)
headers = {
"Authorization": f"Bearer {agent.dify_api_key}",
"Content-Type": "application/json",
}
payload = {
"inputs": DifyService._stringify_inputs(inputs),
"query": str(query or "").strip(),
"response_mode": "streaming",
"user": str(user or "system"),
}
if current_app:
current_app.logger.info(
"[chatflow-once] start agent_id=%s url=%s query_len=%s",
getattr(agent, "id", None),
url,
len(payload["query"]),
)
answer_parts: list[str] = []
final_data: dict[str, Any] = {}
with requests.post(url, headers=headers, json=payload, stream=True, timeout=timeout) as response:
if not response.ok and current_app:
current_app.logger.error(
"[chatflow-once] bad response status=%s url=%s body=%s",
response.status_code,
url,
response.text[:2000],
)
response.raise_for_status()
for line in response.iter_lines():
if not line:
continue
decoded = line.decode("utf-8", errors="replace")
if not decoded.startswith("data: "):
continue
try:
data = json.loads(decoded[6:])
except json.JSONDecodeError:
continue
event = str(data.get("event") or "")
if event == "error":
raise RuntimeError(str(data.get("message") or data))
if event == "message" and data.get("answer"):
answer_parts.append(str(data["answer"]))
if event in {"message_end", "workflow_finished"}:
final_data = data
workflow_data = data.get("data") if isinstance(data.get("data"), dict) else {}
if event == "workflow_finished" and workflow_data.get("status") == "failed":
# Chatflow also emits workflow events; expose the canvas-node error to the review task.
error_text = str(workflow_data.get("error") or "Dify Chatflow workflow failed")
raise RuntimeError(error_text)
final_answer = str(data.get("answer") or "").strip()
if final_answer:
answer_parts = [final_answer]
if event == "message_end":
break
answer = "".join(answer_parts).strip()
if not answer:
raise RuntimeError("Dify Chatflow returned no final answer")
return {
"answer": answer,
"conversation_id": final_data.get("conversation_id"),
"message_id": final_data.get("message_id") or final_data.get("id"),
"event": final_data.get("event") or "message_end",
}
message = DifyService._friendly_stream_request_failure_message(e)
# [STEP 4] 错误事件与持久化对象必须是同一个 dict,确保 chat_log_id 能继续传给 relay/领域 Handler。
error_event = {
'event': 'error',
'conversation_id': normalized_conversation_id,
'answer': message,
'message': message,
'metadata': {},
}
persist_stream_chat(error_event, 'error')
yield f"data: {json.dumps(error_event, ensure_ascii=False)}\n\n"
@staticmethod
def _log_chat(
+9 -9
View File
@@ -2,7 +2,7 @@
backend/app/services/file_assets/cleanup.py
用途:过期未引用 FileAsset 与关联 intake 的清理编排。
依赖:file_assets.storage、models.FileAsset/ShippingNoticeIntake。
依赖:file_assets.storage、models.FileAsset/ShippingOrderIntake。
逻辑:由排程或 file_asset_cleanup Job 调用;先标记 expired → 删 MinIO → 成功后 mark deleted;
MinIO 删除失败不伪装成功,保留记录供下次重试。
"""
@@ -15,7 +15,7 @@ from datetime import datetime
from sqlalchemy import or_
from app import db
from app.models import FileAsset, ShippingNoticeIntake
from app.models import FileAsset, ShippingOrderIntake
from app.services.file_assets.storage import file_asset_storage
_LOGGER = logging.getLogger(__name__)
@@ -49,10 +49,10 @@ def cleanup_expired_temporary_assets(*, limit: int = 100) -> dict[str, int]:
stats = {'scanned': len(assets), 'expired': 0, 'deleted': 0, 'errors': 0}
for asset in assets:
consumed = (
db.session.query(ShippingNoticeIntake.id)
db.session.query(ShippingOrderIntake.id)
.filter(
ShippingNoticeIntake.asset_id == asset.id,
ShippingNoticeIntake.parse_status == 'consumed',
ShippingOrderIntake.asset_id == asset.id,
ShippingOrderIntake.parse_status == 'consumed',
)
.first()
)
@@ -61,11 +61,11 @@ def cleanup_expired_temporary_assets(*, limit: int = 100) -> dict[str, int]:
stats['expired'] += 1
asset.lifecycle_status = 'expired'
(
db.session.query(ShippingNoticeIntake)
db.session.query(ShippingOrderIntake)
.filter(
ShippingNoticeIntake.asset_id == asset.id,
ShippingNoticeIntake.consumed_at.is_(None),
ShippingNoticeIntake.parse_status.notin_(('consumed', 'cancelled')),
ShippingOrderIntake.asset_id == asset.id,
ShippingOrderIntake.consumed_at.is_(None),
ShippingOrderIntake.parse_status.notin_(('consumed', 'cancelled')),
)
.update({'parse_status': 'expired', 'updated_at': now}, synchronize_session=False)
)
Loaded 100 of 1482 files, more files were not shown because too many files have changed in this diff. Show more