feat(shipping-notice): 添加识别定义和规则集管理功能,支持客户和站点的可配置识别规则
This commit is contained in:
1 parent
88408490d7
commit
34d489a2d1
167 files changed
+10365
-7978
No files matched your search
@@ -20,6 +20,7 @@ import app.api.admin.users # noqa: F401
|
||||
import app.api.admin.wecom # noqa: F401
|
||||
import app.api.admin.announcements # noqa: F401
|
||||
import app.api.admin.shipping_customers # noqa: F401
|
||||
import app.api.admin.shipping_identity_rules # noqa: F401
|
||||
import app.api.admin.shipping_inventory # noqa: F401
|
||||
import app.api.admin.shipping_order_schema # noqa: F401
|
||||
|
||||
|
||||
@@ -162,23 +162,21 @@ def deactivate_shipping_customer(customer_id: int):
|
||||
@admin_bp.route('/shipping-customers/<int:customer_id>/identifiers', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_customer_identifier(customer_id: int):
|
||||
"""为客户新增名称、邮箱、域名或模板指纹识别证据。"""
|
||||
return jsonify(shipping_customer_service.create_identifier(
|
||||
customer_id,
|
||||
request.get_json(silent=True) or {},
|
||||
actor_id=_actor_id(),
|
||||
)), 201
|
||||
"""拒绝旧固定类型证据写入口;新增证据必须选择已发布识别定义。"""
|
||||
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):
|
||||
"""审核、停用或调整客户识别证据的自动匹配授权。"""
|
||||
return jsonify(shipping_customer_service.update_identifier(
|
||||
identifier_id,
|
||||
request.get_json(silent=True) or {},
|
||||
actor_id=_actor_id(),
|
||||
))
|
||||
"""拒绝旧固定类型证据写入口;历史记录仅供审计回看。"""
|
||||
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'])
|
||||
|
||||
@@ -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(),
|
||||
))
|
||||
@@ -79,6 +79,15 @@ 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):
|
||||
@@ -156,6 +165,39 @@ def update_shipping_inventory_source(source_id: int):
|
||||
))
|
||||
|
||||
|
||||
@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):
|
||||
@@ -187,6 +229,45 @@ def start_shipping_inventory_configuration_test(source_id: int):
|
||||
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):
|
||||
@@ -249,7 +330,7 @@ def list_shipping_inventory_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']
|
||||
@@ -259,10 +340,8 @@ def list_shipping_inventory_routing_fields():
|
||||
raise
|
||||
order_fields = []
|
||||
published = False
|
||||
from app.services.shipping_notice.routing_facts import ALLOWED_SYSTEM_FACT_KEYS
|
||||
return _ok({
|
||||
'order_fields': order_fields,
|
||||
'system_facts': sorted(ALLOWED_SYSTEM_FACT_KEYS),
|
||||
'order_schema_published': published,
|
||||
})
|
||||
|
||||
@@ -313,8 +392,6 @@ def get_shipping_inventory_configuration_catalog():
|
||||
ALLOWED_SOURCE_KINDS,
|
||||
ALLOWED_SYSTEM_FACTS,
|
||||
)
|
||||
from app.services.shipping_notice.routing_facts import ALLOWED_SYSTEM_FACT_KEYS
|
||||
|
||||
try:
|
||||
contract = order_schema_service.get_published_contract()
|
||||
order_fields = contract['fields']
|
||||
@@ -327,7 +404,6 @@ def get_shipping_inventory_configuration_catalog():
|
||||
return _ok({
|
||||
'order_fields': order_fields,
|
||||
'order_schema_published': published,
|
||||
'routing_system_facts': sorted(ALLOWED_SYSTEM_FACT_KEYS),
|
||||
'inventory_fields': inventory_field_catalog.list_fields(),
|
||||
'template_system_facts': sorted(ALLOWED_SYSTEM_FACTS),
|
||||
'template_source_kinds': sorted(ALLOWED_SOURCE_KINDS),
|
||||
|
||||
+16
-1
@@ -207,7 +207,7 @@ def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str:
|
||||
|
||||
task_match = re.search(r'(SN-\d{8}-[A-Z0-9]+)', value, re.I)
|
||||
task_no = task_match.group(1).upper() if task_match else ''
|
||||
if 'create_task' in value or 'get_task_status' in value or 'parse_notice' in value:
|
||||
if 'create_task' in value or 'get_task_status' in value or 'submit_order_extraction' in value:
|
||||
return f'继续处理当前发货任务 {task_no}'.strip()
|
||||
return value
|
||||
|
||||
@@ -1615,6 +1615,7 @@ def chat_completions():
|
||||
from app.services.chat.stream_relay import (
|
||||
iter_handler_preface_sse,
|
||||
iter_handler_terminal_sse,
|
||||
should_recover_upstream_error,
|
||||
)
|
||||
|
||||
for preface_line in iter_handler_preface_sse(relay_stream_ctx, emitted_keys=emitted_handler_state_keys):
|
||||
@@ -1638,6 +1639,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 == 'error' and should_recover_upstream_error(relay_stream_ctx, event_data):
|
||||
current_app.logger.warning(
|
||||
'[chat-api] recover upstream error from persisted shipping extraction request_id=%s session_id=%s',
|
||||
request_id,
|
||||
local_session_id,
|
||||
)
|
||||
event_data = {
|
||||
**event_data,
|
||||
'event': 'message_end',
|
||||
'answer': '',
|
||||
'replace_answer': False,
|
||||
'recovered_upstream_error': True,
|
||||
}
|
||||
event_name = 'message_end'
|
||||
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)
|
||||
|
||||
@@ -211,14 +211,6 @@ def tool_create_batch():
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已创建批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
|
||||
|
||||
@shipping_notice_bp.route('/tools/parse_notice', methods=['POST'])
|
||||
def tool_parse_notice():
|
||||
"""
|
||||
解析发货通知正文。
|
||||
【AI 触发时机】:当用户上传、粘贴或修正发货通知内容后,需要把文本转成任务单头和订单行时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.parse_notice(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST'])
|
||||
def tool_update_notice_fields():
|
||||
"""
|
||||
@@ -401,6 +393,22 @@ def rpa_inventory_configuration_test_ready():
|
||||
|
||||
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):
|
||||
"""
|
||||
|
||||
@@ -30,14 +30,21 @@ from app.services.shipping_notice.query_service import (
|
||||
get_focus_task_for_batch,
|
||||
get_task_for_user,
|
||||
list_batches_for_user,
|
||||
list_tasks_page_for_user,
|
||||
list_tasks_for_batch,
|
||||
list_tasks_for_user,
|
||||
resolve_task_export_download,
|
||||
serialize_batch_summary,
|
||||
serialize_task_detail,
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.task_disposition_service import (
|
||||
archive_task,
|
||||
load_task_for_disposition,
|
||||
move_task_to_recycle_bin,
|
||||
purge_task_permanently,
|
||||
restore_task_from_recycle_bin,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
|
||||
from app.services.shipping_notice.customer_identity_gate import (
|
||||
confirm_task_customer,
|
||||
@@ -69,12 +76,130 @@ def _ok(payload: dict):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
|
||||
def workspace_shipping_tasks():
|
||||
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
|
||||
"""分页列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
|
||||
user = _require_user()
|
||||
batch_no = str(request.args.get('batch_no') or '').strip() or None
|
||||
process_status = str(request.args.get('process_status') or '').strip() or None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return jsonify(list_tasks_for_user(user.id, batch_no=batch_no, process_status=process_status, limit=limit))
|
||||
lifecycle_status = str(request.args.get('lifecycle_status') or '').strip() or None
|
||||
try:
|
||||
page = int(request.args.get('page') or 1)
|
||||
page_size = int(request.args.get('page_size') or 20)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('page and page_size must be integers') from exc
|
||||
if page < 1 or not 1 <= page_size <= 100:
|
||||
raise ValidationError('page must be positive and page_size must be between 1 and 100')
|
||||
return jsonify(list_tasks_page_for_user(
|
||||
user.id,
|
||||
batch_no=batch_no,
|
||||
process_status=process_status,
|
||||
lifecycle_status=lifecycle_status,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
))
|
||||
|
||||
|
||||
def _batch_task_nos(data: dict) -> list[str]:
|
||||
"""校验批量任务号,统一限制 100 条并去重,避免前端循环绕过服务端门禁。"""
|
||||
raw_task_nos = data.get('task_nos')
|
||||
if not isinstance(raw_task_nos, list) or not raw_task_nos:
|
||||
raise ValidationError('task_nos must be a non-empty list', code='SHIPPING.TASK_SELECTION_INVALID')
|
||||
normalized = list(dict.fromkeys(str(value or '').strip().upper() for value in raw_task_nos if str(value or '').strip()))
|
||||
if not normalized or len(normalized) > 100:
|
||||
raise ValidationError('task_nos must contain 1 to 100 task numbers', code='SHIPPING.TASK_SELECTION_INVALID')
|
||||
return normalized
|
||||
|
||||
|
||||
def _can_dispose_task(user, task: ShippingTask) -> bool:
|
||||
"""管理员可跨用户处置;普通用户仅可处置自己名下或未归属任务。"""
|
||||
return str(getattr(user, 'role', '')).lower() == 'admin' or task.user_id in {None, user.id}
|
||||
|
||||
|
||||
def _batch_dispose(action: str):
|
||||
"""在每条任务行锁下重算权限与资格,返回部分成功明细而不让一条失败回滚整批。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_nos = _batch_task_nos(data)
|
||||
reason = str(data.get('reason') or '').strip()
|
||||
if action == 'delete' and not reason:
|
||||
raise ValidationError('reason is required', code='SHIPPING.TASK_DELETE_REASON_REQUIRED')
|
||||
request_id = getattr(g, 'request_id', None)
|
||||
results = []
|
||||
for task_no in task_nos:
|
||||
try:
|
||||
task = load_task_for_disposition(task_no)
|
||||
if not _can_dispose_task(user, task):
|
||||
results.append({'task_no': task_no, 'status': 'blocked', 'code': 'AUTH.FORBIDDEN'})
|
||||
db.session.rollback()
|
||||
continue
|
||||
if action == 'delete':
|
||||
outcome = move_task_to_recycle_bin(task, actor_id=user.id, reason=reason, request_id=request_id)
|
||||
elif action == 'archive':
|
||||
archive_task(task, actor_id=user.id, request_id=request_id)
|
||||
outcome = 'archived'
|
||||
else:
|
||||
restore_task_from_recycle_bin(task, actor_id=user.id, request_id=request_id)
|
||||
outcome = 'restored'
|
||||
db.session.commit()
|
||||
results.append({'task_no': task_no, 'status': outcome})
|
||||
except AppError as exc:
|
||||
db.session.rollback()
|
||||
results.append({'task_no': task_no, 'status': 'blocked', 'code': exc.code, 'message': exc.message})
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
return _ok({'results': results, 'requested_count': len(task_nos)})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/batch-purge', methods=['POST'])
|
||||
def workspace_batch_purge_shipping_tasks():
|
||||
"""仅管理员可永久清除回收站中的纯误建任务;每条均在行锁下重查全部引用。"""
|
||||
user = _require_user()
|
||||
if str(getattr(user, 'role', '')).lower() != 'admin':
|
||||
from app.core.errors import ForbiddenError
|
||||
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_nos = _batch_task_nos(data)
|
||||
reason = str(data.get('reason') or '').strip()
|
||||
if not reason:
|
||||
raise ValidationError('reason is required', code='SHIPPING.TASK_PURGE_REASON_REQUIRED')
|
||||
results = []
|
||||
for task_no in task_nos:
|
||||
try:
|
||||
task = load_task_for_disposition(task_no)
|
||||
purge_task_permanently(
|
||||
task,
|
||||
actor_id=user.id,
|
||||
reason=reason,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
results.append({'task_no': task_no, 'status': 'purged'})
|
||||
except AppError as exc:
|
||||
db.session.rollback()
|
||||
results.append({'task_no': task_no, 'status': 'blocked', 'code': exc.code, 'message': exc.message})
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
return _ok({'results': results, 'requested_count': len(task_nos)})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/batch-delete', methods=['POST'])
|
||||
def workspace_batch_delete_shipping_tasks():
|
||||
"""批量删除任务到回收站;服务端按行锁判定是否需要同时作废。"""
|
||||
return _batch_dispose('delete')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/batch-archive', methods=['POST'])
|
||||
def workspace_batch_archive_shipping_tasks():
|
||||
"""批量归档任务,适用于已上传或外部处理中而不能作废的任务。"""
|
||||
return _batch_dispose('archive')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/batch-restore', methods=['POST'])
|
||||
def workspace_batch_restore_shipping_tasks():
|
||||
"""批量恢复回收站内仍为 active 的纯误建任务。"""
|
||||
return _batch_dispose('restore')
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET'])
|
||||
def workspace_shipping_batches():
|
||||
|
||||
@@ -208,7 +208,7 @@ 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 优先原则)
|
||||
# 建单后是否延后订单抽取,交由 Dify 画布 LLM + submit_order_extraction 完成(默认 true)。
|
||||
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'
|
||||
@@ -308,13 +308,6 @@ class Config:
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE = float(
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE') or '0.8'
|
||||
)
|
||||
# 订单行双写/切读:默认 dual+shadow;切 table 读前须 verify 零差异并完成观察窗口。
|
||||
SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE = (
|
||||
os.getenv('SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE') or 'dual'
|
||||
).strip().lower()
|
||||
SHIPPING_NOTICE_ORDER_LINES_READ_MODE = (
|
||||
os.getenv('SHIPPING_NOTICE_ORDER_LINES_READ_MODE') or 'shadow'
|
||||
).strip().lower()
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
|
||||
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
||||
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path(
|
||||
@@ -492,6 +485,9 @@ class Config:
|
||||
class DevelopmentConfig(Config):
|
||||
DEBUG = True
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||
# 本机常无 Redis:不强制 Redis,允许进程内存兜底心跳(单进程 run.py 可用)
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
|
||||
|
||||
|
||||
class ProductionConfig(Config):
|
||||
|
||||
@@ -25,9 +25,10 @@ from app.models.shipping import (
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
ShippingTaskEvent,
|
||||
ShippingTaskPurgeAudit,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.models.shipping_task_line import ShippingTaskFieldConflict, ShippingTaskLine
|
||||
from app.models.shipping_task_line import ShippingTaskFieldConflict
|
||||
from app.models.shipping_excel_template import ShippingExcelTemplate, ShippingExportArtifact
|
||||
from app.models.shipping_order_schema import (
|
||||
ShippingOrderExtraction,
|
||||
@@ -45,6 +46,8 @@ from app.models.shipping_inventory_config import (
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryExternalMapping,
|
||||
ShippingInventoryConfigurationTestRun,
|
||||
ShippingInventoryValidationBatch,
|
||||
ShippingInventorySourceParsingBindingAudit,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryRoutingRule,
|
||||
ShippingInventoryRoutingRuleCondition,
|
||||
@@ -67,6 +70,12 @@ from app.models.shipping_customer import (
|
||||
)
|
||||
from app.models.shipping_customer_import import ShippingCustomerImportBatch, ShippingCustomerImportRow
|
||||
from app.models.shipping_customer_resolution import ShippingCustomerShadowMatch, ShippingCustomerShadowResolution
|
||||
from app.models.shipping_identity_rule import (
|
||||
ShippingIdentityDefinition,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingIdentityRuleAuditEvent,
|
||||
ShippingIdentityRuleSet,
|
||||
)
|
||||
from app.models.training import TrainingRecord
|
||||
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
|
||||
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
|
||||
@@ -105,7 +114,6 @@ __all__ = [
|
||||
'ScheduleRun',
|
||||
'ShippingBatch',
|
||||
'ShippingTask',
|
||||
'ShippingTaskLine',
|
||||
'ShippingTaskFieldConflict',
|
||||
'ShippingOrderSchema',
|
||||
'ShippingOrderSchemaVersion',
|
||||
@@ -130,7 +138,12 @@ __all__ = [
|
||||
'ShippingBusinessSequence',
|
||||
'ShippingCustomerShadowResolution',
|
||||
'ShippingCustomerShadowMatch',
|
||||
'ShippingIdentityDefinition',
|
||||
'ShippingIdentityEvidence',
|
||||
'ShippingIdentityRuleSet',
|
||||
'ShippingIdentityRuleAuditEvent',
|
||||
'ShippingTaskEvent',
|
||||
'ShippingTaskPurgeAudit',
|
||||
'ShippingInventoryFile',
|
||||
'ShippingTaskInventoryLink',
|
||||
'ShippingRpaProfile',
|
||||
@@ -142,6 +155,8 @@ __all__ = [
|
||||
'ShippingInventoryRoutingRuleVersion',
|
||||
'ShippingInventoryExternalMapping',
|
||||
'ShippingInventoryConfigurationTestRun',
|
||||
'ShippingInventoryValidationBatch',
|
||||
'ShippingInventorySourceParsingBindingAudit',
|
||||
'ShippingInventoryParsingProfile',
|
||||
'ShippingTemporaryInventorySession',
|
||||
'ShippingExcelTemplate',
|
||||
|
||||
@@ -8,7 +8,7 @@ backend/app/models/shipping.py
|
||||
Intake/Task/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离;
|
||||
Document/Candidate 承载「一邮件多订单」识别;ShippingTask.source_candidate_id 记录正式建单来源;
|
||||
ShippingTask.supersedes_task_id 唯一约束保证修订链线性;
|
||||
order_data_version / order_lines_migration_status 为规范表双写与切读准备,lines_json 暂保留。
|
||||
order_data_version 为动态订单 FieldValue 编辑的乐观锁版本;订单事实仅保存于 Extraction。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -144,14 +144,11 @@ 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)
|
||||
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)
|
||||
ship_to: Mapped[Optional[str]] = mapped_column(Text, 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)
|
||||
@@ -166,23 +163,14 @@ class ShippingTask(Base):
|
||||
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)
|
||||
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)
|
||||
# 规范订单行乐观版本与迁移状态;业务读路径经 task_line_store(json/shadow/table)。
|
||||
# 动态订单 FieldValue 编辑的乐观锁版本。
|
||||
order_data_version: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
default=1,
|
||||
server_default=text('1'),
|
||||
nullable=False,
|
||||
)
|
||||
order_lines_migration_status: Mapped[str] = mapped_column(
|
||||
String(32),
|
||||
default='pending',
|
||||
server_default=text("'pending'"),
|
||||
nullable=False,
|
||||
)
|
||||
current_order_extraction_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey(
|
||||
'shipping_order_extractions.id',
|
||||
@@ -219,6 +207,23 @@ 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(
|
||||
@@ -236,12 +241,6 @@ class ShippingTask(Base):
|
||||
back_populates='task',
|
||||
cascade='all, delete-orphan',
|
||||
)
|
||||
order_lines: Mapped[List['ShippingTaskLine']] = relationship(
|
||||
'ShippingTaskLine',
|
||||
back_populates='task',
|
||||
cascade='all, delete-orphan',
|
||||
order_by='ShippingTaskLine.position',
|
||||
)
|
||||
field_conflicts: Mapped[List['ShippingTaskFieldConflict']] = relationship(
|
||||
'ShippingTaskFieldConflict',
|
||||
back_populates='task',
|
||||
@@ -258,11 +257,28 @@ class ShippingTaskEvent(Base):
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True)
|
||||
event_type: Mapped[str] = mapped_column(String(64), index=True)
|
||||
detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=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')
|
||||
|
||||
|
||||
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):
|
||||
"""货代发货批次库存快照文件,承载一次上传后可被多票任务共用的库存数据。"""
|
||||
|
||||
@@ -543,6 +559,10 @@ class ShippingNoticeCandidate(Base):
|
||||
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,
|
||||
)
|
||||
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)
|
||||
|
||||
@@ -41,10 +41,19 @@ class ShippingCustomerShadowResolution(Base):
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
"""
|
||||
backend/app/models/shipping_identity_rule.py
|
||||
|
||||
用途:定义货代客户/送货站点的可配置识别定义、发布规则集和追加式审计。
|
||||
依赖:订单字段目录、客户/站点主数据、users。
|
||||
逻辑:定义引用稳定订单 field_id;规则集冻结定义快照;证据值绑定定义而不再依赖代码枚举。
|
||||
"""
|
||||
|
||||
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):
|
||||
"""管理员维护的稳定识别定义;平台只校验其受控来源适配器及参数。"""
|
||||
|
||||
__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(
|
||||
"source_adapter_key IN ('email_metadata', 'document_template', 'order_field')",
|
||||
name='ck_shipping_identity_definitions_source_adapter',
|
||||
),
|
||||
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_order_field', 'order_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)
|
||||
source_adapter_key: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
source_selector_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
attribute_key: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
order_field_id: Mapped[Optional[str]] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=True)
|
||||
normalizer_key: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
comparator_key: Mapped[str] = mapped_column(String(64), 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)
|
||||
@@ -108,7 +108,6 @@ class ShippingInventorySource(Base):
|
||||
# 业务报表定义属于 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)
|
||||
match_aliases_json: Mapped[list[str]] = 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)
|
||||
@@ -125,6 +124,30 @@ class ShippingInventorySource(Base):
|
||||
)
|
||||
|
||||
|
||||
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):
|
||||
"""可跨库存源复用的库存文件结构、样本证据与订单匹配配置。"""
|
||||
|
||||
@@ -205,6 +228,10 @@ class ShippingInventoryConfigurationTestRun(Base):
|
||||
|
||||
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)
|
||||
@@ -218,6 +245,28 @@ class ShippingInventoryConfigurationTestRun(Base):
|
||||
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 候选。"""
|
||||
|
||||
@@ -252,14 +301,13 @@ class ShippingInventoryRoutingRule(Base):
|
||||
|
||||
|
||||
class ShippingInventoryRoutingRuleCondition(Base):
|
||||
"""库存源路由条件;订单字段引用稳定 field_id,系统事实使用受控 key。"""
|
||||
"""库存源路由条件;仅引用已发布订单 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 AND system_fact_key IS NULL) OR "
|
||||
"(source_kind = 'system_fact' AND order_field_id IS NULL AND system_fact_key IS NOT NULL)",
|
||||
"source_kind = 'order_field' AND order_field_id IS NOT NULL",
|
||||
name='ck_inventory_routing_condition_source',
|
||||
),
|
||||
)
|
||||
@@ -269,7 +317,6 @@ class ShippingInventoryRoutingRuleCondition(Base):
|
||||
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)
|
||||
system_fact_key: Mapped[Optional[str]] = mapped_column(String(128), 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)
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
"""
|
||||
backend/app/models/shipping_task_line.py
|
||||
|
||||
用途:规范订单行(ShippingTaskLine)与字段冲突审计(ShippingTaskFieldConflict)模型。
|
||||
用途:订单字段冲突审计(ShippingTaskFieldConflict)模型。
|
||||
依赖:models.base.Base、shipping_tasks、users。
|
||||
逻辑:Task.lines_json 在迁移窗口内仍为兼容快照;规范表由阶段四双写填充,阶段六再切读。
|
||||
逻辑:冲突按动态订单 Extraction 的行 position 定位,不保留固定订单行投影。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from typing import TYPE_CHECKING, List, Optional
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import (
|
||||
CheckConstraint,
|
||||
@@ -18,95 +17,14 @@ from sqlalchemy import (
|
||||
Index,
|
||||
Integer,
|
||||
JSON,
|
||||
Numeric,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.shipping import ShippingTask
|
||||
|
||||
|
||||
class ShippingTaskLine(Base):
|
||||
"""
|
||||
任务当前订单行投影;稳定主键 + (task_id, position) 唯一。
|
||||
|
||||
核心逻辑:Candidate 是不可变抽取审计,本表是任务可变真相源;未知历史字段进 extra_json。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_task_lines'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('task_id', 'position', name='uq_shipping_task_lines_task_position'),
|
||||
CheckConstraint('qty > 0', name='ck_shipping_task_lines_qty_positive'),
|
||||
CheckConstraint(
|
||||
"part_number NOT LIKE '%/%'",
|
||||
name='ck_shipping_task_lines_part_number_atomic',
|
||||
),
|
||||
CheckConstraint(
|
||||
"customer_part_number IS NULL OR customer_part_number NOT LIKE '%/%'",
|
||||
name='ck_shipping_task_lines_customer_part_number_atomic',
|
||||
),
|
||||
CheckConstraint(
|
||||
"aws_part_number IS NULL OR aws_part_number NOT LIKE '%/%'",
|
||||
name='ck_shipping_task_lines_aws_part_number_atomic',
|
||||
),
|
||||
Index('ix_shipping_task_lines_task_id', 'task_id'),
|
||||
Index('ix_shipping_task_lines_reservation_id', 'reservation_id'),
|
||||
Index('ix_shipping_task_lines_part_number', 'part_number'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_tasks.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
part_number: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
qty: Mapped[Decimal] = mapped_column(Numeric(18, 6), nullable=False)
|
||||
uom: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
inventory_source_hint: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
required_date: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
customer_part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
aws_part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
allocation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
unit_price: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 6), nullable=True)
|
||||
amount: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 6), nullable=True)
|
||||
currency: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
extra_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
field_sources_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
evidence_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
schema_version: Mapped[str] = mapped_column(
|
||||
String(64),
|
||||
nullable=False,
|
||||
default='shipping-task-line-v2',
|
||||
server_default=text("'shipping-task-line-v2'"),
|
||||
)
|
||||
line_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[ShippingTask] = relationship('ShippingTask', back_populates='order_lines')
|
||||
field_conflicts: Mapped[List[ShippingTaskFieldConflict]] = relationship(
|
||||
'ShippingTaskFieldConflict',
|
||||
back_populates='line',
|
||||
cascade='save-update, merge',
|
||||
)
|
||||
|
||||
|
||||
class ShippingTaskFieldConflict(Base):
|
||||
"""
|
||||
订单字段级冲突审计;未解决冲突将在后续阶段阻断下游流程。
|
||||
@@ -121,25 +39,13 @@ class ShippingTaskFieldConflict(Base):
|
||||
name='ck_shipping_task_field_conflicts_status',
|
||||
),
|
||||
Index('ix_shipping_task_field_conflicts_task_status', 'task_id', 'status'),
|
||||
Index('ix_shipping_task_field_conflicts_line_id', 'line_id'),
|
||||
# NULL 在唯一索引中互不冲突,因此拆成「有行」与「无行」两条部分唯一索引。
|
||||
Index(
|
||||
'uq_shipping_task_field_conflicts_open_line_field',
|
||||
'task_id',
|
||||
'line_id',
|
||||
'field_name',
|
||||
unique=True,
|
||||
postgresql_where=text("status = 'open' AND line_id IS NOT NULL"),
|
||||
sqlite_where=text("status = 'open' AND line_id IS NOT NULL"),
|
||||
),
|
||||
Index(
|
||||
'uq_shipping_task_field_conflicts_open_task_field',
|
||||
'task_id',
|
||||
'field_name',
|
||||
unique=True,
|
||||
# 仅任务级冲突(无行/无 position);行级冲突走 position 唯一索引。
|
||||
postgresql_where=text("status = 'open' AND line_id IS NULL AND position IS NULL"),
|
||||
sqlite_where=text("status = 'open' AND line_id IS NULL AND position IS NULL"),
|
||||
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',
|
||||
@@ -158,11 +64,6 @@ class ShippingTaskFieldConflict(Base):
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
line_id: Mapped[Optional[int]] = mapped_column(
|
||||
# SET NULL:订单行双写重建主键时不得 CASCADE 抹掉冲突审计。
|
||||
ForeignKey('shipping_task_lines.id', ondelete='SET NULL'),
|
||||
nullable=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)
|
||||
@@ -191,7 +92,3 @@ class ShippingTaskFieldConflict(Base):
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
task: Mapped[ShippingTask] = relationship('ShippingTask', back_populates='field_conflicts')
|
||||
line: Mapped[Optional[ShippingTaskLine]] = relationship(
|
||||
'ShippingTaskLine',
|
||||
back_populates='field_conflicts',
|
||||
)
|
||||
@@ -20,6 +20,7 @@ from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingCustomerImportRow,
|
||||
ShippingCustomerLifecycleEvent,
|
||||
ShippingCustomerSite,
|
||||
@@ -89,6 +90,7 @@ def _build_customer_lifecycle_impact(customer: ShippingCustomer) -> dict[str, An
|
||||
'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(),
|
||||
},
|
||||
}
|
||||
@@ -229,6 +231,13 @@ def delete_customer(
|
||||
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 {
|
||||
|
||||
@@ -18,6 +18,7 @@ from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingCustomerLifecycleEvent,
|
||||
ShippingCustomerMerge,
|
||||
ShippingCustomerSite,
|
||||
@@ -72,6 +73,12 @@ def get_customer_merge_impact(source_customer_id: int, target_customer_id: int)
|
||||
(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,
|
||||
@@ -91,6 +98,8 @@ def get_customer_merge_impact(source_customer_id: int, target_customer_id: int)
|
||||
'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,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -155,6 +164,25 @@ def merge_customer(
|
||||
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
|
||||
@@ -191,6 +219,8 @@ def merge_customer(
|
||||
'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),
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
@@ -24,6 +24,7 @@ from app.models import (
|
||||
ShippingCustomerLifecycleEvent,
|
||||
ShippingCustomerSite,
|
||||
ShippingCustomerSiteIdentifier,
|
||||
ShippingIdentityEvidence,
|
||||
)
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
clean_text,
|
||||
@@ -118,6 +119,7 @@ def serialize_customer(
|
||||
include_identifiers: bool = False,
|
||||
case_count: int | None = None,
|
||||
identifier_count: int | None = None,
|
||||
identity_evidence_count: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
序列化标准客户,并可选附带识别证据和业务引用数量。
|
||||
@@ -126,7 +128,8 @@ def serialize_customer(
|
||||
record: 标准客户 ORM 记录。
|
||||
include_identifiers: 是否附带识别证据明细。
|
||||
case_count: 列表查询预聚合的业务单数量;为空时现场查询。
|
||||
identifier_count: 列表查询预聚合的识别证据数量;为空时现场查询。
|
||||
identifier_count: 历史固定类型证据数量,仅供存量审计显示。
|
||||
identity_evidence_count: 配置化客户主体证据数量;为空时现场查询。
|
||||
Returns:
|
||||
管理端客户 JSON 字典。
|
||||
"""
|
||||
@@ -143,9 +146,19 @@ def serialize_customer(
|
||||
'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
|
||||
@@ -173,14 +186,36 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]:
|
||||
.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()
|
||||
@@ -208,8 +243,11 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]:
|
||||
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))
|
||||
for customer, case_count, identifier_count in 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,
|
||||
@@ -293,6 +331,13 @@ def serialize_external_ref(record: ShippingCustomerExternalRef) -> dict[str, Any
|
||||
}
|
||||
|
||||
|
||||
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 {
|
||||
@@ -304,6 +349,13 @@ def serialize_site(record: ShippingCustomerSite) -> dict[str, Any]:
|
||||
'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()
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -20,13 +20,14 @@ from app.models import (
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventorySourceParsingBindingAudit,
|
||||
)
|
||||
from app.services.shipping_notice.credential_crypto import encrypt_credential
|
||||
from app.services.shipping_notice.inventory_source_repository import validate_source_profile
|
||||
from app.services.shipping_notice.routing_facts import ALLOWED_SYSTEM_FACT_KEYS
|
||||
from app.services.shipping_notice.routing_operators import ALLOWED_OPERATORS
|
||||
from app.services.shipping_notice.inventory_routing_engine import ALLOWED_ACTIONS
|
||||
from app.services.shipping_notice import inventory_parsing_profile
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
|
||||
def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None:
|
||||
@@ -238,13 +239,137 @@ def _source_payload(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
'excel_template_id': source.excel_template_id,
|
||||
'warehouse_resolution_mode': source.warehouse_resolution_mode, 'fixed_warehouse_id': source.fixed_warehouse_id,
|
||||
'report_path_json': source.report_path_json or {}, 'query_parameters_json': source.query_parameters_json or [],
|
||||
'match_aliases_json': source.match_aliases_json or [],
|
||||
'snapshot_ttl_seconds': source.snapshot_ttl_seconds, 'enabled': bool(source.enabled),
|
||||
'config_version': source.config_version, 'created_at': _iso(source.created_at), 'updated_at': _iso(source.updated_at),
|
||||
'activation': get_source_activation_status(source),
|
||||
}
|
||||
|
||||
|
||||
def _binding_snapshot(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
"""冻结解析绑定变更的最小站点上下文,避免审计依赖后续可变主数据。"""
|
||||
return {
|
||||
'source_id': source.id,
|
||||
'source_code': source.source_code,
|
||||
'enabled': bool(source.enabled),
|
||||
'parsing_profile_id': source.parsing_profile_id,
|
||||
'parsing_profile_checksum': source.parsing_profile.checksum if source.parsing_profile else None,
|
||||
'excel_template_id': source.excel_template_id,
|
||||
'config_version': source.config_version,
|
||||
}
|
||||
|
||||
|
||||
def _validate_source_parsing_binding(source: ShippingInventorySource, profile: ShippingInventoryParsingProfile) -> None:
|
||||
"""校验停用站点可直接采用的已发布方案与当前发货模板字段契约。"""
|
||||
if source.enabled:
|
||||
raise ConflictError('Disable inventory source before changing parsing profile', code='SHIPPING.INVENTORY_SOURCE_BINDING_BLOCKED')
|
||||
if profile.status != 'published':
|
||||
raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
mapping = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {}
|
||||
if not mapping:
|
||||
raise ValidationError('Published parsing profile is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
|
||||
template = source.excel_template
|
||||
if template is None:
|
||||
return
|
||||
if template.status != 'published':
|
||||
raise ValidationError('Published excel template is required', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED')
|
||||
template_definition = template.definition_json if isinstance(template.definition_json, dict) else {}
|
||||
template_mappings = template_definition.get('mappings') if isinstance(template_definition.get('mappings'), list) else []
|
||||
missing_fields = sorted({
|
||||
str(item.get('source_key') or '')
|
||||
for item in template_mappings
|
||||
if isinstance(item, dict)
|
||||
and item.get('source_kind') == 'inventory_field'
|
||||
and str(item.get('source_key') or '') not in mapping
|
||||
})
|
||||
if missing_fields:
|
||||
raise ValidationError(
|
||||
'Parsing profile does not provide all inventory fields required by the excel template',
|
||||
code='SHIPPING.INVENTORY_SOURCE_BINDING_TEMPLATE_INVALID', details={'inventory_field_ids': missing_fields},
|
||||
)
|
||||
|
||||
|
||||
def bind_source_parsing_profile(
|
||||
source_ids: list[int], profile_id: int, *, actor_id: int | None, reason: str | None = None, operation: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""为一个或多个停用库存站点原子绑定已发布解析方案并写入追加式审计。
|
||||
|
||||
Args:
|
||||
source_ids: 待绑定的库存站点主键,不能为空且不得重复。
|
||||
profile_id: 必须为已发布解析方案主键。
|
||||
actor_id: 当前管理员主键,仅写入审计。
|
||||
reason: 可选的补充说明;未填写时由系统记录本次直接或批量绑定动作。
|
||||
operation: 审计操作类型,仅允许 ``direct`` 或 ``bulk``。
|
||||
|
||||
Returns:
|
||||
list[dict[str, Any]]: 已更新站点的管理端 DTO。
|
||||
|
||||
Raises:
|
||||
ValidationError: 任一站点、方案或模板字段契约不合法;批量请求不会部分写入。
|
||||
ConflictError: 试图变更已启用站点的正式解析方案。
|
||||
"""
|
||||
try:
|
||||
normalized_ids = sorted({int(item) for item in source_ids if int(item) > 0})
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM') from exc
|
||||
if not normalized_ids or len(normalized_ids) != len(source_ids):
|
||||
raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM')
|
||||
if operation not in {'direct', 'bulk'}:
|
||||
raise ValidationError('Binding operation is invalid', code='VALIDATION.INVALID_PARAM')
|
||||
normalized_reason = str(reason or '').strip()
|
||||
if len(normalized_reason) > 500:
|
||||
raise ValidationError('Binding note must not exceed 500 characters', code='VALIDATION.INVALID_PARAM')
|
||||
# 审计必须保留可读动作,但不应把技术审计字段变成管理员的额外填写负担。
|
||||
if not normalized_reason:
|
||||
normalized_reason = '管理员直接绑定已发布解析方案' if operation == 'direct' else '管理员批量绑定已发布解析方案'
|
||||
try:
|
||||
normalized_profile_id = int(profile_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('parsing_profile_id is required', code='VALIDATION.INVALID_PARAM') from exc
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, normalized_profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
|
||||
sources = [db.session.get(ShippingInventorySource, source_id) for source_id in normalized_ids]
|
||||
if any(source is None for source in sources):
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
typed_sources = [source for source in sources if source is not None]
|
||||
# [STEP 1] 全量预检后才变更,避免多站点操作出现部分绑定。
|
||||
for source in typed_sources:
|
||||
_validate_source_parsing_binding(source, profile)
|
||||
for source in typed_sources:
|
||||
before = _binding_snapshot(source)
|
||||
previous_profile_id = source.parsing_profile_id
|
||||
source.parsing_profile = profile
|
||||
source.updated_by = actor_id
|
||||
source.config_version += 1
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventorySourceParsingBindingAudit(
|
||||
inventory_source_id=source.id, previous_parsing_profile_id=previous_profile_id,
|
||||
parsing_profile_id=profile.id, operation=operation, reason=normalized_reason, actor_id=actor_id,
|
||||
source_config_version_before=before['config_version'], source_config_version_after=source.config_version,
|
||||
before_snapshot_json=before, after_snapshot_json=_binding_snapshot(source),
|
||||
))
|
||||
db.session.commit()
|
||||
return [_source_payload(source) for source in typed_sources]
|
||||
|
||||
|
||||
def get_source_parsing_binding_audits(source_id: int) -> list[dict[str, Any]]:
|
||||
"""读取库存站点解析绑定审计,仅返回配置快照和操作者标识。"""
|
||||
if db.session.get(ShippingInventorySource, source_id) is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
rows = ShippingInventorySourceParsingBindingAudit.query.filter_by(
|
||||
inventory_source_id=source_id,
|
||||
).order_by(ShippingInventorySourceParsingBindingAudit.id.desc()).all()
|
||||
return [{
|
||||
'id': row.id, 'operation': row.operation, 'reason': row.reason, 'actor_id': row.actor_id,
|
||||
'previous_parsing_profile_id': row.previous_parsing_profile_id, 'parsing_profile_id': row.parsing_profile_id,
|
||||
'source_config_version_before': row.source_config_version_before,
|
||||
'source_config_version_after': row.source_config_version_after,
|
||||
'before': row.before_snapshot_json, 'after': row.after_snapshot_json,
|
||||
'created_at': row.created_at.isoformat() if row.created_at else None,
|
||||
} for row in rows]
|
||||
|
||||
|
||||
def list_sources() -> list[dict[str, Any]]:
|
||||
"""列出库存源及其稳定业务配置。"""
|
||||
return [_source_payload(item) for item in ShippingInventorySource.query.order_by(ShippingInventorySource.source_code).all()]
|
||||
@@ -397,13 +522,13 @@ def _enabled_external_mapping_exists(source: ShippingInventorySource, warehouse_
|
||||
|
||||
|
||||
def _test_analysis_validation(source: ShippingInventorySource) -> tuple[list[str], dict[str, Any]]:
|
||||
"""复核当前测试文件与已绑定方案,返回解析和仓库映射的启用前置条件。"""
|
||||
"""复核测试连接证据并生成行级解析/调拨映射准备状态,不将后两者作为启用条件。"""
|
||||
missing: list[str] = []
|
||||
details: dict[str, Any] = {'sample_warehouses': []}
|
||||
confirmed_test = ShippingInventoryConfigurationTestRun.query.filter_by(
|
||||
inventory_source_id=source.id,
|
||||
status='completed',
|
||||
source_config_version=source.config_version,
|
||||
confirmed_test = ShippingInventoryConfigurationTestRun.query.filter(
|
||||
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
|
||||
ShippingInventoryConfigurationTestRun.status.in_(['completed', 'completed_empty']),
|
||||
ShippingInventoryConfigurationTestRun.source_config_version == source.config_version,
|
||||
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
|
||||
result = confirmed_test.result_json if confirmed_test and isinstance(confirmed_test.result_json, dict) else {}
|
||||
if (
|
||||
@@ -413,6 +538,12 @@ def _test_analysis_validation(source: ShippingInventorySource) -> tuple[list[str
|
||||
or int(result.get('confirmed_profile_id') or 0) != int(source.parsing_profile_id or 0)
|
||||
):
|
||||
return ['configuration_test'], details
|
||||
if confirmed_test.status == 'completed_empty':
|
||||
# 无库存时只能确认连接与查询成功;行级解析和调拨映射留待首个非空文件或实际调拨前验证。
|
||||
details['data_validation'] = 'pending_first_non_empty_export'
|
||||
details['parsing_validation'] = 'pending_first_non_empty_export'
|
||||
details['warehouse_mapping'] = 'deferred_until_transfer'
|
||||
return missing, details
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, confirmed_test.analysis_id)
|
||||
profile = source.parsing_profile
|
||||
if analysis is None or profile is None:
|
||||
@@ -447,7 +578,7 @@ def _test_analysis_validation(source: ShippingInventorySource) -> tuple[list[str
|
||||
or any(str(value or '').strip() in duplicate_headers for value in mapping.values())
|
||||
or not int((selected or {}).get('sample_row_count') or 0)
|
||||
):
|
||||
missing.append('parsing_validation')
|
||||
details['parsing_validation'] = 'pending_first_non_empty_export'
|
||||
return missing, details
|
||||
column_by_header = {
|
||||
str(item.get('header') or '').strip(): item
|
||||
@@ -466,26 +597,27 @@ def _test_analysis_validation(source: ShippingInventorySource) -> tuple[list[str
|
||||
quantity_column.get('inferred_type') != 'number'
|
||||
or any(not item.get('sample_values') for item in identifier_columns)
|
||||
):
|
||||
missing.append('parsing_validation')
|
||||
details['parsing_validation'] = 'pending_first_non_empty_export'
|
||||
return missing, details
|
||||
if source.warehouse_resolution_mode == 'fixed':
|
||||
if not _enabled_external_mapping_exists(source, source.fixed_warehouse_id):
|
||||
missing.append('warehouse_mapping')
|
||||
details['warehouse_mapping'] = 'ready_for_transfer' if _enabled_external_mapping_exists(source, source.fixed_warehouse_id) else 'deferred_until_transfer'
|
||||
return missing, details
|
||||
warehouse_codes = mapped_ids & usages.get('warehouse_identity', set())
|
||||
if len(warehouse_codes) != 1:
|
||||
missing.append('warehouse_identification')
|
||||
details['warehouse_identification'] = 'pending_first_non_empty_export'
|
||||
return missing, details
|
||||
warehouse_header = next((str(runtime_mapping.get(field) or '').strip() for field in warehouse_codes), '')
|
||||
if not warehouse_header or warehouse_header not in headers or warehouse_header in duplicate_headers:
|
||||
missing.append('warehouse_identification')
|
||||
details['warehouse_identification'] = 'pending_first_non_empty_export'
|
||||
return missing, details
|
||||
column = next((item for item in (selected or {}).get('columns', [])
|
||||
if isinstance(item, dict) and str(item.get('header') or '').strip() == warehouse_header), {})
|
||||
sample_warehouses = sorted({str(value).strip().upper() for value in column.get('sample_values', []) if str(value).strip()})
|
||||
details['sample_warehouses'] = sample_warehouses
|
||||
if not sample_warehouses or any(not _enabled_external_mapping_exists(source, warehouse) for warehouse in sample_warehouses):
|
||||
missing.append('warehouse_mapping')
|
||||
details['warehouse_identification'] = 'ready_for_transfer' if sample_warehouses else 'pending_first_non_empty_export'
|
||||
details['warehouse_mapping'] = 'ready_for_transfer' if sample_warehouses and all(
|
||||
_enabled_external_mapping_exists(source, warehouse) for warehouse in sample_warehouses
|
||||
) else 'deferred_until_transfer'
|
||||
return missing, details
|
||||
|
||||
|
||||
@@ -527,6 +659,8 @@ def _latest_test_run_evidence(source: ShippingInventorySource) -> dict[str, Any]
|
||||
}
|
||||
if run.status == 'failed':
|
||||
return {'state': 'failed', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage}
|
||||
if run.status == 'completed_empty':
|
||||
return {'state': 'empty', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage}
|
||||
return {'state': 'current', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage}
|
||||
|
||||
|
||||
@@ -545,11 +679,7 @@ def _activation_check(
|
||||
|
||||
|
||||
def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str, Any]]:
|
||||
"""构建库存站点正式运行的权威检查清单。
|
||||
|
||||
检查项按管理员完成配置的业务顺序返回。测试、解析、模板和仓库映射均以当前
|
||||
``config_version`` 的持久化事实为准,避免管理端依据本地表单状态猜测启用资格。
|
||||
"""
|
||||
"""构建库存站点启用条件与后续准备项;行级解析和调拨映射不阻断启用。"""
|
||||
validation_missing, validation_details = _test_analysis_validation(source)
|
||||
missing = set(validation_missing)
|
||||
test_evidence = _latest_test_run_evidence(source)
|
||||
@@ -578,28 +708,28 @@ def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str,
|
||||
_activation_check(
|
||||
'configuration_test', passed=test_complete,
|
||||
action='run_configuration_test', evidence=test_evidence,
|
||||
status=test_evidence['state'] if test_evidence['state'] in {'stale', 'failed'} else None,
|
||||
status=test_evidence['state'] if test_evidence['state'] in {'stale', 'failed', 'empty'} else None,
|
||||
),
|
||||
_activation_check(
|
||||
'parsing_validation', passed=test_complete and 'parsing_validation' not in missing,
|
||||
'parsing_validation', passed=test_complete and not validation_details.get('parsing_validation'),
|
||||
action='run_configuration_test', evidence={'sample_warehouses': validation_details['sample_warehouses']},
|
||||
status='pending' if not test_complete else None, blocking='parsing_validation' in missing,
|
||||
status='pending' if validation_details.get('parsing_validation') else None, blocking=False,
|
||||
),
|
||||
]
|
||||
if source.warehouse_resolution_mode == 'inventory_match':
|
||||
checks.append(_activation_check(
|
||||
'warehouse_identification', passed=test_complete and 'warehouse_identification' not in missing,
|
||||
'warehouse_identification', passed=validation_details.get('warehouse_identification') == 'ready_for_transfer',
|
||||
action='configure_parsing_profile', evidence={'sample_warehouses': validation_details['sample_warehouses']},
|
||||
status='pending' if not test_complete else None, blocking='warehouse_identification' in missing,
|
||||
status='pending' if validation_details.get('warehouse_identification') else None, blocking=False,
|
||||
))
|
||||
checks.append(_activation_check(
|
||||
'warehouse_mapping', passed=test_complete and 'warehouse_mapping' not in missing, action='configure_warehouse_mapping',
|
||||
'warehouse_mapping', passed=validation_details.get('warehouse_mapping') == 'ready_for_transfer', action='configure_warehouse_mapping',
|
||||
evidence={
|
||||
'mode': source.warehouse_resolution_mode,
|
||||
'fixed_warehouse_id': source.fixed_warehouse_id,
|
||||
'sample_warehouses': validation_details['sample_warehouses'],
|
||||
},
|
||||
status='pending' if not test_complete else None, blocking='warehouse_mapping' in missing,
|
||||
status='pending' if validation_details.get('warehouse_mapping') else None, blocking=False,
|
||||
))
|
||||
return checks
|
||||
|
||||
@@ -623,6 +753,23 @@ def get_source_activation_status(source: ShippingInventorySource) -> dict[str, A
|
||||
}
|
||||
|
||||
|
||||
def activate_source_if_ready(source: ShippingInventorySource, *, actor_id: int | None) -> bool:
|
||||
"""在测试回调后自动启用已满足全部正式运行条件的停用站点。
|
||||
|
||||
Args:
|
||||
source: 已完成当前版本测试的库存站点;调用方负责统一提交事务。
|
||||
actor_id: 发起测试的管理员标识,仅用于更新审计字段。
|
||||
|
||||
Returns:
|
||||
当本次将站点改为启用时返回 ``True``;条件未齐或已启用时返回 ``False``。
|
||||
"""
|
||||
if source.enabled or not get_source_activation_status(source)['ready']:
|
||||
return False
|
||||
source.enabled = True
|
||||
source.updated_by = actor_id
|
||||
return True
|
||||
|
||||
|
||||
def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""启用完成验证的库存站点;未通过任一前置条件时保持停用。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
@@ -704,7 +851,6 @@ def save_source(
|
||||
source.fixed_warehouse_id = _text(data, 'fixed_warehouse_id')
|
||||
source.report_path_json = _validate_report_path(source.connector_type, _json_object(data, 'report_path_json'))
|
||||
source.query_parameters_json = _validate_query_parameters(data)
|
||||
source.match_aliases_json = _json_string_list(data, 'match_aliases_json')
|
||||
source.snapshot_ttl_seconds = int(data.get('snapshot_ttl_seconds') or 86400)
|
||||
source.enabled = enabled
|
||||
source.updated_by = actor_id
|
||||
@@ -728,7 +874,7 @@ def _rule_payload(rule: ShippingInventoryRoutingRule) -> dict[str, Any]:
|
||||
'priority': rule.priority, 'match_mode': rule.match_mode, 'status': rule.status,
|
||||
'action_type': rule.action_type, 'action_payload_json': rule.action_payload_json or {}, 'version': rule.version,
|
||||
'conditions': [{'source_kind': c.source_kind, 'order_field_id': c.order_field_id,
|
||||
'system_fact_key': c.system_fact_key, 'operator': c.operator, 'expected_value_json': c.expected_value_json,
|
||||
'operator': c.operator, 'expected_value_json': c.expected_value_json,
|
||||
'condition_group': c.condition_group, 'sequence': c.sequence} for c in rule.conditions],
|
||||
}
|
||||
|
||||
@@ -826,22 +972,23 @@ def save_rule(data: dict[str, Any], *, actor_id: int | None, rule_id: int | None
|
||||
raise ValidationError('Routing rule condition is not allowed', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
|
||||
source_kind = str(item.get('source_kind') or 'order_field')
|
||||
order_field_id = str(item.get('order_field_id') or '') or None
|
||||
system_fact_key = str(item.get('system_fact_key') or '') or None
|
||||
field = db.session.get(ShippingOrderField, order_field_id) if order_field_id else None
|
||||
if source_kind == 'order_field':
|
||||
if field is None or field.status != 'active' or field.scope != rule.scope.replace('task', 'header'):
|
||||
raise ValidationError('Routing order field is invalid for rule scope', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
|
||||
system_fact_key = None
|
||||
elif source_kind == 'system_fact':
|
||||
if system_fact_key not in ALLOWED_SYSTEM_FACT_KEYS:
|
||||
raise ValidationError('Routing system fact is invalid', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
|
||||
order_field_id = None
|
||||
published_fields = {
|
||||
str(config.get('field_id'))
|
||||
for config in order_schema_service.get_published_contract()['fields']
|
||||
if config.get('scope') == field.scope
|
||||
}
|
||||
if field.id not in published_fields:
|
||||
raise ValidationError('Routing order field is not published', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
|
||||
else:
|
||||
raise ValidationError('Routing condition source is invalid', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
|
||||
raise ValidationError('Routing conditions must use a published order field', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
|
||||
operator = str(item['operator'])
|
||||
rule.conditions.append(ShippingInventoryRoutingRuleCondition(
|
||||
condition_group=int(item.get('condition_group') or 1), source_kind=source_kind,
|
||||
order_field_id=order_field_id, system_fact_key=system_fact_key,
|
||||
order_field_id=order_field_id,
|
||||
operator=operator, expected_value_json=_validate_rule_condition_expected(
|
||||
operator, item.get('expected_value_json'),
|
||||
), sequence=index,
|
||||
|
||||
@@ -72,3 +72,7 @@ class AgentHandler:
|
||||
) -> Iterator[str]:
|
||||
"""上游 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
|
||||
@@ -414,3 +414,19 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
yield self._format_sse(extraction_event)
|
||||
if event:
|
||||
yield self._format_sse(event)
|
||||
|
||||
def should_recover_upstream_error(self, ctx: ChatStreamContext, event_data: dict[str, Any]) -> bool:
|
||||
"""
|
||||
判断 Dify 流错误能否按已持久化的订单抽取结果正常收口。
|
||||
|
||||
核心逻辑:仅处理当前订单抽取请求;Tool 已写入 completed/partially_completed 时,
|
||||
网络断流不应覆盖订单事实或向前端显示失败。仍为 extracting/failed 的请求维持原错误语义。
|
||||
"""
|
||||
if str(event_data.get('event') or '').strip() != 'error':
|
||||
return False
|
||||
state_event = self.build_order_extraction_state_event(ctx)
|
||||
return bool(
|
||||
state_event
|
||||
and state_event.get('terminal') is True
|
||||
and state_event.get('status') in {'completed', 'partially_completed'}
|
||||
)
|
||||
@@ -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 键则跳过。
|
||||
|
||||
@@ -28,6 +28,7 @@ from app.models import (
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete
|
||||
@@ -50,6 +51,8 @@ from app.services.shipping_notice.open_existing_reservation_backfill import (
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import log_task_event
|
||||
from app.services.shipping_notice.customer_auto_resolution import try_auto_confirm_task_customer
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
|
||||
|
||||
def _batch_intake_nos(batch_id: int) -> set[str]:
|
||||
@@ -750,6 +753,32 @@ def create_shipping_batch_from_candidates(
|
||||
task = task_by_candidate.get(int(candidate.id))
|
||||
if task is None:
|
||||
raise ConflictError(code='SHIPPING.BATCH_CREATE_INCOMPLETE', message='候选任务关联不完整')
|
||||
if candidate.order_extraction_id is None:
|
||||
raise ConflictError(
|
||||
code='SHIPPING.BATCH_CREATE_INCOMPLETE',
|
||||
message='候选订单缺少已裁决的动态订单解析版本',
|
||||
)
|
||||
extraction = db.session.get(ShippingOrderExtraction, int(candidate.order_extraction_id))
|
||||
if extraction is None or extraction.status != 'accepted':
|
||||
raise ConflictError(
|
||||
code='SHIPPING.BATCH_CREATE_INCOMPLETE',
|
||||
message='候选订单解析版本未通过裁决,不能创建任务',
|
||||
)
|
||||
# 编排器启动前绑定任务与锁定 Extraction,避免任何下游入口观察到无订单真相的 Task。
|
||||
task.current_order_extraction_id = int(extraction.id)
|
||||
extraction.task_id = int(task.id)
|
||||
reservation_issues = task_reservation_gate_issues(task)
|
||||
if reservation_issues:
|
||||
apply_task_transition(task, TaskTransition.RSV_REQUIRED)
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload['process_field_gate'] = {
|
||||
'status': 'needs_enrichment',
|
||||
'missing_fields': ['reservation_id'],
|
||||
'issues': reservation_issues,
|
||||
}
|
||||
task.step_payload_json = payload
|
||||
else:
|
||||
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
|
||||
candidate.consumed_task_id = int(task.id)
|
||||
candidate.updated_at = now
|
||||
try_auto_confirm_task_customer(task)
|
||||
|
||||
@@ -65,6 +65,10 @@ def _unmark_running(bucket: set[str], key: str) -> None:
|
||||
|
||||
|
||||
def _should_orchestrate_task(task: Any) -> bool:
|
||||
from app.services.shipping_notice.task_disposition_service import task_is_active
|
||||
|
||||
if not task_is_active(task):
|
||||
return False
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if process_status in _TERMINAL_PROCESS_STATUSES:
|
||||
@@ -86,6 +90,10 @@ def _should_orchestrate_task(task: Any) -> bool:
|
||||
|
||||
def _is_retryable_task(task: Any) -> bool:
|
||||
"""判断任务是否允许由批次重试入口重新派发。"""
|
||||
from app.services.shipping_notice.task_disposition_service import task_is_active
|
||||
|
||||
if not task_is_active(task):
|
||||
return False
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if process_status in _TERMINAL_PROCESS_STATUSES:
|
||||
@@ -187,7 +195,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
)
|
||||
elif process_status == "created":
|
||||
result = run_shipping_parse_via_dify(task.task_no)
|
||||
# Dify 会通过 Tool API 在独立请求中提交 parse_notice;当前 worker session
|
||||
# Dify 会通过 Tool API 在独立请求中提交动态订单抽取;当前 worker session
|
||||
# 可能仍缓存 created 旧对象,必须重新读库后才能决定是否继续 auto_progress。
|
||||
db.session.expire_all()
|
||||
if current_app:
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
services/shipping_notice/customer_auto_resolution.py
|
||||
|
||||
用途:基于管理员审核的强证据受控自动确认客户,并支持历史回填与编号后客户纠错。
|
||||
依赖:ShippingCustomerIdentifier/ShadowResolution/Task、customer_identity_gate、business_numbering_service、Flask 配置。
|
||||
逻辑:Candidate 建单后仅以已审核强证据自动确认;管理员纠错时保留原号作废并创建替代业务单。
|
||||
依赖:ShippingIdentityEvidence/ShadowResolution/Task、customer_identity_gate、business_numbering_service、Flask 配置。
|
||||
逻辑:Candidate 建单后只按影子快照中的已审核授权证据自动确认;管理员纠错时保留原号作废并创建替代业务单。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,8 +17,8 @@ from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingCase,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingTask,
|
||||
ShippingTaskEvent,
|
||||
@@ -29,8 +29,7 @@ from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_in
|
||||
from app.services.shipping_notice.business_case_service import generate_shipping_case_no
|
||||
from app.services.shipping_notice.business_numbering_service import assign_business_number
|
||||
|
||||
AUTO_RESOLUTION_VERSION = "customer-auto-v1"
|
||||
AUTO_IDENTIFIER_TYPES = frozenset({"email", "domain", "template_fingerprint"})
|
||||
AUTO_RESOLUTION_VERSION = "customer-auto-v2"
|
||||
CUSTOMER_AUDIT_EVENT_TYPES = (
|
||||
"customer_auto_resolution_evaluated",
|
||||
"customer_auto_confirmed",
|
||||
@@ -60,7 +59,7 @@ def _auto_confirmation_quality_gate() -> dict[str, Any]:
|
||||
eligible_samples = 0
|
||||
correct_samples = 0
|
||||
for shadow in labeled:
|
||||
decision = _resolve_auto_customer_from_evidence(shadow.evidence_json or [])
|
||||
decision = _resolve_auto_customer_from_shadow_resolution(shadow)
|
||||
if decision['status'] != 'unique_strong_match':
|
||||
continue
|
||||
eligible_samples += 1
|
||||
@@ -85,57 +84,99 @@ def _auto_confirmation_quality_gate() -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _eligible_identifier(identifier: ShippingCustomerIdentifier) -> bool:
|
||||
"""判断识别证据是否达到自动确认门槛。"""
|
||||
if identifier.status != "approved" or not identifier.auto_match_allowed:
|
||||
return False
|
||||
if identifier.identifier_type not in AUTO_IDENTIFIER_TYPES:
|
||||
return False
|
||||
if identifier.identifier_type == "domain" and is_public_email_domain(identifier.normalized_value):
|
||||
return False
|
||||
return True
|
||||
def _rule_snapshot(shadow: ShippingCustomerShadowResolution) -> dict[str, Any] | None:
|
||||
"""读取并校验影子记录冻结的规则集;缺失或不一致时宁可降级,不能回读当前配置。"""
|
||||
context = shadow.resolution_context_json if isinstance(shadow.resolution_context_json, dict) else {}
|
||||
snapshot = context.get('rule_set') if isinstance(context.get('rule_set'), dict) else None
|
||||
if not snapshot or not isinstance(snapshot.get('definitions'), list):
|
||||
return None
|
||||
if snapshot.get('id') != shadow.identity_rule_set_id:
|
||||
return None
|
||||
if snapshot.get('version') != shadow.identity_rule_set_version:
|
||||
return None
|
||||
if snapshot.get('checksum') != shadow.identity_rule_set_checksum:
|
||||
return None
|
||||
return snapshot
|
||||
|
||||
|
||||
def _resolve_auto_customer_from_evidence(evidence_rows: list[object]) -> dict[str, Any]:
|
||||
"""以候选的规范化证据求唯一强规则客户,不读取总开关或质量门禁。"""
|
||||
def _decision_base(shadow: ShippingCustomerShadowResolution, *, status: str) -> dict[str, Any]:
|
||||
"""构造每次自动裁决的可追溯规则版本信息,供任务审计事件永久保存。"""
|
||||
return {
|
||||
'status': status,
|
||||
'rule_version': AUTO_RESOLUTION_VERSION,
|
||||
'customer_id': None,
|
||||
'evidence': [],
|
||||
'candidate_customer_ids': [],
|
||||
'rule_set': {
|
||||
'id': shadow.identity_rule_set_id,
|
||||
'version': shadow.identity_rule_set_version,
|
||||
'checksum': shadow.identity_rule_set_checksum,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadowResolution) -> dict[str, Any]:
|
||||
"""
|
||||
按影子记录的冻结定义和当前已审核授权证据求唯一自动确认客户。
|
||||
|
||||
业务定义、站点证据、公共邮箱域名及快照外字段都不是自动确认依据;多个客户命中时
|
||||
一律返回歧义,即使其中一个客户累积的证据更多。
|
||||
"""
|
||||
snapshot = _rule_snapshot(shadow)
|
||||
if snapshot is None:
|
||||
return _decision_base(shadow, status='rule_snapshot_missing')
|
||||
definitions = {
|
||||
str(item.get('id') or ''): item
|
||||
for item in snapshot['definitions']
|
||||
if isinstance(item, dict) and str(item.get('id') or '')
|
||||
}
|
||||
matched: dict[int, list[dict[str, Any]]] = {}
|
||||
for evidence in evidence_rows:
|
||||
for evidence in shadow.evidence_json or []:
|
||||
if not isinstance(evidence, dict):
|
||||
continue
|
||||
kind = str(evidence.get("type") or "").strip()
|
||||
normalized = str(evidence.get("normalized_value") or "").strip()
|
||||
if kind not in AUTO_IDENTIFIER_TYPES or not normalized:
|
||||
definition_id = str(evidence.get('definition_id') or '').strip()
|
||||
definition = definitions.get(definition_id)
|
||||
normalized = str(evidence.get('normalized_value') or '').strip()
|
||||
if not definition or not normalized:
|
||||
continue
|
||||
identifiers = db.session.query(ShippingCustomerIdentifier).filter_by(
|
||||
identifier_type=kind,
|
||||
if (
|
||||
definition.get('target_type') != 'customer'
|
||||
or definition.get('max_automation') != 'conditional'
|
||||
or definition.get('source_adapter_key') not in {'email_metadata', 'document_template'}
|
||||
):
|
||||
continue
|
||||
email_domain = normalized.rsplit('@', 1)[-1] if '@' in normalized else normalized
|
||||
if definition.get('attribute_key') in {'email', 'domain'} and is_public_email_domain(email_domain):
|
||||
continue
|
||||
records = db.session.query(ShippingIdentityEvidence).filter_by(
|
||||
definition_id=definition_id,
|
||||
normalized_value=normalized,
|
||||
status='approved',
|
||||
auto_match_allowed=True,
|
||||
).all()
|
||||
for identifier in identifiers:
|
||||
if not _eligible_identifier(identifier):
|
||||
for record in records:
|
||||
if record.customer_id is None:
|
||||
continue
|
||||
customer = db.session.get(ShippingCustomer, int(identifier.customer_id))
|
||||
customer = db.session.get(ShippingCustomer, int(record.customer_id))
|
||||
if customer is None or customer.status != "active":
|
||||
continue
|
||||
matched.setdefault(customer.id, []).append({
|
||||
"identifier_id": identifier.id,
|
||||
"identifier_type": kind,
|
||||
"normalized_value": normalized,
|
||||
'evidence_id': record.id,
|
||||
'definition_id': definition_id,
|
||||
'definition_code': definition.get('definition_code'),
|
||||
'normalized_value': normalized,
|
||||
'source': evidence.get('source'),
|
||||
})
|
||||
if len(matched) != 1:
|
||||
return {
|
||||
"status": "ambiguous" if matched else "unmatched",
|
||||
"rule_version": AUTO_RESOLUTION_VERSION,
|
||||
"customer_id": None,
|
||||
"evidence": [item for rows in matched.values() for item in rows],
|
||||
"candidate_customer_ids": sorted(matched),
|
||||
}
|
||||
result = _decision_base(shadow, status='ambiguous' if matched else 'unmatched')
|
||||
result['evidence'] = [item for rows in matched.values() for item in rows]
|
||||
result['candidate_customer_ids'] = sorted(matched)
|
||||
return result
|
||||
customer_id = next(iter(matched))
|
||||
return {
|
||||
"status": "unique_strong_match",
|
||||
"rule_version": AUTO_RESOLUTION_VERSION,
|
||||
"customer_id": customer_id,
|
||||
"evidence": matched[customer_id],
|
||||
}
|
||||
result = _decision_base(shadow, status='unique_strong_match')
|
||||
result['customer_id'] = customer_id
|
||||
result['evidence'] = matched[customer_id]
|
||||
return result
|
||||
|
||||
|
||||
def resolve_auto_customer_from_shadow(task: ShippingTask) -> dict[str, Any]:
|
||||
@@ -172,7 +213,7 @@ def resolve_auto_customer_from_shadow(task: ShippingTask) -> dict[str, Any]:
|
||||
if shadow is None:
|
||||
return {"status": "no_shadow", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
|
||||
|
||||
return {**_resolve_auto_customer_from_evidence(shadow.evidence_json or []), 'quality_gate': quality_gate}
|
||||
return {**_resolve_auto_customer_from_shadow_resolution(shadow), 'quality_gate': quality_gate}
|
||||
|
||||
|
||||
def try_auto_confirm_task_customer(task: ShippingTask) -> dict[str, Any]:
|
||||
|
||||
@@ -8,120 +8,34 @@ backend/app/services/shipping_notice/customer_shadow_resolution.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
from email.utils import parseaddr
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.core.errors import ConflictError, NotFoundError
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerShadowMatch,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeIntake,
|
||||
)
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
is_public_email_domain,
|
||||
normalize_customer_name,
|
||||
normalize_domain,
|
||||
normalize_email,
|
||||
normalize_identifier,
|
||||
)
|
||||
from app.services.shipping_notice.identity_resolution import resolve_candidate_identity
|
||||
|
||||
RESOLUTION_VERSION = 'shadow-v1'
|
||||
EVIDENCE_WEIGHTS = {'email': 100.0, 'domain': 80.0, 'name_alias': 70.0, 'standard_name': 60.0}
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _extract_evidence(candidate: ShippingNoticeCandidate, intake: ShippingNoticeIntake) -> list[dict[str, Any]]:
|
||||
"""从业务摘要和邮件元数据提取可审计证据,不把解析客户码当稳定客户键。"""
|
||||
structured = candidate.structured_result_json if isinstance(candidate.structured_result_json, dict) else {}
|
||||
summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {}
|
||||
intake_structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
email_meta = intake_structured.get('email') if isinstance(intake_structured.get('email'), dict) else {}
|
||||
evidence: list[dict[str, Any]] = []
|
||||
customer_name = str(summary.get('customer_name') or '').strip()
|
||||
if customer_name:
|
||||
evidence.append({'type': 'name_alias', 'raw_value': customer_name, 'normalized_value': normalize_customer_name(customer_name)})
|
||||
template_fingerprint = str(
|
||||
structured.get('template_fingerprint')
|
||||
or intake_structured.get('template_fingerprint')
|
||||
or ''
|
||||
).strip()
|
||||
if template_fingerprint:
|
||||
evidence.append({
|
||||
'type': 'template_fingerprint',
|
||||
'raw_value': template_fingerprint,
|
||||
'normalized_value': normalize_identifier('template_fingerprint', template_fingerprint),
|
||||
})
|
||||
sender = parseaddr(str(email_meta.get('from') or ''))[1].strip().lower()
|
||||
if sender:
|
||||
try:
|
||||
normalized_email = normalize_email(sender)
|
||||
evidence.append({'type': 'email', 'raw_value': sender, 'normalized_value': normalized_email})
|
||||
domain = normalize_domain(normalized_email)
|
||||
if not is_public_email_domain(domain):
|
||||
evidence.append({'type': 'domain', 'raw_value': domain, 'normalized_value': domain})
|
||||
except ValidationError:
|
||||
pass
|
||||
return evidence
|
||||
|
||||
|
||||
def _rank_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""仅用启用客户和 approved 标识聚合确定性分数,返回稳定排序候选。"""
|
||||
scores: dict[int, float] = defaultdict(float)
|
||||
reasons: dict[int, list[dict[str, Any]]] = defaultdict(list)
|
||||
active_customers = db.session.query(ShippingCustomer).filter_by(status='active').all()
|
||||
active_ids = {int(item.id) for item in active_customers}
|
||||
by_name: dict[str, list[ShippingCustomer]] = defaultdict(list)
|
||||
for customer in active_customers:
|
||||
by_name[normalize_customer_name(customer.standard_name)].append(customer)
|
||||
for item in evidence:
|
||||
kind = str(item.get('type') or '')
|
||||
normalized = str(item.get('normalized_value') or '')
|
||||
if kind == 'name_alias' and normalized in by_name:
|
||||
for customer in by_name[normalized]:
|
||||
scores[customer.id] += EVIDENCE_WEIGHTS['standard_name']
|
||||
reasons[customer.id].append({'type': 'standard_name', 'value': normalized})
|
||||
identifiers = db.session.query(ShippingCustomerIdentifier).filter_by(
|
||||
identifier_type=kind,
|
||||
normalized_value=normalized,
|
||||
status='approved',
|
||||
).all()
|
||||
for identifier in identifiers:
|
||||
if int(identifier.customer_id) not in active_ids:
|
||||
continue
|
||||
scores[identifier.customer_id] += EVIDENCE_WEIGHTS.get(kind, 0.0)
|
||||
reasons[identifier.customer_id].append({'type': kind, 'identifier_id': identifier.id, 'value': normalized})
|
||||
customers = {item.id: item for item in active_customers}
|
||||
return sorted(
|
||||
[
|
||||
{
|
||||
'customer_id': customer_id,
|
||||
'standard_name': customers[customer_id].standard_name,
|
||||
'short_code': customers[customer_id].short_code,
|
||||
'score': score,
|
||||
'reasons': reasons[customer_id],
|
||||
}
|
||||
for customer_id, score in scores.items()
|
||||
],
|
||||
key=lambda item: (-float(item['score']), int(item['customer_id'])),
|
||||
)
|
||||
|
||||
|
||||
def refresh_candidate_shadow_resolution(candidate: ShippingNoticeCandidate) -> ShippingCustomerShadowResolution:
|
||||
"""幂等刷新 Candidate 影子识别;只写审计结果,不执行客户绑定或自动确认。"""
|
||||
intake = db.session.get(ShippingNoticeIntake, int(candidate.intake_id))
|
||||
if intake is None:
|
||||
raise NotFoundError('Shipping intake not found', code='SHIPPING_NOTICE.INTAKE_NOT_FOUND')
|
||||
evidence = _extract_evidence(candidate, intake)
|
||||
matches = _rank_matches(evidence)
|
||||
resolution = resolve_candidate_identity(candidate, intake)
|
||||
evidence = list(resolution['evidence'])
|
||||
matches = list(resolution['customer_matches'])
|
||||
top_score = float(matches[0]['score']) if matches else None
|
||||
tied = [item for item in matches if float(item['score']) == top_score] if top_score is not None else []
|
||||
status = 'unmatched' if not matches else 'unique_candidate' if len(tied) == 1 else 'ambiguous'
|
||||
@@ -130,11 +44,20 @@ def refresh_candidate_shadow_resolution(candidate: ShippingNoticeCandidate) -> S
|
||||
row = ShippingCustomerShadowResolution(candidate_id=int(candidate.id), intake_id=int(candidate.intake_id))
|
||||
db.session.add(row)
|
||||
row.intake_id = int(candidate.intake_id)
|
||||
row.resolution_version = RESOLUTION_VERSION
|
||||
row.status = status
|
||||
row.identity_rule_set_id = resolution['rule_set']['id']
|
||||
row.identity_rule_set_version = resolution['rule_set']['version']
|
||||
row.identity_rule_set_checksum = resolution['rule_set']['checksum']
|
||||
row.order_schema_version_id = resolution['order_schema_version_id']
|
||||
row.resolution_version = resolution['resolution_version']
|
||||
row.status = str(resolution['status'])
|
||||
row.evidence_json = evidence
|
||||
row.candidate_matches_json = matches
|
||||
row.top_customer_id = int(matches[0]['customer_id']) if status == 'unique_candidate' else None
|
||||
row.resolution_context_json = {
|
||||
'rule_set': resolution['rule_set'],
|
||||
'order_extraction_id': resolution['order_extraction_id'],
|
||||
'site_matches': resolution['site_matches'],
|
||||
}
|
||||
row.top_customer_id = int(matches[0]['customer_id']) if row.status == 'unique_candidate' else None
|
||||
row.top_score = top_score
|
||||
# 规范化候选关联用于客户生命周期约束;JSON 继续保留完整证据供展示与审计。
|
||||
# 先落库删除旧快照,避免 SQLite/PostgreSQL 在同次 flush 中先插入后删除而触发唯一约束。
|
||||
@@ -181,10 +104,11 @@ def refresh_candidate_shadow_resolution_safely(candidate: ShippingNoticeCandidat
|
||||
intake_id=int(candidate.intake_id),
|
||||
)
|
||||
db.session.add(row)
|
||||
row.resolution_version = RESOLUTION_VERSION
|
||||
row.resolution_version = 'shadow-v2'
|
||||
row.status = 'failed'
|
||||
row.evidence_json = []
|
||||
row.candidate_matches_json = []
|
||||
row.resolution_context_json = {}
|
||||
row.top_customer_id = None
|
||||
row.top_score = None
|
||||
db.session.query(ShippingCustomerShadowMatch).filter_by(resolution_id=row.id).delete(
|
||||
@@ -236,9 +160,14 @@ def serialize_shadow_resolution(
|
||||
'candidate_no': candidate.candidate_no if candidate else None,
|
||||
'intake_no': intake.intake_no if intake else None,
|
||||
'resolution_version': row.resolution_version,
|
||||
'identity_rule_set_id': row.identity_rule_set_id,
|
||||
'identity_rule_set_version': row.identity_rule_set_version,
|
||||
'identity_rule_set_checksum': row.identity_rule_set_checksum,
|
||||
'order_schema_version_id': row.order_schema_version_id,
|
||||
'status': row.status,
|
||||
'evidence': row.evidence_json or [],
|
||||
'matches': row.candidate_matches_json or [],
|
||||
'context': row.resolution_context_json or {},
|
||||
'top_customer_id': row.top_customer_id,
|
||||
'top_score': row.top_score,
|
||||
'manual_customer_id': row.manual_customer_id,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/decision_workflow.py
|
||||
|
||||
用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配和重解析。
|
||||
依赖:state_machine、tool_response、query_service、库存源 Gate、fulfillment_workflow、task_line_store。
|
||||
依赖:state_machine、tool_response、query_service、库存源 Gate、fulfillment_workflow、动态订单字段编辑器。
|
||||
逻辑:由 task_workflow 对外转调本文件;本文件在当前任务上下文内执行决策分支,并在必要时回调后端 orchestrator。
|
||||
"""
|
||||
|
||||
@@ -23,7 +23,7 @@ from app.services.shipping_notice.constants import (
|
||||
RS_SHORTAGE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_completed, match_inventory
|
||||
from app.services.shipping_notice.task_line_store import clear_task_order_lines
|
||||
from app.services.shipping_notice.task_order_field_editor import retire_current_order_extraction
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
is_inventory_source_stable,
|
||||
@@ -377,7 +377,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task.process_status = "created"
|
||||
task.review_status = None
|
||||
task.pending_human_reason = None
|
||||
clear_task_order_lines(task)
|
||||
retire_current_order_extraction(task)
|
||||
task.parse_confidence = None
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
|
||||
@@ -106,7 +106,7 @@ def run_shipping_parse_via_dify(task_no: str) -> dict[str, Any]:
|
||||
"""
|
||||
由后台排程器触发 Dify 处理单票发货通知解析。
|
||||
|
||||
这里不做批次循环,只让 Dify 完成“当前票 AI 解析 + parse_notice”这一步。
|
||||
这里不做批次循环,只让 Dify 完成“当前票 AI 订单抽取 + submit_order_extraction”这一步。
|
||||
"""
|
||||
task = get_task_by_ref(task_no)
|
||||
if not task:
|
||||
|
||||
@@ -152,7 +152,7 @@ def build_dify_chat_inputs(
|
||||
locale=locale,
|
||||
scope="task_run" if trigger_source == "backend_orchestrator" else "chat_turn",
|
||||
run_purpose=(
|
||||
"parse_notice"
|
||||
"order_extraction"
|
||||
if trigger_source == "backend_orchestrator"
|
||||
else ("temporary_inventory" if temporary_inventory_asset_no else ("order_extraction" if intake_nos else "chat_turn"))
|
||||
),
|
||||
|
||||
@@ -226,6 +226,44 @@ def create_draft_from_existing(template_id: int, *, actor_id: int | None) -> dic
|
||||
return _payload(item)
|
||||
|
||||
|
||||
def clone_as_new_template(template_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""复制任意已有模板为独立模板草稿,新编码从 v1 开始且不影响来源模板。"""
|
||||
source = db.session.get(ShippingExcelTemplate, template_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND')
|
||||
code = str(data.get('template_code') or '').strip().upper()
|
||||
name = str(data.get('display_name') or '').strip()
|
||||
if not code or not name or not re.fullmatch(r'[A-Z0-9_-]{2,64}', code):
|
||||
raise ValidationError('template_code and display_name are invalid', code='SHIPPING.EXCEL_TEMPLATE_INVALID')
|
||||
if ShippingExcelTemplate.query.filter_by(template_code=code).count():
|
||||
raise ConflictError('Template code already exists', code='SHIPPING.EXCEL_TEMPLATE_CODE_EXISTS')
|
||||
raw = file_asset_storage.get_bytes(source.storage_key)
|
||||
if hashlib.sha256(raw).hexdigest() != source.file_checksum:
|
||||
raise ValidationError('Template asset is missing or changed', code='SHIPPING.EXCEL_TEMPLATE_ASSET_INVALID')
|
||||
storage_key = _storage_key(code, 1)
|
||||
file_asset_storage.upload_bytes(
|
||||
storage_key=storage_key, data=raw,
|
||||
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
item = ShippingExcelTemplate(
|
||||
template_code=code, display_name=name, version=1, status='draft',
|
||||
storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key,
|
||||
original_filename=source.original_filename, file_checksum=hashlib.sha256(raw).hexdigest(),
|
||||
definition_json=json.loads(json.dumps(source.definition_json or {}, ensure_ascii=False)), created_by=actor_id,
|
||||
)
|
||||
try:
|
||||
db.session.add(item)
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
try:
|
||||
file_asset_storage.delete_object(storage_key)
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
return _payload(item)
|
||||
|
||||
|
||||
def _validate_definition(item: ShippingExcelTemplate) -> dict[str, Any]:
|
||||
"""验证模板定义、实际工作表和稳定字段引用,返回规范化定义。"""
|
||||
definition = item.definition_json if isinstance(item.definition_json, dict) else {}
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/extract.py
|
||||
|
||||
用途:抽取发货通知中的单头字段与订单行,并在收尾阶段补充文档级字段和告警。
|
||||
依赖:po_number、reservation_id、notice_lines 中的标准化与回填工具。
|
||||
逻辑:由 task_workflow.parse_notice 调用;优先 Dify 传入的 structured,无则走后端启发式规则兜底。
|
||||
逻辑:保留历史启发式文本工具;正式订单抽取已统一由 Dify 调用 get_order_extraction_context / submit_order_extraction。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -60,10 +60,10 @@ def extract_notice_fields(
|
||||
) -> tuple[dict[str, Any], float, list[str]]:
|
||||
"""
|
||||
抽取发货通知单头与订单行,并计算置信度与 warnings。
|
||||
【AI 触发时机】:由 parse_notice Tool 调用;Dify 画布/Agent 应先用 LLM 产出 structured 再传入,勿依赖本函数做 LLM 抽取。
|
||||
【AI 触发时机】:仅限内部文本预处理或迁移诊断;正式 Dify 画布不得调用本函数。
|
||||
|
||||
解析优先级:
|
||||
1. structured:Dify LLM/画布已抽取并传入 parse_notice
|
||||
1. structured:调用方已完成结构化抽取并传入
|
||||
2. 后端启发式规则(_heuristic_extract,仅作 Dify 无法实现时的兜底)
|
||||
|
||||
Args:
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
services/shipping_notice/fulfillment_workflow.py
|
||||
|
||||
用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传/RPA 与自动串联编排。
|
||||
依赖:customer_identity_gate、reservation_gate、match、export、rpa、query_service、inventory_workflow、inventory_mapping_workflow、task_line_store、tool_common、tool_response。
|
||||
依赖:customer_identity_gate、reservation_gate、match、export、rpa、query_service、inventory_workflow、inventory_mapping_workflow、动态订单字段、tool_common、tool_response。
|
||||
逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match;
|
||||
订单行读取统一经 read_task_order_lines。
|
||||
订单行按锁定 Schema 的业务用途从当前 Extraction FieldValue 读取。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -32,9 +32,9 @@ from app.services.shipping_notice.query_service import (
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
|
||||
from app.services.shipping_notice.order_field_purposes import task_line_purpose_values
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
|
||||
from app.services.shipping_notice.task_line_store import read_task_order_lines
|
||||
from app.services.shipping_notice.rpa import write_upload_trigger
|
||||
from app.services.shipping_notice.rpa_attempts import (
|
||||
max_rpa_upload_attempts,
|
||||
@@ -45,6 +45,7 @@ from app.services.shipping_notice.customer_identity_gate import customer_gate_to
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_common import prepend_tool_message, set_task_step_progress
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
from app.services.shipping_notice.task_disposition_service import task_execution_block_reason
|
||||
|
||||
|
||||
def _cfg_bool(key: str, default: bool = False) -> bool:
|
||||
@@ -56,6 +57,20 @@ def _cfg_bool(key: str, default: bool = False) -> bool:
|
||||
return str(val).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _task_disposition_gate_response(task: ShippingTask) -> dict[str, Any] | None:
|
||||
"""在履约副作用前阻断回收站、作废或归档任务,避免迟到请求继续改变业务事实。"""
|
||||
reason = task_execution_block_reason(task)
|
||||
if reason is None:
|
||||
return None
|
||||
return tool_response(
|
||||
status='failed',
|
||||
task=task,
|
||||
message='任务已删除、作废或归档,不能继续执行履约操作。',
|
||||
data={**serialize_task_for_tool(task), 'disposition_block_reason': reason},
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
|
||||
def _reservation_gate_response(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
@@ -72,7 +87,7 @@ def _reservation_gate_response(
|
||||
Returns:
|
||||
存在缺失/非法订单行时返回 needs_human,否则返回 None。
|
||||
"""
|
||||
issues = reservation_gate_issues(read_task_order_lines(task))
|
||||
issues = task_reservation_gate_issues(task)
|
||||
if not issues:
|
||||
return None
|
||||
detail = {
|
||||
@@ -268,6 +283,9 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
|
||||
disposition_gate = _task_disposition_gate_response(task)
|
||||
if disposition_gate is not None:
|
||||
return disposition_gate
|
||||
|
||||
customer_gate = customer_gate_tool_response(task, operation='match_inventory')
|
||||
if customer_gate is not None:
|
||||
@@ -309,14 +327,14 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if lang:
|
||||
inv_payload["lang"] = lang
|
||||
return ensure_inventory(inv_payload)
|
||||
notice_lines = read_task_order_lines(task)
|
||||
_order_header_values, order_field_lines = order_field_id_values(task)
|
||||
purpose_lines = task_line_purpose_values(task, required={'part_number', 'quantity', 'reservation_id'})
|
||||
for index, order_line in enumerate(order_field_lines):
|
||||
legacy_line = notice_lines[index] if index < len(notice_lines) else {}
|
||||
order_line['__required_qty'] = legacy_line.get('qty')
|
||||
order_line['__display_part_number'] = legacy_line.get('part_number')
|
||||
order_line['__display_reservation_id'] = legacy_line.get('reservation_id')
|
||||
total_notice_lines = len(notice_lines)
|
||||
purpose_line = purpose_lines[index] if index < len(purpose_lines) else {}
|
||||
order_line['__required_qty'] = purpose_line.get('quantity')
|
||||
order_line['__display_part_number'] = purpose_line.get('part_number')
|
||||
order_line['__display_reservation_id'] = purpose_line.get('reservation_id')
|
||||
total_notice_lines = len(order_field_lines)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
@@ -460,6 +478,9 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
|
||||
disposition_gate = _task_disposition_gate_response(task)
|
||||
if disposition_gate is not None:
|
||||
return disposition_gate
|
||||
|
||||
customer_gate = customer_gate_tool_response(task, operation='generate_excel')
|
||||
if customer_gate is not None:
|
||||
@@ -578,6 +599,9 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
|
||||
disposition_gate = _task_disposition_gate_response(task)
|
||||
if disposition_gate is not None:
|
||||
return disposition_gate
|
||||
|
||||
customer_gate = customer_gate_tool_response(task, operation='upload_to_freight')
|
||||
if customer_gate is not None:
|
||||
@@ -801,6 +825,9 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
|
||||
disposition_gate = _task_disposition_gate_response(task)
|
||||
if disposition_gate is not None:
|
||||
return disposition_gate
|
||||
|
||||
success = bool(payload.get("success", True))
|
||||
if success:
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
"""统一客户身份取证与影子候选解析入口。"""
|
||||
|
||||
from app.services.shipping_notice.identity_resolution.resolver import resolve_candidate_identity
|
||||
|
||||
__all__ = ['resolve_candidate_identity']
|
||||
@@ -0,0 +1,259 @@
|
||||
"""
|
||||
用途:基于已发布身份规则集产生客户主体与送货站点的可解释影子候选。
|
||||
依赖:身份规则快照、受控订单字段裁决值、客户/站点证据主数据和邮件接入元数据。
|
||||
逻辑:只读取邮件元数据及 accepted/corroborated Header FieldValue;站点候选独立保存,绝不反向确认客户主体。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from email.utils import parseaddr
|
||||
import hashlib
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerSite,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingIdentityRuleSet,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
)
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
normalize_customer_name,
|
||||
normalize_domain,
|
||||
normalize_email,
|
||||
)
|
||||
|
||||
RESOLUTION_VERSION = 'shadow-v2'
|
||||
ACCEPTED_DECISION_STATUSES = frozenset({'accepted', 'corroborated'})
|
||||
|
||||
|
||||
def _normalize(definition: dict[str, Any], value: object) -> str | None:
|
||||
"""按发布定义快照生成稳定匹配键;无效输入仅跳过当前证据而不影响其余取证。"""
|
||||
try:
|
||||
normalizer = str(definition.get('normalizer_key') or '')
|
||||
if normalizer == 'email':
|
||||
return normalize_email(value)
|
||||
if normalizer == 'domain':
|
||||
return normalize_domain(value)
|
||||
if normalizer == 'name':
|
||||
return normalize_customer_name(value) or None
|
||||
normalized = str(value or '').strip().upper()
|
||||
return normalized or None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _published_rule_set() -> ShippingIdentityRuleSet | None:
|
||||
"""读取唯一已发布规则集;未发布时安全返回空候选而不是回退旧硬编码规则。"""
|
||||
return ShippingIdentityRuleSet.query.filter_by(status='published').one_or_none()
|
||||
|
||||
|
||||
def _mail_values(intake: ShippingNoticeIntake) -> dict[str, str]:
|
||||
"""从接入邮件元数据取邮箱和域名投影,不读取订单解析或 LLM 摘要。"""
|
||||
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
email_meta = structured.get('email') if isinstance(structured.get('email'), dict) else {}
|
||||
sender = parseaddr(str(email_meta.get('from') or ''))[1].strip()
|
||||
if not sender:
|
||||
return {}
|
||||
try:
|
||||
email = normalize_email(sender)
|
||||
domain = normalize_domain(email)
|
||||
except Exception:
|
||||
return {}
|
||||
return {'email': email, 'domain': domain}
|
||||
|
||||
|
||||
def _template_fingerprint(candidate: ShippingNoticeCandidate) -> str | None:
|
||||
"""由主文档文本生成脱敏模板指纹;只保留哈希,不将正文或个人信息写入识别快照。"""
|
||||
document = db.session.get(ShippingNoticeDocument, int(candidate.primary_document_id))
|
||||
if document is None or int(document.intake_id) != int(candidate.intake_id):
|
||||
return None
|
||||
text = str(document.extracted_text or '').upper().strip()
|
||||
if not text:
|
||||
return None
|
||||
# 订单编号、日期、金额等可变字面量不参与模板身份,减少同模板不同订单的误分裂。
|
||||
template_shape = re.sub(r'\b[A-Z0-9][A-Z0-9_\-/]{2,}\b', '<TOKEN>', text)
|
||||
template_shape = re.sub(r'\d+', '<NUMBER>', template_shape)
|
||||
template_shape = re.sub(r'\s+', ' ', template_shape).strip()
|
||||
if not template_shape:
|
||||
return None
|
||||
return hashlib.sha256(template_shape.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _accepted_header_values(candidate: ShippingNoticeCandidate) -> tuple[ShippingOrderExtraction | None, dict[str, str]]:
|
||||
"""仅从 Candidate 外键关联的已裁决 Header FieldValue 读取业务证据,拒绝原始 JSON 和 Line 字段。"""
|
||||
if candidate.order_extraction_id is None:
|
||||
return None, {}
|
||||
extraction = db.session.get(ShippingOrderExtraction, int(candidate.order_extraction_id))
|
||||
if extraction is None or int(extraction.intake_id) != int(candidate.intake_id):
|
||||
return None, {}
|
||||
rows = (
|
||||
db.session.query(ShippingOrderFieldValue, ShippingOrderFieldDecision)
|
||||
.join(ShippingOrderFieldDecision, ShippingOrderFieldDecision.id == ShippingOrderFieldValue.decision_id)
|
||||
.filter(
|
||||
ShippingOrderFieldValue.extraction_id == extraction.id,
|
||||
ShippingOrderFieldValue.line_id.is_(None),
|
||||
ShippingOrderFieldDecision.line_id.is_(None),
|
||||
ShippingOrderFieldDecision.decision_status.in_(ACCEPTED_DECISION_STATUSES),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
return extraction, {
|
||||
str(value.field_id): str(value.value_text or value.value_json or '').strip()
|
||||
for value, _decision in rows
|
||||
if str(value.value_text or value.value_json or '').strip()
|
||||
}
|
||||
|
||||
|
||||
def _source_evidence(
|
||||
definitions: list[dict[str, Any]], *, candidate: ShippingNoticeCandidate, intake: ShippingNoticeIntake,
|
||||
) -> tuple[list[dict[str, Any]], ShippingOrderExtraction | None]:
|
||||
"""按规则快照的受控来源适配器编译证据输入,拒绝按定义编码决定取值。"""
|
||||
extraction, header_values = _accepted_header_values(candidate)
|
||||
mail_values = _mail_values(intake)
|
||||
template_fingerprint = _template_fingerprint(candidate)
|
||||
evidence: list[dict[str, Any]] = []
|
||||
for definition in definitions:
|
||||
definition_id = str(definition.get('id') or '')
|
||||
code = str(definition.get('definition_code') or '')
|
||||
adapter_key = str(definition.get('source_adapter_key') or '')
|
||||
selector = definition.get('source_selector') if isinstance(definition.get('source_selector'), dict) else {}
|
||||
value: str | None = None
|
||||
source: dict[str, Any] = {'kind': 'unsupported_source_adapter'}
|
||||
if adapter_key == 'order_field':
|
||||
field_id = str(selector.get('order_field_id') or definition.get('order_field_id') or '')
|
||||
value = header_values.get(field_id)
|
||||
source = {'kind': 'order_field_value', 'order_field_id': field_id, 'extraction_id': extraction.id if extraction else None}
|
||||
elif adapter_key == 'email_metadata':
|
||||
projection = str(selector.get('projection') or '')
|
||||
if selector.get('attribute') == 'email.from' and projection in {'email', 'domain'}:
|
||||
value = mail_values.get(projection)
|
||||
source = {'kind': 'mail_metadata', 'attribute': 'email.from', 'projection': projection}
|
||||
elif adapter_key == 'document_template' and selector == {'document': 'primary'}:
|
||||
value = template_fingerprint
|
||||
source = {'kind': 'document_template_fingerprint', 'document_id': candidate.primary_document_id}
|
||||
if not value:
|
||||
continue
|
||||
normalized = _normalize(definition, value)
|
||||
if not normalized:
|
||||
continue
|
||||
evidence.append({
|
||||
'definition_id': definition_id,
|
||||
'definition_code': code,
|
||||
'source_adapter_key': adapter_key,
|
||||
'source_selector': selector,
|
||||
'target_type': definition.get('target_type'),
|
||||
'attribute_key': definition.get('attribute_key'),
|
||||
'raw_value': value,
|
||||
'normalized_value': normalized,
|
||||
'weight': int(definition.get('default_weight') or 0),
|
||||
'source': source,
|
||||
})
|
||||
return evidence, extraction
|
||||
|
||||
|
||||
def _customer_match_payload(customer: ShippingCustomer, *, score: float, reasons: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""构建客户候选快照,避免前端或后续流程回读可变主数据推断命中原因。"""
|
||||
return {
|
||||
'customer_id': customer.id,
|
||||
'standard_name': customer.standard_name,
|
||||
'short_code': customer.short_code,
|
||||
'score': score,
|
||||
'reasons': reasons,
|
||||
}
|
||||
|
||||
|
||||
def _rank_customer_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""按同定义已审核证据聚合客户候选;同分保留歧义,禁止排序取首条。"""
|
||||
scores: dict[int, float] = defaultdict(float)
|
||||
reasons: dict[int, list[dict[str, Any]]] = defaultdict(list)
|
||||
customers = {item.id: item for item in ShippingCustomer.query.filter_by(status='active').all()}
|
||||
for item in evidence:
|
||||
if item['target_type'] != 'customer':
|
||||
continue
|
||||
records = ShippingIdentityEvidence.query.filter_by(
|
||||
definition_id=item['definition_id'], normalized_value=item['normalized_value'], status='approved',
|
||||
).all()
|
||||
for record in records:
|
||||
customer = customers.get(record.customer_id) if record.customer_id is not None else None
|
||||
if customer is None:
|
||||
continue
|
||||
scores[customer.id] += item['weight']
|
||||
reasons[customer.id].append({**item, 'evidence_id': record.id, 'match_kind': 'approved_identity_evidence'})
|
||||
return sorted(
|
||||
[_customer_match_payload(customers[customer_id], score=score, reasons=reasons[customer_id]) for customer_id, score in scores.items()],
|
||||
key=lambda item: (-float(item['score']), int(item['customer_id'])),
|
||||
)
|
||||
|
||||
|
||||
def _rank_site_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""独立聚合站点候选;站点命中仅供 Ship-to 人工复核,不构成客户主体候选。"""
|
||||
scores: dict[int, float] = defaultdict(float)
|
||||
reasons: dict[int, list[dict[str, Any]]] = defaultdict(list)
|
||||
customers = {item.id: item for item in ShippingCustomer.query.filter_by(status='active').all()}
|
||||
sites = {
|
||||
item.id: item for item in ShippingCustomerSite.query.filter_by(status='active').all()
|
||||
if item.customer_id in customers
|
||||
}
|
||||
for item in evidence:
|
||||
if item['target_type'] != 'site':
|
||||
continue
|
||||
records = ShippingIdentityEvidence.query.filter_by(
|
||||
definition_id=item['definition_id'], normalized_value=item['normalized_value'], status='approved',
|
||||
).all()
|
||||
for record in records:
|
||||
site = sites.get(record.site_id) if record.site_id is not None else None
|
||||
if site is None:
|
||||
continue
|
||||
scores[site.id] += item['weight']
|
||||
reasons[site.id].append({**item, 'evidence_id': record.id, 'match_kind': 'approved_identity_evidence'})
|
||||
return sorted([
|
||||
{
|
||||
'site_id': site_id,
|
||||
'site_name': sites[site_id].site_name,
|
||||
'site_code': sites[site_id].site_code,
|
||||
'customer_id': sites[site_id].customer_id,
|
||||
'customer_name': customers[sites[site_id].customer_id].standard_name,
|
||||
'score': score,
|
||||
'reasons': reasons[site_id],
|
||||
}
|
||||
for site_id, score in scores.items()
|
||||
], key=lambda item: (-float(item['score']), int(item['site_id'])))
|
||||
|
||||
|
||||
def resolve_candidate_identity(candidate: ShippingNoticeCandidate, intake: ShippingNoticeIntake) -> dict[str, Any]:
|
||||
"""
|
||||
解析一个 Candidate 的身份影子候选。
|
||||
|
||||
仅在 Candidate/Intake 已持久化后调用;返回快照数据,不绑定业务单、不编号,也不读取 raw_llm_output_json。
|
||||
"""
|
||||
rule_set = _published_rule_set()
|
||||
definitions = list((rule_set.definition_json or {}).get('definitions') or []) if rule_set else []
|
||||
evidence, extraction = _source_evidence(definitions, candidate=candidate, intake=intake)
|
||||
customer_matches = _rank_customer_matches(evidence)
|
||||
site_matches = _rank_site_matches(evidence)
|
||||
top_score = float(customer_matches[0]['score']) if customer_matches else None
|
||||
tied = [item for item in customer_matches if float(item['score']) == top_score] if top_score is not None else []
|
||||
return {
|
||||
'resolution_version': RESOLUTION_VERSION,
|
||||
'status': 'unmatched' if not customer_matches else 'unique_candidate' if len(tied) == 1 else 'ambiguous',
|
||||
'evidence': evidence,
|
||||
'customer_matches': customer_matches,
|
||||
'site_matches': site_matches,
|
||||
'rule_set': {
|
||||
'id': rule_set.id if rule_set else None,
|
||||
'version': rule_set.version if rule_set else None,
|
||||
'checksum': rule_set.checksum if rule_set else None,
|
||||
'definitions': definitions,
|
||||
},
|
||||
'order_schema_version_id': extraction.schema_version_id if extraction else None,
|
||||
'order_extraction_id': extraction.id if extraction else None,
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
"""货代客户识别规则领域服务包。"""
|
||||
@@ -0,0 +1,572 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/identity_rules/service.py
|
||||
|
||||
用途:管理货代客户识别定义、规则集版本和新证据值。
|
||||
依赖:订单 Schema 字段目录、客户/站点主数据、customer_normalization、统一异常。
|
||||
逻辑:平台只提供受控来源适配器;所有定义由管理员创建,发布规则集冻结全量快照。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerLifecycleEvent,
|
||||
ShippingCustomerSite,
|
||||
ShippingIdentityDefinition,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingIdentityRuleAuditEvent,
|
||||
ShippingIdentityRuleSet,
|
||||
ShippingOrderField,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
clean_text,
|
||||
is_public_email_domain,
|
||||
normalize_customer_name,
|
||||
normalize_domain,
|
||||
normalize_email,
|
||||
)
|
||||
|
||||
DEFINITION_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,63}$')
|
||||
TARGET_TYPES = frozenset({'customer', 'site'})
|
||||
SOURCE_ADAPTERS = {
|
||||
'email_metadata': {
|
||||
'display_name': '邮件发件人',
|
||||
'description': '从来件的发件人读取完整邮箱或企业域名。',
|
||||
'selectors': {'attribute': 'email.from', 'projections': {'email', 'domain'}},
|
||||
'options': {
|
||||
'email': {'display_name': '发件人邮箱', 'normalizer_key': 'email', 'max_automation': 'conditional'},
|
||||
'domain': {'display_name': '企业域名', 'normalizer_key': 'domain', 'max_automation': 'conditional'},
|
||||
},
|
||||
},
|
||||
'document_template': {
|
||||
'display_name': '单据版式',
|
||||
'description': '根据主单据的固定版式特征识别。',
|
||||
'selectors': {'document': 'primary'},
|
||||
'options': {
|
||||
'template': {'display_name': '当前单据版式', 'normalizer_key': 'text_upper', 'max_automation': 'conditional'},
|
||||
},
|
||||
},
|
||||
'order_field': {
|
||||
'display_name': '已解析订单字段',
|
||||
'description': '读取已发布订单字段中已经确认的内容,仅供人工复核使用。',
|
||||
'options': {},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _copy(value: Any) -> Any:
|
||||
"""复制目录或快照值,并将集合规范化为稳定 JSON 数组避免 API 序列化失败。"""
|
||||
def _json_default(item: Any) -> list[Any]:
|
||||
if isinstance(item, (set, frozenset)):
|
||||
return sorted(item)
|
||||
raise TypeError(f'Unsupported JSON value: {type(item).__name__}')
|
||||
|
||||
return json.loads(json.dumps(value, ensure_ascii=True, default=_json_default))
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
"""输出可空时间的 API ISO 值。"""
|
||||
return value.isoformat() if value else None
|
||||
|
||||
|
||||
def _definition_payload(row: ShippingIdentityDefinition, *, field: ShippingOrderField | None = None) -> dict[str, Any]:
|
||||
"""序列化识别定义及其稳定订单字段引用,不依赖前端自行判定权限。"""
|
||||
field = field or (db.session.get(ShippingOrderField, row.order_field_id) if row.order_field_id else None)
|
||||
return {
|
||||
'id': row.id,
|
||||
'definition_code': row.definition_code,
|
||||
'display_name': row.display_name or row.definition_code,
|
||||
'description': row.description,
|
||||
'evidence_label': row.evidence_label or '识别证据',
|
||||
'target_type': row.target_type,
|
||||
'source_adapter_key': row.source_adapter_key,
|
||||
'source_selector': _copy(row.source_selector_json or {}),
|
||||
'attribute_key': row.attribute_key,
|
||||
'order_field_id': row.order_field_id,
|
||||
'order_field': ({
|
||||
'field_id': field.id, 'field_code': field.field_code, 'display_name': _field_catalog_item(field)['display_name'],
|
||||
'scope': field.scope, 'value_type': field.value_type, 'status': field.status,
|
||||
} if field else None),
|
||||
'normalizer_key': row.normalizer_key,
|
||||
'comparator_key': row.comparator_key,
|
||||
'default_weight': row.default_weight,
|
||||
'max_automation': row.max_automation,
|
||||
'status': row.status,
|
||||
'created_at': _iso(row.created_at),
|
||||
'updated_at': _iso(row.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _write_audit(
|
||||
event_type: str, *, definition: ShippingIdentityDefinition | None = None,
|
||||
rule_set: ShippingIdentityRuleSet | None = None, actor_id: int | None = None,
|
||||
request_id: str | None = None, before: dict[str, Any] | None = None,
|
||||
after: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""追加定义或规则集变更快照;与调用方业务写入处于同一事务。"""
|
||||
db.session.add(ShippingIdentityRuleAuditEvent(
|
||||
event_type=event_type,
|
||||
definition_id=definition.id if definition else None,
|
||||
rule_set_id=rule_set.id if rule_set else None,
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
before_snapshot_json=_copy(before) if before is not None else None,
|
||||
after_snapshot_json=_copy(after) if after is not None else None,
|
||||
))
|
||||
|
||||
|
||||
def _source_adapter_catalog() -> list[dict[str, Any]]:
|
||||
"""返回只读来源适配器目录;客户端只能选择受控参数,不能提交任意取值路径。"""
|
||||
return [
|
||||
{
|
||||
'key': key,
|
||||
'display_name': value['display_name'],
|
||||
'description': value['description'],
|
||||
'selectors': _copy(value.get('selectors') or {}),
|
||||
'options': _copy(value.get('options') or {}),
|
||||
}
|
||||
for key, value in SOURCE_ADAPTERS.items()
|
||||
]
|
||||
|
||||
|
||||
def _validate_source(
|
||||
*, adapter_key: str, selector: object, field_id: str, target_type: str,
|
||||
) -> tuple[dict[str, Any], ShippingOrderField | None, str, str, str]:
|
||||
"""校验受控来源并推导内部执行参数,业务端不能提交属性或自动化等级。"""
|
||||
adapter = SOURCE_ADAPTERS.get(adapter_key)
|
||||
if adapter is None or not isinstance(selector, dict):
|
||||
raise ValidationError('Identity definition source is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
if adapter_key == 'order_field':
|
||||
field = _published_header_field(field_id)
|
||||
expected = {'order_field_id': field.id}
|
||||
if selector != expected:
|
||||
raise ValidationError('Identity definition source is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
return expected, field, 'text_upper', 'order_field_value', 'none'
|
||||
if field_id:
|
||||
raise ValidationError('Identity definition source is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
if adapter_key == 'email_metadata':
|
||||
if target_type != 'customer':
|
||||
raise ValidationError('Identity definition source is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
projection = clean_text(selector.get('projection')).lower()
|
||||
if selector != {'attribute': 'email.from', 'projection': projection} or projection not in {'email', 'domain'}:
|
||||
raise ValidationError('Identity definition source is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
option = adapter['options'][projection]
|
||||
return {'attribute': 'email.from', 'projection': projection}, None, option['normalizer_key'], projection, option['max_automation']
|
||||
if adapter_key == 'document_template':
|
||||
if target_type != 'customer' or selector != {'document': 'primary'}:
|
||||
raise ValidationError('Identity definition source is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
option = adapter['options']['template']
|
||||
return {'document': 'primary'}, None, option['normalizer_key'], 'template', option['max_automation']
|
||||
raise ValidationError('Identity definition source is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
|
||||
|
||||
def _published_header_field(field_id: str) -> ShippingOrderField:
|
||||
"""验证业务来源字段已发布、启用且为可识别的 Header 文本字段。"""
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
if field is None or field.status != 'active' or field.scope != 'header' or field.value_type not in {'string', 'enum'}:
|
||||
raise ValidationError('Identity order field is invalid', code='SHIPPING.IDENTITY_ORDER_FIELD_INVALID')
|
||||
published = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
enabled_ids = {
|
||||
str(item.get('field_id')) for item in ((published.definition_json if published else {}) or {}).get('fields', [])
|
||||
if item.get('enabled', True)
|
||||
}
|
||||
if field.id not in enabled_ids:
|
||||
raise ValidationError('Identity order field is not published', code='SHIPPING.IDENTITY_ORDER_FIELD_INVALID')
|
||||
return field
|
||||
|
||||
|
||||
def list_definitions(*, target_type: str | None = None, active_only: bool = False) -> dict[str, Any]:
|
||||
"""返回管理端可选择的识别定义和当前已发布 Header 字段目录。"""
|
||||
query = ShippingIdentityDefinition.query
|
||||
if target_type:
|
||||
if target_type not in TARGET_TYPES:
|
||||
raise ValidationError('Identity target type is invalid', code='SHIPPING.IDENTITY_TARGET_INVALID')
|
||||
query = query.filter_by(target_type=target_type)
|
||||
if active_only:
|
||||
query = query.filter_by(status='active')
|
||||
rows = query.order_by(ShippingIdentityDefinition.definition_code).all()
|
||||
return {
|
||||
'definitions': [_definition_payload(row) for row in rows],
|
||||
'order_fields': [_field_catalog_item(row) for row in _published_header_fields()],
|
||||
'catalog': {
|
||||
'target_types': sorted(TARGET_TYPES),
|
||||
'source_adapters': _source_adapter_catalog(),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def list_published_evidence_definitions(*, target_type: str | None = None) -> dict[str, Any]:
|
||||
"""返回当前发布规则集中可维护证据值的业务定义,避免录入未投产配置。"""
|
||||
if target_type is not None and target_type not in TARGET_TYPES:
|
||||
raise ValidationError('Identity target type is invalid', code='SHIPPING.IDENTITY_TARGET_INVALID')
|
||||
rule_set = ShippingIdentityRuleSet.query.filter_by(status='published').one_or_none()
|
||||
snapshots = list((rule_set.definition_json or {}).get('definitions') or []) if rule_set else []
|
||||
definitions = [
|
||||
item for item in snapshots
|
||||
if (target_type is None or item.get('target_type') == target_type)
|
||||
]
|
||||
return {
|
||||
'rule_set': _rule_set_payload(rule_set, include_definition=False) if rule_set else None,
|
||||
'definitions': definitions,
|
||||
'disabled_reason': None if rule_set else 'published_rule_set_required',
|
||||
}
|
||||
|
||||
|
||||
def _published_header_fields() -> list[ShippingOrderField]:
|
||||
"""读取当前发布版本实际纳入契约的 Header 文本字段。"""
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
if version is None:
|
||||
return []
|
||||
ids = [str(item.get('field_id')) for item in (version.definition_json or {}).get('fields', [])
|
||||
if item.get('enabled', True) and item.get('scope') == 'header' and item.get('value_type') in {'string', 'enum'}]
|
||||
return ShippingOrderField.query.filter(ShippingOrderField.id.in_(ids), ShippingOrderField.status == 'active').all() if ids else []
|
||||
|
||||
|
||||
def _field_catalog_item(field: ShippingOrderField) -> dict[str, Any]:
|
||||
"""返回可供业务人员选择的已发布订单字段,稳定编码仅作回退展示。"""
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
snapshot = next((item for item in ((version.definition_json if version else {}) or {}).get('fields', [])
|
||||
if str(item.get('field_id')) == field.id), {})
|
||||
display_name = clean_text(snapshot.get('display_name')) or field.field_code
|
||||
return {
|
||||
'field_id': field.id, 'field_code': field.field_code, 'display_name': display_name,
|
||||
'scope': field.scope, 'value_type': field.value_type,
|
||||
}
|
||||
|
||||
|
||||
def save_definition(data: dict[str, Any], *, actor_id: int | None, request_id: str | None = None,
|
||||
definition_id: str | None = None) -> dict[str, Any]:
|
||||
"""创建或更新业务识别定义;执行属性和自动化上限只由受控来源推导。"""
|
||||
row = db.session.get(ShippingIdentityDefinition, definition_id) if definition_id else None
|
||||
if definition_id and row is None:
|
||||
raise NotFoundError('Identity definition not found', code='SHIPPING.IDENTITY_DEFINITION_NOT_FOUND')
|
||||
display_name = clean_text(data.get('display_name'))
|
||||
description = clean_text(data.get('description')) or None
|
||||
evidence_label = clean_text(data.get('evidence_label'))
|
||||
code = clean_text(data.get('definition_code')).lower() or f'identity_rule_{uuid.uuid4().hex[:12]}'
|
||||
target = clean_text(data.get('target_type')).lower()
|
||||
field_id = clean_text(data.get('order_field_id'))
|
||||
adapter_key = clean_text(data.get('source_adapter_key')).lower()
|
||||
selector = data.get('source_selector')
|
||||
if not DEFINITION_CODE_RE.fullmatch(code) or target not in TARGET_TYPES:
|
||||
raise ValidationError('Identity definition is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
# 兼容服务层既有调用;管理端新建规则始终提交业务名称与证据名称。
|
||||
display_name = display_name or code
|
||||
evidence_label = evidence_label or display_name
|
||||
selector, field, normalizer, attribute, automation = _validate_source(
|
||||
adapter_key=adapter_key, selector=selector, field_id=field_id, target_type=target,
|
||||
)
|
||||
comparator = 'normalized_exact'
|
||||
requested_automation = clean_text(data.get('max_automation')).lower() if 'max_automation' in data else automation
|
||||
if requested_automation not in {'none', automation}:
|
||||
raise ValidationError('Identity definition automation is invalid', code='SHIPPING.IDENTITY_AUTOMATION_FORBIDDEN')
|
||||
before = _definition_payload(row) if row else None
|
||||
try:
|
||||
weight = int(data.get('default_weight') or 0)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Identity definition weight is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID') from exc
|
||||
if not 0 <= weight <= 1000:
|
||||
raise ValidationError('Identity definition weight is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
row = row or ShippingIdentityDefinition(
|
||||
definition_code=code, display_name=display_name, description=description, evidence_label=evidence_label,
|
||||
target_type=target, source_adapter_key=adapter_key, source_selector_json=selector,
|
||||
attribute_key=attribute, order_field_id=field.id if field else None, normalizer_key=normalizer, comparator_key=comparator,
|
||||
default_weight=weight, max_automation=automation,
|
||||
created_by_id=actor_id,
|
||||
)
|
||||
row.definition_code = code
|
||||
row.display_name = display_name
|
||||
row.description = description
|
||||
row.evidence_label = evidence_label
|
||||
row.target_type = target
|
||||
row.source_adapter_key = adapter_key
|
||||
row.source_selector_json = selector
|
||||
row.attribute_key = attribute
|
||||
row.order_field_id = field.id if field else None
|
||||
row.normalizer_key = normalizer
|
||||
row.comparator_key = comparator
|
||||
row.default_weight = weight
|
||||
row.max_automation = automation
|
||||
row.updated_by_id = actor_id
|
||||
if row.id is None:
|
||||
db.session.add(row)
|
||||
db.session.flush()
|
||||
after = _definition_payload(row, field=field)
|
||||
_write_audit('definition_updated' if before else 'definition_created', definition=row, actor_id=actor_id,
|
||||
request_id=request_id, before=before, after=after)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Identity definition conflict', code='SHIPPING.IDENTITY_DEFINITION_CONFLICT') from exc
|
||||
return after
|
||||
|
||||
|
||||
def retire_definition(definition_id: str, *, actor_id: int | None, request_id: str | None = None) -> dict[str, Any]:
|
||||
"""退役管理员业务定义;已有证据值不被物理删除以保留审计。"""
|
||||
row = db.session.get(ShippingIdentityDefinition, definition_id)
|
||||
if row is None:
|
||||
raise NotFoundError('Identity definition not found', code='SHIPPING.IDENTITY_DEFINITION_NOT_FOUND')
|
||||
before = _definition_payload(row)
|
||||
row.status = 'retired'
|
||||
row.updated_by_id = actor_id
|
||||
after = _definition_payload(row)
|
||||
_write_audit('definition_retired', definition=row, actor_id=actor_id, request_id=request_id, before=before, after=after)
|
||||
db.session.commit()
|
||||
return after
|
||||
|
||||
|
||||
def _definition_snapshot(row: ShippingIdentityDefinition) -> dict[str, Any]:
|
||||
"""生成规则发布所需的不可变定义快照。"""
|
||||
return _definition_payload(row)
|
||||
|
||||
|
||||
def _rule_set_payload(row: ShippingIdentityRuleSet, *, include_definition: bool = True) -> dict[str, Any]:
|
||||
"""序列化规则集版本,草稿和发布均以 definition_json 作为唯一真相。"""
|
||||
result = {
|
||||
'id': row.id, 'version': row.version, 'status': row.status, 'lock_version': row.lock_version,
|
||||
'checksum': row.checksum, 'change_note': row.change_note, 'source_rule_set_id': row.source_rule_set_id,
|
||||
'published_at': _iso(row.published_at), 'retired_at': _iso(row.retired_at),
|
||||
'created_at': _iso(row.created_at), 'updated_at': _iso(row.updated_at),
|
||||
}
|
||||
if include_definition:
|
||||
result['definition'] = _copy(row.definition_json or {'definitions': []})
|
||||
return result
|
||||
|
||||
|
||||
def create_rule_set(data: dict[str, Any], *, actor_id: int | None, request_id: str | None = None) -> dict[str, Any]:
|
||||
"""从当前定义目录或不可变历史版本创建下一份规则集草稿。"""
|
||||
source_id = data.get('copy_from_rule_set_id')
|
||||
source = db.session.get(ShippingIdentityRuleSet, int(source_id)) if str(source_id or '').isdigit() else None
|
||||
if source_id is not None and (source is None or source.status not in {'published', 'retired'}):
|
||||
raise ValidationError('Source identity rule set is invalid', code='SHIPPING.IDENTITY_RULE_SET_INVALID')
|
||||
version = (db.session.query(func.max(ShippingIdentityRuleSet.version)).scalar() or 0) + 1
|
||||
definition = _copy(source.definition_json) if source else {
|
||||
'definitions': [_definition_snapshot(row) for row in ShippingIdentityDefinition.query.filter_by(status='active').order_by(ShippingIdentityDefinition.definition_code).all()]
|
||||
}
|
||||
row = ShippingIdentityRuleSet(version=version, status='draft', definition_json=definition,
|
||||
source_rule_set_id=source.id if source else None, created_by_id=actor_id,
|
||||
change_note=clean_text(data.get('change_note')) or None)
|
||||
db.session.add(row)
|
||||
db.session.flush()
|
||||
_write_audit('rule_set_created', rule_set=row, actor_id=actor_id, request_id=request_id, after=_rule_set_payload(row))
|
||||
db.session.commit()
|
||||
return _rule_set_payload(row)
|
||||
|
||||
|
||||
def save_rule_set(rule_set_id: int, data: dict[str, Any], *, actor_id: int | None,
|
||||
request_id: str | None = None) -> dict[str, Any]:
|
||||
"""保存规则集草稿;只允许引用当前启用定义并采用乐观锁。"""
|
||||
row = db.session.get(ShippingIdentityRuleSet, rule_set_id)
|
||||
if row is None:
|
||||
raise NotFoundError('Identity rule set not found', code='SHIPPING.IDENTITY_RULE_SET_NOT_FOUND')
|
||||
if row.status != 'draft':
|
||||
raise ConflictError('Published identity rule set is immutable', code='SHIPPING.IDENTITY_RULE_SET_IMMUTABLE')
|
||||
if data.get('expected_lock_version') != row.lock_version:
|
||||
raise ConflictError('Identity rule set changed', code='SHIPPING.IDENTITY_RULE_SET_CONFLICT')
|
||||
ids = data.get('definition_ids')
|
||||
if not isinstance(ids, list) or not ids:
|
||||
raise ValidationError('Identity rule definitions are required', code='SHIPPING.IDENTITY_RULE_SET_INVALID')
|
||||
if len({str(item) for item in ids}) != len(ids):
|
||||
raise ValidationError('Identity rule definitions are duplicated', code='SHIPPING.IDENTITY_RULE_SET_INVALID')
|
||||
rows = ShippingIdentityDefinition.query.filter(ShippingIdentityDefinition.id.in_([str(item) for item in ids]), ShippingIdentityDefinition.status == 'active').all()
|
||||
if len(rows) != len(ids):
|
||||
raise ValidationError('Identity rule definition is invalid', code='SHIPPING.IDENTITY_RULE_SET_INVALID')
|
||||
before = _rule_set_payload(row)
|
||||
row.definition_json = {'definitions': [_definition_snapshot(item) for item in sorted(rows, key=lambda item: item.definition_code)]}
|
||||
row.lock_version += 1
|
||||
row.change_note = clean_text(data.get('change_note')) or row.change_note
|
||||
after = _rule_set_payload(row)
|
||||
_write_audit('rule_set_saved', rule_set=row, actor_id=actor_id, request_id=request_id, before=before, after=after)
|
||||
db.session.commit()
|
||||
return after
|
||||
|
||||
|
||||
def publish_rule_set(rule_set_id: int, *, expected_lock_version: int | None, actor_id: int | None,
|
||||
request_id: str | None = None) -> dict[str, Any]:
|
||||
"""发布规则集并退役前一版本;发布快照 checksum 是运行期审计锚点。"""
|
||||
row = db.session.get(ShippingIdentityRuleSet, rule_set_id)
|
||||
if row is None:
|
||||
raise NotFoundError('Identity rule set not found', code='SHIPPING.IDENTITY_RULE_SET_NOT_FOUND')
|
||||
if row.status != 'draft' or expected_lock_version != row.lock_version:
|
||||
raise ConflictError('Identity rule set cannot be published', code='SHIPPING.IDENTITY_RULE_SET_CONFLICT')
|
||||
definitions = (row.definition_json or {}).get('definitions') or []
|
||||
if not definitions:
|
||||
raise ValidationError('Identity rule definitions are required', code='SHIPPING.IDENTITY_RULE_SET_INVALID')
|
||||
active_ids = {item.id for item in ShippingIdentityDefinition.query.filter_by(status='active').all()}
|
||||
if any(str(item.get('id') or '') not in active_ids for item in definitions):
|
||||
raise ConflictError('Identity rule set references retired definitions', code='SHIPPING.IDENTITY_RULE_SET_CONFLICT')
|
||||
current = ShippingIdentityRuleSet.query.filter_by(status='published').one_or_none()
|
||||
now = datetime.utcnow()
|
||||
if current:
|
||||
current.status, current.retired_at = 'retired', now
|
||||
row.status, row.published_at, row.published_by_id = 'published', now, actor_id
|
||||
encoded = json.dumps(row.definition_json, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode('utf-8')
|
||||
row.checksum = hashlib.sha256(encoded).hexdigest()
|
||||
_write_audit('rule_set_published', rule_set=row, actor_id=actor_id, request_id=request_id, after=_rule_set_payload(row))
|
||||
db.session.commit()
|
||||
return _rule_set_payload(row)
|
||||
|
||||
|
||||
def list_rule_sets() -> dict[str, Any]:
|
||||
"""读取规则集版本列表和当前发布版本,供管理页追溯配置。"""
|
||||
return {'items': [_rule_set_payload(row) for row in ShippingIdentityRuleSet.query.order_by(ShippingIdentityRuleSet.version.desc()).all()]}
|
||||
|
||||
|
||||
def _normalize_for_definition(definition: ShippingIdentityDefinition, value: object) -> str:
|
||||
"""按定义受控 normalizer 生成证据匹配键,禁止前端传入任意处理方式。"""
|
||||
if definition.normalizer_key == 'email':
|
||||
return normalize_email(value)
|
||||
if definition.normalizer_key == 'domain':
|
||||
return normalize_domain(value)
|
||||
if definition.normalizer_key == 'name':
|
||||
return normalize_customer_name(value)
|
||||
result = clean_text(value).upper()
|
||||
if not result:
|
||||
raise ValidationError('Identity evidence value is required', code='SHIPPING.IDENTITY_EVIDENCE_VALUE_REQUIRED')
|
||||
return result
|
||||
|
||||
|
||||
def create_evidence(*, target_type: str, target_id: int, data: dict[str, Any], actor_id: int | None) -> dict[str, Any]:
|
||||
"""为客户或站点创建按定义约束的新证据值;弱定义不可获自动确认授权。"""
|
||||
definition_id = clean_text(data.get('definition_id'))
|
||||
definition = db.session.get(ShippingIdentityDefinition, definition_id)
|
||||
if definition is None or definition.status != 'active' or definition.target_type != target_type:
|
||||
raise ValidationError('Identity definition cannot target this object', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
published = ShippingIdentityRuleSet.query.filter_by(status='published').one_or_none()
|
||||
published_ids = {
|
||||
str(item.get('id') or '') for item in ((published.definition_json if published else {}) or {}).get('definitions', [])
|
||||
}
|
||||
if definition.id not in published_ids:
|
||||
raise ValidationError('Identity definition is not published for evidence maintenance', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
target = db.session.get(ShippingCustomer if target_type == 'customer' else ShippingCustomerSite, target_id)
|
||||
if target is None or getattr(target, 'status', None) != 'active':
|
||||
raise ValidationError('Identity evidence target is invalid', code='SHIPPING.IDENTITY_TARGET_INVALID')
|
||||
if target_type == 'site':
|
||||
customer = db.session.get(ShippingCustomer, int(target.customer_id))
|
||||
if customer is None or customer.status != 'active':
|
||||
raise ValidationError('Identity evidence target is invalid', code='SHIPPING.IDENTITY_TARGET_INVALID')
|
||||
raw = clean_text(data.get('raw_value') or data.get('identifier_value'))
|
||||
normalized = _normalize_for_definition(definition, raw)
|
||||
status = clean_text(data.get('status') or 'pending').lower()
|
||||
allowed = data.get('auto_match_allowed', False)
|
||||
if status not in {'pending', 'approved', 'disabled'} or not isinstance(allowed, bool):
|
||||
raise ValidationError('Identity evidence status is invalid', code='SHIPPING.IDENTITY_EVIDENCE_INVALID')
|
||||
if allowed and (status != 'approved' or definition.max_automation != 'conditional'):
|
||||
raise ValidationError('Identity evidence cannot auto confirm', code='SHIPPING.IDENTITY_AUTOMATION_FORBIDDEN')
|
||||
if allowed and definition.attribute_key == 'domain' and is_public_email_domain(normalized):
|
||||
raise ValidationError('Public email domain cannot auto confirm', code='SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN')
|
||||
row = ShippingIdentityEvidence(
|
||||
definition_id=definition.id, customer_id=target_id if target_type == 'customer' else None,
|
||||
site_id=target_id if target_type == 'site' else None, raw_value=raw, normalized_value=normalized,
|
||||
status=status, auto_match_allowed=allowed, 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(row)
|
||||
customer_id = target_id if target_type == 'customer' else int(target.customer_id)
|
||||
customer = db.session.get(ShippingCustomer, customer_id)
|
||||
if customer is not None:
|
||||
db.session.add(ShippingCustomerLifecycleEvent(
|
||||
event_type='identity_evidence_created', customer_id_snapshot=customer.id,
|
||||
customer_name_snapshot=customer.standard_name, customer_short_code_snapshot=customer.short_code,
|
||||
actor_id=actor_id, detail_json={
|
||||
'definition_id': definition.id, 'definition_code': definition.definition_code,
|
||||
'target_type': target_type, 'target_id': target_id, 'normalized_value': normalized,
|
||||
'status': status, 'auto_match_allowed': allowed,
|
||||
},
|
||||
))
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Identity evidence conflict', code='SHIPPING.IDENTITY_EVIDENCE_CONFLICT') from exc
|
||||
return serialize_evidence(row)
|
||||
|
||||
|
||||
def update_evidence(evidence_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""审核、停用或授权已存在证据;自动化状态变更必须带原因并沿用定义上限。"""
|
||||
row = db.session.get(ShippingIdentityEvidence, evidence_id)
|
||||
if row is None:
|
||||
raise NotFoundError('Identity evidence not found', code='SHIPPING.IDENTITY_EVIDENCE_NOT_FOUND')
|
||||
definition = db.session.get(ShippingIdentityDefinition, row.definition_id)
|
||||
target_type = 'customer' if row.customer_id is not None else 'site'
|
||||
target_id = int(row.customer_id if row.customer_id is not None else row.site_id)
|
||||
target = db.session.get(ShippingCustomer if target_type == 'customer' else ShippingCustomerSite, target_id)
|
||||
if definition is None or target is None or getattr(target, 'status', None) != 'active':
|
||||
raise ValidationError('Identity evidence target is invalid', code='SHIPPING.IDENTITY_TARGET_INVALID')
|
||||
next_status = clean_text(data.get('status')).lower() if 'status' in data else row.status
|
||||
next_allowed = data.get('auto_match_allowed') if 'auto_match_allowed' in data else row.auto_match_allowed
|
||||
if next_status not in {'pending', 'approved', 'disabled'} or not isinstance(next_allowed, bool):
|
||||
raise ValidationError('Identity evidence status is invalid', code='SHIPPING.IDENTITY_EVIDENCE_INVALID')
|
||||
if next_status != 'approved':
|
||||
next_allowed = False
|
||||
if next_allowed and definition.max_automation != 'conditional':
|
||||
raise ValidationError('Identity evidence cannot auto confirm', code='SHIPPING.IDENTITY_AUTOMATION_FORBIDDEN')
|
||||
if next_allowed and definition.attribute_key == 'domain' and is_public_email_domain(row.normalized_value):
|
||||
raise ValidationError('Public email domain cannot auto confirm', code='SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN')
|
||||
next_remark = clean_text(data.get('remark')) or None if 'remark' in data else row.remark
|
||||
changed = (next_status, bool(next_allowed), next_remark) != (row.status, bool(row.auto_match_allowed), row.remark)
|
||||
if not changed:
|
||||
return serialize_evidence(row)
|
||||
reason = clean_text(data.get('reason'))
|
||||
if not reason:
|
||||
raise ValidationError('Identity evidence change reason is required', code='SHIPPING.CUSTOMER_CHANGE_REASON_REQUIRED')
|
||||
customer_id = int(row.customer_id) if row.customer_id is not None else int(target.customer_id)
|
||||
customer = db.session.get(ShippingCustomer, customer_id)
|
||||
before = {'status': row.status, 'auto_match_allowed': bool(row.auto_match_allowed), 'remark': row.remark}
|
||||
row.status, row.auto_match_allowed, row.remark = next_status, next_allowed, next_remark
|
||||
if next_status == 'approved' and row.confirmed_at is None:
|
||||
row.confirmed_by_id, row.confirmed_at = actor_id, datetime.utcnow()
|
||||
if customer is not None:
|
||||
db.session.add(ShippingCustomerLifecycleEvent(
|
||||
event_type='identity_evidence_updated', 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={
|
||||
'evidence_id': row.id, 'definition_id': row.definition_id, 'target_type': target_type,
|
||||
'target_id': target_id, 'before': before,
|
||||
'after': {'status': row.status, 'auto_match_allowed': bool(row.auto_match_allowed), 'remark': row.remark},
|
||||
},
|
||||
))
|
||||
db.session.commit()
|
||||
return serialize_evidence(row)
|
||||
|
||||
|
||||
def serialize_evidence(row: ShippingIdentityEvidence) -> dict[str, Any]:
|
||||
"""返回证据值及关联定义,供客户/站点管理端显示可解释身份属性。"""
|
||||
definition = db.session.get(ShippingIdentityDefinition, row.definition_id)
|
||||
return {
|
||||
'id': row.id, 'definition_id': row.definition_id, 'definition': _definition_payload(definition) if definition else None,
|
||||
'customer_id': row.customer_id, 'site_id': row.site_id, 'raw_value': row.raw_value,
|
||||
'normalized_value': row.normalized_value, 'status': row.status,
|
||||
'auto_match_allowed': bool(row.auto_match_allowed), 'remark': row.remark,
|
||||
'confirmed_at': _iso(row.confirmed_at), 'created_at': _iso(row.created_at), 'updated_at': _iso(row.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def active_definition_field_references(field_id: str) -> list[str]:
|
||||
"""供订单 Schema 退役/发布门禁查询仍被启用业务定义引用的稳定字段。"""
|
||||
references: list[str] = []
|
||||
if ShippingIdentityDefinition.query.filter_by(
|
||||
source_adapter_key='order_field', order_field_id=field_id, status='active',
|
||||
).count():
|
||||
references.append('identity_definition')
|
||||
if any(
|
||||
any(str(item.get('order_field_id') or '') == field_id for item in (rule_set.definition_json or {}).get('definitions', []))
|
||||
for rule_set in ShippingIdentityRuleSet.query.filter(ShippingIdentityRuleSet.status.in_(['draft', 'published'])).all()
|
||||
):
|
||||
references.append('identity_rule_set')
|
||||
return references
|
||||
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/intake_business_parser.py
|
||||
|
||||
用途:从发货通知抽取文本产出稳定业务摘要(预解析阶段,不创建 ShippingTask)。
|
||||
依赖:extract.extract_notice_fields、notice_lines。
|
||||
逻辑:由 intake_parse_workflow 在文本抽取成功后调用;与正式 parse_notice 共用字段口径。
|
||||
逻辑:由 intake_parse_workflow 在文本抽取成功后调用;仅作预解析摘要,不参与正式动态订单落库。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -852,9 +852,7 @@ def candidate_to_notice_item(
|
||||
'fingerprint_version': candidate.fingerprint_version,
|
||||
'content_fingerprint': candidate.content_fingerprint,
|
||||
'content_fingerprint_version': candidate.content_fingerprint_version,
|
||||
'structured': {
|
||||
**(structured.get('business_summary') or {}),
|
||||
},
|
||||
# Candidate 已持有锁定 Schema 的 FieldValue;建 Task 时不得再把旧摘要送入固定字段解析旁路。
|
||||
'document_version': 1,
|
||||
'duplicate_resolution_type': 'normal',
|
||||
'supersedes_task_id': None,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_configuration_test.py
|
||||
|
||||
用途:编排库存站点测试导出、RPA 回调文件分析和管理员确认解析方案。
|
||||
用途:编排库存站点测试导出、RPA 回调文件分析和自动启用判定。
|
||||
依赖:库存站点/RPA trigger、库存结构分析、库存解析方案模型。
|
||||
逻辑:管理端仅对停用站点发起测试;RPA 文件只写测试运行和结构分析,不创建生产快照、不关联订单任务。
|
||||
"""
|
||||
@@ -19,6 +19,7 @@ from app.models import (
|
||||
ShippingInventoryConfigurationTestRun,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventorySource,
|
||||
ShippingInventoryValidationBatch,
|
||||
)
|
||||
|
||||
|
||||
@@ -26,6 +27,7 @@ def _payload(run: ShippingInventoryConfigurationTestRun) -> dict[str, Any]:
|
||||
"""投影测试运行状态,避免暴露 RPA 文件的服务器路径。"""
|
||||
return {
|
||||
'id': run.id, 'run_no': run.run_no, 'inventory_source_id': run.inventory_source_id,
|
||||
'validation_batch_id': run.validation_batch_id, 'rpa_batch_run_no': run.rpa_batch_run_no,
|
||||
'source_config_version': run.source_config_version, 'rpa_profile_config_version': run.rpa_profile_config_version,
|
||||
'status': run.status, 'stage': run.stage,
|
||||
'analysis_id': run.analysis_id, 'result': run.result_json or {}, 'error_message': run.error_message,
|
||||
@@ -34,6 +36,174 @@ def _payload(run: ShippingInventoryConfigurationTestRun) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _batch_payload(batch: ShippingInventoryValidationBatch) -> dict[str, Any]:
|
||||
"""投影批量验证进度及其逐站点运行,供管理端按批次轮询。"""
|
||||
runs = ShippingInventoryConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).order_by(
|
||||
ShippingInventoryConfigurationTestRun.id.asc(),
|
||||
).all()
|
||||
return {
|
||||
'id': batch.id, 'batch_no': batch.batch_no, 'status': batch.status,
|
||||
'total_count': batch.total_count, 'success_count': batch.success_count,
|
||||
'empty_count': batch.empty_count, 'failed_count': batch.failed_count,
|
||||
'stale_count': batch.stale_count,
|
||||
'retry_of_batch_id': batch.retry_of_batch_id,
|
||||
'created_at': batch.created_at.isoformat() if batch.created_at else None,
|
||||
'completed_at': batch.completed_at.isoformat() if batch.completed_at else None,
|
||||
'runs': [_payload(run) for run in runs],
|
||||
}
|
||||
|
||||
|
||||
def _refresh_batch(batch_id: int | None) -> None:
|
||||
"""按逐站点终态重算批次汇总;一个站点失败绝不覆盖其他站点结果。"""
|
||||
if not batch_id:
|
||||
return
|
||||
batch = db.session.get(ShippingInventoryValidationBatch, batch_id)
|
||||
if batch is None:
|
||||
return
|
||||
runs = ShippingInventoryConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all()
|
||||
terminal = {'completed', 'completed_empty', 'failed'}
|
||||
batch.total_count = len(runs)
|
||||
batch.success_count = sum(run.status == 'completed' for run in runs)
|
||||
batch.empty_count = sum(run.status == 'completed_empty' for run in runs)
|
||||
batch.failed_count = sum(run.status == 'failed' for run in runs)
|
||||
batch.stale_count = sum(
|
||||
run.status == 'failed' and bool((run.result_json or {}).get('stale_configuration'))
|
||||
for run in runs
|
||||
)
|
||||
if not runs or not all(run.status in terminal for run in runs):
|
||||
batch.status = 'running'
|
||||
batch.completed_at = None
|
||||
elif batch.failed_count == 0:
|
||||
batch.status = 'completed'
|
||||
batch.completed_at = datetime.utcnow()
|
||||
elif batch.failed_count == len(runs):
|
||||
batch.status = 'failed'
|
||||
batch.completed_at = datetime.utcnow()
|
||||
else:
|
||||
batch.status = 'partial_failed'
|
||||
batch.completed_at = datetime.utcnow()
|
||||
|
||||
|
||||
def _validate_batch_sources(source_ids: list[int]) -> list[ShippingInventorySource]:
|
||||
"""预检批量验证站点,强制使用已发布解析定义以明确空库存的业务语义。"""
|
||||
ids: list[int] = []
|
||||
for source_id in source_ids:
|
||||
try:
|
||||
value = int(source_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('Inventory source ids must be positive integers', code='SHIPPING.INVENTORY_BATCH_SOURCE_REQUIRED')
|
||||
if value > 0 and value not in ids:
|
||||
ids.append(value)
|
||||
if not ids:
|
||||
raise ValidationError('At least one inventory source is required', code='SHIPPING.INVENTORY_BATCH_SOURCE_REQUIRED')
|
||||
sources = ShippingInventorySource.query.filter(ShippingInventorySource.id.in_(ids)).all()
|
||||
by_id = {source.id: source for source in sources}
|
||||
if len(by_id) != len(ids):
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
ordered = [by_id[source_id] for source_id in ids]
|
||||
for source in ordered:
|
||||
if source.enabled:
|
||||
raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID')
|
||||
if source.rpa_profile is None or not source.rpa_profile.enabled:
|
||||
raise ValidationError('Enabled RPA Profile is required', code='SHIPPING.RPA_PROFILE_DISABLED')
|
||||
if source.parsing_profile is None or source.parsing_profile.status != 'published':
|
||||
raise ValidationError('Published parsing profile is required for batch test', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
|
||||
_expire_timed_out_runs(source)
|
||||
active = ShippingInventoryConfigurationTestRun.query.filter(
|
||||
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
|
||||
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
|
||||
).first()
|
||||
if active:
|
||||
raise ConflictError('Inventory source already has an active configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_ACTIVE')
|
||||
return ordered
|
||||
|
||||
|
||||
def start_batch_test_export(source_ids: list[int], *, actor_id: int | None, retry_of_batch_id: int | None = None) -> dict[str, Any]:
|
||||
"""创建批量验证并按连接配置分组投递 RPA;每站点保留独立运行与回调结果。"""
|
||||
sources = _validate_batch_sources(source_ids)
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
|
||||
stamp = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
|
||||
batch = ShippingInventoryValidationBatch(
|
||||
batch_no=f'CONFIG-BATCH-{stamp}', status='queued', total_count=len(sources), created_by=actor_id,
|
||||
retry_of_batch_id=retry_of_batch_id,
|
||||
)
|
||||
db.session.add(batch)
|
||||
db.session.flush()
|
||||
grouped: dict[tuple[int, str], list[tuple[ShippingInventoryConfigurationTestRun, dict[str, Any]]]] = {}
|
||||
for source in sources:
|
||||
run = ShippingInventoryConfigurationTestRun(
|
||||
run_no=f'CONFIG-{source.source_code}-{stamp}-{source.id}', validation_batch_id=batch.id,
|
||||
inventory_source_id=source.id,
|
||||
source_config_version=source.config_version, rpa_profile_config_version=source.rpa_profile.config_version,
|
||||
status='awaiting_rpa', stage='waiting_worker', result_json={}, created_by=actor_id,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
source_payload = get_database_inventory_source(source.source_code, enabled_only=False)
|
||||
if source_payload is None:
|
||||
raise ValidationError('Inventory Source is invalid', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
|
||||
source_payload = {**source_payload, 'validation_run_no': run.run_no}
|
||||
grouped.setdefault((source.rpa_profile_id, source.connector_type), []).append((run, source_payload))
|
||||
db.session.commit()
|
||||
|
||||
for (profile_id, _connector), entries in grouped.items():
|
||||
group_run_no = f'{batch.batch_no}-P{profile_id}'
|
||||
for run, _source_payload in entries:
|
||||
run.rpa_batch_run_no = group_run_no
|
||||
db.session.commit()
|
||||
try:
|
||||
trigger = write_inventory_export_batch_trigger(group_run_no, [payload for _, payload in entries], payload={
|
||||
'trigger_type': 'configuration_test_batch', 'validation_batch_id': batch.id, 'batch_no': batch.batch_no,
|
||||
})
|
||||
if not trigger:
|
||||
raise RuntimeError('RPA Worker is not ready')
|
||||
for run, _source_payload in entries:
|
||||
run.result_json = {'trigger_written': True, 'validation_batch_id': batch.id}
|
||||
except Exception as exc:
|
||||
for run, _source_payload in entries:
|
||||
run.status = 'failed'; run.stage = 'failed'; run.error_message = str(exc)[:500]; run.completed_at = datetime.utcnow()
|
||||
_refresh_batch(batch.id)
|
||||
db.session.commit()
|
||||
return _batch_payload(batch)
|
||||
|
||||
|
||||
def get_validation_batch(batch_id: int) -> dict[str, Any]:
|
||||
"""返回批量验证当前汇总与逐站点结果,读取时同时收口超时任务。"""
|
||||
batch = db.session.get(ShippingInventoryValidationBatch, batch_id)
|
||||
if batch is None:
|
||||
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND')
|
||||
for run in ShippingInventoryConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all():
|
||||
source = db.session.get(ShippingInventorySource, run.inventory_source_id)
|
||||
if source is not None:
|
||||
_expire_timed_out_runs(source)
|
||||
_refresh_batch(batch.id)
|
||||
db.session.commit()
|
||||
return _batch_payload(batch)
|
||||
|
||||
|
||||
def get_latest_active_validation_batch() -> dict[str, Any] | None:
|
||||
"""恢复最近仍在执行的批量验证,供管理端刷新后继续查看真实进度。"""
|
||||
batch = ShippingInventoryValidationBatch.query.filter(
|
||||
ShippingInventoryValidationBatch.status.in_(['queued', 'running']),
|
||||
).order_by(ShippingInventoryValidationBatch.id.desc()).first()
|
||||
return get_validation_batch(batch.id) if batch is not None else None
|
||||
|
||||
|
||||
def retry_failed_validation_batch(batch_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""仅重新投递失败或配置已变更的站点,已成功及空库存站点不重复执行。"""
|
||||
batch = db.session.get(ShippingInventoryValidationBatch, batch_id)
|
||||
if batch is None:
|
||||
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND')
|
||||
failed_ids = [run.inventory_source_id for run in ShippingInventoryConfigurationTestRun.query.filter_by(
|
||||
validation_batch_id=batch.id, status='failed',
|
||||
).all()]
|
||||
if not failed_ids:
|
||||
raise ConflictError('No failed inventory validation runs to retry', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NO_FAILURE')
|
||||
return start_batch_test_export(failed_ids, actor_id=actor_id, retry_of_batch_id=batch.id)
|
||||
|
||||
|
||||
def _matches_current_configuration(run: ShippingInventoryConfigurationTestRun, source: ShippingInventorySource) -> bool:
|
||||
"""判断测试运行是否仍对应当前站点与 RPA 连接配置,避免旧任务阻塞新配置测试。"""
|
||||
return bool(
|
||||
@@ -141,14 +311,35 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(run_no=run_no).first()
|
||||
if run is None:
|
||||
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND')
|
||||
if run.status in {'completed', 'failed'}:
|
||||
if run.status in {'completed', 'completed_empty', 'failed'}:
|
||||
return _payload(run)
|
||||
source = db.session.get(ShippingInventorySource, run.inventory_source_id)
|
||||
if source is None or not _matches_current_configuration(run, source):
|
||||
run.status = 'failed'; run.stage = 'failed'; run.error_message = '库存站点配置已变更,请重新测试'; run.completed_at = datetime.utcnow()
|
||||
run.result_json = {**(run.result_json or {}), 'stale_configuration': True}
|
||||
_refresh_batch(run.validation_batch_id)
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
status = str(payload.get('status') or 'success').lower()
|
||||
if status == 'empty':
|
||||
# 空库存是查询业务结果,不代表登录、报表路径或 RPA 执行失败。
|
||||
if source.parsing_profile is None or source.parsing_profile.status != 'published':
|
||||
run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出无库存数据,且尚未绑定已发布库存解析方案'; run.completed_at = datetime.utcnow()
|
||||
else:
|
||||
run.status = 'completed_empty'; run.stage = 'empty_data_pending_validation'
|
||||
run.result_json = {
|
||||
'export_result': 'empty', 'structure_validation': 'not_observed',
|
||||
'data_validation': 'pending_first_non_empty_export',
|
||||
'message': str(payload.get('message') or '库存查询成功但当前无库存数据')[:500],
|
||||
'confirmed_profile_id': source.parsing_profile_id,
|
||||
'confirmed_profile_checksum': source.parsing_profile.checksum,
|
||||
}
|
||||
run.completed_at = datetime.utcnow()
|
||||
# 空库存同样证明当前配置可查询;全部必要条件满足时自动投入正式运行。
|
||||
from app.services.admin.shipping_inventory_service import activate_source_if_ready
|
||||
activate_source_if_ready(source, actor_id=run.created_by)
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
if status != 'success':
|
||||
run.status = 'failed'; run.stage = 'failed'; run.error_message = str(payload.get('error_message') or '测试导出失败')[:500]; run.completed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
@@ -180,7 +371,28 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
db.session.add(analysis); db.session.flush()
|
||||
analysis.match_result_json = recommend_profiles({'structure': structure, 'suggested_mapping': suggested, 'exact_structure_fingerprint': analysis.exact_structure_fingerprint, 'compatibility_fingerprint': analysis.compatibility_fingerprint})
|
||||
run.analysis_id = analysis.id; run.status = 'completed'; run.stage = 'ready_for_confirmation'; run.result_json = {'analysis': serialize_analysis(analysis)}; run.completed_at = datetime.utcnow()
|
||||
current_profile_candidate = next((
|
||||
candidate for candidate in (analysis.match_result_json.get('candidates') or [])
|
||||
if int(candidate.get('profile_id') or 0) == int(source.parsing_profile_id or 0)
|
||||
), None)
|
||||
run.analysis_id = analysis.id; run.status = 'completed'
|
||||
if current_profile_candidate is not None:
|
||||
# 当前绑定的方案已验证时,测试应直接成为站点启用证据,无需管理员重复确认相同方案。
|
||||
run.stage = 'current_profile_verified'
|
||||
run.result_json = {
|
||||
'analysis': serialize_analysis(analysis),
|
||||
'confirmed_profile_id': source.parsing_profile_id,
|
||||
'confirmed_profile_checksum': source.parsing_profile.checksum if source.parsing_profile else None,
|
||||
'current_profile_verified': True,
|
||||
'profile_match_level': current_profile_candidate.get('level'),
|
||||
}
|
||||
# 当前绑定解析已由本次文件验证,无需管理员重复确认或手动启用。
|
||||
from app.services.admin.shipping_inventory_service import activate_source_if_ready
|
||||
activate_source_if_ready(source, actor_id=run.created_by)
|
||||
else:
|
||||
run.stage = 'ready_for_confirmation'
|
||||
run.result_json = {'analysis': serialize_analysis(analysis)}
|
||||
run.completed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
@@ -188,6 +400,71 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return _payload(run)
|
||||
|
||||
|
||||
def report_batch_test_exports(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""接收批量 Worker 回调并逐项回写;未知运行标识只忽略,不影响同批其他站点。"""
|
||||
batch_id = int(payload.get('validation_batch_id') or 0)
|
||||
batch = db.session.get(ShippingInventoryValidationBatch, batch_id)
|
||||
if batch is None:
|
||||
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND')
|
||||
results = payload.get('results') or []
|
||||
if not isinstance(results, list):
|
||||
raise ValidationError('Batch results must be a list', code='SHIPPING.INVENTORY_VALIDATION_BATCH_INVALID')
|
||||
updated: list[dict[str, Any]] = []
|
||||
ignored = 0
|
||||
for item in results:
|
||||
if not isinstance(item, dict):
|
||||
ignored += 1
|
||||
continue
|
||||
run_no = str(item.get('validation_run_no') or '').strip()
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(
|
||||
run_no=run_no, validation_batch_id=batch.id,
|
||||
).first()
|
||||
if run is None:
|
||||
ignored += 1
|
||||
continue
|
||||
status = str(item.get('status') or '').lower()
|
||||
callback = {
|
||||
'run_no': run_no,
|
||||
'status': 'empty' if status == 'skipped' and item.get('skip_reason') == 'no_inventory_data' else status,
|
||||
'file_path': item.get('file_path'),
|
||||
'message': item.get('message'),
|
||||
'error_message': item.get('error_message') or item.get('message'),
|
||||
}
|
||||
updated.append(report_test_export(callback))
|
||||
_refresh_batch(batch.id)
|
||||
db.session.commit()
|
||||
return {**_batch_payload(batch), 'updated_count': len(updated), 'ignored_count': ignored}
|
||||
|
||||
|
||||
def report_batch_test_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""记录 Worker 已领取的批量测试站点,供管理端展示真实执行中状态。"""
|
||||
batch_id = int(payload.get('validation_batch_id') or 0)
|
||||
run_no = str(payload.get('validation_run_no') or '').strip()
|
||||
if not batch_id or not run_no:
|
||||
raise ValidationError('Batch id and validation run number are required', code='SHIPPING.INVENTORY_VALIDATION_PROGRESS_INVALID')
|
||||
batch = db.session.get(ShippingInventoryValidationBatch, batch_id)
|
||||
if batch is None:
|
||||
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND')
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(
|
||||
run_no=run_no, validation_batch_id=batch.id,
|
||||
).first()
|
||||
if run is None:
|
||||
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND')
|
||||
if run.status in {'completed', 'completed_empty', 'failed'}:
|
||||
return _payload(run)
|
||||
|
||||
# 仅接受 Worker 领取后的执行阶段,防止外部回调任意覆盖运行状态。
|
||||
stage = str(payload.get('stage') or 'rpa_exporting').strip().lower()
|
||||
if stage not in {'rpa_exporting'}:
|
||||
raise ValidationError('Unsupported inventory validation progress stage', code='SHIPPING.INVENTORY_VALIDATION_PROGRESS_INVALID')
|
||||
run.status = 'processing'
|
||||
run.stage = stage
|
||||
run.result_json = {**(run.result_json or {}), 'worker_claimed_at': datetime.utcnow().isoformat()}
|
||||
_refresh_batch(batch.id)
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
|
||||
|
||||
def confirm_test_profile(source_id: int, run_no: str, profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""管理员确认测试结果使用的已发布方案,才更新停用库存站点的解析方案绑定。"""
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(inventory_source_id=source_id, run_no=run_no).first()
|
||||
|
||||
@@ -20,7 +20,7 @@ from app.services.shipping_notice.inventory_file_store import (
|
||||
from app.services.shipping_notice.inventory_snapshot import build_field_alignment_preview
|
||||
from app.services.shipping_notice.query_service import serialize_task_for_tool
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.task_line_store import read_task_order_lines
|
||||
from app.services.shipping_notice.order_field_purposes import task_line_purpose_values
|
||||
from app.services.shipping_notice.tool_common import log_task_event, set_task_step_progress
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
|
||||
@@ -67,9 +67,13 @@ def inventory_loaded_response(
|
||||
else:
|
||||
task.inventory_lines_json = inventory_lines
|
||||
|
||||
try:
|
||||
order_lines = task_line_purpose_values(task)
|
||||
except ValueError:
|
||||
order_lines = []
|
||||
field_alignment = build_field_alignment_preview(
|
||||
inventory_lines,
|
||||
read_task_order_lines(task),
|
||||
order_lines,
|
||||
column_meta=column_meta,
|
||||
)
|
||||
set_task_step_progress(
|
||||
|
||||
@@ -60,9 +60,8 @@ def recommend_profiles(analysis: dict[str, Any]) -> dict[str, Any]:
|
||||
if exact and profile.exact_structure_fingerprint == exact:
|
||||
level = 'exact'
|
||||
elif _core_mapping_matches(analysis, profile):
|
||||
difference = _difference(analysis, profile)
|
||||
if not difference['missing_columns']:
|
||||
level = 'compatible'
|
||||
# 方案实际使用的匹配和数量栏位仍在即可复用;历史样本中的无关列可自由增减。
|
||||
level = 'compatible'
|
||||
if level:
|
||||
candidates.append({
|
||||
'profile_id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/inventory_routing_engine.py
|
||||
|
||||
用途:执行已发布的通用库存源路由规则并生成可解释的 Source 候选。
|
||||
依赖:库存路由模型、routing_facts、routing_operators。
|
||||
依赖:库存路由模型、动态订单 FieldValue、routing_operators。
|
||||
逻辑:只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。
|
||||
"""
|
||||
|
||||
@@ -13,7 +13,6 @@ from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventoryRoutingRule, ShippingOrderFieldValue, ShippingOrderLine
|
||||
from app.services.shipping_notice.routing_facts import build_routing_facts, read_system_fact
|
||||
from app.services.shipping_notice.routing_operators import matches_operator
|
||||
|
||||
|
||||
@@ -30,11 +29,10 @@ class InventoryRoutingResult:
|
||||
evidence: dict[str, Any]
|
||||
|
||||
|
||||
def _condition_value(condition: Any, *, task: Any, line: dict[str, Any] | None,
|
||||
facts: dict[str, dict[str, Any]]) -> Any:
|
||||
"""读取受控系统事实或 Task 当前 Extraction 的动态订单字段值。"""
|
||||
if condition.source_kind == 'system_fact':
|
||||
return read_system_fact(facts, condition.system_fact_key)
|
||||
def _condition_value(condition: Any, *, task: Any, line: dict[str, Any] | None) -> Any:
|
||||
"""只读取 Task 当前 Extraction 的动态订单 FieldValue。"""
|
||||
if condition.source_kind != 'order_field':
|
||||
return None
|
||||
extraction_id = getattr(task, 'current_order_extraction_id', None)
|
||||
if not extraction_id:
|
||||
return None
|
||||
@@ -51,11 +49,10 @@ def _condition_value(condition: Any, *, task: Any, line: dict[str, Any] | None,
|
||||
return value.value_json if value is not None else None
|
||||
|
||||
|
||||
def _rule_matches(rule: ShippingInventoryRoutingRule, *, task: Any, line: dict[str, Any] | None,
|
||||
facts: dict[str, dict[str, Any]]) -> bool:
|
||||
def _rule_matches(rule: ShippingInventoryRoutingRule, *, task: Any, line: dict[str, Any] | None) -> bool:
|
||||
"""判断规则条件按 all/any 语义是否命中。"""
|
||||
results = [
|
||||
matches_operator(_condition_value(condition, task=task, line=line, facts=facts), condition.operator, condition.expected_value_json)
|
||||
matches_operator(_condition_value(condition, task=task, line=line), condition.operator, condition.expected_value_json)
|
||||
for condition in rule.conditions
|
||||
]
|
||||
if not results:
|
||||
@@ -77,16 +74,15 @@ def evaluate_inventory_source_rules(*, task: Any, line: dict[str, Any] | None =
|
||||
"""
|
||||
moment = now or datetime.utcnow()
|
||||
scope = 'line' if line is not None else 'task'
|
||||
facts = build_routing_facts(task=task, line=line)
|
||||
query = ShippingInventoryRoutingRule.query.filter_by(status='published', scope=scope)
|
||||
rules = [
|
||||
rule for rule in query.order_by(ShippingInventoryRoutingRule.priority.desc(), ShippingInventoryRoutingRule.id.asc()).all()
|
||||
if (rule.effective_from is None or rule.effective_from <= moment)
|
||||
and (rule.effective_to is None or rule.effective_to >= moment)
|
||||
]
|
||||
matched = [rule for rule in rules if _rule_matches(rule, task=task, line=line, facts=facts)]
|
||||
matched = [rule for rule in rules if _rule_matches(rule, task=task, line=line)]
|
||||
if not matched:
|
||||
return InventoryRoutingResult('unresolved', (), (), {'facts': facts, 'matched_rules': []})
|
||||
return InventoryRoutingResult('unresolved', (), (), {'matched_rules': []})
|
||||
priority = matched[0].priority
|
||||
top_rules = [rule for rule in matched if rule.priority == priority]
|
||||
source_codes: set[str] = set()
|
||||
@@ -109,5 +105,5 @@ def evaluate_inventory_source_rules(*, task: Any, line: dict[str, Any] | None =
|
||||
status,
|
||||
tuple(sorted(source_codes)),
|
||||
tuple(rule.id for rule in top_rules),
|
||||
{'facts': facts, 'priority': priority, 'matched_rules': [rule.rule_code for rule in top_rules]},
|
||||
{'priority': priority, 'matched_rules': [rule.rule_code for rule in top_rules]},
|
||||
)
|
||||
@@ -2,9 +2,9 @@
|
||||
services/shipping_notice/inventory_rpa_workflow.py
|
||||
|
||||
用途:发货通知库存 RPA 编排(触发导出、等待/超时、回调落盘)。
|
||||
依赖:customer_identity_gate、reservation_gate、rpa、rpa_attempts、inventory_snapshot、inventory_mapping_workflow、query_service、task_line_store、tool_common、state_machine、tool_response。
|
||||
依赖:customer_identity_gate、reservation_gate、rpa、rpa_attempts、inventory_snapshot、inventory_mapping_workflow、query_service、动态订单字段、tool_common、state_machine、tool_response。
|
||||
逻辑:inventory_workflow.ensure_inventory 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新;tools 门面 re-export rpa_report_inventory;
|
||||
Reservation 门禁订单行经 read_task_order_lines 读取。
|
||||
Reservation 门禁从当前 Extraction 的动态 FieldValue 读取。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -62,8 +62,7 @@ from app.services.shipping_notice.query_service import (
|
||||
resolve_task_from_payload,
|
||||
serialize_task_for_tool,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
|
||||
from app.services.shipping_notice.task_line_store import read_task_order_lines
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
|
||||
from app.services.shipping_notice.rpa import (
|
||||
inventory_processed_dir,
|
||||
@@ -81,6 +80,7 @@ from app.services.shipping_notice.tool_common import (
|
||||
set_task_step_progress,
|
||||
)
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
from app.services.shipping_notice.task_disposition_service import task_execution_block_reason
|
||||
|
||||
|
||||
def latest_task_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent | None:
|
||||
@@ -696,11 +696,21 @@ def _validate_rpa_callback_gate(task: ShippingTask) -> dict[str, Any] | None:
|
||||
核心逻辑:先阻断新增字段冲突和 Reservation 异常,再校验客户、库存源;
|
||||
防止 RPA 执行期间人工改单后,旧回调继续把库存快照写入已失效任务。
|
||||
"""
|
||||
disposition_reason = task_execution_block_reason(task)
|
||||
if disposition_reason is not None:
|
||||
return tool_response(
|
||||
status='failed',
|
||||
task=task,
|
||||
message='任务已删除、作废或归档,RPA 回调仅归档原文件,不再写入任务。',
|
||||
data={**serialize_task_for_tool(task), 'disposition_block_reason': disposition_reason},
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
conflict_gate = field_conflict_gate_response(task, lang="zh")
|
||||
if conflict_gate is not None:
|
||||
return conflict_gate
|
||||
|
||||
reservation_issues = reservation_gate_issues(read_task_order_lines(task))
|
||||
reservation_issues = task_reservation_gate_issues(task)
|
||||
if reservation_issues:
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
@@ -957,6 +967,16 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
manual_retry_round = mode == "retry_rpa"
|
||||
|
||||
disposition_reason = task_execution_block_reason(task)
|
||||
if disposition_reason is not None:
|
||||
return tool_response(
|
||||
status='failed',
|
||||
task=task,
|
||||
message='任务已删除、作废或归档,不能启动库存 RPA。',
|
||||
data={**serialize_task_for_tool(task), 'disposition_block_reason': disposition_reason},
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
customer_gate = customer_gate_tool_response(task, operation='ensure_inventory_via_rpa')
|
||||
if customer_gate is not None:
|
||||
return customer_gate
|
||||
@@ -965,7 +985,7 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
if conflict_gate is not None:
|
||||
return conflict_gate
|
||||
|
||||
reservation_issues = reservation_gate_issues(read_task_order_lines(task))
|
||||
reservation_issues = task_reservation_gate_issues(task)
|
||||
if reservation_issues:
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
@@ -1760,6 +1780,23 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
})
|
||||
continue
|
||||
|
||||
if raw_status == 'skipped' and str(merged_item.get('skip_reason') or '') == 'no_inventory_data':
|
||||
# 调度空结果保留为审计快照,但绝不链接给任务或作为 ready 库存复用。
|
||||
source = _resolve_batch_callback_source(None, merged_item)
|
||||
if source and not task_no:
|
||||
from app.services.shipping_notice.inventory_snapshot_store import create_empty_rpa_inventory_snapshot
|
||||
|
||||
snapshot = create_empty_rpa_inventory_snapshot(
|
||||
source=source, rpa_run_no=run_no or None, schedule_run_id=schedule_run_id,
|
||||
trigger_type=str(payload.get('trigger_type') or 'scheduled'),
|
||||
message=str(merged_item.get('message') or ''),
|
||||
)
|
||||
skipped.append({
|
||||
'source_code': source_code, 'warehouse_id': warehouse_id,
|
||||
'skip_reason': 'no_inventory_data', 'inventory_file_no': snapshot.inventory_file_no,
|
||||
})
|
||||
continue
|
||||
|
||||
source = _resolve_batch_callback_source(task, merged_item)
|
||||
if not source:
|
||||
error = {
|
||||
|
||||
@@ -27,6 +27,7 @@ from app.services.shipping_notice.inventory_file_store import (
|
||||
from app.services.shipping_notice.inventory_snapshot import read_inventory_schema_preview
|
||||
|
||||
_SNAPSHOT_STATUS_READY = "ready"
|
||||
_SNAPSHOT_STATUS_EMPTY = "empty"
|
||||
_SNAPSHOT_STATUS_FAILED = "failed"
|
||||
_SNAPSHOT_STATUS_EXPIRED = "expired"
|
||||
_WAREHOUSE_ID_HEADER_ALIASES = {
|
||||
@@ -381,6 +382,40 @@ def create_inventory_snapshot_from_rpa(
|
||||
return inv_file
|
||||
|
||||
|
||||
def create_empty_rpa_inventory_snapshot(
|
||||
*, source: dict[str, Any], rpa_run_no: str | None, schedule_run_id: int | None,
|
||||
trigger_type: str, message: str | None = None,
|
||||
) -> ShippingInventoryFile:
|
||||
"""记录 RPA 已成功执行但没有库存行的空快照;空快照永不参与库存匹配。"""
|
||||
exported_at = datetime.utcnow()
|
||||
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
|
||||
|
||||
source_code = str(source.get('source_code') or '').strip().upper()
|
||||
warehouse_id = str(source.get('warehouse_id') or '').strip().upper() or None
|
||||
run_no = str(rpa_run_no or '').strip() or None
|
||||
if run_no and source_code:
|
||||
existing = ShippingInventoryFile.query.filter_by(
|
||||
rpa_run_no=run_no, source_code=source_code, warehouse_id=warehouse_id,
|
||||
snapshot_status=_SNAPSHOT_STATUS_EMPTY,
|
||||
).order_by(ShippingInventoryFile.id.desc()).first()
|
||||
if existing is not None:
|
||||
return existing
|
||||
inv_file = ShippingInventoryFile(
|
||||
inventory_file_no=generate_inventory_file_no(), storage_path=f'empty://{source_code or "inventory"}',
|
||||
schema_preview_json={'export_result': 'empty', 'message': str(message or '库存查询成功但当前无库存数据')[:500]},
|
||||
share_mode='warehouse_pool', line_count=0, inventory_lines_json=[], warehouse_id=warehouse_id,
|
||||
warehouse_code=warehouse_id, source_code=source_code or None,
|
||||
source_type=str(source.get('connector_type') or '').strip() or None,
|
||||
source_config_version=inventory_sources_runtime_version(), identity_status='not_applicable',
|
||||
snapshot_status=_SNAPSHOT_STATUS_EMPTY, exported_at=exported_at, expires_at=snapshot_expires_at(exported_at),
|
||||
rpa_run_no=run_no, schedule_run_id=schedule_run_id,
|
||||
source_query_json={'trigger_type': trigger_type, 'export_result': 'empty'},
|
||||
)
|
||||
db.session.add(inv_file)
|
||||
db.session.flush()
|
||||
return inv_file
|
||||
|
||||
|
||||
def link_snapshot_to_task(
|
||||
task: ShippingTask,
|
||||
inv_file: ShippingInventoryFile,
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/inventory_source_gate.py
|
||||
|
||||
用途:库存源稳定性门禁、独立字段写入与路由指纹管理。
|
||||
依赖:inventory_source_rules、inventory_source_repository、models.ShippingTask、core.errors。
|
||||
逻辑:parse_notice 先裁决线索;解析确认通过后未稳定才进入 inventory_source_review;
|
||||
逻辑:动态订单抽取先裁决线索;解析确认通过后未稳定才进入 inventory_source_review;
|
||||
RPA/库存/匹配/导出统一经本模块硬门禁,禁止散落判断。
|
||||
"""
|
||||
|
||||
@@ -201,7 +201,7 @@ def apply_inventory_source_adjudication(
|
||||
def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySourceAdjudication:
|
||||
"""
|
||||
对任务执行库存源裁决并写入独立字段。
|
||||
【AI 触发时机】:订单解析完成后由 parse_notice 调用;重解析时同样调用以刷新裁决。
|
||||
【AI 触发时机】:订单抽取提交完成后由后端编排调用;重解析时同样调用以刷新裁决。
|
||||
"""
|
||||
context = extract_routing_context(task)
|
||||
if inventory_source_config_changed(task) or routing_fingerprint_changed(task, context):
|
||||
|
||||
@@ -74,7 +74,6 @@ def get_database_inventory_source(source_code: str, *, enabled_only: bool = True
|
||||
'excel_template_id': source.excel_template_id,
|
||||
'report_path_json': dict(source.report_path_json or {}),
|
||||
'query_parameters_json': list(source.query_parameters_json or []),
|
||||
'match_aliases_json': list(source.match_aliases_json or []),
|
||||
'rpa_profile_code': profile.profile_code,
|
||||
# 与既有 worker 契约的适配层:不再从 Profile 取报表路径或查询参数。
|
||||
'navigation': source_navigation,
|
||||
@@ -136,7 +135,6 @@ def inventory_sources_runtime_version() -> str:
|
||||
'fixed_warehouse_id': source.fixed_warehouse_id,
|
||||
'report_path_json': source.report_path_json or {},
|
||||
'query_parameters_json': source.query_parameters_json or [],
|
||||
'match_aliases_json': source.match_aliases_json or [],
|
||||
'snapshot_ttl_seconds': source.snapshot_ttl_seconds,
|
||||
},
|
||||
'profile_config': {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/inventory_source_rules.py
|
||||
|
||||
用途:将通用路由规则的 Source 候选转为任务可持久化的裁决结果。
|
||||
依赖:inventory_routing_engine、inventory_source_repository、task_line_store。
|
||||
依赖:inventory_routing_engine、inventory_source_repository、order_field_purposes。
|
||||
逻辑:规则只决定 Source;fixed Warehouse 由 Source 给出,inventory_match Warehouse 延后到库存行匹配。
|
||||
"""
|
||||
|
||||
@@ -22,7 +22,8 @@ from app.services.shipping_notice.inventory_source_repository import (
|
||||
inventory_sources_runtime_version,
|
||||
list_database_inventory_sources,
|
||||
)
|
||||
from app.services.shipping_notice.task_line_store import read_task_order_lines
|
||||
from app.services.shipping_notice.order_field_purposes import task_line_purpose_values
|
||||
from app.services.shipping_notice.task_order_field_editor import current_header_field_values_or_empty
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -49,13 +50,14 @@ InventorySourceResolution = InventorySourceAdjudication
|
||||
def extract_routing_context(task: ShippingTask) -> dict[str, Any]:
|
||||
"""投影任务字段为路由审计上下文,不依赖 YAML 目的地别名。"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
header = current_header_field_values_or_empty(task)
|
||||
return {
|
||||
'destination_code': task.destination_code,
|
||||
'destination_city': task.destination_city,
|
||||
'destination_country': task.destination_country,
|
||||
'warehouse_hint': task.warehouse_hint,
|
||||
'customer_code': task.customer_code,
|
||||
'customer_name': task.customer_name,
|
||||
'customer_code': header.get('customer_code'),
|
||||
'customer_name': header.get('customer_name') or header.get('bill_to_customer'),
|
||||
'order_type': payload.get('order_type'),
|
||||
'destination_candidates': [],
|
||||
}
|
||||
@@ -122,6 +124,15 @@ def _snapshot_match_key(row: dict[str, Any]) -> tuple[str, str] | None:
|
||||
return (part_number, reservation_id) if part_number and reservation_id else None
|
||||
|
||||
|
||||
def _task_routing_lines(task: ShippingTask, *, required: set[str] | None = None) -> list[dict[str, Any]]:
|
||||
"""读取锁定 Extraction 的行用途值并保留位置,供路由规则和快照键关联使用。"""
|
||||
try:
|
||||
values = task_line_purpose_values(task, required=required)
|
||||
except ValueError:
|
||||
return []
|
||||
return [{**line, '_position': position} for position, line in enumerate(values)]
|
||||
|
||||
|
||||
def resolve_ambiguous_source_from_ready_snapshots(
|
||||
task: ShippingTask,
|
||||
adjudication: InventorySourceAdjudication,
|
||||
@@ -141,15 +152,16 @@ def resolve_ambiguous_source_from_ready_snapshots(
|
||||
for item in adjudication.candidates
|
||||
if isinstance(item, dict) and str(item.get('source_code') or '').strip()
|
||||
}
|
||||
order_lines = _task_routing_lines(task, required={'part_number', 'reservation_id'})
|
||||
order_keys = {
|
||||
key for row in read_task_order_lines(task)
|
||||
key for row in order_lines
|
||||
if isinstance(row, dict) and (key := _snapshot_match_key(row))
|
||||
}
|
||||
if not candidate_codes or not order_keys:
|
||||
return adjudication
|
||||
|
||||
# A partial or malformed order cannot be silently routed from a file.
|
||||
if len(order_keys) != len(read_task_order_lines(task)):
|
||||
if len(order_keys) != len(order_lines):
|
||||
return adjudication
|
||||
|
||||
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
|
||||
@@ -219,7 +231,7 @@ def adjudicate_inventory_source(task: ShippingTask) -> InventorySourceAdjudicati
|
||||
task_result = evaluate_inventory_source_rules(task=task)
|
||||
if task_result.status != 'unresolved':
|
||||
return _result_to_adjudication(task_result, context)
|
||||
line_results = [evaluate_inventory_source_rules(task=task, line=line) for line in read_task_order_lines(task)]
|
||||
line_results = [evaluate_inventory_source_rules(task=task, line=line) for line in _task_routing_lines(task)]
|
||||
resolved_codes = {item.source_codes[0] for item in line_results if item.status == 'resolved' and len(item.source_codes) == 1}
|
||||
if len(resolved_codes) == 1 and all(item.status == 'resolved' for item in line_results):
|
||||
return _result_to_adjudication(next(item for item in line_results if item.status == 'resolved'), context)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/inventory_warehouse_resolution.py
|
||||
|
||||
用途:按库存解析方案的匹配关系,从订单行与库存行确定动态 Warehouse。
|
||||
依赖:ShippingInventoryField/Source、动态订单字段投影、task_line_store。
|
||||
依赖:ShippingInventoryField/Source、动态订单字段投影。
|
||||
逻辑:仅在 inventory_match Source 链接库存快照时调用;字段 ID 和用途决定匹配及仓库取值。
|
||||
"""
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/inventory_workflow.py
|
||||
|
||||
用途:发货通知正式库存阶段编排(上传、复用已解析库存文件);RPA 见 inventory_rpa_workflow。
|
||||
依赖:customer_identity_gate、reservation_gate、inventory_file_store、inventory_mapping_workflow、query_service、state_machine、task_line_store。
|
||||
依赖:customer_identity_gate、reservation_gate、inventory_file_store、inventory_mapping_workflow、query_service、state_machine、动态订单字段。
|
||||
逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除。
|
||||
"""
|
||||
|
||||
@@ -27,8 +27,7 @@ from app.services.shipping_notice.query_service import (
|
||||
serialize_batch_for_tool,
|
||||
serialize_task_for_tool,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
|
||||
from app.services.shipping_notice.task_line_store import read_task_order_lines
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable
|
||||
@@ -63,7 +62,7 @@ def _reservation_gate_response(task: ShippingTask, *, lang: str) -> dict[str, An
|
||||
|
||||
核心逻辑:任一订单行缺失/非法时阻断,并禁止同轮继续库存副作用。
|
||||
"""
|
||||
reservation_issues = reservation_gate_issues(read_task_order_lines(task))
|
||||
reservation_issues = task_reservation_gate_issues(task)
|
||||
if not reservation_issues:
|
||||
return None
|
||||
return tool_response(
|
||||
|
||||
@@ -259,21 +259,6 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"写入任务库存行或执行库存匹配。"
|
||||
),
|
||||
),
|
||||
"/tools/parse_notice": _post_op(
|
||||
"parse_notice",
|
||||
"解析发货通知文本",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"raw_text": _str_prop("待解析的发货通知全文"),
|
||||
"structured": {
|
||||
"type": "object",
|
||||
"description": "Dify LLM 解析后的结构化结果对象。若提供,后端优先使用该对象中的 lines/confidence/reservation_id 等字段落库。",
|
||||
"additionalProperties": True,
|
||||
},
|
||||
"lang": _str_prop("可选语言代码:zh|en|th"),
|
||||
},
|
||||
required=["task_id"],
|
||||
),
|
||||
"/tools/update_notice_fields": _post_op(
|
||||
"update_notice_fields",
|
||||
"更新解析后的发货通知单头字段,如客户、PO、交期、收货地",
|
||||
|
||||
@@ -27,7 +27,6 @@ from app.models import (
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
|
||||
@@ -957,6 +956,7 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
db.session.add(candidate)
|
||||
candidate.primary_document_id = int(document.id)
|
||||
candidate.source_order_index = index
|
||||
candidate.order_extraction_id = int(dynamic['extraction'].id)
|
||||
candidate.extraction_source = 'dify_chatflow'
|
||||
candidate.classification_confidence = classification_confidence
|
||||
candidate.field_confidence_json = {}
|
||||
@@ -1038,6 +1038,10 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
candidate.selected = False
|
||||
candidate.validation_status = 'needs_review'
|
||||
candidate.updated_at = datetime.utcnow()
|
||||
# Candidate 已关联本轮受控 FieldValue 后刷新影子识别;不读取其 LLM 摘要,也不触发自动确认。
|
||||
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution_safely
|
||||
|
||||
refresh_candidate_shadow_resolution_safely(candidate)
|
||||
document_candidate_keys[int(document.id)].append(candidate_key)
|
||||
document_has_pending[int(document.id)] = document_has_pending[int(document.id)] or bool(reasons)
|
||||
if candidate.selected and candidate.validation_status == 'ready':
|
||||
@@ -1110,20 +1114,7 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
candidate_nos=auto_candidate_nos,
|
||||
create_idempotency_key=idem,
|
||||
)
|
||||
# [STEP 4A] Candidate 被创建或打开到 Task 后,回填当前动态订单真相版本。
|
||||
for candidate in auto_candidates:
|
||||
if candidate.consumed_task_id is None:
|
||||
continue
|
||||
extraction_data = (
|
||||
candidate.structured_result_json.get('extraction', {}).get('field_adjudication', {})
|
||||
if isinstance(candidate.structured_result_json, dict)
|
||||
else {}
|
||||
)
|
||||
extraction_id = extraction_data.get('extraction_id') if isinstance(extraction_data, dict) else None
|
||||
task = db.session.get(ShippingTask, int(candidate.consumed_task_id))
|
||||
if task is not None and str(extraction_id or '').isdigit():
|
||||
task.current_order_extraction_id = int(extraction_id)
|
||||
db.session.get(ShippingOrderExtraction, int(extraction_id)).task_id = int(task.id)
|
||||
# 建批事务已在启动编排器前绑定 Task 与已接受 Extraction;此处只完成本轮提交收口。
|
||||
db.session.commit()
|
||||
else:
|
||||
# [STEP 4] 没有待处理订单时(空数组或仅明确非发货内容),消费 Intake 但不产生 Batch/Task。
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""
|
||||
services/shipping_notice/order_field_purposes.py
|
||||
|
||||
用途:将当前已接受订单解析的 FieldValue 按已发布 Schema 业务用途投影给履约链。
|
||||
依赖:order_schema.service、export.order_field_id_values、ShippingTask。
|
||||
逻辑:路由、门禁、匹配和展示只通过发布快照中的 business_purpose 定位稳定 field_id,禁止读取任务行固定业务列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingOrderExtraction, ShippingTask
|
||||
from app.services.shipping_notice.export import order_field_id_values
|
||||
|
||||
|
||||
def task_line_purpose_field_ids(task: ShippingTask, *, required: set[str] | None = None) -> dict[str, str]:
|
||||
"""读取任务锁定 Schema 快照的行级用途与字段 ID,防止后续发布版本重解释历史任务。"""
|
||||
extraction = (
|
||||
db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
if task.current_order_extraction_id is not None else None
|
||||
)
|
||||
if extraction is None or extraction.status != 'accepted':
|
||||
raise ValueError('任务没有可用于履约的已接受订单解析版本')
|
||||
purposes = {
|
||||
str(config.get('business_purpose')): str(config.get('field_id'))
|
||||
for config in (extraction.schema_version.definition_json or {}).get('fields') or []
|
||||
if config.get('scope') == 'line' and config.get('business_purpose') not in (None, '', 'general')
|
||||
}
|
||||
missing = sorted((required or set()) - set(purposes))
|
||||
if missing:
|
||||
raise ValueError(f'已发布订单 Schema 缺少业务用途:{", ".join(missing)}')
|
||||
return purposes
|
||||
|
||||
|
||||
def task_line_purpose_values(task: ShippingTask, *, required: set[str] | None = None) -> list[dict[str, Any]]:
|
||||
"""按订单行位置返回用途键值,值只来自任务当前 accepted Extraction 的 FieldValue。"""
|
||||
purpose_ids = task_line_purpose_field_ids(task, required=required)
|
||||
_header, lines = order_field_id_values(task)
|
||||
return [
|
||||
{purpose: line.get(field_id) for purpose, field_id in purpose_ids.items()}
|
||||
for line in lines
|
||||
]
|
||||
@@ -52,6 +52,10 @@ from app.services.shipping_notice.order_schema.diff import compare_definitions
|
||||
SCHEMA_CODE = 'SHIPPING_ORDER'
|
||||
FIELD_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,63}$')
|
||||
EVIDENCE_KEYS = {'required', 'source_precedence', 'conflict_policy', 'allow_single_source'}
|
||||
BUSINESS_PURPOSES = frozenset({
|
||||
'general', 'part_number', 'quantity', 'reservation_id', 'inventory_source_hint',
|
||||
})
|
||||
_LINE_STRING_PURPOSES = frozenset({'part_number', 'reservation_id', 'inventory_source_hint'})
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
@@ -101,6 +105,22 @@ def _enabled_fields(definition: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
return [dict(item) for item in definition.get('fields') or [] if item.get('enabled', True)]
|
||||
|
||||
|
||||
def _business_purpose(raw: Any, *, field: ShippingOrderField) -> str:
|
||||
"""规范化字段业务用途,确保下游只通过已发布快照的稳定 field_id 定位业务字段。"""
|
||||
purpose = str(raw or 'general').strip() or 'general'
|
||||
if purpose not in BUSINESS_PURPOSES:
|
||||
raise ValidationError('business_purpose is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
if purpose == 'general':
|
||||
return purpose
|
||||
if field.scope != 'line':
|
||||
raise ValidationError('business_purpose requires a line field', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
if purpose in _LINE_STRING_PURPOSES and field.value_type != 'string':
|
||||
raise ValidationError('business_purpose requires a string field', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
if purpose == 'quantity' and field.value_type not in {'decimal', 'integer'}:
|
||||
raise ValidationError('quantity purpose requires a numeric field', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
return purpose
|
||||
|
||||
|
||||
def _audit_summary(before: dict[str, Any] | None, after: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""生成阶段一审计摘要;阶段三在此基础上提供完整字段级语义差异。"""
|
||||
before_fields = {str(item.get('field_id')): item for item in (before or {}).get('fields', [])}
|
||||
@@ -610,6 +630,9 @@ def _field_runtime_references(field_id: str) -> list[str]:
|
||||
)
|
||||
if template_reference:
|
||||
references.append('excel_template')
|
||||
# 识别定义同样消费稳定订单字段;字段退役或发布移除前必须先完成规则替换/退役。
|
||||
from app.services.shipping_notice.identity_rules.service import active_definition_field_references
|
||||
references.extend(active_definition_field_references(field_id))
|
||||
return references
|
||||
|
||||
|
||||
@@ -718,6 +741,7 @@ def save_draft(
|
||||
item.id: item for item in ShippingOrderField.query.filter_by(schema_id=version.schema_id, status='active').all()
|
||||
}
|
||||
seen: set[str] = set()
|
||||
enabled_purposes: set[str] = set()
|
||||
normalized_fields: list[dict[str, Any]] = []
|
||||
for sequence, raw in enumerate(configs, start=1):
|
||||
if not isinstance(raw, dict) or str(raw.get('field_id') or '') not in active_fields:
|
||||
@@ -752,6 +776,14 @@ def save_draft(
|
||||
raise ValidationError('enum field requires enum_options', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
if field.value_type != 'enum' and enum_options:
|
||||
raise ValidationError('enum_options only applies to enum fields', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
business_purpose = _business_purpose(raw.get('business_purpose'), field=field)
|
||||
if enabled and business_purpose != 'general':
|
||||
if business_purpose in enabled_purposes:
|
||||
raise ValidationError(
|
||||
'business_purpose must be unique among enabled fields',
|
||||
code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID',
|
||||
)
|
||||
enabled_purposes.add(business_purpose)
|
||||
normalized_fields.append({
|
||||
'field_id': field_id,
|
||||
'field_code': field.field_code,
|
||||
@@ -760,6 +792,7 @@ def save_draft(
|
||||
'enabled': enabled,
|
||||
'display_name': display_name,
|
||||
'description': str(raw.get('description') or '').strip() or None,
|
||||
'business_purpose': business_purpose,
|
||||
'required': required,
|
||||
'aliases': aliases,
|
||||
'normalizer_key': normalizer,
|
||||
|
||||
@@ -3,8 +3,7 @@ services/shipping_notice/parse_summary.py
|
||||
|
||||
用途:把发货通知解析结果格式化成适合聊天区展示的摘要文本。
|
||||
依赖:shipping_notice.i18n 中的语言解析与文案函数、订单行格式化辅助函数。
|
||||
逻辑:由 task_workflow.parse_notice 在解析完成后调用本文件,向前端或 Agent 返回可直接展示的解析总结。
|
||||
库存源门禁路径不经本模块,由 parse_notice 直接拼接 issues 列表文案。
|
||||
逻辑:保留历史解析摘要格式化能力;正式动态订单抽取不依赖本模块。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -96,7 +95,7 @@ def format_parse_summary(
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> str:
|
||||
"""
|
||||
生成 parse_notice 固定 Markdown 摘要(Agent 须原文展示给用户)。
|
||||
生成历史解析的固定 Markdown 摘要;不得作为动态订单抽取的结果来源。
|
||||
|
||||
Args:
|
||||
low_confidence: True 时追加低置信度提示。
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
services/shipping_notice/query_service.py
|
||||
|
||||
用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链与重复决策字段)。
|
||||
依赖:models.ShippingBatch、ShippingCase、ShippingNoticeCandidate、ShippingTask、ShippingTaskEvent、task_line_store。
|
||||
依赖:models.ShippingBatch、ShippingCase、ShippingNoticeCandidate、ShippingTask、ShippingTaskEvent、动态订单字段编辑器。
|
||||
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
|
||||
tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉;
|
||||
SUMMARY/DETAIL 经 _task_version_chain_fields 暴露 document_version / supersedes / duplicate_*;
|
||||
DETAIL 另投影 parse_validation / process_field_gate / source_candidate 供持久只读展示;
|
||||
订单行经 task_line_store.read_task_order_lines,支持 shadow 差异观测。
|
||||
订单行仅从任务锁定 Extraction 的 FieldValue 投影,未抽取任务返回空行集。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -27,7 +27,10 @@ from app.models import (
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.task_line_store import read_task_order_lines
|
||||
from app.services.shipping_notice.task_order_field_editor import (
|
||||
current_header_field_values_or_empty,
|
||||
current_line_field_values_or_empty,
|
||||
)
|
||||
|
||||
EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
|
||||
@@ -355,6 +358,7 @@ def _task_tool_payload(task: ShippingTask) -> dict[str, Any]:
|
||||
from app.services.shipping_notice.rpa import rpa_runtime_mode
|
||||
|
||||
step_payload = task.step_payload_json or {}
|
||||
header = current_header_field_values_or_empty(task)
|
||||
payload: dict[str, Any] = {
|
||||
"task_no": task.task_no,
|
||||
"shipping_case_id": task.shipping_case_id,
|
||||
@@ -365,17 +369,17 @@ def _task_tool_payload(task: ShippingTask) -> dict[str, Any]:
|
||||
"review_status": task.review_status,
|
||||
"match_status": task.match_status,
|
||||
"pending_human_reason": task.pending_human_reason,
|
||||
"customer_name": task.customer_name,
|
||||
"customer_code": task.customer_code,
|
||||
"customer_name": header.get('customer_name') or header.get('bill_to_customer'),
|
||||
"customer_code": header.get('customer_code'),
|
||||
"customer_resolution_status": task.customer_resolution_status,
|
||||
"customer_resolution_method": task.customer_resolution_method,
|
||||
"customer_id": task.shipping_case.customer_id if task.shipping_case else None,
|
||||
"customer_name_snapshot": task.shipping_case.customer_name_snapshot if task.shipping_case else None,
|
||||
"customer_short_code_snapshot": task.shipping_case.customer_short_code_snapshot if task.shipping_case else None,
|
||||
"ship_to": task.ship_to,
|
||||
"po_number": task.po_number,
|
||||
"required_date": task.required_date,
|
||||
"lines": read_task_order_lines(task),
|
||||
"ship_to": header.get('ship_to') or header.get('ship_to_address'),
|
||||
"po_number": header.get('po_number'),
|
||||
"required_date": header.get('required_date'),
|
||||
"lines": current_line_field_values_or_empty(task),
|
||||
"shortage": task.shortage_json,
|
||||
"line_results": task.line_results_json,
|
||||
"export_file_name": task.export_file_name,
|
||||
@@ -504,6 +508,7 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
|
||||
return _task_tool_payload(task)
|
||||
if projection == TaskProjection.SUMMARY:
|
||||
step_payload = task.step_payload_json or {}
|
||||
header = current_header_field_values_or_empty(task)
|
||||
data = {
|
||||
"id": task.id,
|
||||
"task_no": task.task_no,
|
||||
@@ -516,7 +521,7 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
|
||||
"source_file_type": task.source_file_type,
|
||||
"batch_index": task.batch_index,
|
||||
"batch_total": task.batch_total,
|
||||
"customer_name": task.customer_name,
|
||||
"customer_name": header.get('customer_name') or header.get('bill_to_customer'),
|
||||
"customer_resolution_status": task.customer_resolution_status,
|
||||
"customer_resolution_method": task.customer_resolution_method,
|
||||
"customer_id": task.shipping_case.customer_id if task.shipping_case else None,
|
||||
@@ -531,6 +536,11 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
|
||||
"upload_attempt": task.upload_attempt,
|
||||
"pending_human_reason": task.pending_human_reason,
|
||||
"error_message": task.error_message or task.upload_error_message,
|
||||
"lifecycle_status": str(getattr(task, 'lifecycle_status', 'active') or 'active'),
|
||||
"deleted_at": task.deleted_at.isoformat() if getattr(task, 'deleted_at', None) else None,
|
||||
"voided_at": task.voided_at.isoformat() if getattr(task, 'voided_at', None) else None,
|
||||
"void_reason": getattr(task, 'void_reason', None),
|
||||
"archived_at": task.archived_at.isoformat() if getattr(task, 'archived_at', None) else None,
|
||||
"conversation_id": task.conversation_id,
|
||||
"export_file_name": task.export_file_name,
|
||||
"freight_ref_no": task.freight_ref_no,
|
||||
@@ -558,20 +568,32 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
|
||||
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
|
||||
}
|
||||
data.update(_task_version_chain_fields(task))
|
||||
from app.services.shipping_notice.task_disposition_service import task_disposition_capability
|
||||
|
||||
data['disposition_capabilities'] = {
|
||||
action: {
|
||||
'allowed': result.allowed,
|
||||
'code': result.code,
|
||||
'reason': result.reason,
|
||||
}
|
||||
for action in ('delete', 'void', 'archive', 'restore')
|
||||
for result in (task_disposition_capability(task, action),)
|
||||
}
|
||||
return data
|
||||
if projection == TaskProjection.DETAIL:
|
||||
step_payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
header = current_header_field_values_or_empty(task)
|
||||
data = serialize_task(task, TaskProjection.SUMMARY)
|
||||
data.update({
|
||||
"customer_code": task.customer_code,
|
||||
"ship_to": task.ship_to,
|
||||
"po_number": task.po_number,
|
||||
"required_date": task.required_date,
|
||||
"customer_code": header.get('customer_code'),
|
||||
"ship_to": header.get('ship_to') or header.get('ship_to_address'),
|
||||
"po_number": header.get('po_number'),
|
||||
"required_date": header.get('required_date'),
|
||||
"step_payload": step_payload,
|
||||
"upload_receipt": task.upload_receipt_json or {},
|
||||
"export_version": task.export_version,
|
||||
"idempotency_key": task.idempotency_key,
|
||||
"lines": read_task_order_lines(task),
|
||||
"lines": current_line_field_values_or_empty(task),
|
||||
"shortage": task.shortage_json,
|
||||
"line_results": task.line_results_json or [],
|
||||
"parse_confidence": task.parse_confidence,
|
||||
@@ -755,6 +777,67 @@ def list_tasks_for_user(
|
||||
return [serialize_task_summary(c) for c in rows]
|
||||
|
||||
|
||||
def list_tasks_page_for_user(
|
||||
user_id: int,
|
||||
*,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
batch_no: str | None = None,
|
||||
process_status: str | None = None,
|
||||
lifecycle_status: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
分页列出当前用户可见的发货任务摘要。
|
||||
|
||||
工作台任务量增长后必须由数据库分页,不能先拉取固定上限再在浏览器切页;
|
||||
`items` 仅表示当前页,`total` 用于计算稳定的页码与空页回退。
|
||||
"""
|
||||
normalized_page = max(1, int(page))
|
||||
normalized_page_size = max(1, min(int(page_size), 100))
|
||||
q = ShippingTask.query.filter(
|
||||
(ShippingTask.user_id == user_id) | (ShippingTask.user_id.is_(None))
|
||||
)
|
||||
if batch_no:
|
||||
batch = get_batch_for_user(batch_no, user_id)
|
||||
if not batch:
|
||||
return {"items": [], "page": normalized_page, "page_size": normalized_page_size, "total": 0}
|
||||
q = q.filter(ShippingTask.batch_id == batch.id)
|
||||
if process_status:
|
||||
if process_status == "shortage_review":
|
||||
q = q.filter(
|
||||
(ShippingTask.review_status == "shortage_review")
|
||||
| (ShippingTask.pending_human_reason.in_(("shortage", "shortage_review")))
|
||||
)
|
||||
else:
|
||||
q = q.filter(ShippingTask.process_status == process_status)
|
||||
if lifecycle_status:
|
||||
normalized_lifecycle = str(lifecycle_status).strip().lower()
|
||||
if normalized_lifecycle == 'deleted':
|
||||
q = q.filter(ShippingTask.deleted_at.is_not(None))
|
||||
elif normalized_lifecycle == 'active':
|
||||
q = q.filter(ShippingTask.deleted_at.is_(None), ShippingTask.lifecycle_status == 'active')
|
||||
elif normalized_lifecycle == 'voided':
|
||||
# 作废后移入回收站的任务仍须出现在“已作废”视图,便于业务审计与追溯。
|
||||
q = q.filter(ShippingTask.lifecycle_status == normalized_lifecycle)
|
||||
else:
|
||||
q = q.filter(ShippingTask.deleted_at.is_(None), ShippingTask.lifecycle_status == normalized_lifecycle)
|
||||
else:
|
||||
q = q.filter(ShippingTask.deleted_at.is_(None), ShippingTask.lifecycle_status == 'active')
|
||||
total = q.order_by(None).count()
|
||||
rows = (
|
||||
q.order_by(desc(ShippingTask.created_at))
|
||||
.offset((normalized_page - 1) * normalized_page_size)
|
||||
.limit(normalized_page_size)
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
"items": [serialize_task_summary(item) for item in rows],
|
||||
"page": normalized_page,
|
||||
"page_size": normalized_page_size,
|
||||
"total": total,
|
||||
}
|
||||
|
||||
|
||||
def get_task_for_user(task_no: str, user_id: int) -> ShippingTask | None:
|
||||
"""按 task_no 查找任务并校验 user_id 归属。"""
|
||||
task = get_task_by_ref(task_no)
|
||||
|
||||
@@ -64,6 +64,10 @@ def _should_requeue_waiting_external_result(task_no: str) -> bool:
|
||||
task = get_task_by_ref(task_no)
|
||||
if not task:
|
||||
return False
|
||||
from app.services.shipping_notice.task_disposition_service import task_is_active
|
||||
|
||||
if not task_is_active(task):
|
||||
return False
|
||||
process_status = str(task.process_status or '').strip()
|
||||
pending_reason = str(task.pending_human_reason or '').strip()
|
||||
return (
|
||||
@@ -189,7 +193,18 @@ def run_shipping_notice_job(payload: dict[str, Any], logger: logging.Logger | No
|
||||
if not task_no:
|
||||
return False, 'missing_task_no'
|
||||
|
||||
result = _run_single_task(task_no)
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
from app.services.shipping_notice.task_disposition_service import task_execution_block_reason
|
||||
|
||||
task = get_task_by_ref(task_no)
|
||||
disposition_reason = task_execution_block_reason(task) if task is not None else None
|
||||
# [STEP 1] 已领取的 Job 即使任务被删除,也必须走 finish_job 收口,不能提前 return 留在 running。
|
||||
if task is None:
|
||||
result = {'status': 'skipped', 'message': 'task not found'}
|
||||
elif disposition_reason:
|
||||
result = {'status': 'skipped', 'message': disposition_reason}
|
||||
else:
|
||||
result = _run_single_task(task_no)
|
||||
status = str(result.get('status') or '').strip().lower()
|
||||
success = status in {'ok', 'running', 'needs_human', 'skipped'}
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.order_field_purposes import task_line_purpose_values
|
||||
from app.services.shipping_notice.reservation_id import is_valid_reservation_id
|
||||
|
||||
|
||||
@@ -63,3 +65,20 @@ def reservation_gate_issues(lines: list[Any] | None) -> list[dict[str, Any]]:
|
||||
}
|
||||
)
|
||||
return issues
|
||||
|
||||
|
||||
def task_reservation_gate_issues(task: ShippingTask) -> list[dict[str, Any]]:
|
||||
"""读取当前已裁决订单字段的预定单号并执行门禁。"""
|
||||
try:
|
||||
lines = task_line_purpose_values(task, required={'reservation_id'})
|
||||
except ValueError as exc:
|
||||
return [{
|
||||
'line_index': None,
|
||||
'part_number': '',
|
||||
'field': 'reservation_id',
|
||||
'reason': 'order_schema_unavailable',
|
||||
'severity': 'blocking',
|
||||
'raw_value': '',
|
||||
'detail': str(exc),
|
||||
}]
|
||||
return reservation_gate_issues(lines)
|
||||
@@ -1,64 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/routing_facts.py
|
||||
|
||||
用途:构造库存源路由规则可读取的受控业务事实。
|
||||
依赖:无 ORM 写入依赖;调用方传入已完成解析和标准化的任务/订单行数据。
|
||||
逻辑:规则引擎只能通过本模块的白名单读取事实,避免管理端规则访问任意模型字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
ALLOWED_SYSTEM_FACT_KEYS = frozenset({
|
||||
'task.customer_code', 'task.destination_country', 'task.destination_city', 'task.destination_port',
|
||||
'task.warehouse_hint', 'task.order_type', 'task.sender_email', 'task.sender_domain',
|
||||
'line.reservation_id', 'line.part_number', 'line.customer_part_number', 'line.aws_part_number',
|
||||
'line.inventory_source_hint',
|
||||
})
|
||||
|
||||
|
||||
def build_routing_facts(*, task: Any, line: dict[str, Any] | None = None) -> dict[str, dict[str, Any]]:
|
||||
"""
|
||||
将任务和订单行投影为路由规则可读取的稳定事实。
|
||||
|
||||
Args:
|
||||
task: ShippingTask 或提供同名属性的对象。
|
||||
line: 单条规范订单行;任务级规则传 None。
|
||||
|
||||
Returns:
|
||||
dict: 使用 task/line 两层命名空间的只读事实字典。
|
||||
"""
|
||||
line_data = dict(line or {})
|
||||
sender_email = str(getattr(task, 'sender_email', '') or '').strip().lower()
|
||||
sender_domain = sender_email.rsplit('@', 1)[-1] if '@' in sender_email else ''
|
||||
return {
|
||||
'task': {
|
||||
'customer_code': str(getattr(task, 'customer_code', '') or '').strip().upper(),
|
||||
'destination_country': str(getattr(task, 'destination_country', '') or '').strip().upper(),
|
||||
'destination_city': str(getattr(task, 'destination_city', '') or '').strip().upper(),
|
||||
'destination_port': str(getattr(task, 'destination_code', '') or '').strip().upper(),
|
||||
'warehouse_hint': str(getattr(task, 'warehouse_hint', '') or '').strip().upper(),
|
||||
'order_type': str(getattr(task, 'order_type', '') or '').strip().upper(),
|
||||
'sender_email': sender_email,
|
||||
'sender_domain': sender_domain,
|
||||
},
|
||||
'line': {
|
||||
key: str(line_data.get(key) or '').strip().upper()
|
||||
for key in ('reservation_id', 'part_number', 'customer_part_number', 'aws_part_number', 'inventory_source_hint')
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def read_system_fact(facts: dict[str, dict[str, Any]], fact_path: str) -> Any:
|
||||
"""
|
||||
读取白名单路由事实。
|
||||
|
||||
Raises:
|
||||
KeyError: 规则引用未注册字段时抛出,调用方应拒绝发布或执行该规则。
|
||||
"""
|
||||
if fact_path not in ALLOWED_SYSTEM_FACT_KEYS:
|
||||
raise KeyError(f'Unsupported routing fact: {fact_path}')
|
||||
namespace, field = fact_path.split('.', 1)
|
||||
return facts.get(namespace, {}).get(field)
|
||||
@@ -130,7 +130,7 @@ def write_inventory_export_batch_trigger(
|
||||
continue
|
||||
# 调用方只持有非敏感快照;写 trigger 前在服务端按 Source 补入 Profile 密文。
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
configuration_test = str((payload or {}).get('trigger_type') or '') == 'configuration_test'
|
||||
configuration_test = str((payload or {}).get('trigger_type') or '') in {'configuration_test', 'configuration_test_batch'}
|
||||
trigger_source = get_rpa_trigger_inventory_source(
|
||||
str(source["source_code"]), enabled_only=not configuration_test,
|
||||
) or source
|
||||
@@ -149,6 +149,8 @@ def write_inventory_export_batch_trigger(
|
||||
"parameters": source.get("parameters") or [],
|
||||
"query": source.get("query") or {},
|
||||
"credential_envelope": source.get("credential_envelope") or {},
|
||||
# 配置测试回调据此将批次结果精确回写到各自站点运行。
|
||||
"validation_run_no": source.get("validation_run_no"),
|
||||
})
|
||||
if not inventory_sources:
|
||||
return None
|
||||
|
||||
@@ -233,7 +233,7 @@ def build_shipping_runtime_context(
|
||||
request_id: 本次请求 ID。
|
||||
locale: 用户语言。
|
||||
scope: 上下文作用域。
|
||||
run_purpose: 本次 Dify run 的目的,如 parse_notice。
|
||||
run_purpose: 本次 Dify run 的目的,如 order_extraction。
|
||||
intake_nos: 尚未建 Task 时的 Intake 编号集合。
|
||||
capability: 当前固定画布能力。
|
||||
temporary_inventory_asset_no: 本轮对话临时库存文件资产编号;仅供 Dify 调用受控 Tool。
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
services/shipping_notice/state_machine.py
|
||||
|
||||
用途:发货通知人工节点(checkpoint)与动作按钮的单一注册表,负责任务 DB 字段与 UI 状态的映射。
|
||||
依赖:models.ShippingTask、constants(CP_*/PH_*/RS_*)、rpa_attempts、task_line_store。
|
||||
依赖:models.ShippingTask、constants(CP_*/PH_*/RS_*)、rpa_attempts、order_field_purposes。
|
||||
逻辑:tools.py 通过 apply_task_transition 写库并返回 checkpoint;ui_state.py 与历史兼容模块都从本文件读取按钮/状态;新增人工节点时仅改本文件与测试;
|
||||
是否具备可匹配订单行经 read_task_order_lines 判断。
|
||||
是否具备可匹配订单行经锁定 Extraction 的 FieldValue 判断。
|
||||
|
||||
扩展说明(开发者):
|
||||
- checkpoint id 即 API `checkpoint` / Dify `flow_ckpt`
|
||||
@@ -19,7 +19,7 @@ from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.task_line_store import read_task_order_lines
|
||||
from app.services.shipping_notice.order_field_purposes import task_line_purpose_values
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_EXPORT_READY,
|
||||
CP_EXPORT_GENERATED,
|
||||
@@ -53,6 +53,14 @@ from app.services.shipping_notice.constants import (
|
||||
RS_RSV_REQ,
|
||||
RS_SHORTAGE_REVIEW,
|
||||
)
|
||||
|
||||
|
||||
def _task_has_dynamic_order_lines(task: ShippingTask) -> bool:
|
||||
"""仅在当前已接受 Extraction 含行 FieldValue 时开放库存匹配检查点。"""
|
||||
try:
|
||||
return bool(task_line_purpose_values(task))
|
||||
except ValueError:
|
||||
return False
|
||||
from app.services.shipping_notice.rpa_attempts import (
|
||||
inventory_rpa_attempts,
|
||||
max_rpa_inventory_attempts,
|
||||
@@ -290,7 +298,7 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
|
||||
and not task.review_status
|
||||
and not task.pending_human_reason
|
||||
and not task.match_status
|
||||
and len(read_task_order_lines(task)) > 0
|
||||
and bool(_task_has_dynamic_order_lines(task))
|
||||
):
|
||||
return TaskUiState(
|
||||
checkpoint=CP_READY_MATCH,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/shipping_notice/task_candidate_reconciliation.py
|
||||
|
||||
用途:将 Candidate 订单行对账到既有 Task(字段级自动补齐 / 冲突落库)。
|
||||
依赖:po_number、reservation_id、task_line_store、task_field_conflict_service、state_machine。
|
||||
依赖:po_number、reservation_id、动态订单 FieldValue、task_field_conflict_service、state_machine。
|
||||
逻辑:batch_from_intakes / open_existing 路径调用;仅安全态任务可自动补齐。
|
||||
"""
|
||||
|
||||
@@ -15,18 +15,19 @@ from typing import Any
|
||||
from app.models import ShippingNoticeCandidate, ShippingTask
|
||||
from app.services.shipping_notice.constants import PH_RSV_REQ
|
||||
from app.services.shipping_notice.po_number import normalize_po_number
|
||||
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
from app.services.shipping_notice.reservation_id import (
|
||||
is_valid_reservation_id,
|
||||
validated_reservation_id,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.task_field_conflict_service import (
|
||||
line_id_for_conflict_position,
|
||||
list_open_field_conflicts,
|
||||
upsert_open_field_conflict,
|
||||
from app.services.shipping_notice.task_field_conflict_service import list_open_field_conflicts, upsert_open_field_conflict
|
||||
from app.services.shipping_notice.task_order_field_editor import (
|
||||
current_header_field_values,
|
||||
current_line_field_configs,
|
||||
current_line_field_values,
|
||||
replace_current_line_field_value,
|
||||
)
|
||||
from app.services.shipping_notice.task_line_store import read_task_order_lines, replace_task_order_lines
|
||||
|
||||
# 可自动对账字段;part_number/Qty 仅作行对齐键,禁止被 Candidate 覆盖。
|
||||
RECONCILE_FIELDS: tuple[str, ...] = (
|
||||
@@ -104,7 +105,8 @@ def build_candidate_reconciliation_plan(
|
||||
Returns:
|
||||
{status, reason?, fills[], conflicts[], ambiguous_keys[], unverified_indexes[]}
|
||||
"""
|
||||
target_lines = read_task_order_lines(task)
|
||||
target_lines = current_line_field_values(task)
|
||||
allowed_field_names = set(current_line_field_configs(task))
|
||||
candidate_lines = [
|
||||
dict(item) for item in (candidate_summary.get('lines') or []) if isinstance(item, dict)
|
||||
]
|
||||
@@ -135,6 +137,8 @@ def build_candidate_reconciliation_plan(
|
||||
continue
|
||||
field_payload: dict[str, Any] = {}
|
||||
for field_name in RECONCILE_FIELDS:
|
||||
if field_name not in allowed_field_names:
|
||||
continue
|
||||
raw = line.get(field_name)
|
||||
normalized = _normalize_field_value(field_name, raw)
|
||||
if not normalized:
|
||||
@@ -233,11 +237,12 @@ def build_candidate_reconciliation_plan(
|
||||
}
|
||||
|
||||
|
||||
def _apply_fills_to_lines(
|
||||
def _apply_fills_to_current_extraction(
|
||||
task: ShippingTask,
|
||||
target_lines: list[dict[str, Any]],
|
||||
fills: list[dict[str, Any]],
|
||||
) -> set[int]:
|
||||
"""仅对空字段执行 fills,返回变更过的行下标。"""
|
||||
"""仅向当前 Extraction 的空 FieldValue 写入补齐值,返回变更过的行下标。"""
|
||||
updated: set[int] = set()
|
||||
for item in fills:
|
||||
position = int(item['position'])
|
||||
@@ -246,6 +251,12 @@ def _apply_fills_to_lines(
|
||||
field_name = str(item['field_name'])
|
||||
if str(target_lines[position].get(field_name) or '').strip():
|
||||
continue
|
||||
replace_current_line_field_value(
|
||||
task=task,
|
||||
position=position,
|
||||
field_code=field_name,
|
||||
value=item['value'],
|
||||
)
|
||||
target_lines[position][field_name] = item['value']
|
||||
updated.add(position)
|
||||
return updated
|
||||
@@ -261,7 +272,7 @@ def apply_candidate_reconciliation_plan(
|
||||
"""
|
||||
应用对账计划:自动补齐或落库冲突。
|
||||
|
||||
核心逻辑:ready/conflicted 均先安全应用空字段 fills(双写);
|
||||
核心逻辑:ready/conflicted 均先安全应用空字段 fills 到当前 FieldValue;
|
||||
conflicted 额外落库字段冲突,不覆盖双方已有且不同的业务值。
|
||||
"""
|
||||
status = str(plan.get('status') or '')
|
||||
@@ -273,15 +284,9 @@ def apply_candidate_reconciliation_plan(
|
||||
'details': plan.get('details') or {},
|
||||
}
|
||||
|
||||
# [STEP 1] 无论 ready/conflicted,都先安全应用空字段 fills,并确保规范行存在以便绑定 line_id。
|
||||
target_lines = [dict(item) for item in read_task_order_lines(task)]
|
||||
updated_indexes = _apply_fills_to_lines(target_lines, list(plan.get('fills') or []))
|
||||
target_lines = replace_task_order_lines(
|
||||
task,
|
||||
target_lines,
|
||||
normalize=False,
|
||||
bump_version=bool(updated_indexes) or status == 'conflicted',
|
||||
)
|
||||
# [STEP 1] 无论 ready/conflicted,都只更新当前锁定 Extraction 的空 FieldValue。
|
||||
target_lines = [dict(item) for item in current_line_field_values(task)]
|
||||
updated_indexes = _apply_fills_to_current_extraction(task, target_lines, list(plan.get('fills') or []))
|
||||
|
||||
if status == 'conflicted':
|
||||
for item in plan.get('conflicts') or []:
|
||||
@@ -291,10 +296,9 @@ def apply_candidate_reconciliation_plan(
|
||||
field_name=str(item['field_name']),
|
||||
existing_value=item.get('existing_value'),
|
||||
incoming_value=item.get('incoming_value'),
|
||||
existing_source='task_lines',
|
||||
existing_source='order_field_value',
|
||||
incoming_source=source,
|
||||
position=position,
|
||||
line_id=line_id_for_conflict_position(task, position),
|
||||
incoming_evidence=[
|
||||
{
|
||||
'candidate_no': candidate.candidate_no,
|
||||
@@ -303,7 +307,7 @@ def apply_candidate_reconciliation_plan(
|
||||
],
|
||||
)
|
||||
open_rows = list_open_field_conflicts(task)
|
||||
issues = reservation_gate_issues(target_lines)
|
||||
issues = task_reservation_gate_issues(task)
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
step_payload['parse_validation'] = {
|
||||
'status': 'needs_review',
|
||||
@@ -341,7 +345,7 @@ def apply_candidate_reconciliation_plan(
|
||||
'updated_line_indexes': [],
|
||||
}
|
||||
|
||||
issues = reservation_gate_issues(target_lines)
|
||||
issues = task_reservation_gate_issues(task)
|
||||
open_rows = list_open_field_conflicts(task)
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
step_payload['parse_validation'] = {
|
||||
@@ -412,7 +416,7 @@ def reconcile_exact_file_open_existing(
|
||||
return {'status': 'skipped', 'reason': 'target_task_not_safe'}
|
||||
|
||||
candidate_po = normalize_po_number(candidate_summary.get('po_number'))
|
||||
task_po = normalize_po_number(task.po_number)
|
||||
task_po = normalize_po_number(current_header_field_values(task).get('po_number'))
|
||||
if not candidate_po or not task_po or candidate_po != task_po:
|
||||
return {'status': 'skipped', 'reason': 'po_number_mismatch'}
|
||||
|
||||
@@ -423,7 +427,7 @@ def reconcile_exact_file_open_existing(
|
||||
)
|
||||
# 兼容旧语义:仅 Reservation 已齐且无其他可填字段时视为 target_already_complete。
|
||||
if plan.get('status') == 'skipped' and plan.get('reason') == 'no_fillable_fields':
|
||||
lines = read_task_order_lines(task)
|
||||
lines = current_line_field_values(task)
|
||||
if lines and all(is_valid_reservation_id(line.get('reservation_id')) for line in lines):
|
||||
return {'status': 'skipped', 'reason': 'target_already_complete'}
|
||||
return {'status': 'skipped', 'reason': 'no_unique_empty_target_line'}
|
||||
|
||||
@@ -0,0 +1,419 @@
|
||||
"""
|
||||
services/shipping_notice/task_disposition_service.py
|
||||
|
||||
用途:集中处理发货任务的回收站、作废与归档生命周期,避免复用 process_status 的业务含义。
|
||||
依赖:ShippingTask / ShippingTaskEvent、SQLAlchemy 行锁、ShippingCase 生命周期事实。
|
||||
逻辑:workspace 批量处置 API(后续阶段)通过本模块锁定任务、重算资格、写审计;编排与回调阶段读取本模块的 active 判定以阻断副作用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal
|
||||
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingBatch,
|
||||
ShippingExportArtifact,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
ShippingTaskEvent,
|
||||
ShippingTaskInventoryLink,
|
||||
ShippingTaskPurgeAudit,
|
||||
)
|
||||
|
||||
TaskDispositionAction = Literal['delete', 'void', 'archive', 'restore']
|
||||
|
||||
_EXTERNAL_UPLOAD_STATUSES = frozenset({
|
||||
'queued', 'pending', 'triggered', 'running', 'uploading', 'uploaded', 'succeeded', 'success',
|
||||
})
|
||||
_EXTERNAL_PROCESS_STATUSES = frozenset({'uploaded', 'completed', 'closed'})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TaskDispositionCapability:
|
||||
"""单个处置动作的服务端资格结论;供批量接口逐票返回。"""
|
||||
|
||||
allowed: bool
|
||||
code: str | None = None
|
||||
reason: str | None = None
|
||||
|
||||
|
||||
def task_is_active(task: ShippingTask) -> bool:
|
||||
"""
|
||||
判断任务是否仍可触发履约副作用。
|
||||
|
||||
核心逻辑:回收站、作废和归档都不是 process_status,因此所有异步入口必须统一调用本函数。
|
||||
|
||||
Args:
|
||||
task: 已加载的发货任务。
|
||||
|
||||
Returns:
|
||||
bool: 仅 active 且不在回收站中的任务返回 True。
|
||||
"""
|
||||
return (
|
||||
str(getattr(task, 'lifecycle_status', 'active') or 'active').strip().lower() == 'active'
|
||||
and getattr(task, 'deleted_at', None) is None
|
||||
)
|
||||
|
||||
|
||||
def task_execution_block_reason(task: ShippingTask) -> str | None:
|
||||
"""
|
||||
为异步编排和外部回调提供统一的副作用熔断原因。
|
||||
|
||||
Args:
|
||||
task: 已加载的发货任务。
|
||||
|
||||
Returns:
|
||||
str | None: 非活动任务返回稳定原因;活动任务返回 None。
|
||||
"""
|
||||
if task_is_active(task):
|
||||
return None
|
||||
if task.deleted_at is not None:
|
||||
return 'task_in_recycle_bin'
|
||||
lifecycle = str(task.lifecycle_status or '').strip().lower()
|
||||
return f'task_lifecycle_{lifecycle or "inactive"}'
|
||||
|
||||
|
||||
def load_task_for_disposition(task_no: str) -> ShippingTask:
|
||||
"""
|
||||
以行锁加载任务,供同一事务内重新判定并写入处置结果。
|
||||
|
||||
Args:
|
||||
task_no: 内部 SN 技术编号,不能为空。
|
||||
|
||||
Returns:
|
||||
ShippingTask: 已加行锁且预加载业务单的任务。
|
||||
|
||||
Raises:
|
||||
ValidationError: 任务号为空。
|
||||
NotFoundError: 任务不存在。
|
||||
"""
|
||||
normalized_task_no = str(task_no or '').strip().upper()
|
||||
if not normalized_task_no:
|
||||
raise ValidationError('task_no is required', code='SHIPPING.TASK_NO_REQUIRED')
|
||||
task = (
|
||||
ShippingTask.query.options(joinedload(ShippingTask.shipping_case))
|
||||
.filter(ShippingTask.task_no == normalized_task_no)
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if task is None:
|
||||
raise NotFoundError('Shipping task not found', code='SHIPPING.TASK_NOT_FOUND')
|
||||
return task
|
||||
|
||||
|
||||
def _has_external_fulfillment(task: ShippingTask) -> bool:
|
||||
"""识别已提交、正在提交或已有货代回执的任务;这些任务不可在平台单方作废。"""
|
||||
upload_status = str(task.upload_status or '').strip().lower()
|
||||
process_status = str(task.process_status or '').strip().lower()
|
||||
return bool(
|
||||
task.freight_ref_no
|
||||
or task.upload_receipt_json
|
||||
or upload_status in _EXTERNAL_UPLOAD_STATUSES
|
||||
or process_status in _EXTERNAL_PROCESS_STATUSES
|
||||
)
|
||||
|
||||
|
||||
def _has_successor(task: ShippingTask) -> bool:
|
||||
"""修订链存在后继时禁止作废旧任务,避免破坏版本追溯。"""
|
||||
return (
|
||||
db.session.query(ShippingTask.id)
|
||||
.filter(ShippingTask.supersedes_task_id == int(task.id))
|
||||
.first()
|
||||
is not None
|
||||
)
|
||||
|
||||
|
||||
def task_disposition_capability(
|
||||
task: ShippingTask,
|
||||
action: TaskDispositionAction,
|
||||
) -> TaskDispositionCapability:
|
||||
"""
|
||||
基于当前数据库事实计算任务处置资格。
|
||||
|
||||
核心逻辑:外部履约状态优先于平台操作;已上传或上传中的任务只能归档,不能被平台标为作废。
|
||||
|
||||
Args:
|
||||
task: 待处置任务;批量路径必须先以行锁重新读取。
|
||||
action: delete/void/archive/restore 之一。
|
||||
|
||||
Returns:
|
||||
TaskDispositionCapability: 是否可执行及稳定阻断码。
|
||||
"""
|
||||
lifecycle = str(task.lifecycle_status or 'active').strip().lower()
|
||||
if action == 'restore':
|
||||
if task.deleted_at is None:
|
||||
return TaskDispositionCapability(False, 'SHIPPING.TASK_NOT_DELETED', 'Task is not in recycle bin')
|
||||
if lifecycle != 'active':
|
||||
return TaskDispositionCapability(False, 'SHIPPING.TASK_RESTORE_BLOCKED', 'Voided or archived task cannot be restored')
|
||||
return TaskDispositionCapability(True)
|
||||
|
||||
if task.deleted_at is not None:
|
||||
return TaskDispositionCapability(False, 'SHIPPING.TASK_ALREADY_DELETED', 'Task is already in recycle bin')
|
||||
if lifecycle != 'active':
|
||||
return TaskDispositionCapability(False, 'SHIPPING.TASK_LIFECYCLE_CONFLICT', 'Task is no longer active')
|
||||
if action == 'archive':
|
||||
return TaskDispositionCapability(True)
|
||||
if _has_external_fulfillment(task):
|
||||
return TaskDispositionCapability(
|
||||
False,
|
||||
'SHIPPING.TASK_EXTERNAL_VOID_BLOCKED',
|
||||
'External fulfillment exists or is in progress; archive the task instead',
|
||||
)
|
||||
if action in {'delete', 'void'} and _has_successor(task):
|
||||
return TaskDispositionCapability(
|
||||
False,
|
||||
'SHIPPING.TASK_SUCCESSOR_VOID_BLOCKED',
|
||||
'Task has a revision successor',
|
||||
)
|
||||
if action == 'delete':
|
||||
return TaskDispositionCapability(True)
|
||||
if action == 'void':
|
||||
return TaskDispositionCapability(True)
|
||||
raise ValidationError('Unsupported task disposition action', code='SHIPPING.TASK_DISPOSITION_INVALID')
|
||||
|
||||
|
||||
def _write_disposition_event(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
event_type: str,
|
||||
actor_id: int | None,
|
||||
request_id: str | None,
|
||||
detail: dict[str, Any],
|
||||
) -> None:
|
||||
"""以独立审计事件记录处置前后事实,避免任务字段覆盖后无法追溯。"""
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=int(task.id),
|
||||
event_type=event_type,
|
||||
actor_id=actor_id,
|
||||
request_id=str(request_id or '').strip()[:64] or None,
|
||||
detail_json=detail,
|
||||
))
|
||||
|
||||
|
||||
def move_task_to_recycle_bin(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
actor_id: int,
|
||||
reason: str,
|
||||
request_id: str | None = None,
|
||||
) -> str:
|
||||
"""
|
||||
将任务移入回收站;非纯草稿会先作废以保留业务终止事实。
|
||||
|
||||
Args:
|
||||
task: 已行锁加载的任务。
|
||||
actor_id: 当前操作者 ID,必须存在。
|
||||
reason: 删除原因,禁止为空。
|
||||
request_id: 可选请求追踪 ID。
|
||||
|
||||
Returns:
|
||||
str: `deleted` 或 `voided_and_deleted`,供批量结果展示。
|
||||
|
||||
Raises:
|
||||
ValidationError: 删除原因为空。
|
||||
ConflictError: 当前状态不允许删除。
|
||||
"""
|
||||
normalized_reason = str(reason or '').strip()
|
||||
if not normalized_reason:
|
||||
raise ValidationError('reason is required', code='SHIPPING.TASK_DELETE_REASON_REQUIRED')
|
||||
capability = task_disposition_capability(task, 'delete')
|
||||
if not capability.allowed:
|
||||
raise ConflictError(capability.reason or 'Task delete is blocked', code=capability.code or 'SHIPPING.TASK_DELETE_BLOCKED')
|
||||
|
||||
# [STEP 1] 已解析或已产生内部引用的任务先作废,再进入回收站;纯 created 误建仅隐藏。
|
||||
has_internal_business_record = bool(
|
||||
task.shipping_case_id
|
||||
or task.source_candidate_id
|
||||
or task.match_status
|
||||
or task.export_file_path
|
||||
or db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).first()
|
||||
or db.session.query(ShippingExportArtifact.id).filter_by(task_id=int(task.id)).first()
|
||||
or db.session.query(ShippingNoticeCandidate.id).filter_by(consumed_task_id=int(task.id)).first()
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
task.deleted_at = now
|
||||
task.deleted_by_id = int(actor_id)
|
||||
task.deletion_reason = normalized_reason
|
||||
if has_internal_business_record:
|
||||
task.lifecycle_status = 'voided'
|
||||
task.voided_at = now
|
||||
task.voided_by_id = int(actor_id)
|
||||
task.void_reason = normalized_reason
|
||||
outcome = 'voided_and_deleted'
|
||||
else:
|
||||
outcome = 'deleted'
|
||||
_write_disposition_event(
|
||||
task,
|
||||
event_type='task_deleted',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
detail={
|
||||
'outcome': outcome,
|
||||
'reason': normalized_reason,
|
||||
'process_status_before': task.process_status,
|
||||
'lifecycle_status_after': task.lifecycle_status,
|
||||
},
|
||||
)
|
||||
return outcome
|
||||
|
||||
|
||||
def void_task(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
actor_id: int,
|
||||
reason: str,
|
||||
request_id: str | None = None,
|
||||
) -> None:
|
||||
"""作废未产生外部履约的活动任务,并保留可审计原因。"""
|
||||
normalized_reason = str(reason or '').strip()
|
||||
if not normalized_reason:
|
||||
raise ValidationError('reason is required', code='SHIPPING.TASK_VOID_REASON_REQUIRED')
|
||||
capability = task_disposition_capability(task, 'void')
|
||||
if not capability.allowed:
|
||||
raise ConflictError(capability.reason or 'Task void is blocked', code=capability.code or 'SHIPPING.TASK_VOID_BLOCKED')
|
||||
now = datetime.utcnow()
|
||||
task.lifecycle_status = 'voided'
|
||||
task.voided_at = now
|
||||
task.voided_by_id = int(actor_id)
|
||||
task.void_reason = normalized_reason
|
||||
_write_disposition_event(
|
||||
task,
|
||||
event_type='task_voided',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
detail={'reason': normalized_reason, 'process_status_before': task.process_status},
|
||||
)
|
||||
|
||||
|
||||
def archive_task(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
actor_id: int,
|
||||
request_id: str | None = None,
|
||||
) -> None:
|
||||
"""归档任务以隐藏默认列表,不改变外部或 process_status 业务事实。"""
|
||||
capability = task_disposition_capability(task, 'archive')
|
||||
if not capability.allowed:
|
||||
raise ConflictError(capability.reason or 'Task archive is blocked', code=capability.code or 'SHIPPING.TASK_ARCHIVE_BLOCKED')
|
||||
task.lifecycle_status = 'archived'
|
||||
task.archived_at = datetime.utcnow()
|
||||
task.archived_by_id = int(actor_id)
|
||||
_write_disposition_event(
|
||||
task,
|
||||
event_type='task_archived',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
detail={'process_status': task.process_status},
|
||||
)
|
||||
|
||||
|
||||
def restore_task_from_recycle_bin(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
actor_id: int,
|
||||
request_id: str | None = None,
|
||||
) -> None:
|
||||
"""恢复未作废的纯误建任务;已作废任务必须按受控新建/修订流程处理。"""
|
||||
capability = task_disposition_capability(task, 'restore')
|
||||
if not capability.allowed:
|
||||
raise ConflictError(capability.reason or 'Task restore is blocked', code=capability.code or 'SHIPPING.TASK_RESTORE_BLOCKED')
|
||||
task.deleted_at = None
|
||||
task.deleted_by_id = None
|
||||
task.deletion_reason = None
|
||||
_write_disposition_event(
|
||||
task,
|
||||
event_type='task_restored',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
detail={},
|
||||
)
|
||||
|
||||
|
||||
def purge_task_permanently(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
actor_id: int,
|
||||
reason: str,
|
||||
request_id: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
永久删除回收站中的纯误建任务,并以无外键快照保留最低审计。
|
||||
|
||||
Args:
|
||||
task: 已行锁加载的回收站任务。
|
||||
actor_id: 管理员 ID。
|
||||
reason: 清除原因,禁止为空。
|
||||
request_id: 可选请求追踪 ID。
|
||||
|
||||
Raises:
|
||||
ConflictError: 任一业务、解析、库存、导出、修订或外部引用存在时阻断。
|
||||
"""
|
||||
normalized_reason = str(reason or '').strip()
|
||||
if not normalized_reason:
|
||||
raise ValidationError('reason is required', code='SHIPPING.TASK_PURGE_REASON_REQUIRED')
|
||||
if task.deleted_at is None or str(task.lifecycle_status or 'active') != 'active':
|
||||
raise ConflictError('Only deleted pure draft task can be purged', code='SHIPPING.TASK_PURGE_BLOCKED')
|
||||
|
||||
from app.models import ShippingOrderExtraction, ShippingTemporaryInventorySession
|
||||
from app.models.shipping_task_line import ShippingTaskFieldConflict
|
||||
|
||||
# [STEP 1] 不依赖前端预检,事务内重新统计全部会破坏可追溯性的引用。
|
||||
blocking_counts = {
|
||||
'shipping_case': int(bool(task.shipping_case_id)),
|
||||
'batch': int(bool(task.batch_id)),
|
||||
'batch_focus_reference': db.session.query(ShippingBatch.id).filter(
|
||||
ShippingBatch.current_focus_task_no == task.task_no,
|
||||
).count(),
|
||||
'source_asset': int(bool(task.source_asset_id)),
|
||||
'source_intake': int(bool(task.source_intake_id)),
|
||||
'source_candidate': int(bool(task.source_candidate_id)),
|
||||
'current_order_extraction': int(bool(task.current_order_extraction_id)),
|
||||
'inventory_snapshot': int(bool(task.inventory_snapshot_id)),
|
||||
'successor': int(_has_successor(task)),
|
||||
'duplicate_link': int(bool(task.duplicate_source_task_id)),
|
||||
'duplicate_source_for_other_task': db.session.query(ShippingTask.id).filter(
|
||||
ShippingTask.duplicate_source_task_id == int(task.id),
|
||||
).count(),
|
||||
'external_upload_fact': int(_has_external_fulfillment(task)),
|
||||
'inventory_link': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(),
|
||||
'export_artifact': db.session.query(ShippingExportArtifact.id).filter_by(task_id=int(task.id)).count(),
|
||||
'candidate_consumed': db.session.query(ShippingNoticeCandidate.id).filter_by(consumed_task_id=int(task.id)).count(),
|
||||
'intake_consumed': db.session.query(ShippingNoticeIntake.id).filter_by(consumed_task_id=int(task.id)).count(),
|
||||
'order_extraction': db.session.query(ShippingOrderExtraction.id).filter_by(task_id=int(task.id)).count(),
|
||||
'temporary_inventory_session': db.session.query(ShippingTemporaryInventorySession.id).filter_by(task_id=int(task.id)).count(),
|
||||
'field_conflict': db.session.query(ShippingTaskFieldConflict.id).filter_by(task_id=int(task.id)).count(),
|
||||
'non_disposition_event': db.session.query(ShippingTaskEvent.id).filter(
|
||||
ShippingTaskEvent.task_id == int(task.id),
|
||||
ShippingTaskEvent.event_type.notin_(('task_deleted', 'task_restored')),
|
||||
).count(),
|
||||
}
|
||||
blocking = {key: value for key, value in blocking_counts.items() if value}
|
||||
if blocking:
|
||||
raise ConflictError(
|
||||
'Task has business or audit references and cannot be purged',
|
||||
code='SHIPPING.TASK_PURGE_BLOCKED',
|
||||
details={'blocking_references': blocking},
|
||||
)
|
||||
|
||||
# [STEP 2] 审计快照不得保留 task_id,随后删除 task 的级联事件仍不会抹掉清除记录。
|
||||
db.session.add(ShippingTaskPurgeAudit(
|
||||
task_no_snapshot=task.task_no,
|
||||
actor_id=int(actor_id),
|
||||
reason=normalized_reason,
|
||||
request_id=str(request_id or '').strip()[:64] or None,
|
||||
snapshot_json={
|
||||
'task_no': task.task_no,
|
||||
'process_status': task.process_status,
|
||||
'lifecycle_status': task.lifecycle_status,
|
||||
'deleted_at': task.deleted_at.isoformat() if task.deleted_at else None,
|
||||
'deletion_reason': task.deletion_reason,
|
||||
},
|
||||
))
|
||||
db.session.delete(task)
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/shipping_notice/task_field_conflict_service.py
|
||||
|
||||
用途:订单字段冲突的创建、查询与人工解决。
|
||||
依赖:ShippingTask、ShippingTaskFieldConflict、ShippingTaskLine、task_line_store、state_machine。
|
||||
依赖:ShippingTask、ShippingTaskFieldConflict、动态订单 FieldValue、state_machine。
|
||||
逻辑:对账模块写入 open 冲突;workspace API 查询/解决;解决后回写订单行并重算门禁。
|
||||
"""
|
||||
|
||||
@@ -13,10 +13,10 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import ShippingTask, ShippingTaskFieldConflict, ShippingTaskLine
|
||||
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
|
||||
from app.models import ShippingTask, ShippingTaskFieldConflict
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.task_line_store import read_task_order_lines, replace_task_order_lines
|
||||
from app.services.shipping_notice.task_order_field_editor import replace_current_line_field_value
|
||||
from app.services.shipping_notice.tool_common import log_task_event
|
||||
|
||||
|
||||
@@ -25,7 +25,6 @@ def serialize_field_conflict(row: ShippingTaskFieldConflict) -> dict[str, Any]:
|
||||
return {
|
||||
'id': row.id,
|
||||
'task_id': row.task_id,
|
||||
'line_id': row.line_id,
|
||||
'position': row.position,
|
||||
'field_name': row.field_name,
|
||||
'existing_value': row.existing_value,
|
||||
@@ -44,7 +43,6 @@ def serialize_field_conflict(row: ShippingTaskFieldConflict) -> dict[str, Any]:
|
||||
'updated_at': row.updated_at.isoformat() if row.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
def list_open_field_conflicts(task: ShippingTask) -> list[ShippingTaskFieldConflict]:
|
||||
"""返回任务未解决字段冲突(open),按 position/field 排序。"""
|
||||
rows = (
|
||||
@@ -69,7 +67,6 @@ def upsert_open_field_conflict(
|
||||
existing_evidence: list[dict[str, Any]] | None = None,
|
||||
incoming_evidence: list[dict[str, Any]] | None = None,
|
||||
position: int | None = None,
|
||||
line_id: int | None = None,
|
||||
) -> ShippingTaskFieldConflict:
|
||||
"""
|
||||
创建或刷新同一 (task, line, field) 的 open 冲突。
|
||||
@@ -81,14 +78,11 @@ def upsert_open_field_conflict(
|
||||
field_name=str(field_name),
|
||||
status='open',
|
||||
)
|
||||
# 行级冲突优先按 position 定位,避免 line_id 重建或为空时多行同字段被压成一条。
|
||||
# 行级冲突只按动态 Extraction 的 position 定位。
|
||||
if position is not None:
|
||||
query = query.filter_by(position=int(position))
|
||||
elif line_id is not None:
|
||||
query = query.filter_by(line_id=int(line_id))
|
||||
else:
|
||||
query = query.filter(
|
||||
ShippingTaskFieldConflict.line_id.is_(None),
|
||||
ShippingTaskFieldConflict.position.is_(None),
|
||||
)
|
||||
row = query.first()
|
||||
@@ -104,7 +98,6 @@ def upsert_open_field_conflict(
|
||||
if row is None:
|
||||
row = ShippingTaskFieldConflict(
|
||||
task_id=int(task.id),
|
||||
line_id=line_id,
|
||||
field_name=str(field_name),
|
||||
status='open',
|
||||
conflict_version=1,
|
||||
@@ -119,17 +112,6 @@ def upsert_open_field_conflict(
|
||||
return row
|
||||
|
||||
|
||||
def _line_id_for_position(task: ShippingTask, position: int | None) -> int | None:
|
||||
"""按 position 解析规范行主键;无规范行时返回 None。"""
|
||||
if position is None:
|
||||
return None
|
||||
row = (
|
||||
ShippingTaskLine.query.filter_by(task_id=int(task.id), position=int(position))
|
||||
.first()
|
||||
)
|
||||
return int(row.id) if row else None
|
||||
|
||||
|
||||
def resolve_field_conflict(
|
||||
*,
|
||||
task: ShippingTask,
|
||||
@@ -146,7 +128,7 @@ def resolve_field_conflict(
|
||||
人工解决字段冲突并回写订单行。
|
||||
|
||||
核心逻辑:校验版本;按 keep_existing / take_incoming / custom 取值;
|
||||
经 task_line_store 双写后标记 resolved,并回到 parse_review。
|
||||
写回当前动态 FieldValue 后标记 resolved,并回到 parse_review。
|
||||
|
||||
Args:
|
||||
resolution: keep_existing | take_incoming | custom
|
||||
@@ -213,12 +195,11 @@ def resolve_field_conflict(
|
||||
code='SHIPPING.INVALID_CONFLICT_RESOLUTION',
|
||||
)
|
||||
|
||||
# [STEP 2] 行级冲突回写 lines;任务级冲突暂只关闭审计(当前仅行字段)。
|
||||
before_lines = read_task_order_lines(task)
|
||||
after_lines = [dict(item) for item in before_lines]
|
||||
if conflict.position is not None and 0 <= int(conflict.position) < len(after_lines):
|
||||
after_lines[int(conflict.position)][conflict.field_name] = value
|
||||
replace_task_order_lines(task, after_lines, normalize=False)
|
||||
# [STEP 2] 行级冲突回写当前 FieldValue;旧任务行投影不再参与业务真相。
|
||||
if conflict.position is not None:
|
||||
replace_current_line_field_value(
|
||||
task=task, position=int(conflict.position), field_code=conflict.field_name, value=value,
|
||||
)
|
||||
|
||||
conflict.status = 'resolved'
|
||||
conflict.resolved_value = value
|
||||
@@ -229,7 +210,7 @@ def resolve_field_conflict(
|
||||
conflict.updated_at = datetime.utcnow()
|
||||
|
||||
remaining = list_open_field_conflicts(task)
|
||||
issues = reservation_gate_issues(read_task_order_lines(task))
|
||||
issues = task_reservation_gate_issues(task)
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
step_payload['field_conflicts'] = {
|
||||
'open_count': len(remaining),
|
||||
@@ -293,8 +274,3 @@ def resolve_field_conflict(
|
||||
'open_conflict_count': len(remaining),
|
||||
'idempotent_replay': False,
|
||||
}
|
||||
|
||||
|
||||
def line_id_for_conflict_position(task: ShippingTask, position: int | None) -> int | None:
|
||||
"""对外暴露 position→line_id 解析,供对账写入使用。"""
|
||||
return _line_id_for_position(task, position)
|
||||
@@ -1,447 +0,0 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/task_line_store.py
|
||||
|
||||
用途:统一订单行读写与双写;在同一事务内维护规范表与 lines_json 快照。
|
||||
依赖:ShippingTask、ShippingTaskLine、notice_lines.normalize_notice_lines、Flask current_app。
|
||||
逻辑:task_workflow / open_existing 回填 / decision_workflow 等写入口委托本模块;
|
||||
WRITE_MODE=json|dual|table,READ_MODE=json|shadow|table;默认 dual/shadow。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy import delete
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingTask, ShippingTaskLine
|
||||
from app.services.shipping_notice.notice_lines import normalize_notice_lines
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_STANDARD_FIELDS = (
|
||||
'part_number',
|
||||
'qty',
|
||||
'uom',
|
||||
'reservation_id',
|
||||
'inventory_source_hint',
|
||||
'line_no',
|
||||
'required_date',
|
||||
'customer_part_number',
|
||||
'aws_part_number',
|
||||
'po_number',
|
||||
'allocation_id',
|
||||
'unit_price',
|
||||
'amount',
|
||||
'currency',
|
||||
'remark',
|
||||
)
|
||||
|
||||
|
||||
def order_lines_write_mode() -> str:
|
||||
"""读取订单行写模式:json / dual / table。"""
|
||||
mode = str(current_app.config.get('SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE') or 'dual').strip().lower()
|
||||
return mode if mode in {'json', 'dual', 'table'} else 'dual'
|
||||
|
||||
|
||||
def order_lines_read_mode() -> str:
|
||||
"""读取订单行读模式:json / shadow / table。"""
|
||||
mode = str(current_app.config.get('SHIPPING_NOTICE_ORDER_LINES_READ_MODE') or 'shadow').strip().lower()
|
||||
return mode if mode in {'json', 'shadow', 'table'} else 'shadow'
|
||||
|
||||
|
||||
def _to_decimal(value: Any) -> Decimal | None:
|
||||
"""将数量/金额转为 Decimal;非法值返回 None。"""
|
||||
if value is None or value == '':
|
||||
return None
|
||||
try:
|
||||
return Decimal(str(value))
|
||||
except (InvalidOperation, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _decimal_to_json_number(value: Decimal) -> int | str:
|
||||
"""
|
||||
将 Decimal 转为 JSON 友好数值。
|
||||
|
||||
核心逻辑:整数保持 int;非整数用去尾零十进制字符串,避免 float 精度假差异。
|
||||
"""
|
||||
normalized = value.normalize()
|
||||
as_int = int(normalized)
|
||||
if Decimal(as_int) == normalized:
|
||||
return as_int
|
||||
text = format(normalized, 'f')
|
||||
if '.' in text:
|
||||
text = text.rstrip('0').rstrip('.')
|
||||
return text
|
||||
|
||||
|
||||
def _json_safe(value: Any) -> Any:
|
||||
"""把 Decimal 等转为 JSON 可序列化值,主要用于规范表→投影。"""
|
||||
if isinstance(value, Decimal):
|
||||
return _decimal_to_json_number(value)
|
||||
return value
|
||||
|
||||
|
||||
def line_to_json(line: ShippingTaskLine) -> dict[str, Any]:
|
||||
"""
|
||||
将规范行投影为 shipping-task-line-v2 的 lines_json 元素。
|
||||
|
||||
Args:
|
||||
line: ShippingTaskLine 实例。
|
||||
Returns:
|
||||
含标准字段与 extra_json 展开项的字典。
|
||||
"""
|
||||
payload: dict[str, Any] = {
|
||||
'part_number': line.part_number,
|
||||
'qty': _json_safe(line.qty),
|
||||
}
|
||||
for field in _STANDARD_FIELDS:
|
||||
if field in {'part_number', 'qty'}:
|
||||
continue
|
||||
value = getattr(line, field, None)
|
||||
if value in (None, ''):
|
||||
continue
|
||||
payload[field] = _json_safe(value)
|
||||
if isinstance(line.extra_json, dict):
|
||||
for key, value in line.extra_json.items():
|
||||
if key not in payload and value not in (None, ''):
|
||||
payload[key] = value
|
||||
return payload
|
||||
|
||||
|
||||
# 影子对账时统一为字符串的标识类字段,避免 JSON number vs 规范表 str 假阳性。
|
||||
_CHECKSUM_STRING_FIELDS = frozenset(
|
||||
{
|
||||
'part_number',
|
||||
'uom',
|
||||
'reservation_id',
|
||||
'inventory_source_hint',
|
||||
'line_no',
|
||||
'required_date',
|
||||
'customer_part_number',
|
||||
'aws_part_number',
|
||||
'po_number',
|
||||
'allocation_id',
|
||||
'currency',
|
||||
'remark',
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _canonicalize_line_for_checksum(line: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
将订单行投影规范为可比较形态。
|
||||
|
||||
核心逻辑:数值字段统一为去尾零十进制字符串;标识字段统一 strip 字符串;
|
||||
忽略空值,避免 JSON number / Decimal / 规范表 str 往返假差异。
|
||||
"""
|
||||
payload: dict[str, Any] = {}
|
||||
for key, value in line.items():
|
||||
if value in (None, ''):
|
||||
continue
|
||||
if key in {'qty', 'unit_price', 'amount'}:
|
||||
decimal_value = _to_decimal(value)
|
||||
if decimal_value is None:
|
||||
payload[key] = value
|
||||
else:
|
||||
normalized = format(decimal_value.normalize(), 'f')
|
||||
if '.' in normalized:
|
||||
normalized = normalized.rstrip('0').rstrip('.')
|
||||
payload[key] = normalized
|
||||
continue
|
||||
if key in _CHECKSUM_STRING_FIELDS or isinstance(value, (str, int, float, bool)):
|
||||
text = str(value).strip()
|
||||
if text == '':
|
||||
continue
|
||||
payload[key] = text
|
||||
continue
|
||||
payload[key] = _json_safe(value)
|
||||
return payload
|
||||
|
||||
|
||||
def lines_checksum(lines: list[dict[str, Any]]) -> str:
|
||||
"""计算订单行投影稳定 checksum,供影子校验与回填对账。"""
|
||||
canonical_lines = [_canonicalize_line_for_checksum(dict(item)) for item in lines if isinstance(item, dict)]
|
||||
canonical = json.dumps(canonical_lines, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
|
||||
return hashlib.sha256(canonical.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _build_line_row(*, task_id: int, position: int, raw: dict[str, Any]) -> ShippingTaskLine:
|
||||
"""
|
||||
从 shipping-task-line-v2 字典构建规范行,未知扩展字段进入 extra_json。
|
||||
|
||||
核心逻辑:先验证内部料号是非空原子值,再验证正数数量;旧料号字段不作兼容转换。
|
||||
Args:
|
||||
task_id: 所属任务主键。
|
||||
position: 订单行位置。
|
||||
raw: 仅接受 v2 标准字段的订单行。
|
||||
Returns:
|
||||
可加入当前事务的 ShippingTaskLine。
|
||||
Raises:
|
||||
ValueError: part_number 缺失、包含 `/` 或 qty 非正数。
|
||||
"""
|
||||
extra = {
|
||||
key: value
|
||||
for key, value in raw.items()
|
||||
if key not in _STANDARD_FIELDS and value not in (None, '')
|
||||
}
|
||||
qty = _to_decimal(raw.get('qty'))
|
||||
if qty is None or qty <= 0:
|
||||
raise ValueError(f'invalid qty at position={position}')
|
||||
part_number = str(raw.get('part_number') or '').strip()
|
||||
if not part_number:
|
||||
raise ValueError(f'missing part_number at position={position}')
|
||||
if '/' in part_number:
|
||||
raise ValueError(f'non-atomic part_number at position={position}')
|
||||
optional_part_numbers = {
|
||||
field: str(raw.get(field) or '').strip() or None
|
||||
for field in ('customer_part_number', 'aws_part_number')
|
||||
}
|
||||
invalid_optional = next(
|
||||
(field for field, value in optional_part_numbers.items() if value and '/' in value),
|
||||
None,
|
||||
)
|
||||
if invalid_optional:
|
||||
raise ValueError(f'non-atomic {invalid_optional} at position={position}')
|
||||
return ShippingTaskLine(
|
||||
task_id=task_id,
|
||||
position=position,
|
||||
part_number=part_number,
|
||||
qty=qty,
|
||||
uom=str(raw.get('uom') or '').strip() or None,
|
||||
reservation_id=str(raw.get('reservation_id') or '').strip() or None,
|
||||
inventory_source_hint=str(raw.get('inventory_source_hint') or '').strip() or None,
|
||||
line_no=str(raw.get('line_no') or '').strip() or None,
|
||||
required_date=str(raw.get('required_date') or '').strip() or None,
|
||||
customer_part_number=optional_part_numbers['customer_part_number'],
|
||||
aws_part_number=optional_part_numbers['aws_part_number'],
|
||||
po_number=str(raw.get('po_number') or '').strip() or None,
|
||||
allocation_id=str(raw.get('allocation_id') or '').strip() or None,
|
||||
unit_price=_to_decimal(raw.get('unit_price')),
|
||||
amount=_to_decimal(raw.get('amount')),
|
||||
currency=str(raw.get('currency') or '').strip() or None,
|
||||
remark=str(raw.get('remark') or '').strip() or None,
|
||||
extra_json=extra or None,
|
||||
field_sources_json=None,
|
||||
evidence_json=None,
|
||||
schema_version='shipping-task-line-v2',
|
||||
line_version=1,
|
||||
)
|
||||
|
||||
|
||||
def replace_task_order_lines(
|
||||
task: ShippingTask,
|
||||
lines: list[dict[str, Any]] | None,
|
||||
*,
|
||||
bump_version: bool = True,
|
||||
normalize: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
原子替换任务订单行。
|
||||
|
||||
核心逻辑:可选标准化 → 写 lines_json 与/或规范表 → 递增 order_data_version。
|
||||
同一调用方事务内提交;失败时两侧一起回滚。
|
||||
|
||||
Args:
|
||||
task: 目标任务(调用方应已持有合适行锁)。
|
||||
lines: 新订单行列表;None/空表示清空。
|
||||
bump_version: 是否递增乐观版本。
|
||||
normalize: 是否先走 normalize_notice_lines;默认 False,以免丢掉未知字段。
|
||||
|
||||
Returns:
|
||||
实际写入的 JSON 投影列表。
|
||||
"""
|
||||
raw_lines = list(lines or [])
|
||||
normalized = normalize_notice_lines(raw_lines) if normalize else [
|
||||
dict(item) for item in raw_lines if isinstance(item, dict)
|
||||
]
|
||||
write_mode = order_lines_write_mode()
|
||||
|
||||
# [STEP 1] 规范表外键需要稳定 task.id;新建任务须先 flush。
|
||||
if write_mode in {'dual', 'table'} and task.id is None:
|
||||
db.session.flush()
|
||||
|
||||
# [STEP 2] 先构造全部行再落库,避免非法行导致 JSON 已改、规范表半写。
|
||||
built_rows: list[ShippingTaskLine] = []
|
||||
if write_mode in {'dual', 'table'}:
|
||||
built_rows = [
|
||||
_build_line_row(task_id=int(task.id), position=position, raw=item)
|
||||
for position, item in enumerate(normalized)
|
||||
]
|
||||
|
||||
if write_mode in {'json', 'dual'}:
|
||||
task.lines_json = normalized
|
||||
|
||||
if write_mode in {'dual', 'table'}:
|
||||
# [STEP 3] 删除旧规范行;line_id FK 为 ON DELETE SET NULL,冲突审计保留。
|
||||
from app.models import ShippingTaskFieldConflict
|
||||
|
||||
db.session.execute(
|
||||
delete(ShippingTaskLine).where(ShippingTaskLine.task_id == int(task.id))
|
||||
)
|
||||
for row in built_rows:
|
||||
db.session.add(row)
|
||||
db.session.flush()
|
||||
# [STEP 4] 按 position 重绑冲突到新行主键。
|
||||
position_to_line_id = {
|
||||
int(row.position): int(row.id)
|
||||
for row in built_rows
|
||||
if row.id is not None
|
||||
}
|
||||
conflicts = (
|
||||
ShippingTaskFieldConflict.query.filter(
|
||||
ShippingTaskFieldConflict.task_id == int(task.id),
|
||||
ShippingTaskFieldConflict.position.isnot(None),
|
||||
)
|
||||
.execution_options(populate_existing=True)
|
||||
.all()
|
||||
)
|
||||
for conflict in conflicts:
|
||||
rebound = position_to_line_id.get(int(conflict.position))
|
||||
if rebound is not None:
|
||||
conflict.line_id = rebound
|
||||
task.order_lines_migration_status = 'synced'
|
||||
if 'order_lines' in task.__dict__:
|
||||
db.session.expire(task, ['order_lines'])
|
||||
|
||||
if bump_version:
|
||||
task.order_data_version = int(task.order_data_version or 1) + 1
|
||||
return normalized
|
||||
|
||||
|
||||
def clear_task_order_lines(task: ShippingTask, *, bump_version: bool = True) -> None:
|
||||
"""清空任务订单行(JSON 与规范表按写模式同步)。"""
|
||||
replace_task_order_lines(task, [], bump_version=bump_version, normalize=False)
|
||||
|
||||
|
||||
def sync_task_order_lines_from_json(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
dry_run: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将现有 lines_json 同步到规范表(历史回填专用)。
|
||||
|
||||
核心逻辑:不改写 lines_json、不递增 order_data_version;非法行返回 failed 原因。
|
||||
幂等:两侧 checksum 已一致时标记 synced 并跳过。
|
||||
|
||||
Args:
|
||||
task: 待回填任务。
|
||||
dry_run: True 时只校验不写入。
|
||||
|
||||
Returns:
|
||||
{status: synced|skipped|failed, reason?, line_count?, checksum?}
|
||||
"""
|
||||
json_lines = [dict(item) for item in (task.lines_json or []) if isinstance(item, dict)]
|
||||
comparison = compare_task_order_line_projections(task)
|
||||
if comparison['equal'] and task.order_lines_migration_status == 'synced':
|
||||
return {
|
||||
'status': 'skipped',
|
||||
'reason': 'already_synced',
|
||||
'line_count': comparison['json_count'],
|
||||
'checksum': comparison['json_checksum'],
|
||||
}
|
||||
|
||||
# [STEP 1] 先构造行对象以捕获非法 part_number/qty,避免半写。
|
||||
built_rows: list[ShippingTaskLine] = []
|
||||
try:
|
||||
for position, item in enumerate(json_lines):
|
||||
built_rows.append(_build_line_row(task_id=int(task.id), position=position, raw=item))
|
||||
except (ValueError, TypeError) as exc:
|
||||
return {
|
||||
'status': 'failed',
|
||||
'reason': str(exc),
|
||||
'line_count': len(json_lines),
|
||||
'checksum': lines_checksum(json_lines),
|
||||
}
|
||||
|
||||
if dry_run:
|
||||
return {
|
||||
'status': 'synced',
|
||||
'reason': 'dry_run',
|
||||
'line_count': len(built_rows),
|
||||
'checksum': lines_checksum(json_lines),
|
||||
}
|
||||
|
||||
db.session.execute(
|
||||
delete(ShippingTaskLine).where(ShippingTaskLine.task_id == int(task.id))
|
||||
)
|
||||
for row in built_rows:
|
||||
db.session.add(row)
|
||||
task.order_lines_migration_status = 'synced'
|
||||
if 'order_lines' in task.__dict__:
|
||||
db.session.expire(task, ['order_lines'])
|
||||
return {
|
||||
'status': 'synced',
|
||||
'line_count': len(built_rows),
|
||||
'checksum': lines_checksum(json_lines),
|
||||
}
|
||||
|
||||
|
||||
def _table_order_lines_for_task(task: ShippingTask) -> list[dict[str, Any]]:
|
||||
"""
|
||||
读取规范表订单行投影。
|
||||
|
||||
核心逻辑:未落库(task.id 为空)时返回空列表,避免 int(None) 与无效查询。
|
||||
"""
|
||||
if task.id is None:
|
||||
return []
|
||||
table_rows = (
|
||||
ShippingTaskLine.query.filter_by(task_id=int(task.id))
|
||||
.order_by(ShippingTaskLine.position.asc())
|
||||
.all()
|
||||
)
|
||||
return [line_to_json(row) for row in table_rows]
|
||||
|
||||
|
||||
def read_task_order_lines(task: ShippingTask) -> list[dict[str, Any]]:
|
||||
"""
|
||||
按读模式返回订单行投影。
|
||||
|
||||
核心逻辑:json 直接读快照;table 读规范表;shadow 对外仍返回 JSON,并记录差异。
|
||||
"""
|
||||
json_lines = [dict(item) for item in (task.lines_json or []) if isinstance(item, dict)]
|
||||
mode = order_lines_read_mode()
|
||||
if mode == 'json':
|
||||
return json_lines
|
||||
|
||||
table_lines = _table_order_lines_for_task(task)
|
||||
if mode == 'table':
|
||||
return table_lines
|
||||
|
||||
# shadow:对外仍读 JSON,差异只记日志不改响应。
|
||||
json_checksum = lines_checksum(json_lines)
|
||||
table_checksum = lines_checksum(table_lines)
|
||||
if json_checksum != table_checksum:
|
||||
logger.warning(
|
||||
'shipping task line shadow mismatch task_no=%s json_count=%s table_count=%s '
|
||||
'json_checksum=%s table_checksum=%s',
|
||||
task.task_no,
|
||||
len(json_lines),
|
||||
len(table_lines),
|
||||
json_checksum,
|
||||
table_checksum,
|
||||
)
|
||||
return json_lines
|
||||
|
||||
|
||||
def compare_task_order_line_projections(task: ShippingTask) -> dict[str, Any]:
|
||||
"""比较 JSON 快照与规范表投影,返回差异摘要。"""
|
||||
json_lines = [dict(item) for item in (task.lines_json or []) if isinstance(item, dict)]
|
||||
table_lines = _table_order_lines_for_task(task)
|
||||
json_checksum = lines_checksum(json_lines)
|
||||
table_checksum = lines_checksum(table_lines)
|
||||
return {
|
||||
'task_no': task.task_no,
|
||||
'json_count': len(json_lines),
|
||||
'table_count': len(table_lines),
|
||||
'json_checksum': json_checksum,
|
||||
'table_checksum': table_checksum,
|
||||
'equal': json_checksum == table_checksum,
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
"""
|
||||
services/shipping_notice/task_order_field_editor.py
|
||||
|
||||
用途:在人工复核时更新任务当前订单解析的已裁决 FieldValue。
|
||||
依赖:订单 Schema 运行模型、ShippingTaskFieldConflict、SQLAlchemy db。
|
||||
逻辑:按当前发布契约的 field_code 找到稳定 field_id,仅修改当前 accepted Extraction 对应行的 Decision/FieldValue,不回写旧任务行投影。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
ShippingOrderExtraction, ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingTask,
|
||||
)
|
||||
|
||||
|
||||
def current_line_field_values(task: ShippingTask) -> list[dict[str, Any]]:
|
||||
"""按锁定 Schema 快照返回当前已接受 Extraction 的行字段值,供人工编辑和审计展示使用。"""
|
||||
extraction = _current_extraction(task)
|
||||
configs = current_line_field_configs(task)
|
||||
values = {
|
||||
(int(item.line_id), str(item.field_id)): item.value_json
|
||||
for item in ShippingOrderFieldValue.query.filter_by(extraction_id=extraction.id).all()
|
||||
if item.line_id is not None
|
||||
}
|
||||
lines = ShippingOrderLine.query.filter_by(extraction_id=extraction.id).order_by(ShippingOrderLine.position).all()
|
||||
return [
|
||||
{
|
||||
str(config['field_code']): values.get((int(line.id), str(config['field_id'])))
|
||||
for config in configs.values()
|
||||
}
|
||||
for line in lines
|
||||
]
|
||||
|
||||
|
||||
def current_line_field_values_or_empty(task: ShippingTask) -> list[dict[str, Any]]:
|
||||
"""为未完成订单抽取的任务提供空行集,供只读投影安全展示。"""
|
||||
try:
|
||||
return current_line_field_values(task)
|
||||
except ConflictError:
|
||||
return []
|
||||
|
||||
|
||||
def current_header_field_values(task: ShippingTask) -> dict[str, Any]:
|
||||
"""按任务锁定 Schema 快照返回当前已接受 Extraction 的单头字段值。"""
|
||||
extraction = _current_extraction(task)
|
||||
configs = {
|
||||
str(item['field_id']): str(item['field_code'])
|
||||
for item in (extraction.schema_version.definition_json or {}).get('fields') or []
|
||||
if item.get('scope') == 'header'
|
||||
}
|
||||
values = {
|
||||
str(item.field_id): item.value_json
|
||||
for item in ShippingOrderFieldValue.query.filter_by(extraction_id=extraction.id, line_id=None).all()
|
||||
}
|
||||
return {code: values.get(field_id) for field_id, code in configs.items()}
|
||||
|
||||
|
||||
def current_header_field_values_or_empty(task: ShippingTask) -> dict[str, Any]:
|
||||
"""为未完成订单抽取的任务提供空单头集,供读模型安全展示。"""
|
||||
try:
|
||||
return current_header_field_values(task)
|
||||
except ConflictError:
|
||||
return {}
|
||||
|
||||
|
||||
def bump_order_data_version(task: ShippingTask) -> None:
|
||||
"""订单 FieldValue 发生业务变更后递增乐观锁版本。"""
|
||||
task.order_data_version = int(task.order_data_version or 1) + 1
|
||||
|
||||
|
||||
def retire_current_order_extraction(task: ShippingTask) -> None:
|
||||
"""废弃当前订单真相版本并解除任务指针,供整单重新解析或重新上传使用。"""
|
||||
extraction = (
|
||||
db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
if task.current_order_extraction_id is not None else None
|
||||
)
|
||||
if extraction is not None and extraction.status == 'accepted':
|
||||
extraction.status = 'superseded'
|
||||
task.current_order_extraction_id = None
|
||||
bump_order_data_version(task)
|
||||
|
||||
|
||||
def current_line_field_configs(task: ShippingTask) -> dict[str, dict[str, Any]]:
|
||||
"""按锁定 Schema 快照返回行字段配置,禁止人工编辑按当前发布版本解释旧任务。"""
|
||||
extraction = _current_extraction(task)
|
||||
return {
|
||||
str(item['field_code']): item
|
||||
for item in (extraction.schema_version.definition_json or {}).get('fields') or []
|
||||
if item.get('scope') == 'line'
|
||||
}
|
||||
|
||||
|
||||
def _current_extraction(task: ShippingTask) -> ShippingOrderExtraction:
|
||||
"""读取任务当前已接受 Extraction;人工编辑绝不回退旧任务行投影。"""
|
||||
extraction = (
|
||||
db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
if task.current_order_extraction_id is not None else None
|
||||
)
|
||||
if extraction is None or extraction.status != 'accepted':
|
||||
raise ConflictError('Task has no accepted order extraction', code='SHIPPING.ORDER_FIELD_EDIT_BLOCKED')
|
||||
return extraction
|
||||
|
||||
|
||||
def _normalized_value(value: Any, config: dict[str, Any]) -> Any:
|
||||
"""按锁定字段类型转换人工输入,避免人工路径绕过动态 Schema 的基础类型约束。"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
value_type = str(config.get('value_type') or 'string')
|
||||
try:
|
||||
if value_type == 'decimal':
|
||||
return Decimal(str(value).replace(',', '').strip())
|
||||
if value_type == 'integer':
|
||||
return int(str(value).replace(',', '').strip())
|
||||
except (InvalidOperation, ValueError, TypeError) as exc:
|
||||
raise ValidationError('Order field value type is invalid', code='SHIPPING.ORDER_FIELD_EDIT_INVALID') from exc
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def _field_value_columns(value: Any, value_type: str) -> dict[str, Any]:
|
||||
"""生成唯一 FieldValue 的类型化列,JSON 值始终作为下游读取的统一入口。"""
|
||||
return {
|
||||
'value_text': str(value) if value is not None and value_type in {'string', 'enum'} else None,
|
||||
'value_decimal': value if value_type == 'decimal' else None,
|
||||
'value_integer': value if value_type == 'integer' else None,
|
||||
'value_date': value if value_type == 'date' else None,
|
||||
'value_boolean': value if value_type == 'boolean' else None,
|
||||
'value_json': value,
|
||||
}
|
||||
|
||||
|
||||
def replace_current_line_field_value(*, task: ShippingTask, position: int, field_code: str, value: Any) -> None:
|
||||
"""将人工确认值写入当前 accepted Extraction 的稳定字段,缺少值投影时补建 FieldValue。"""
|
||||
extraction = _current_extraction(task)
|
||||
config = next(
|
||||
(
|
||||
item for item in (extraction.schema_version.definition_json or {}).get('fields') or []
|
||||
if item.get('scope') == 'line' and item.get('field_code') == field_code
|
||||
),
|
||||
None,
|
||||
)
|
||||
if config is None:
|
||||
raise ValidationError('Conflict field is not in the published order schema', code='SHIPPING.ORDER_FIELD_EDIT_INVALID')
|
||||
normalized = _normalized_value(value, config)
|
||||
line = ShippingOrderLine.query.filter_by(
|
||||
extraction_id=extraction.id, position=int(position),
|
||||
).one_or_none()
|
||||
if line is None:
|
||||
raise ConflictError('Order extraction line is unavailable', code='SHIPPING.ORDER_FIELD_EDIT_BLOCKED')
|
||||
decision = ShippingOrderFieldDecision.query.filter_by(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=str(config['field_id']),
|
||||
).one_or_none()
|
||||
field_value = ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=str(config['field_id']),
|
||||
).one_or_none()
|
||||
if decision is None:
|
||||
raise ConflictError('Order field decision is unavailable', code='SHIPPING.ORDER_FIELD_EDIT_BLOCKED')
|
||||
# 人工复核后的值成为当前决策真相,保留原 Observation 与冲突审计链。
|
||||
decision.decision_status = 'accepted'
|
||||
decision.resolved_value_json = normalized
|
||||
columns = _field_value_columns(normalized, str(config.get('value_type') or 'string'))
|
||||
if field_value is None:
|
||||
field_value = ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=str(config['field_id']),
|
||||
decision_id=decision.id, **columns,
|
||||
)
|
||||
db.session.add(field_value)
|
||||
else:
|
||||
for key, item in columns.items():
|
||||
setattr(field_value, key, item)
|
||||
bump_order_data_version(task)
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def replace_current_header_field_value(*, task: ShippingTask, field_code: str, value: Any) -> None:
|
||||
"""将人工确认值写入当前 accepted Extraction 的单头 FieldValue。"""
|
||||
extraction = _current_extraction(task)
|
||||
config = next(
|
||||
(
|
||||
item for item in (extraction.schema_version.definition_json or {}).get('fields') or []
|
||||
if item.get('scope') == 'header' and item.get('field_code') == field_code
|
||||
),
|
||||
None,
|
||||
)
|
||||
if config is None:
|
||||
raise ValidationError('Header field is not in the published order schema', code='SHIPPING.ORDER_FIELD_EDIT_INVALID')
|
||||
normalized = _normalized_value(value, config)
|
||||
decision = ShippingOrderFieldDecision.query.filter_by(
|
||||
extraction_id=extraction.id, line_id=None, field_id=str(config['field_id']),
|
||||
).one_or_none()
|
||||
field_value = ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=extraction.id, line_id=None, field_id=str(config['field_id']),
|
||||
).one_or_none()
|
||||
if decision is None:
|
||||
raise ConflictError('Order header decision is unavailable', code='SHIPPING.ORDER_FIELD_EDIT_BLOCKED')
|
||||
decision.decision_status = 'accepted'
|
||||
decision.resolved_value_json = normalized
|
||||
columns = _field_value_columns(normalized, str(config.get('value_type') or 'string'))
|
||||
if field_value is None:
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=None, field_id=str(config['field_id']),
|
||||
decision_id=decision.id, **columns,
|
||||
))
|
||||
else:
|
||||
for key, item in columns.items():
|
||||
setattr(field_value, key, item)
|
||||
bump_order_data_version(task)
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def replace_current_line_fields(*, task: ShippingTask, lines: list[dict[str, Any]]) -> None:
|
||||
"""以人工确认的完整行集创建新的已接受 Extraction,供新增或删除订单行使用。"""
|
||||
extraction = _current_extraction(task)
|
||||
configs = [
|
||||
item for item in (extraction.schema_version.definition_json or {}).get('fields') or []
|
||||
if item.get('scope') == 'line'
|
||||
]
|
||||
replacement = ShippingOrderExtraction(
|
||||
task_id=task.id,
|
||||
intake_id=extraction.intake_id,
|
||||
schema_version_id=extraction.schema_version_id,
|
||||
input_snapshot_hash=extraction.input_snapshot_hash,
|
||||
input_snapshot_json=extraction.input_snapshot_json,
|
||||
status='accepted',
|
||||
raw_llm_output_json=extraction.raw_llm_output_json,
|
||||
normalized_result_json={'header': (extraction.normalized_result_json or {}).get('header') or {}, 'lines': lines},
|
||||
validation_result_json={'blocked_fields': []},
|
||||
created_by_id=extraction.created_by_id,
|
||||
)
|
||||
db.session.add(replacement)
|
||||
db.session.flush()
|
||||
# 单头同样属于锁定 Extraction;新行版本必须保留其已裁决值,不能让人工行编辑抹掉客户或 PO 事实。
|
||||
header_decisions = ShippingOrderFieldDecision.query.filter_by(
|
||||
extraction_id=extraction.id, line_id=None,
|
||||
).all()
|
||||
header_values = {
|
||||
str(item.field_id): item
|
||||
for item in ShippingOrderFieldValue.query.filter_by(extraction_id=extraction.id, line_id=None).all()
|
||||
}
|
||||
for previous in header_decisions:
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=replacement.id,
|
||||
line_id=None,
|
||||
field_id=str(previous.field_id),
|
||||
decision_status=previous.decision_status,
|
||||
resolved_value_json=previous.resolved_value_json,
|
||||
supporting_observation_ids_json=[],
|
||||
reason_code='copied_from_human_line_revision',
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
previous_value = header_values.get(str(previous.field_id))
|
||||
if previous_value is not None:
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=replacement.id,
|
||||
line_id=None,
|
||||
field_id=str(previous.field_id),
|
||||
decision_id=decision.id,
|
||||
value_text=previous_value.value_text,
|
||||
value_decimal=previous_value.value_decimal,
|
||||
value_integer=previous_value.value_integer,
|
||||
value_date=previous_value.value_date,
|
||||
value_boolean=previous_value.value_boolean,
|
||||
value_json=previous_value.value_json,
|
||||
))
|
||||
for position, values in enumerate(lines):
|
||||
line = ShippingOrderLine(extraction_id=replacement.id, position=position)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for config in configs:
|
||||
value = _normalized_value(values.get(str(config['field_code'])), config)
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=replacement.id,
|
||||
line_id=line.id,
|
||||
field_id=str(config['field_id']),
|
||||
decision_status='accepted' if value is not None else 'missing',
|
||||
resolved_value_json=value,
|
||||
supporting_observation_ids_json=[],
|
||||
reason_code='human_line_set' if value is not None else 'missing',
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
if value is not None:
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=replacement.id,
|
||||
line_id=line.id,
|
||||
field_id=str(config['field_id']),
|
||||
decision_id=decision.id,
|
||||
**_field_value_columns(value, str(config.get('value_type') or 'string')),
|
||||
))
|
||||
extraction.status = 'superseded'
|
||||
task.current_order_extraction_id = replacement.id
|
||||
bump_order_data_version(task)
|
||||
db.session.flush()
|
||||
@@ -2,9 +2,8 @@
|
||||
services/shipping_notice/task_workflow.py
|
||||
|
||||
用途:发货通知任务/批次生命周期、解析与单头/订单行编辑的主编排入口。
|
||||
依赖:query_service、tool_common、decision_workflow、progress_workflow、state_machine、task_line_store。
|
||||
逻辑:tools.py 门面委托本模块;人工决策与自动推进分支已下沉到独立 workflow,本文件保留核心任务创建、解析和编辑入口;
|
||||
订单行写/读路径统一经 task_line_store(双写 + read_task_order_lines)。
|
||||
依赖:query_service、tool_common、decision_workflow、progress_workflow、state_machine、动态订单字段编辑器。
|
||||
逻辑:tools.py 门面委托本模块;建单只创建待动态订单抽取任务,人工编辑只更新锁定 Extraction 的 FieldValue。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,37 +12,23 @@ import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
CP_PARSE_OK,
|
||||
CP_PARSE_REVIEW,
|
||||
CP_RSV_REQ,
|
||||
CP_TASK_EXISTS,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
RS_PARSE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
adjudicate_and_apply_inventory_source,
|
||||
is_inventory_source_stable,
|
||||
)
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.constants import CP_TASK_EXISTS
|
||||
from app.services.shipping_notice.decision_workflow import submit_decision
|
||||
from app.services.shipping_notice.extract import extract_notice_fields
|
||||
from app.services.shipping_notice.notice_lines import normalize_notice_lines
|
||||
from app.services.shipping_notice.parse_summary import format_parse_summary
|
||||
from app.services.shipping_notice.task_line_store import (
|
||||
clear_task_order_lines,
|
||||
read_task_order_lines,
|
||||
replace_task_order_lines,
|
||||
from app.services.shipping_notice.task_order_field_editor import (
|
||||
current_header_field_values,
|
||||
retire_current_order_extraction,
|
||||
current_line_field_configs,
|
||||
current_line_field_values,
|
||||
replace_current_header_field_value,
|
||||
replace_current_line_field_value,
|
||||
replace_current_line_fields,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
from app.services.shipping_notice.progress_workflow import auto_progress
|
||||
from app.services.shipping_notice.query_service import (
|
||||
TaskProjection,
|
||||
@@ -56,7 +41,6 @@ from app.services.shipping_notice.query_service import (
|
||||
serialize_task as qs_serialize_task,
|
||||
serialize_task_for_tool,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_id import is_valid_reservation_id
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
from app.services.shipping_notice.user_facing_status import user_facing_task_stage
|
||||
@@ -75,8 +59,6 @@ from app.services.shipping_notice.batch_create_idempotency import (
|
||||
)
|
||||
from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
auto_progress_enabled,
|
||||
defer_parse_to_dify_enabled,
|
||||
generate_task_no,
|
||||
log_task_event,
|
||||
set_task_step_progress,
|
||||
@@ -94,116 +76,6 @@ EDITABLE_NOTICE_LINE_FIELDS = frozenset({
|
||||
})
|
||||
|
||||
|
||||
def _capture_destination_context(task: ShippingTask, parsed: dict[str, Any], lines: list[Any]) -> None:
|
||||
"""保存 Dify/启发式解析出的目的地候选,供 HXOPS 库存源规则解析使用。"""
|
||||
payload = dict(task.step_payload_json or {})
|
||||
candidates: list[Any] = []
|
||||
destination = parsed.get("destination")
|
||||
if isinstance(destination, dict):
|
||||
payload["destination"] = destination
|
||||
candidates.append(destination)
|
||||
task.destination_code = str(destination.get("port_code") or destination.get("destination_code") or "").strip().upper() or None
|
||||
task.destination_city = str(destination.get("city") or "").strip() or None
|
||||
task.destination_country = str(destination.get("country") or "").strip().upper() or None
|
||||
task.warehouse_hint = str(destination.get("warehouse_hint") or "").strip() or None
|
||||
elif destination:
|
||||
candidates.append(destination)
|
||||
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to_location"):
|
||||
if parsed.get(key):
|
||||
candidates.append(parsed.get(key))
|
||||
if parsed.get("destination_port") and not task.destination_code:
|
||||
task.destination_code = str(parsed.get("destination_port") or "").strip().upper() or None
|
||||
if parsed.get("destination_city") and not task.destination_city:
|
||||
task.destination_city = str(parsed.get("destination_city") or "").strip() or None
|
||||
if parsed.get("destination_country") and not task.destination_country:
|
||||
task.destination_country = str(parsed.get("destination_country") or "").strip().upper() or None
|
||||
if parsed.get("warehouse_hint") and not task.warehouse_hint:
|
||||
task.warehouse_hint = str(parsed.get("warehouse_hint") or "").strip() or None
|
||||
if task.ship_to:
|
||||
candidates.append(task.ship_to)
|
||||
for line in lines:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
if line.get("destination"):
|
||||
candidates.append(line.get("destination"))
|
||||
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to"):
|
||||
if line.get(key):
|
||||
candidates.append(line.get(key))
|
||||
if candidates:
|
||||
payload["destination_candidates"] = candidates
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def _has_parse_review_content(task: ShippingTask, lines: list[Any]) -> bool:
|
||||
"""判断解析结果是否有足够内容进入人工复核卡片。"""
|
||||
if any(isinstance(line, dict) for line in lines):
|
||||
return True
|
||||
return any(
|
||||
str(value or "").strip()
|
||||
for value in (
|
||||
task.customer_name,
|
||||
task.customer_code,
|
||||
task.ship_to,
|
||||
task.po_number,
|
||||
task.required_date,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _missing_reservation_lines(lines: list[Any]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
检查解析结果中缺少 Reservation ID / COM ID 的订单行。
|
||||
|
||||
核心逻辑:复用库存匹配阶段的 Reservation ID 提取规则;解析阶段缺失时提前阻断,
|
||||
避免用户确认后才在库存匹配阶段失败。
|
||||
"""
|
||||
missing: list[dict[str, Any]] = []
|
||||
for index, line in enumerate(lines):
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
if is_valid_reservation_id(line.get("reservation_id")):
|
||||
continue
|
||||
missing.append(
|
||||
{
|
||||
"line_index": index,
|
||||
"part_number": str(line.get("part_number") or "").strip(),
|
||||
"reservation_id": str(line.get("reservation_id") or "").strip(),
|
||||
}
|
||||
)
|
||||
return missing
|
||||
|
||||
|
||||
def _missing_process_field_issues(lines: list[Any]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
检查 Task 进入库存链前必须补齐的订单行流程字段。
|
||||
|
||||
核心逻辑:所有入口只检查 Reservation ID;行级 inventory_source_hint 是可选库存源路由线索,
|
||||
缺失时不阻断进入库存链,但必须独立持久化以便工作台展示与人工修订。
|
||||
|
||||
Args:
|
||||
lines: 已标准化的订单行。
|
||||
Returns:
|
||||
每个缺失或格式非法 Reservation ID 对应的结构化 issue。
|
||||
"""
|
||||
issues: list[dict[str, Any]] = []
|
||||
for index, line in enumerate(lines):
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
part_number = str(line.get('part_number') or '').strip()
|
||||
raw_reservation = str(line.get('reservation_id') or '').strip()
|
||||
if is_valid_reservation_id(raw_reservation):
|
||||
continue
|
||||
issues.append({
|
||||
'line_index': index,
|
||||
'part_number': part_number,
|
||||
'field': 'reservation_id',
|
||||
'reason': 'invalid_format' if raw_reservation else 'missing',
|
||||
'severity': 'blocking',
|
||||
'raw_value': raw_reservation,
|
||||
})
|
||||
return issues
|
||||
|
||||
|
||||
def start_task_orchestrator(task_no: str | None) -> bool:
|
||||
"""延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。"""
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start
|
||||
@@ -211,15 +83,6 @@ def start_task_orchestrator(task_no: str | None) -> bool:
|
||||
return _start(task_no)
|
||||
|
||||
|
||||
def _upsert_parse_review_chat_message(task: ShippingTask) -> None:
|
||||
"""
|
||||
保留旧调用点但不再写聊天表单消息。
|
||||
|
||||
核心逻辑:解析复核动作统一由当前任务动作按钮和轻量工作台承载,避免可编辑表单进入聊天历史后在其他会话复活。
|
||||
"""
|
||||
_ = task
|
||||
|
||||
|
||||
def recompute_batch_summary(batch: ShippingBatch | None) -> None:
|
||||
"""写路径:重算批次汇总并校正 current_focus_task_no。"""
|
||||
if not batch:
|
||||
@@ -306,23 +169,12 @@ def _create_single_task_batch(payload: dict[str, Any]) -> ShippingBatch:
|
||||
return batch
|
||||
|
||||
|
||||
def _should_defer_notice_parse(payload: dict[str, Any], item: dict[str, Any]) -> bool:
|
||||
"""判断是否将 parse_notice 延后到 Dify 画布(有 structured 或显式 auto_parse 时不延后)。"""
|
||||
if isinstance(item.get("structured"), dict) and item.get("structured"):
|
||||
return False
|
||||
if payload.get("auto_parse") is True:
|
||||
return False
|
||||
if payload.get("defer_parse") is False:
|
||||
return False
|
||||
return defer_parse_to_dify_enabled()
|
||||
|
||||
|
||||
def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
一次创建批次,并为每个 notice_item 创建任务;默认将字段解析延后到 Dify 画布。
|
||||
【AI 触发时机】:当用户批量上传多份发货通知附件,希望系统自动拆成多个任务时调用。
|
||||
|
||||
核心逻辑:先创建批次,再逐个创建任务;若 notice_item 已带 structured 或 auto_parse=true 则立即 parse_notice,否则仅保存 raw_text 待 Dify 续办。
|
||||
核心逻辑:先创建批次,再逐个创建待订单抽取任务;任务只能由完整动态订单抽取结果绑定 FieldValue 后进入履约。
|
||||
Args:
|
||||
payload: 包含 user_id、conversation_id、notice_items、file_count 等批量建单数据;
|
||||
defer_commit=True 时仅 flush,由调用方与 intake 回写同事务提交。
|
||||
@@ -465,36 +317,16 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if replay is not None:
|
||||
return replay
|
||||
raise
|
||||
parse_payload: dict[str, Any] = {
|
||||
"task_id": task.task_no,
|
||||
"user_id": payload.get("user_id"),
|
||||
"conversation_id": payload.get("conversation_id"),
|
||||
"raw_text": item.get("raw_text"),
|
||||
"structured": item.get("structured"),
|
||||
}
|
||||
warnings = item.get("warnings")
|
||||
if isinstance(warnings, list):
|
||||
parse_payload["warnings"] = warnings
|
||||
if _should_defer_notice_parse(payload, item):
|
||||
log_task_event(
|
||||
task,
|
||||
"parse_deferred_to_dify",
|
||||
{"batch_no": batch.batch_no, "reason": "SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY"},
|
||||
)
|
||||
created_tasks.append(
|
||||
{
|
||||
"task_id": task.task_no,
|
||||
"batch_index": idx,
|
||||
"parse_status": "deferred",
|
||||
}
|
||||
)
|
||||
continue
|
||||
parse_result = parse_notice(parse_payload)
|
||||
log_task_event(
|
||||
task,
|
||||
"order_extraction_required",
|
||||
{"batch_no": batch.batch_no},
|
||||
)
|
||||
created_tasks.append(
|
||||
{
|
||||
"task_id": task.task_no,
|
||||
"batch_index": idx,
|
||||
"parse_status": parse_result.get("status"),
|
||||
"parse_status": "awaiting_order_extraction",
|
||||
}
|
||||
)
|
||||
|
||||
@@ -617,389 +449,6 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
|
||||
def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
解析发货通知正文并回写任务单头、订单行与解析状态。
|
||||
【AI 触发时机】:当用户上传或粘贴发货通知文本后调用;也可用于人工更正后重新解析。
|
||||
|
||||
核心逻辑:解析 notice 文本/结构化输入,回填任务字段,按置信度决定自动通过、人工确认或继续库存链路。
|
||||
Args:
|
||||
payload: 可包含 task_id、conversation_id、raw_text、structured、notice_files、lang 等参数。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: Tool 标准响应,包含解析摘要、warnings 与下一步动作提示。
|
||||
"""
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
|
||||
# [STEP 1] 解析任务上下文:终态会话收到新通知时自动建新票,避免覆盖已完结任务。
|
||||
conv_id = str(payload.get("conversation_id") or "").strip()
|
||||
explicit_task_ref = bool(str(payload.get("task_id") or payload.get("task_no") or "").strip())
|
||||
new_notice_payload = bool(
|
||||
str(payload.get("raw_text") or "").strip()
|
||||
or (isinstance(payload.get("structured"), dict) and payload.get("structured"))
|
||||
or (isinstance(payload.get("notice_files"), list) and payload.get("notice_files"))
|
||||
)
|
||||
if (
|
||||
(not explicit_task_ref)
|
||||
and conv_id
|
||||
and new_notice_payload
|
||||
and str(task.process_status or "").strip().lower() in {"uploaded", "rejected", "closed"}
|
||||
):
|
||||
batch = _create_single_task_batch(payload)
|
||||
db.session.flush()
|
||||
shipping_case = resolve_shipping_case_for_new_task(created_by_id=payload.get("user_id"))
|
||||
new_task = ShippingTask(
|
||||
task_no=generate_task_no(),
|
||||
shipping_case_id=shipping_case.id,
|
||||
batch_id=batch.id,
|
||||
user_id=payload.get("user_id"),
|
||||
conversation_id=conv_id or None,
|
||||
source_type=str(payload.get("source_type") or task.source_type or "manual"),
|
||||
batch_index=1,
|
||||
batch_total=1,
|
||||
raw_content=None,
|
||||
customer_resolution_status=(
|
||||
'confirmed' if shipping_case.customer_id is not None else 'pending'
|
||||
),
|
||||
customer_resolution_method=(
|
||||
'inherited' if shipping_case.customer_id is not None else None
|
||||
),
|
||||
process_status="created",
|
||||
)
|
||||
db.session.add(new_task)
|
||||
log_task_event(
|
||||
new_task,
|
||||
"task_created",
|
||||
{"source_type": new_task.source_type, "created_from": task.task_no, "batch_no": batch.batch_no},
|
||||
)
|
||||
db.session.flush()
|
||||
batch.current_focus_task_no = new_task.task_no
|
||||
recompute_batch_summary(batch)
|
||||
db.session.commit()
|
||||
task = new_task
|
||||
|
||||
if conv_id and not task.conversation_id:
|
||||
task.conversation_id = conv_id
|
||||
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step1_notice_submit",
|
||||
step_title="提交通知",
|
||||
status="running",
|
||||
message="正在解析发货通知",
|
||||
progress_percent=20,
|
||||
detail="正在抽取单头、订单行与关键字段",
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
# [STEP 2] 提取单头、订单行与置信度,回写任务字段。
|
||||
raw_text = str(payload.get("raw_text") or task.raw_content or "").strip()
|
||||
structured = payload.get("structured") if isinstance(payload.get("structured"), dict) else None
|
||||
notice_files = payload.get("notice_files")
|
||||
if not isinstance(notice_files, list) or not all(isinstance(i, dict) for i in notice_files):
|
||||
notice_files = None
|
||||
parsed, confidence, warnings = extract_notice_fields(
|
||||
raw_text=raw_text,
|
||||
source_type=task.source_type,
|
||||
structured=structured,
|
||||
notice_files=notice_files,
|
||||
)
|
||||
|
||||
task.raw_content = raw_text or task.raw_content
|
||||
task.customer_name = str(parsed.get("customer_name") or "").strip() or None
|
||||
task.customer_code = str(parsed.get("customer_code") or "").strip() or None
|
||||
task.ship_to = str(parsed.get("ship_to") or "").strip() or None
|
||||
task.po_number = str(parsed.get("po_number") or "").strip() or None
|
||||
lines = parsed.get("lines") if isinstance(parsed.get("lines"), list) else []
|
||||
required_date = str(parsed.get("required_date") or "").strip()
|
||||
if not required_date:
|
||||
for line in lines:
|
||||
if isinstance(line, dict):
|
||||
line_date = str(line.get("required_date") or "").strip()
|
||||
if line_date:
|
||||
required_date = line_date
|
||||
break
|
||||
task.required_date = required_date or None
|
||||
lines = replace_task_order_lines(task, lines, normalize=False)
|
||||
task.parse_confidence = confidence
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
step_payload["parse_validation"] = {
|
||||
"status": str(parsed.get("validation_status") or "ready"),
|
||||
"issues": parsed.get("parse_issues") if isinstance(parsed.get("parse_issues"), list) else [],
|
||||
}
|
||||
task.step_payload_json = step_payload
|
||||
_capture_destination_context(task, parsed, lines)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step2_parse_confirm",
|
||||
step_title="确认解析",
|
||||
status="needs_human" if confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7) else "completed",
|
||||
message="发货通知解析已完成",
|
||||
progress_percent=100,
|
||||
current=len(lines),
|
||||
total=len(lines),
|
||||
detail=f"已识别 {len(lines)} 行订单,解析置信度 {confidence:.2f}",
|
||||
extra={"warnings": warnings},
|
||||
)
|
||||
|
||||
summary_kwargs = {
|
||||
"task_no": task.task_no,
|
||||
"po_number": task.po_number,
|
||||
"ship_to": task.ship_to,
|
||||
"customer_name": task.customer_name,
|
||||
"required_date": task.required_date,
|
||||
"lines": lines,
|
||||
"warnings": warnings,
|
||||
}
|
||||
|
||||
# [STEP 3] 流程字段是后续库存匹配硬前置;允许 Task 创建,但缺失时停在字段补充门禁。
|
||||
process_field_issues = _missing_process_field_issues(lines)
|
||||
if process_field_issues:
|
||||
missing_reservation = list(process_field_issues)
|
||||
missing_fields = ['reservation_id']
|
||||
apply_task_transition(task, TaskTransition.RSV_REQUIRED)
|
||||
task.error_message = "解析失败:未识别到 Reservation ID / COM ID(预定单号)"
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
step_payload['process_field_gate'] = {
|
||||
'status': 'needs_enrichment',
|
||||
'missing_fields': missing_fields,
|
||||
'issues': process_field_issues,
|
||||
}
|
||||
task.step_payload_json = step_payload
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step2_parse_confirm",
|
||||
step_title="确认解析",
|
||||
status="failed",
|
||||
message="订单流程字段待补充",
|
||||
progress_percent=100,
|
||||
current=max(0, len(lines) - len({int(item['line_index']) for item in process_field_issues})),
|
||||
total=len(lines),
|
||||
detail="可直接通过自然对话补充 Reservation ID;补齐前不会进入库存流程。",
|
||||
extra={
|
||||
"warnings": warnings,
|
||||
"missing_reservation": missing_reservation[:5],
|
||||
"missing_process_fields": missing_fields,
|
||||
"process_field_issues": process_field_issues[:15],
|
||||
},
|
||||
)
|
||||
detail = {
|
||||
"missing_count": len(missing_reservation),
|
||||
"missing_preview": missing_reservation[:5],
|
||||
"missing_process_fields": missing_fields,
|
||||
"process_field_issues": process_field_issues[:15],
|
||||
"warnings": warnings,
|
||||
}
|
||||
log_task_event(task, "notice_process_fields_missing", detail)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=(
|
||||
"解析失败:未识别到 Reservation ID / COM ID(预定单号),"
|
||||
"当前任务无法继续匹配库存。请重新上传包含该字段的通知,或重新解析后补充预定单号。"
|
||||
),
|
||||
data={**serialize_task_for_tool(task), "missing_reservation": detail},
|
||||
checkpoint=CP_RSV_REQ,
|
||||
human_options=["replace_notice_file", "reparse", "reject"],
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
|
||||
)
|
||||
|
||||
# [STEP 4] 格式合法但与原文证据冲突等问题同样属于硬阻断,禁止被 LLM 高置信度绕过。
|
||||
parse_issues = parsed.get("parse_issues") if isinstance(parsed.get("parse_issues"), list) else []
|
||||
blocking_parse_issues = [
|
||||
item for item in parse_issues
|
||||
if isinstance(item, dict) and item.get("severity") == "blocking"
|
||||
]
|
||||
if blocking_parse_issues:
|
||||
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
|
||||
task.error_message = "解析结果与原文证据存在冲突,请人工核对关键字段。"
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step2_parse_confirm",
|
||||
step_title="确认解析",
|
||||
status="needs_human",
|
||||
message="解析关键字段需要人工核对",
|
||||
progress_percent=100,
|
||||
current=len(lines),
|
||||
total=len(lines),
|
||||
detail="Reservation ID、SKU 或数量存在来源冲突,确认前不会进入库存匹配。",
|
||||
extra={"warnings": warnings, "parse_issues": blocking_parse_issues[:10]},
|
||||
)
|
||||
log_task_event(task, "notice_parse_validation_blocked", {"parse_issues": blocking_parse_issues[:10]})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="解析结果与原文证据存在冲突,请核对后再确认。",
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"parse_validation": (task.step_payload_json or {}).get("parse_validation"),
|
||||
},
|
||||
checkpoint=CP_PARSE_REVIEW,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
|
||||
)
|
||||
|
||||
# [STEP 5] 无可审核内容时优先返回 notice_text_extraction_failed,不进入库存源裁决。
|
||||
if not _has_parse_review_content(task, lines):
|
||||
apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED)
|
||||
log_task_event(task, "notice_text_extraction_failed", {"confidence": confidence, "warnings": warnings})
|
||||
db.session.commit()
|
||||
message = (
|
||||
"未能从发货通知中解析到可审核内容,请重新上传清晰版 PDF/文本,"
|
||||
"或复制粘贴通知正文后重新解析。"
|
||||
)
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=message,
|
||||
data={**serialize_task_for_tool(task), "warnings": warnings},
|
||||
checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
)
|
||||
|
||||
# [STEP 6] 先裁决库存源线索(写入 destination / 候选),但低置信度必须先走解析复核。
|
||||
# 业务顺序:确认解析正确 → 再人工确认库存源 → 才允许库存/RPA。
|
||||
low_confidence = confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7)
|
||||
adjudication = adjudicate_and_apply_inventory_source(task)
|
||||
source_stable = is_inventory_source_stable(task)
|
||||
|
||||
if low_confidence:
|
||||
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
|
||||
log_task_event(
|
||||
task,
|
||||
"parse_needs_review",
|
||||
{
|
||||
"confidence": confidence,
|
||||
"warnings": warnings,
|
||||
"inventory_source_status": adjudication.status,
|
||||
"inventory_source_stable": source_stable,
|
||||
},
|
||||
)
|
||||
_upsert_parse_review_chat_message(task)
|
||||
db.session.commit()
|
||||
summary_text = format_parse_summary(**summary_kwargs, low_confidence=True, payload=payload)
|
||||
if not source_stable:
|
||||
summary_text = (
|
||||
f"{summary_text}\n\n"
|
||||
"解析确认通过后,若库存源仍无法唯一命中,将再请你选择正式库存源;"
|
||||
"站点与库位将由系统根据配置自动填充。"
|
||||
)
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=summary_text,
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"warnings": warnings,
|
||||
"inventory_source_candidates": adjudication.candidates,
|
||||
"inventory_source_status": adjudication.status,
|
||||
"inventory_source_reason": adjudication.reason,
|
||||
"destination_candidates": adjudication.destination_candidates,
|
||||
},
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
|
||||
)
|
||||
|
||||
# [STEP 7] 解析已自动接受(高置信度);库存源未稳定时才进入库存源人工确认。
|
||||
if not source_stable:
|
||||
from app.services.shipping_notice.inventory_source_gate import transition_task_to_inventory_source_review
|
||||
|
||||
transition_task_to_inventory_source_review(
|
||||
task,
|
||||
adjudication,
|
||||
error_message="无法根据发货通知唯一确定库存查询来源",
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step2_parse_confirm",
|
||||
step_title="确认解析",
|
||||
status="needs_human",
|
||||
message="库存源待确认",
|
||||
progress_percent=100,
|
||||
detail="解析已通过,请确认本票应使用哪个库存源后继续。",
|
||||
extra={"warnings": warnings, "inventory_source_status": adjudication.status},
|
||||
)
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_source_review_required",
|
||||
{
|
||||
"status": adjudication.status,
|
||||
"reason": adjudication.reason,
|
||||
"destination_candidates": adjudication.destination_candidates,
|
||||
"candidate_source_codes": [item.get("source_code") for item in adjudication.candidates],
|
||||
"warnings": warnings,
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
message_parts = [
|
||||
"订单解析已通过,但库存源仍待确认:",
|
||||
"- 无法根据发货通知唯一确定库存查询来源",
|
||||
]
|
||||
for warning in warnings:
|
||||
text = str(warning or "").strip()
|
||||
if text:
|
||||
message_parts.append(f"- {text}")
|
||||
message_parts.extend(
|
||||
[
|
||||
"",
|
||||
"请选择正式库存源后继续;站点与库位将由系统根据配置自动填充。",
|
||||
]
|
||||
)
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="\n".join(message_parts),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"warnings": warnings,
|
||||
"inventory_source_candidates": adjudication.candidates,
|
||||
"inventory_source_status": adjudication.status,
|
||||
"inventory_source_reason": adjudication.reason,
|
||||
"destination_candidates": adjudication.destination_candidates,
|
||||
},
|
||||
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
|
||||
)
|
||||
|
||||
apply_task_transition(task, TaskTransition.PARSED)
|
||||
log_task_event(task, "parsed", {"confidence": confidence, "warnings": warnings})
|
||||
db.session.commit()
|
||||
auto_threshold = float(current_app.config.get("SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE") or 0.8)
|
||||
should_auto_continue = confidence >= auto_threshold and not task.inventory_lines_json
|
||||
lang = resolve_lang(payload)
|
||||
summary_text = format_parse_summary(
|
||||
**summary_kwargs,
|
||||
payload=payload,
|
||||
include_confirmation_hint=not should_auto_continue,
|
||||
)
|
||||
|
||||
# [STEP 7] 高置信度且库存源稳定:后续库存/匹配/导出交给后台 worker。
|
||||
if should_auto_continue:
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
merged_message = (
|
||||
f"{summary_text}\n\n{t('workflow.parse.auto_continued', lang=lang)}"
|
||||
if orchestrator_started
|
||||
else f"{summary_text}\n\n{t('workflow.parse.check_later', lang=lang)}"
|
||||
)
|
||||
return tool_response(
|
||||
status="running" if orchestrator_started else "ok",
|
||||
task=task,
|
||||
message=merged_message,
|
||||
data={**serialize_task_for_tool(task), "warnings": warnings},
|
||||
)
|
||||
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
message=summary_text,
|
||||
data={**serialize_task_for_tool(task), "warnings": warnings},
|
||||
)
|
||||
|
||||
|
||||
def _clean_notice_text(value: Any) -> str | None:
|
||||
text = str(value or "").strip()
|
||||
@@ -1007,13 +456,7 @@ def _clean_notice_text(value: Any) -> str | None:
|
||||
|
||||
|
||||
def _notice_header_snapshot(task: ShippingTask) -> dict[str, Any]:
|
||||
return {
|
||||
"customer_name": task.customer_name,
|
||||
"customer_code": task.customer_code,
|
||||
"ship_to": task.ship_to,
|
||||
"po_number": task.po_number,
|
||||
"required_date": task.required_date,
|
||||
}
|
||||
return current_header_field_values(task)
|
||||
|
||||
|
||||
def _reset_notice_edit_downstream(task: ShippingTask) -> None:
|
||||
@@ -1094,12 +537,7 @@ def replace_task_notice(
|
||||
task.source_file_name = source_file_name
|
||||
if source_file_type:
|
||||
task.source_file_type = source_file_type
|
||||
task.customer_name = None
|
||||
task.customer_code = None
|
||||
task.ship_to = None
|
||||
task.po_number = None
|
||||
task.required_date = None
|
||||
clear_task_order_lines(task)
|
||||
retire_current_order_extraction(task)
|
||||
task.parse_confidence = None
|
||||
task.review_status = None
|
||||
task.pending_human_reason = None
|
||||
@@ -1229,7 +667,7 @@ def _commit_notice_edit(
|
||||
) -> dict[str, Any]:
|
||||
# [STEP 1] 人工编辑后的业务值拥有最终优先级,但仍必须通过同一流程字段契约。
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
validation_issues = _missing_process_field_issues(read_task_order_lines(task))
|
||||
validation_issues = task_reservation_gate_issues(task)
|
||||
step_payload["parse_validation"] = {
|
||||
"status": "needs_review" if validation_issues else "ready",
|
||||
"issues": validation_issues,
|
||||
@@ -1314,10 +752,11 @@ def update_notice_fields(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
before_header = _notice_header_snapshot(task)
|
||||
changed = False
|
||||
header = current_header_field_values(task)
|
||||
for key, value in patch.items():
|
||||
normalized = _clean_notice_text(value)
|
||||
if getattr(task, key) != normalized:
|
||||
setattr(task, key, normalized)
|
||||
if header.get(key) != normalized:
|
||||
replace_current_header_field_value(task=task, field_code=key, value=normalized)
|
||||
changed = True
|
||||
|
||||
if not changed:
|
||||
@@ -1370,7 +809,7 @@ def update_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not isinstance(patch, dict) or not patch:
|
||||
return tool_response(status="failed", task=task, message="patch 不能为空")
|
||||
|
||||
lines = read_task_order_lines(task)
|
||||
lines = current_line_field_values(task)
|
||||
if line_index < 0 or line_index >= len(lines):
|
||||
return tool_response(status="failed", task=task, message="line_index 超出范围")
|
||||
|
||||
@@ -1379,23 +818,17 @@ def update_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(status="failed", task=task, message="没有可更新的行字段")
|
||||
|
||||
before_lines = [dict(item) for item in lines]
|
||||
line = dict(lines[line_index])
|
||||
if "quantity" in normalized_patch and "qty" not in normalized_patch:
|
||||
normalized_patch["qty"] = normalized_patch.pop("quantity")
|
||||
|
||||
line.update(normalized_patch)
|
||||
normalized_lines = normalize_notice_lines(
|
||||
[line if idx == line_index else item for idx, item in enumerate(lines)]
|
||||
)
|
||||
if len(normalized_lines) != len(lines):
|
||||
schema_fields = current_line_field_configs(task)
|
||||
if 'quantity' in normalized_patch and 'quantity' not in schema_fields and 'qty' in schema_fields:
|
||||
normalized_patch['qty'] = normalized_patch.pop('quantity')
|
||||
unknown_fields = sorted(set(normalized_patch) - set(schema_fields))
|
||||
if unknown_fields:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
message="更新后的行数据不合法,请确认 SKU 与数量格式正确。",
|
||||
status='failed', task=task,
|
||||
message=f"当前订单 Schema 未配置可编辑字段:{', '.join(unknown_fields)}",
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
if normalized_lines == before_lines:
|
||||
if all(lines[line_index].get(key) == value for key, value in normalized_patch.items()):
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
@@ -1403,13 +836,17 @@ def update_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
normalized_lines = replace_task_order_lines(task, normalized_lines, normalize=False)
|
||||
for field_code, value in normalized_patch.items():
|
||||
replace_current_line_field_value(
|
||||
task=task, position=line_index, field_code=field_code, value=value,
|
||||
)
|
||||
after_lines = current_line_field_values(task)
|
||||
return _commit_notice_edit(
|
||||
task,
|
||||
event_type="notice_line_updated",
|
||||
comment=str(payload.get("comment") or "").strip(),
|
||||
before_lines=before_lines,
|
||||
after_lines=[dict(item) for item in normalized_lines],
|
||||
after_lines=after_lines,
|
||||
idempotency_key=str(payload.get("idempotency_key") or "").strip() or None,
|
||||
)
|
||||
|
||||
@@ -1441,23 +878,15 @@ def add_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not isinstance(line, dict) or not line:
|
||||
return tool_response(status="failed", task=task, message="line 不能为空")
|
||||
|
||||
before_lines = read_task_order_lines(task)
|
||||
normalized_lines = normalize_notice_lines(before_lines + [line])
|
||||
if len(normalized_lines) != len(before_lines) + 1:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
message="新增的订单行不合法,请确认 SKU 与数量格式正确。",
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
normalized_lines = replace_task_order_lines(task, normalized_lines, normalize=False)
|
||||
before_lines = current_line_field_values(task)
|
||||
replace_current_line_fields(task=task, lines=[*before_lines, line])
|
||||
after_lines = current_line_field_values(task)
|
||||
return _commit_notice_edit(
|
||||
task,
|
||||
event_type="notice_line_added",
|
||||
comment=str(payload.get("comment") or "").strip(),
|
||||
before_lines=before_lines,
|
||||
after_lines=[dict(item) for item in normalized_lines],
|
||||
after_lines=after_lines,
|
||||
idempotency_key=str(payload.get("idempotency_key") or "").strip() or None,
|
||||
)
|
||||
|
||||
@@ -1490,20 +919,20 @@ def remove_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
except (TypeError, ValueError):
|
||||
return tool_response(status="failed", task=task, message="line_index 非法")
|
||||
|
||||
before_lines = read_task_order_lines(task)
|
||||
before_lines = current_line_field_values(task)
|
||||
if line_index < 0 or line_index >= len(before_lines):
|
||||
return tool_response(status="failed", task=task, message="line_index 超出范围")
|
||||
if len(before_lines) <= 1:
|
||||
return tool_response(status="failed", task=task, message="至少保留一条订单行,无法删除最后一行")
|
||||
|
||||
normalized_lines = [dict(item) for idx, item in enumerate(before_lines) if idx != line_index]
|
||||
normalized_lines = replace_task_order_lines(task, normalized_lines, normalize=False)
|
||||
after_lines = [dict(item) for idx, item in enumerate(before_lines) if idx != line_index]
|
||||
replace_current_line_fields(task=task, lines=after_lines)
|
||||
return _commit_notice_edit(
|
||||
task,
|
||||
event_type="notice_line_removed",
|
||||
comment=str(payload.get("comment") or "").strip(),
|
||||
before_lines=before_lines,
|
||||
after_lines=normalized_lines,
|
||||
after_lines=after_lines,
|
||||
idempotency_key=str(payload.get("idempotency_key") or "").strip() or None,
|
||||
)
|
||||
|
||||
@@ -1535,7 +964,10 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task.pending_human_reason = None
|
||||
task.error_message = None
|
||||
|
||||
order_lines = read_task_order_lines(task)
|
||||
try:
|
||||
order_lines = current_line_field_values(task)
|
||||
except ConflictError:
|
||||
order_lines = []
|
||||
if not task.raw_content and not order_lines:
|
||||
task.process_status = "created"
|
||||
elif order_lines:
|
||||
|
||||
@@ -85,7 +85,7 @@ def auto_mapping_allow_llm() -> bool:
|
||||
|
||||
|
||||
def defer_parse_to_dify_enabled() -> bool:
|
||||
"""建单后是否延后 parse_notice,交由 Dify 画布完成 LLM 抽取与落库。"""
|
||||
"""建单后是否延后订单抽取,交由 Dify 画布完成并通过 submit_order_extraction 落库。"""
|
||||
return cfg_bool("SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY", True)
|
||||
|
||||
|
||||
|
||||
@@ -48,11 +48,10 @@ def submit_order_extraction(payload: dict):
|
||||
|
||||
return _submit(payload)
|
||||
|
||||
# 任务 / 批次 / 解析 / 决策
|
||||
# 任务 / 批次 / 决策
|
||||
create_batch = task_workflow.create_batch
|
||||
create_batch_tasks = task_workflow.create_batch_tasks
|
||||
create_task = task_workflow.create_task
|
||||
parse_notice = task_workflow.parse_notice
|
||||
auto_progress = task_workflow.auto_progress
|
||||
submit_decision = task_workflow.submit_decision
|
||||
get_task_status = task_workflow.get_task_status
|
||||
|
||||
Reference in new issue
Block a user