!13 feat(shipping-freight-auto-upload): 新增货代发货Excel连接级自动上传全链路功能

Merge pull request !13 from 曹惠鹏/hugo-shipping-notice
This commit is contained in:
sophie authored and Gitee committed 2026-08-27 07:51:42 +00:00
commit 2921c8d90f
93 files changed
+4867 -601

No files matched your search

+7
View File
@@ -351,6 +351,13 @@ def rpa_inventory_batch_claimed():
return jsonify({'success': True, 'data': claim_inventory_batch(_payload())})
@shipping_notice_bp.route('/rpa/inventory-batch-progress', methods=['POST'])
def rpa_inventory_batch_progress():
"""RPA 批量库存导出进度回调:实时回写排程 run 计数(非终态,最终以 batch-ready 为准)。"""
from app.services.shipping_notice.inventory_rpa_workflow import report_inventory_batch_progress
return jsonify(report_inventory_batch_progress(_payload()))
@shipping_notice_bp.route('/rpa/inventory-configuration-test-ready', methods=['POST'])
def rpa_inventory_configuration_test_ready():
"""RPA 配置测试回调:仅分析文件结构,不创建生产库存快照或任务关联。"""
+39 -4
View File
@@ -548,10 +548,9 @@ def workspace_shipping_task_detail(task_no: str):
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
if not task:
raise NotFoundError('Not found')
return _ok({
**serialize_task_detail(task, viewer_user_id=user.id, is_admin=is_admin),
'ui_state': build_task_ui_state(task, include_stage_context=True),
})
return _ok(serialize_task_detail(
task, viewer_user_id=user.id, is_admin=is_admin, include_stage_context=True,
))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/audit-timeline', methods=['GET'])
@@ -877,9 +876,43 @@ def workspace_mark_manual_uploaded(task_no: str):
run_task_auto_progress(
str(task.task_no), trigger='manual_upload_confirmed', operator_id=int(user.id),
)
# 终态兜底:确认上传必须收口正式 Execution Gate,不允许依赖 auto_progress/Job 链。
_ensure_uploaded_execution_gates_closed(task, actor_id=int(user.id))
return _ok(result)
def _ensure_uploaded_execution_gates_closed(task: ShippingNotice, *, actor_id: int) -> None:
"""人工确认上传(终态)后兜底收口正式 Execution 门禁,禁止依赖 auto_progress/Job 链。
核心逻辑:upload_manual_confirmed 是业务终态事实;只有把正式 Execution 的前置履约
Gate 一并收口,批次中心/对话卡才不会因陈旧「库存不足」Gate 把阶段回退成「通知准备」。
``auto_progress_enabled()`` 可能为 False(``run_task_auto_progress`` 提前返回),
或 ``submit_auto_progress`` 存在活动 Job / 候选集等早退分支而跳过 sync,故此处兜底:
仅当 Execution 尚未 completed 时显式同步(幂等,重复无害)。已 completed 时不重复处理,
避免与 ``_active_execution_for_task`` 将 completed Execution 误判为可重建。
Args:
task: 已确认人工上传的正式 ShippingNotice。
actor_id: 触发确认的服务端用户主键。
"""
from app.services.shipping_notice.process_gate_bridge import (
find_execution_for_task,
sync_fulfillment_gates_from_task,
)
execution = find_execution_for_task(task)
if execution is None:
return
if str(getattr(execution, 'status', '') or '').strip().lower() == 'completed':
return
sync_fulfillment_gates_from_task(
execution=execution,
actor_type='user',
actor_id=actor_id,
)
db.session.flush()
def _confirm_notice_uploaded(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]:
"""
按发货通知单号确认唯一 Excel 已上传;内部 task_no 仅用于既有状态机和审计追溯。
@@ -916,6 +949,8 @@ def _confirm_notice_uploaded(*, business_no: str, user_id: int, artifact_id: int
run_task_auto_progress(
str(task.task_no), trigger='manual_upload_confirmed', operator_id=user_id,
)
# 终态兜底:确认上传必须收口正式 Execution Gate,不允许依赖 auto_progress/Job 链。
_ensure_uploaded_execution_gates_closed(task, actor_id=user_id)
return {'business_no': str(task.business_no), **dict(result or {})}
+1 -25
View File
@@ -257,9 +257,6 @@ class Config:
SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED = (
os.getenv('SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY = int(
os.getenv('SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY') or '3'
)
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
SHIPPING_NOTICE_WORKER_CONCURRENCY = int(os.getenv('SHIPPING_NOTICE_WORKER_CONCURRENCY', '2'))
@@ -270,11 +267,7 @@ class Config:
SHIPPING_NOTICE_STP_WAITING_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_STP_WAITING_TIMEOUT_SECONDS', '120') or '120'
)
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
SHIPPING_NOTICE_AUTO_PROGRESS_RECOVERY_MAX_AGE_HOURS = int(
os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_RECOVERY_MAX_AGE_HOURS', '72') or '72'
)
SHIPPING_NOTICE_WORKER_RECOVERY_TICK_SECONDS = float(
os.getenv('SHIPPING_NOTICE_WORKER_RECOVERY_TICK_SECONDS', '60') or '60'
)
@@ -301,22 +294,10 @@ class Config:
os.getenv('SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED', 'false').lower() == 'true'
)
# XFA 数据路径 Profile:识别到 xfa_hybrid 后允许使用 datasets adapter。
# XFA 资源上限(max_pdf/packet/xml/line/retries/parse_timeout)由 xfa_contract 常量承担,不再经环境变量注入。
SHIPPING_NOTICE_XFA_ENABLED = (
os.getenv('SHIPPING_NOTICE_XFA_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_XFA_MAX_PDF_BYTES = int(
os.getenv('SHIPPING_NOTICE_XFA_MAX_PDF_BYTES') or str(20 * 1024 * 1024)
)
SHIPPING_NOTICE_XFA_MAX_PACKET_BYTES = int(
os.getenv('SHIPPING_NOTICE_XFA_MAX_PACKET_BYTES') or str(10 * 1024 * 1024)
)
SHIPPING_NOTICE_XFA_MAX_XML_DEPTH = int(os.getenv('SHIPPING_NOTICE_XFA_MAX_XML_DEPTH') or '64')
SHIPPING_NOTICE_XFA_MAX_XML_NODES = int(os.getenv('SHIPPING_NOTICE_XFA_MAX_XML_NODES') or '100000')
SHIPPING_NOTICE_XFA_MAX_LINE_ROWS = int(os.getenv('SHIPPING_NOTICE_XFA_MAX_LINE_ROWS') or '2000')
SHIPPING_NOTICE_XFA_PARSE_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_XFA_PARSE_TIMEOUT_SECONDS') or '30'
)
SHIPPING_NOTICE_XFA_MAX_RETRIES = int(os.getenv('SHIPPING_NOTICE_XFA_MAX_RETRIES') or '2')
SHIPPING_NOTICE_LLM_REVIEW_ENABLED = (
os.getenv('SHIPPING_NOTICE_LLM_REVIEW_ENABLED', 'false').lower() == 'true'
)
@@ -422,9 +403,6 @@ class Config:
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED = (
os.getenv('SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE = float(
os.getenv('SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE') or '0.8'
)
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(
@@ -680,8 +658,6 @@ class Config:
# parser v6:阶段二附件派生 FileAsset + Document/Candidate;相对 v5 须强制重解析
# parser v5:mixed 保留独立 HTML 段 + 附件型 alternative 可提取正文
SHIPPING_NOTICE_EML_MAX_ATTACHMENTS = int(os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENTS', '20'))
# 单次批量上传通知文件上限;与 EML 内附件上限独立,防止请求级资源耗尽。
SHIPPING_NOTICE_BATCH_MAX_FILES = int(os.getenv('SHIPPING_NOTICE_BATCH_MAX_FILES', '20'))
SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES = int(
os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES', str(20 * 1024 * 1024))
)
@@ -67,6 +67,12 @@ class ShippingRpaProfile(Base):
login_config_json: Mapped[dict[str, Any]] = mapped_column(
JSON, default=lambda: {'auth_mode': 'password'}, nullable=False,
)
# 连接级“发货 Excel 自动上传”配置。先使用 login_url 登录,再访问 upload_config_json.entry_url 进入上传页;
# 上传配置由管理端表单编辑,后端白名单校验后保存为受限 JSON。白名单字段仅
# enabled / entry_url / file_input_selector / submit_mode / submit_selector /
# result_mode / result_selector / success_texts / timeout_seconds。
# 一条连接只保存一份上传配置;该配置变更不递增 config_version(见 admin 服务)。
upload_config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
credential_updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
@@ -26,6 +26,7 @@ from app.models import (
from app.services.shipping_notice.audit_service import append_shipping_audit_event
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.upload_config_validation import validate_upload_config
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
@@ -162,6 +163,7 @@ def _profile_payload(profile: ShippingRpaProfile) -> dict[str, Any]:
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'connector_type': profile.connector_type, 'login_url': profile.login_url,
'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled),
'upload_config_json': profile.upload_config_json,
'config_version': profile.config_version, 'username_masked': _mask(profile.username_ciphertext),
'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at),
'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at),
@@ -199,6 +201,13 @@ def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int
if profile_id and profile is None:
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
profile = profile or ShippingRpaProfile(profile_code='', display_name='', connector_type='', login_url='', login_config_json={})
# 记录“非 upload_config”的既有运行时配置快照:仅当这些字段变化才递增 config_version,
# upload_config_json 属于连接上传配置,变更不得误判库存 RPA 配置测试过期。
prev_non_upload = (
profile.profile_code, profile.display_name, profile.connector_type, profile.login_url,
dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled),
bool(profile.username_ciphertext), bool(profile.password_ciphertext),
) if profile_id else None
profile.profile_code = str(_text(data, 'profile_code', required=True)).upper()
profile.display_name = str(_text(data, 'display_name', required=True))
profile.connector_type = str(_text(data, 'connector_type', required=True)).lower()
@@ -218,9 +227,18 @@ def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int
profile.password_ciphertext = encrypt_credential(password)
if username is not None or password is not None:
profile.credential_updated_at = datetime.utcnow()
# 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。
if 'upload_config_json' in data:
profile.upload_config_json = validate_upload_config(profile.connector_type, data.get('upload_config_json'))
profile.updated_by = actor_id
if profile_id:
profile.config_version += 1
now_non_upload = (
profile.profile_code, profile.display_name, profile.connector_type, profile.login_url,
dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled),
bool(profile.username_ciphertext), bool(profile.password_ciphertext),
)
if now_non_upload != prev_non_upload:
profile.config_version += 1
if not profile_id:
profile.created_by = actor_id
db.session.add(profile)
@@ -70,15 +70,23 @@ def _reset_inventory_state_for_forced_rpa(task) -> None:
def _request_formal_gate_action(**kwargs):
"""决策工作流的正式 20-Gate 适配器,避免外部入口直调旧库存函数。"""
"""决策工作流的正式 20-Gate 适配器,避免外部入口直调旧库存函数。
核心逻辑:请求正式 Gate 恢复前先清除任务级解析/复核阻断残留
(review_status / pending_human_reason / error_message / upload 错误),
避免旧阻断事实污染重启后的 Gate 投影。写入由被调用方的事务统一提交。
"""
task = kwargs.get('task')
if task is not None:
task.upload_error_message = None
task.upload_receipt_json = None
task.review_status = None
task.pending_human_reason = None
task.error_message = None
from app.services.shipping_notice.task_retry_decision_service import _request_formal_gate_action as _request
return _request(**kwargs)
task.upload_error_message = None
task.upload_receipt_json = None
task.review_status = None
task.pending_human_reason = None
task.error_message = None
def _prepare_task_for_inventory_reupload(task) -> None:
+20 -3
View File
@@ -195,20 +195,24 @@ def _mapping_value(
excel_business_no: str | None = None,
notice_no: str | None = None,
export_date: date | None = None,
field_id_by_code: dict[str, str] | None = None,
) -> Any:
"""
按映射来源类型读取值;未知来源已在模板发布时被拒绝。
核心逻辑:order_field 读订单快照;inventory_field 读库存行;system_fact 仅读白名单事实;
export_sequence 优先用调用方传入值,缺失时回退行上注入的 ``__export_sequence``。
项次缺失时经 order_line_no_resolver 统一解析(line_no 字段 → 客户 PO 行号 →
导出行序号),与 UI 展示同一口径,禁止此处另造回退链。
Args:
mapping: 已发布模板映射项。
task: 发货任务。
order_values: 当前行或表头订单字段值。
order_values: 当前行或表头订单字段值(field_id 为键)。
inventory_values: 当前行库存字段值。
header_values: 明细行模式下可回退的表头字段。
export_sequence: 本次导出行序号(1..N)。
field_id_by_code: field_code → field_id 映射(快照 Schema);缺失时按 code 键兼容。
Returns:
经 formatter 处理后的单元格值。
@@ -219,8 +223,14 @@ def _mapping_value(
value = order_values.get(key)
field = db.session.get(ShippingOrderField, key) if key else None
field_code = str(field.field_code or '') if field else ''
if value in (None, '') and field_code == 'line_no' and export_sequence is not None:
value = export_sequence
if value in (None, '') and field_code == 'line_no':
from app.services.shipping_notice.order_line_no_resolver import resolve_order_line_no
value = resolve_order_line_no(
field_values=order_values,
field_id_by_code=field_id_by_code,
fallback_sequence=export_sequence,
)['value']
if value is None and mapping.get('row_mode') == 'line' and header_values is not None:
value = header_values.get(key)
elif kind == 'inventory_field':
@@ -617,6 +627,11 @@ def generate_shipment_excel(
# [STEP 4] Notice 的业务单号与首个 Excel 同一事务产生。此处已完成业务、
# 库存和导出行校验;随后 Excel、Artifact 或 Reservation 任一步失败都会回滚编号流水。
from app.services.shipping_notice.order_line_no_resolver import field_id_by_code_from_definition
field_id_by_code = field_id_by_code_from_definition(
snapshot.schema_version.definition_json if snapshot.schema_version is not None else None,
)
if not task.business_no:
from app.services.shipping_notice.business_numbering_service import assign_notice_business_number
@@ -650,6 +665,7 @@ def generate_shipment_excel(
mapping, task=task, order_values=header_values, inventory_values=header_inventory,
excel_business_no=excel_business_no,
export_date=export_date,
field_id_by_code=field_id_by_code,
)
continue
row_count = max(len(line_values), 1)
@@ -662,6 +678,7 @@ def generate_shipment_excel(
export_sequence=int(order_line.get('__export_sequence') or (index + 1)),
excel_business_no=excel_business_no,
export_date=export_date,
field_id_by_code=field_id_by_code,
)
wb.save(path)
finally:
@@ -64,6 +64,9 @@ from app.services.shipping_notice.rpa_attempts import (
max_rpa_upload_attempts,
upload_rpa_attempts,
)
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
from app.services.shipping_notice.upload_config_validation import compute_upload_config_hash
from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
@@ -439,14 +442,49 @@ def _trigger_freight_upload_rpa(
except (ConflictError, ValidationError) as exc:
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
queue_path, trigger_path = write_upload_trigger(
# [STEP] 读取该任务已确定的系统连接及其 upload_config_json;未配置/未启用则 fail-closed 转人工。
# 连接级受控上传是“外例”,只作用于货代上传,不向库存 RPA 或收料 RPA 扩散。
rpa_source = task_rpa_inventory_source(task) or {}
connector_type = str(rpa_source.get('connector_type') or '').strip().lower()
source_code = str(rpa_source.get('source_code') or '').strip().upper()
# 通过 get_rpa_trigger_inventory_source 取带登录凭据与上传配置的连接快照(供 Worker 登录后访问上传页)。
upload_source = get_rpa_trigger_inventory_source(source_code) if source_code else None
if not isinstance(upload_source, dict):
upload_source = dict(rpa_source)
upload_config = upload_source.get('upload_config_json') if isinstance(upload_source, dict) else None
if connector_type not in {'dbs', 'crane'} or not isinstance(upload_config, dict) or not upload_config.get('enabled'):
task.error_message = (
'该连接未启用“发货 Excel 自动上传”,请管理员先在“系统连接”完成上传配置并启用后再触发,'
'或人工下载 Excel 后上传并登记凭据。'
)
log_task_event(task, 'upload_rpa_config_missing', {'connector_type': connector_type or None})
db.session.commit()
return tool_response(
status='needs_human',
task=task,
message=task.error_message,
data=serialize_task_for_tool(task),
stop_agent_turn=True,
next_required_action='请在“系统连接”补齐上传配置并启用,或人工上传。',
)
callback_id = f'upload:{task.task_no}:attempt:{int(attempt.id)}'
queue_path, trigger_path, callback_id = write_upload_trigger(
task.task_no,
str(task.export_file_path),
payload={
'attempt_id': int(attempt.id),
'artifact_id': int(attempt.artifact_id),
'mode': str(body.get('mode') or 'auto'),
},
attempt_id=int(attempt.id),
artifact_id=int(attempt.artifact_id),
connector_type=connector_type,
upload_config=dict(upload_config),
upload_config_hash=compute_upload_config_hash(upload_config),
login_url=str(upload_source.get('login_url') or '').strip() or None,
credential_envelope=upload_source.get('credential_envelope'),
callback_id=callback_id,
business_no=task.business_no,
)
if not trigger_path:
attempt.status = 'failed'
@@ -581,20 +619,17 @@ def _sync_workflow_stage(
)
def match_completed(task: ShippingNotice) -> bool:
"""
STP 整单满足性门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时通过。
def _released_line_keys_for_task(task: ShippingNotice) -> set[str]:
"""读取当前任务已审计的短缺放行行键集,供满足性与聚合重算共用。
核心逻辑:该函数只代表整单满足性,不代表滚动 Excel 是否存在可导出行。
核心逻辑:只认活动 ``release_inventory_shortage`` 决定;无放行事实时返回空集,
保证聚合重算与 ``match_completed`` 读到的放行语义完全一致,避免两处分裂。
"""
from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderReviewCase, ShippingOrderReviewLineDecision
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
if task.id is None:
return False
rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
if not rows:
return False
released_keys = {
return set()
return {
str(row.line_key)
for row in (
ShippingOrderReviewLineDecision.query
@@ -607,6 +642,23 @@ def match_completed(task: ShippingNotice) -> bool:
.all()
)
}
def match_completed(task: ShippingNotice) -> bool:
"""
STP 整单满足性门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时通过。
核心逻辑:该函数只代表整单满足性,不代表滚动 Excel 是否存在可导出行。
已人工放行的短缺行视同满足(与 ``_recompute_task_match_aggregate`` 同源)。
"""
from app.models import ShippingNoticeLineInventoryMatch
if task.id is None:
return False
rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
if not rows:
return False
released_keys = _released_line_keys_for_task(task)
for row in rows:
result = str(row.match_result or '').strip()
shortage = _line_shortage_qty(getattr(row, 'shortage_qty', None))
@@ -1171,7 +1223,12 @@ def _merge_line_inventory_resolutions(
def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dict[str, Any]]]:
"""根据 ShippingNoticeLineInventoryMatch(current=True)重新聚合成 match_status(fulfillable/partial/unfulfillable)+ shortages。"""
"""根据 ShippingNoticeLineInventoryMatch(current=True)重新聚合成 match_status(fulfillable/partial/unfulfillable)+ shortages。
核心逻辑:与 ``match_completed`` 同款放行语义——已人工放行(release_inventory_shortage)
且仍有缺口的行视同满足,不再计入 has_block/缺货;否则会与 Excel 门禁分裂,
出现"Gate 认为满足、任务却仍标 unfulfillable"的矛盾。
"""
rows = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), is_current=True)
@@ -1179,6 +1236,7 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
)
if not rows:
return 'unfulfillable', []
released_keys = _released_line_keys_for_task(task)
has_ok = False
has_block = False
shortages: list[dict[str, Any]] = []
@@ -1200,16 +1258,21 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
'available_qty': float(available_qty) if available_qty is not None else 0.0,
'shortage_qty': float(shortage_qty) if shortage_qty is not None else 0.0,
}
entry['line_status'] = (
'ok' if match_result == 'matched' and entry['shortage_qty'] <= 0
else 'shortage'
)
task.line_results_json.append(entry)
if match_result == 'matched':
# 已审计放行的短缺行视同满足:不阻断、不进入缺货列表。
shortage = _line_shortage_qty(shortage_qty)
released = str(getattr(row, 'line_key', '') or '') in released_keys
if match_result == 'matched' and shortage <= 0:
entry['line_status'] = 'ok'
has_ok = True
continue
has_block = True
shortages.append(entry)
elif released and shortage > 0:
# 放行行状态仍暴露"放行",但聚合按满足计入,避免整单误判缺货。
entry['line_status'] = 'released'
has_ok = True
else:
entry['line_status'] = 'shortage'
has_block = True
shortages.append(entry)
task.line_results_json.append(entry)
task.shortage_json = {'lines': shortages}
if has_block and has_ok:
status = 'partial'
@@ -1229,6 +1292,28 @@ def _current_line_results(task: ShippingNotice) -> list[dict[str, Any]]:
return list(task.line_results_json or [])
def recompute_task_fulfillment_state(task: ShippingNotice) -> str:
"""按当前匹配/放行事实重算任务履约态:match_status、line_results_json、shortage_json 与 review/pending。
核心逻辑:委托 ``_recompute_task_match_aggregate``(与 ``match_completed`` 同款放行语义),
再据此同步 ``review_status``/``pending_human_reason`` 并应用对应任务迁移。
供放行(release)回调、库存满足性复核与其它恢复路径复用,杜绝旧状态残留。
Args:
task: 待重算的 ShippingNotice(尚未 commit)。
Returns:
重算后的 match_status(fulfillable / partial / unfulfillable)。
"""
status, _shortages = _recompute_task_match_aggregate(task)
task.match_status = status
if status == 'fulfillable':
apply_task_transition(task, TaskTransition.MATCHED_FULFILLABLE)
else:
apply_task_transition(task, TaskTransition.MATCH_SHORTAGE)
return status
def _profile_match_persistence_payload(
line_results: list[dict[str, Any]],
*,
@@ -1956,14 +2041,6 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
if reservation_gate is not None:
return reservation_gate
if not is_inventory_source_stable(task):
return tool_response(
status="failed",
task=task,
message="库存源尚未确定,无法上传货代系统。",
data=serialize_task_for_tool(task),
)
# [STEP 1] 先确保至少有一份 Artifact;后续上传始终由 Artifact 而非 Task 文件指针驱动。
if not task.export_file_path:
gen = generate_excel({"task_id": task.task_no})
@@ -1989,6 +2066,15 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
stop_agent_turn=True,
next_required_action='请在任务处理工作台使用「确认已上传」。',
)
# RPA 上传仍需从库存源取数,必须在触发前确认源仍可用;
# 人工确认已上传不在此路径,不依赖库存源(Excel 已生成、外部已上传)。
if not is_inventory_source_stable(task):
return tool_response(
status="failed",
task=task,
message="库存源尚未确定,无法上传货代系统。",
data=serialize_task_for_tool(task),
)
return _trigger_freight_upload_rpa(
task,
payload={**payload, 'artifact_id': artifact_id, 'mode': mode},
@@ -2112,6 +2198,14 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
success = _rpa_callback_success(payload.get("success"))
except ValidationError as exc:
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
# 三态结果:success / failed / unknown。result 显式给定则优先,否则由 success 布尔推导。
raw_result = str(payload.get('result') or '').strip().lower()
if raw_result in {'success', 'failed', 'unknown'}:
result_status = raw_result
else:
result_status = 'success' if success else 'failed'
# 成功证据只在 success 时才要求;unknown/failed 不索取页面证据。
success = result_status == 'success'
success_evidence: dict[str, Any] | None = None
if success:
expected_filename = (
@@ -2139,6 +2233,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
completed = complete_attempt(
attempt, success=success, callback_id=str(payload.get('callback_id') or f'rpa:{attempt.id}'),
freight_ref_no=str(payload.get('freight_ref_no') or ''), error_message=str(payload.get('error_message') or ''),
result=result_status,
)
except (ConflictError, ValidationError) as exc:
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
@@ -2204,6 +2299,28 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
checkpoint=CP_UPLOADED if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
)
if completed.status == 'unknown':
# unknown 已可能提交但无法确认外部系统结果:保持待人工,禁止自动重试,避免重复上传。
task.upload_finished_at = datetime.utcnow()
set_task_step_progress(
task,
step_key="step7_upload_freight",
step_title="上传货代",
status="needs_human",
message=t("workflow.fulfillment.upload_unknown_wait_manual", lang=lang),
progress_percent=100,
detail=t("workflow.fulfillment.upload_unknown_detail", lang=lang),
)
task.error_message = completed.error_message or 'RPA upload result unknown'
log_task_event(task, "upload_rpa_unknown", {"artifact_id": completed.artifact_id, "attempt_id": completed.id, "error": task.error_message})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=task.error_message,
data=serialize_task_for_tool(task),
)
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
task.upload_finished_at = datetime.utcnow()
set_task_step_progress(
@@ -137,6 +137,8 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.rpa_uploaded_done": "RPA 已成功上传货代系统,任务已全部处理完毕。",
"workflow.fulfillment.upload_failed_wait_manual": "货代上传失败,等待人工处理",
"workflow.fulfillment.upload_failed_detail": "可重试上传或改为手工上传",
"workflow.fulfillment.upload_unknown_wait_manual": "货代上传结果未知,必须人工核验后再处理",
"workflow.fulfillment.upload_unknown_detail": "文件可能已提交但未能从页面确认结果;为避免重复上传,请人工核验货代系统后处理。",
},
"en": {
"parse.title": "[Shipping notice parsed] Task: {task_no}",
@@ -260,6 +262,8 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.rpa_uploaded_done": "RPA uploaded to the freight system successfully. The task is fully completed.",
"workflow.fulfillment.upload_failed_wait_manual": "Freight upload failed. Waiting for manual handling.",
"workflow.fulfillment.upload_failed_detail": "You may retry the upload or switch to manual upload.",
"workflow.fulfillment.upload_unknown_wait_manual": "Freight upload result is unknown. Manual verification is required.",
"workflow.fulfillment.upload_unknown_detail": "The file may have been submitted but the result could not be confirmed from the page. To avoid a duplicate upload, please verify the freight system manually.",
},
"th": {
"parse.title": "【ยืนยันการแยกใบแจ้งส่งสินค้า】งาน: {task_no}",
@@ -383,6 +387,8 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.rpa_uploaded_done": "RPA อัปโหลดเข้าระบบขนส่งสำเร็จแล้ว และงานเสร็จสมบูรณ์",
"workflow.fulfillment.upload_failed_wait_manual": "อัปโหลดเข้าระบบขนส่งล้มเหลว กำลังรอให้คนจัดการต่อ",
"workflow.fulfillment.upload_failed_detail": "สามารถลองอัปโหลดใหม่หรือเปลี่ยนเป็นอัปโหลดด้วยตนเองได้",
"workflow.fulfillment.upload_unknown_wait_manual": "ผลการอัปโหลดขนส่งไม่ทราบแน่ชัด ต้องให้คนตรวจสอบก่อนดำเนินการ",
"workflow.fulfillment.upload_unknown_detail": "ไฟล์อาจถูกส่งไปแล้วแต่ไม่สามารถยืนยันผลจากหน้าเว็บได้ เพื่อหลีกเลี่ยงการอัปโหลดซ้ำ กรุณาตรวจสอบระบบขนส่งด้วยตนเอง",
},
}
@@ -472,9 +472,22 @@ def project_inventory_candidate_facts(
serialized_matches: list[dict[str, Any]] = []
stale_details: dict[str, Any] | None = None
out_of_scope_details: dict[str, Any] | None = None
for row in _current_match_rows(task, session=sess):
current_match_rows = _current_match_rows(task, session=sess)
# [BE-性能] 批量预取当前匹配行引用的库存快照,避免循环内逐行 sess.get() 造成 N+1。
snapshot_ids = {
int(row.inventory_snapshot_id)
for row in current_match_rows
if getattr(row, 'inventory_snapshot_id', None) is not None
}
snapshot_by_id: dict[int, Any] = {}
if snapshot_ids:
snapshot_by_id = {
int(item.id): item
for item in sess.query(ShippingInventoryFile).filter(ShippingInventoryFile.id.in_(snapshot_ids)).all()
}
for row in current_match_rows:
snapshot = (
sess.get(ShippingInventoryFile, int(row.inventory_snapshot_id))
snapshot_by_id.get(int(row.inventory_snapshot_id))
if getattr(row, 'inventory_snapshot_id', None) is not None else None
)
allowed_codes = _normalized_codes(getattr(row, 'allowed_source_codes_snapshot', None))
@@ -67,6 +67,16 @@ def inventory_loaded_response(
else:
task.inventory_lines_json = inventory_lines
# [BE-放行-恢复] 库存内容已重新载入/复用,旧匹配结果必然失效:清空任务级派生状态,
# 强制 Gate 链路在下一轮重新匹配,避免复用旧快照的短缺/匹配结果而造成"库存已刷新
# 却仍显示旧缺口/旧 match_status"的矛盾(对 task 及其同库存文件的关联任务一并清理)。
for affected in [task, *linked_tasks]:
if affected is None:
continue
affected.match_status = None
affected.line_results_json = None
affected.shortage_json = None
try:
order_lines = task_line_purpose_values(task)
except ValueError:
@@ -918,6 +918,73 @@ def _validate_schedule_batch_callback_run_no(schedule_run_id: int | None, callba
return None
def report_inventory_batch_progress(payload: dict[str, Any]) -> dict[str, Any]:
"""
RPA 批量导出进度回调:实时回写排程 run 的成功/跳过/失败笔数(非终态)。
【AI 触发时机】:freight_rpa_worker 每完成一个库存站点导出后调用,用于管理端实时
展示"执行中"run 的笔数;最终计数仍以 inventory-batch-ready 回调为准(终态化时重算覆盖)。
核心逻辑:校验 schema_version、schedule_run_id 与 run_no 匹配且 run 仍处于 awaiting_rpa;
仅更新计数列与 response_summary_json.progress,不修改 status/started_at/finished_at,
不影响超时回收与最终终态化。计数采用 max(现有, 上报) 防乱序回退。
Returns:
tool_response: 进度已回写为 ok;无效/非等待态为 failed(不改变 run 状态)。
"""
if payload.get('schema_version') != 'shipping_inventory_rpa.v2':
return tool_response(status='failed', message='callback_schema_invalid', data={
'progress_status': 'invalid', 'error_code': 'callback_schema_invalid',
})
schedule_run_id = payload.get('schedule_run_id')
try:
schedule_run_id = int(schedule_run_id) if schedule_run_id is not None else None
except (TypeError, ValueError):
schedule_run_id = None
run_no = str(payload.get('batch_run_no') or payload.get('run_no') or '').strip()
if not schedule_run_id or not run_no:
return tool_response(status='failed', message='progress_schema_invalid', data={
'progress_status': 'invalid', 'error_code': 'callback_schema_invalid',
})
schedule_run_error = _validate_schedule_batch_callback_run_no(schedule_run_id, run_no)
if schedule_run_error:
return tool_response(status='failed', message=f'排程进度回调无效: {schedule_run_error}', data={
'progress_status': 'rejected', 'schedule_run_error': schedule_run_error,
})
from app.models import ScheduleRun
run = db.session.get(ScheduleRun, schedule_run_id)
if run is None:
return tool_response(status='failed', message='schedule_run_not_found', data={
'progress_status': 'rejected', 'schedule_run_error': 'schedule_run_not_found',
})
incoming = {
'success_count': max(0, int(payload.get('success_count') or 0)),
'skipped_count': max(0, int(payload.get('skipped_count') or 0)),
'failed_count': max(0, int(payload.get('failed_count') or 0)),
}
run.success_count = max(int(run.success_count or 0), incoming['success_count'])
run.skipped_count = max(int(run.skipped_count or 0), incoming['skipped_count'])
run.failed_count = max(int(run.failed_count or 0), incoming['failed_count'])
summary = dict(run.response_summary_json or {})
summary['progress'] = {
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
'batch_run_no': run_no,
'updated_at': datetime.utcnow().isoformat(),
}
run.response_summary_json = summary
db.session.commit()
return tool_response(status='ok', message='库存 RPA 导出进度已回写', data={
'progress_status': 'updated',
'run_no': run_no,
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
})
def _validate_rpa_callback_inventory_source(task: ShippingNotice, payload: dict[str, Any]) -> dict[str, Any] | None:
"""
校验 RPA 成功回调是否允许处理当前任务库存(门禁 + 轮次 + 身份)。
@@ -14,6 +14,8 @@ from pathlib import Path
from typing import Any
from flask import current_app
from sqlalchemy import event as _sa_event
from sqlalchemy.orm import Session
from app import db
from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink
@@ -30,6 +32,24 @@ _SNAPSHOT_STATUS_READY = "ready"
_SNAPSHOT_STATUS_EMPTY = "empty"
_SNAPSHOT_STATUS_FAILED = "failed"
_SNAPSHOT_STATUS_EXPIRED = "expired"
# 请求内只读缓存(key: (source_code, warehouse_id) → ShippingInventoryFile | None)。
# 同一请求内 _build_stp_facts / _build_stage_context / 行级匹配会重复查询同一
# (source, warehouse) 的最新 ready 快照(实测 task detail 一次请求重复 3 次)。
# 任何快照行写入(新建/过期/更新)都会由 after_flush 事件失效,保证写后读可见。
_READ_CACHE_KEY = "shipping_inventory_snapshot_read_cache"
@_sa_event.listens_for(Session, "after_flush")
def _clear_snapshot_read_cache_on_write(session, flush_context): # noqa: ANN001
"""快照写入路径统一失效点:覆盖全部创建/过期/更新调用方,无需逐处接线。"""
touched = (
any(isinstance(obj, ShippingInventoryFile) for obj in session.new)
or any(isinstance(obj, ShippingInventoryFile) for obj in session.dirty)
or any(isinstance(obj, ShippingInventoryFile) for obj in session.deleted)
)
if touched:
session.info.pop(_READ_CACHE_KEY, None)
_WAREHOUSE_ID_HEADER_ALIASES = {
"warehouseid",
"warehouse",
@@ -77,12 +97,22 @@ def find_latest_ready_snapshot(
"""
查找指定 Source 的最新 ready 且未过期库存快照。
核心逻辑:固定 Source 限定 Warehouse;动态 Source 先复用文件,再由 reservation + PN 匹配确定 Warehouse。
性能约束:结果按 (source_code, warehouse_id) 请求内记忆化——同一读请求中 STP 事实、
阶段上下文与行级匹配会重复调用;任何快照写入都会失效该缓存(after_flush 事件)。
"""
code = str(source_code or "").strip().upper()
warehouse = str(warehouse_id or "").strip().upper()
if not code:
return None
read_cache = db.session.info.get(_READ_CACHE_KEY)
if not isinstance(read_cache, dict):
read_cache = {}
db.session.info[_READ_CACHE_KEY] = read_cache
cache_key = (code, warehouse)
if cache_key in read_cache:
return read_cache[cache_key]
query = ShippingInventoryFile.query.filter_by(
source_code=code,
snapshot_status=_SNAPSHOT_STATUS_READY,
@@ -91,10 +121,13 @@ def find_latest_ready_snapshot(
query = query.filter_by(warehouse_id=warehouse)
rows = query.order_by(ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc()).limit(5).all()
result = None
for row in rows:
if is_snapshot_fresh(row):
return row
return None
result = row
break
read_cache[cache_key] = result
return result
def find_ready_rpa_inventory_snapshot(
@@ -42,34 +42,17 @@ INVENTORY_SOURCE_ERROR_CODES = {
}
def _inventory_source_config_current(task: ShippingNotice) -> bool:
"""任务上记录的库存源配置版本须与当前数据库版本一致。"""
# 兼容旧任务/轻量测试桩:缺失版本字段等同于未冻结当前配置。
stored = str(getattr(task, 'inventory_source_config_version', None) or "").strip()
current = inventory_sources_runtime_version()
if not stored:
return False
return stored == current
def is_inventory_source_stable(task: ShippingNotice) -> bool:
"""
判断任务库存源是否稳定,可供后续库存/RPA/匹配流程使用。
核心逻辑:单源须 Source/Driver/配置一致;STP 多候选冻结(candidates_frozen)
在配置版本与指纹有效且候选非空时亦视为稳定,可进入库存准备。
核心逻辑(档位一:只做必要管控):单源须 Source 存在且启用、Driver 一致;
STP 多候选冻结(candidates_frozen)在候选非空且各候选源存在时视为稳定。
不比对全局配置版本 hash 或路由指纹——无关库存源的改动不使本任务失效。
"""
status = str(task.inventory_source_status or "").strip()
if status not in STABLE_INVENTORY_SOURCE_STATUSES:
return False
if not _inventory_source_config_current(task):
return False
fingerprint = str(task.inventory_routing_fingerprint or "").strip()
if not fingerprint:
return False
context = extract_routing_context(task)
if fingerprint != compute_routing_fingerprint(context):
return False
if status == "candidates_frozen":
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
@@ -107,11 +90,17 @@ def routing_fingerprint_changed(task: ShippingNotice, context: dict[str, Any]) -
def inventory_source_config_changed(task: ShippingNotice) -> bool:
"""配置版本变化会使已有库存源裁决失效。"""
stored = str(task.inventory_source_config_version or "").strip()
if not stored:
return bool(str(task.inventory_source_status or "").strip())
return stored != inventory_sources_runtime_version()
"""
配置变更判定(档位一收窄):仅当任务实际选中的库存源自身不再可用时才算配置已变。
核心逻辑:不再比对全局配置版本 hash——无关库存源的改动不影响本任务;
只检查任务冻结时选中的源(或冻结候选集)当前是否仍可用(存在且启用、驱动一致)。
"""
status = str(task.inventory_source_status or "").strip()
if status not in STABLE_INVENTORY_SOURCE_STATUSES:
# 未稳定任务沿用旧语义:已有裁决状态即视为需要重新裁决。
return bool(status)
return not is_inventory_source_stable(task)
def apply_destination_fields(task: ShippingNotice, context: dict[str, Any]) -> None:
@@ -75,6 +75,9 @@ def get_database_inventory_source(source_code: str, *, enabled_only: bool = True
'report_path_json': dict(source.report_path_json or {}),
'query_parameters_json': list(source.query_parameters_json or []),
'rpa_profile_code': profile.profile_code,
# 连接级受控上传配置(受限 JSON):Worker 用 login_url 登录后访问 upload_config.entry_url 上传页,
# 平台差异(文件选择、提交与结果判定)由 Worker 受控 Adapter 固化。
'upload_config_json': profile.upload_config_json,
# 与既有 worker 契约的适配层:不再从 Profile 取报表路径或查询参数。
'navigation': source_navigation,
'parameters': list(source.query_parameters_json or []),
@@ -3361,9 +3361,25 @@ def list_order_extraction_run_summaries(
}
def _run_no_via_fk(fk_id: int | None) -> str | None:
"""
按自引用外键经 identity map 读取父/后继 Run 号。
性能约束:禁止再走 reparse_source/superseding_run 关系懒加载——它们每次都会
全列 SELECT 父行(含 MB 级 input_snapshot_json);父行通常已由谱系遍历加载,
此处命中 identity map 后 0 SQL。
"""
if fk_id is None:
return None
parent = db.session.get(ShippingOrderProcessingRun, int(fk_id))
return parent.run_no if parent is not None else None
def _reparse_difference_summary(run: ShippingOrderProcessingRun) -> dict[str, Any] | None:
"""返回新版与来源 Run 的脱敏规则差异计数,禁止比较或暴露邮件正文和 Provider 输出。"""
source = run.reparse_source
if not run.reparse_of_run_id:
return None
source = db.session.get(ShippingOrderProcessingRun, int(run.reparse_of_run_id))
if source is None:
return None
current = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
@@ -3602,8 +3618,9 @@ def serialize_order_extraction_run(run: ShippingOrderProcessingRun) -> dict[str,
'schema_checksum': schema_snapshot.get('checksum'),
'attempt_count': int(run.attempt_count or 0),
'reparse': {
'source_run_no': run.reparse_source.run_no if run.reparse_source is not None else None,
'superseding_run_no': run.superseding_run.run_no if run.superseding_run is not None else None,
# [PERF] 用 identity-map 直取替代关系加载,避免对父行重复全列 SELECT(含 MB 级 JSON)。
'source_run_no': _run_no_via_fk(run.reparse_of_run_id),
'superseding_run_no': _run_no_via_fk(run.superseded_by_run_id),
'reason': run.reparse_reason,
'superseded_at': run.superseded_at.isoformat() + 'Z' if run.superseded_at else None,
'difference_summary': _reparse_difference_summary(run),
@@ -0,0 +1,153 @@
"""
backend/app/services/shipping_notice/order_line_no_resolver.py
用途:内部项次(line_no)展示/导出值的唯一解析器——冻结字段真实值 → 客户 PO 行号 →
行展示序号,并输出来源标注(field / customer_po_line_no / sequence / None)。
依赖:app.models(ShippingNotice/Snapshot/Extraction)、order_schema.field_rules(格式门禁)。
逻辑:Excel 导出(export._mapping_value)与 UI 投影(query_service / ui_state)统一调用
本模块,禁止各调用方自行兜底,避免同一数据出现两套口径;缺失事实必须显式标注来源,
不得把内部行号伪装成业务项次。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.models import ShippingNotice, ShippingOrderExtraction, ShippingOrderSnapshot
from app.services.shipping_notice.order_schema.field_rules import is_valid_line_no_value
LINE_NO_SOURCE_FIELD = 'field'
LINE_NO_SOURCE_CUSTOMER_PO_LINE = 'customer_po_line_no'
LINE_NO_SOURCE_SEQUENCE = 'sequence'
def field_id_by_code_from_definition(
definition_json: dict[str, Any] | None,
) -> dict[str, str]:
"""从 Schema 版本定义提取 field_code → field_id 映射。
Args:
definition_json: 已发布 Schema 版本的 definition_json;无 fields 时返回空映射。
Returns:
{field_code: field_id};仅保留同时具备 code/id 的字段。
"""
fields = (definition_json or {}).get('fields') or []
return {
str(item.get('field_code')): str(item.get('field_id'))
for item in fields
if isinstance(item, dict) and item.get('field_code') and item.get('field_id')
}
def notice_line_field_id_map(task: ShippingNotice) -> dict[str, str]:
"""按任务冻结 Schema 构建行字段 code→id 映射。
核心逻辑:优先读冻结快照的 Schema 版本(与快照行 field_values_json 的 field_id 键同源);
无快照时回退当前探测 Extraction 的 Schema 版本;均不可得时返回空映射,
由解析器按 field_code 键兼容读取(历史/测试数据)。
Args:
task: 正式发货任务。
Returns:
{field_code: field_id};无法取得 Schema 时返回空映射。
"""
snapshot_id = getattr(task, 'order_snapshot_id', None)
if snapshot_id:
snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id))
if snapshot is not None and snapshot.schema_version is not None:
return field_id_by_code_from_definition(snapshot.schema_version.definition_json)
extraction_id = getattr(task, 'current_order_extraction_id', None)
if extraction_id:
extraction = db.session.get(ShippingOrderExtraction, int(extraction_id))
if extraction is not None and extraction.schema_version is not None:
return field_id_by_code_from_definition(extraction.schema_version.definition_json)
return {}
def _read_field(
field_values: dict[str, Any] | None,
field_id_by_code: dict[str, str] | None,
code: str,
) -> str | None:
"""按 field_id 优先、field_code 兼容的稳定顺序读取行字段值。
核心逻辑:冻结 JSON 以 field_id(UUID)为键;历史/测试数据可能仍按 field_code 存储。
任一键命中且非空即返回规范化字符串,避免把 0/False 等合法值误判为空。
"""
values = field_values if isinstance(field_values, dict) else {}
field_id = str(field_id_by_code.get(code) or '') if field_id_by_code else ''
if field_id and field_id in values:
raw = values[field_id]
if raw not in (None, ''):
text = str(raw).strip()
return text or None
if code in values:
raw = values[code]
if raw not in (None, ''):
text = str(raw).strip()
return text or None
return None
def resolve_order_line_no(
*,
field_values: dict[str, Any] | None,
field_id_by_code: dict[str, str] | None,
fallback_sequence: int | None = None,
) -> dict[str, Any]:
"""解析一行内部项次展示值(唯一权威入口)。
【AI 触发时机】需要展示或导出某订单行的项次时统一调用;禁止在展示层自行回退。
核心逻辑:
[STEP 1] line_no 字段真实值(须通过 is_valid_line_no_value 格式门禁)→ source=field;
[STEP 2] customer_po_line_no 字段真实值(同格式门禁)→ source=customer_po_line_no;
[STEP 3] 调用方提供的 1..N 行序号 → source=sequence(明确标注为展示序号);
[STEP 4] 全部缺失 → {'value': None, 'source': None}。
与派生规则同门禁:非法项次格式(非 1–6 位数字)一律跳过,不得以序号冒充业务值。
Args:
field_values: 行字段值 JSON(field_id 或 field_code 键均可)。
field_id_by_code: field_code → field_id 映射;为空时仅按 field_code 键兼容读取。
fallback_sequence: 1 基展示序号;None 表示无序号兜底。
Returns:
{'value': 规范化字符串或 None, 'source': 'field'|'customer_po_line_no'|'sequence'|None}。
"""
line_no = _read_field(field_values, field_id_by_code, 'line_no')
if line_no is not None and is_valid_line_no_value(line_no):
return {'value': line_no, 'source': LINE_NO_SOURCE_FIELD}
customer_line_no = _read_field(field_values, field_id_by_code, 'customer_po_line_no')
if customer_line_no is not None and is_valid_line_no_value(customer_line_no):
return {'value': customer_line_no, 'source': LINE_NO_SOURCE_CUSTOMER_PO_LINE}
if fallback_sequence is not None and int(fallback_sequence) >= 1:
return {'value': str(int(fallback_sequence)), 'source': LINE_NO_SOURCE_SEQUENCE}
return {'value': None, 'source': None}
def resolve_order_line_no_projection(
*,
field_values: dict[str, Any] | None,
field_id_by_code: dict[str, str] | None,
fallback_sequence: int | None = None,
) -> dict[str, Any]:
"""与 resolve_order_line_no 同源的 UI/导出投影形(line_no / line_no_source 键)。
核心逻辑:仅供展示层消费;把语义结果映射为前端契约键,避免各处手写
{'line_no': result['value'], 'line_no_source': result['source']} 产生分叉。
Returns:
{'line_no': str|None, 'line_no_source': 'field'|'customer_po_line_no'|'sequence'|None}。
"""
resolved = resolve_order_line_no(
field_values=field_values,
field_id_by_code=field_id_by_code,
fallback_sequence=fallback_sequence,
)
return {'line_no': resolved['value'], 'line_no_source': resolved['source']}
@@ -18,6 +18,8 @@ from __future__ import annotations
import uuid
from typing import Any, NoReturn
from sqlalchemy.orm import defer
from app import db
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.models import (
@@ -44,16 +46,41 @@ _NON_ORDER_REASONS = frozenset({'non_order', 'duplicate_file', 'other'})
_TERMINAL_DISPOSITION_STATUSES = frozenset({'confirmed', 'non_order', 'superseded', 'reparse_pending'})
_RUN_LINEAGE_ROOT_CACHE_KEY = 'shipping_order_review_run_lineage_root_cache'
def _run_lineage_root(*, run: ShippingOrderProcessingRun) -> ShippingOrderProcessingRun:
"""沿重解析父链定位批次的初始 Run,阻止从局部子 Run 缩小原批次范围。"""
"""
沿重解析父链定位批次的初始 Run,阻止从局部子 Run 缩小原批次范围。
性能约束:父链每跳只窄列读取(defer 大 JSON 冻结快照),同一请求内按 Run 记忆化,
避免工作台每次投影都沿谱系重拉整行 input_snapshot_json(MB 级)。
"""
cache = db.session.info.get(_RUN_LINEAGE_ROOT_CACHE_KEY)
if not isinstance(cache, dict):
cache = {}
db.session.info[_RUN_LINEAGE_ROOT_CACHE_KEY] = cache
cached = cache.get(int(run.id))
if cached is not None:
return cached
current = run
seen_ids = {int(run.id)}
while current.reparse_of_run_id:
parent = db.session.get(ShippingOrderProcessingRun, int(current.reparse_of_run_id))
parent = (
ShippingOrderProcessingRun.query
.options(
defer(ShippingOrderProcessingRun.input_snapshot_json),
defer(ShippingOrderProcessingRun.execution_result_json),
defer(ShippingOrderProcessingRun.result_json),
)
.filter(ShippingOrderProcessingRun.id == int(current.reparse_of_run_id))
.first()
)
if parent is None or int(parent.id) in seen_ids:
break
seen_ids.add(int(parent.id))
current = parent
cache[int(run.id)] = current
return current
@@ -429,6 +429,23 @@ def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, act
task = db.session.get(ShippingNotice, int(task_id))
if task is None:
return
# [BE-释放-重算] 放行是库存充分性 Gate 的受控业务事实:必须先把任务级履约态
# (match_status/line_results_json/shortage_json/review_status/pending_human_reason)
# 重算到与放行决定一致,否则 Gate 重投影后任务仍残留 shortage/unfulfillable,
# 出现"Excel 已生成但任务仍显示库存不足/缺货"的矛盾。仅当任务确有匹配行事实时重算,
# 空事实任务不得被误标为缺货。
if getattr(task, 'id', None) is not None:
from app.models import ShippingNoticeLineInventoryMatch as _MatchRow
has_match_rows = (
_MatchRow.query.filter_by(task_id=int(task.id), is_current=True).first()
is not None
)
if has_match_rows:
from app.services.shipping_notice.fulfillment_workflow import (
recompute_task_fulfillment_state,
)
recompute_task_fulfillment_state(task)
execution_id = getattr(task, 'active_process_execution_id', None)
if execution_id is not None:
from app.models import ShippingProcessExecution
@@ -1185,15 +1185,39 @@ def serialize_review_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
.all()
)
counts = {key: 0 for key in ('unreviewed', 'draft', 'ready', 'confirmed', 'non_order', 'quality_issue')}
items = []
for case in cases:
counts[case.status] = counts.get(case.status, 0) + 1
items.append(_serialize_review_case_summary(case, run=run))
batch = _load_review_case_summary_batch([(case, run) for case in cases])
previous_cache = db.session.info.get('shipping_conversation_projection_read_cache')
cache = dict(previous_cache) if isinstance(previous_cache, dict) else {}
cache['stp_jobs_by_ref'] = {**cache.get('stp_jobs_by_ref', {}), **batch['jobs_by_ref']}
cache['stp_jobs_by_prefix'] = {**cache.get('stp_jobs_by_prefix', {}), **batch['jobs_by_prefix']}
cache['execution_by_case_id'] = {**cache.get('execution_by_case_id', {}), **batch['executions_by_case_id']}
cache['gates_by_execution_id'] = {**cache.get('gates_by_execution_id', {}), **batch['gates_by_execution_id']}
cache['latest_attempt_by_id'] = {**cache.get('latest_attempt_by_id', {}), **batch['latest_attempt_by_id']}
db.session.info['shipping_conversation_projection_read_cache'] = cache
try:
items = []
for case in cases:
counts[case.status] = counts.get(case.status, 0) + 1
items.append(_serialize_review_case_summary(
case,
run=run,
candidates_by_id=batch['candidates_by_id'],
intakes_by_no=batch['intakes_by_no'],
drafts_by_id=batch['drafts_by_id'],
))
finally:
if previous_cache is None:
db.session.info.pop('shipping_conversation_projection_read_cache', None)
else:
db.session.info['shipping_conversation_projection_read_cache'] = previous_cache
# 同一事务中刚写入 superseded_by_run_id 时,SQLAlchemy 不会自动刷新已加载的
# self-referential relationship。投影按外键补读,保证旧 Run 可稳定指向后继 Run。
superseding_run = run.superseding_run
if superseding_run is None and run.superseded_by_run_id is not None:
superseding_run = db.session.get(ShippingOrderProcessingRun, int(run.superseded_by_run_id))
# self-referential relationship。投影按外键直取,保证旧 Run 可稳定指向后继 Run。
superseding_run = (
db.session.get(ShippingOrderProcessingRun, int(run.superseded_by_run_id))
if run.superseded_by_run_id is not None
else None
)
return {
'run_no': run.run_no,
'superseded_by_run_no': superseding_run.run_no if superseding_run is not None else None,
@@ -1204,49 +1228,28 @@ def serialize_review_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
}
def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str, Any]:
"""返回会话级文件当前队列;Run/Case 历史均不参与主队列平铺。"""
if not runs:
return {'conversation_id': None, 'summary': {'total': 0, 'needs_action': 0, 'processing': 0, 'completed': 0}, 'items': []}
conversation_id = str(runs[0].conversation_id)
owner_ids = {int(run.user_id) for run in runs if run.user_id is not None}
query = (
db.session.query(ShippingOrderReviewStream, ShippingOrderReviewCase, ShippingOrderProcessingRun)
.join(ShippingOrderReviewCase, ShippingOrderReviewCase.id == ShippingOrderReviewStream.current_case_id)
.join(ShippingOrderProcessingRun, ShippingOrderProcessingRun.id == ShippingOrderReviewCase.run_id)
.filter(ShippingOrderProcessingRun.conversation_id == conversation_id)
.filter(ShippingOrderReviewCase.status != 'superseded')
.options(
Load(ShippingOrderReviewCase).load_only(
ShippingOrderReviewCase.id,
ShippingOrderReviewCase.stream_id,
ShippingOrderReviewCase.revision_no,
ShippingOrderReviewCase.case_no,
ShippingOrderReviewCase.run_id,
ShippingOrderReviewCase.document_id,
ShippingOrderReviewCase.candidate_id,
ShippingOrderReviewCase.current_draft_id,
ShippingOrderReviewCase.confirmed_task_id,
ShippingOrderReviewCase.status,
ShippingOrderReviewCase.disposition,
),
Load(ShippingOrderProcessingRun).load_only(
ShippingOrderProcessingRun.id,
ShippingOrderProcessingRun.run_no,
ShippingOrderProcessingRun.conversation_id,
ShippingOrderProcessingRun.user_id,
ShippingOrderProcessingRun.schema_version_id,
ShippingOrderProcessingRun.input_snapshot_json,
),
)
)
if owner_ids:
query = query.filter(ShippingOrderReviewStream.owner_user_id.in_(owner_ids))
rows = query.order_by(ShippingOrderReviewStream.updated_at.desc(), ShippingOrderReviewStream.id.desc()).all()
case_ids = [int(case.id) for _, case, _ in rows]
candidate_ids = [int(case.candidate_id) for _, case, _ in rows if case.candidate_id]
draft_ids = [int(case.current_draft_id) for _, case, _ in rows if case.current_draft_id]
task_ids = [int(case.confirmed_task_id) for _, case, _ in rows if case.confirmed_task_id]
def _load_review_case_summary_batch(
rows: list[tuple[ShippingOrderReviewCase, ShippingOrderProcessingRun]],
) -> dict[str, Any]:
"""
一次性批量预取列表投影所需的子实体,禁止按 Case N+1 查询。
性能约束:候选 / Draft / Intake / 正式 Notice / STP Job / Execution / Gate / Attempt
全部聚合为固定次数批量查询;STP Job 与 Execution 事实写入会话级只读缓存
(shipping_conversation_projection_read_cache),供既有 find_active_stp_job 等消费,
保证会话队列与单 Run 摘要在同一请求内复用同一批事实。正式 Notice 仅预热身份映射,
后续 resolve_formal_ot / ui_state 的 db.session.get 命中 identity map(0 SQL)。
Args:
rows: (Case, Run) 行列表。
Returns:
批量化后的候选 / Draft / Intake 映射与 STP Job / Execution 缓存数据。
"""
case_ids = [int(case.id) for case, _ in rows]
candidate_ids = [int(case.candidate_id) for case, _ in rows if case.candidate_id]
draft_ids = [int(case.current_draft_id) for case, _ in rows if case.current_draft_id]
task_ids = [int(case.confirmed_task_id) for case, _ in rows if case.confirmed_task_id]
candidates_by_id = {
int(candidate.id): candidate
for candidate in ShippingOrderCandidate.query.filter(ShippingOrderCandidate.id.in_(candidate_ids)).all()
@@ -1255,13 +1258,11 @@ def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str,
int(draft.id): draft
for draft in ShippingOrderReviewDraft.query.filter(ShippingOrderReviewDraft.id.in_(draft_ids)).all()
} if draft_ids else {}
_tasks_by_id = {
int(task.id): task
for task in ShippingNotice.query.filter(ShippingNotice.id.in_(task_ids)).all()
} if task_ids else {}
if task_ids:
ShippingNotice.query.filter(ShippingNotice.id.in_(task_ids)).all()
intake_nos = {
str(intake_snapshot.get('intake_no') or '').strip().upper()
for _, case, run in rows
for case, run in rows
for intake_snapshot in (run.input_snapshot_json or {}).get('intakes', [])
if isinstance(intake_snapshot, dict)
for document in intake_snapshot.get('documents') or []
@@ -1277,7 +1278,7 @@ def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str,
stp_prefixes = {
f"stp-auto:{run.run_no}:doc-{int(case.document_id)}:"
for _, case, run in rows
for case, run in rows
if case.document_id is not None
}
stp_refs = {
@@ -1286,7 +1287,7 @@ def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str,
document_id=int(case.document_id),
draft_version=int(drafts_by_id[int(case.current_draft_id)].draft_version),
)
for _, case, run in rows
for case, run in rows
if case.current_draft_id and int(case.current_draft_id) in drafts_by_id
}
jobs_by_ref: dict[str, list[Job]] = {ref: [] for ref in stp_refs}
@@ -1345,23 +1346,75 @@ def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str,
ShippingProcessGateAttempt.id.in_(latest_attempt_ids),
).all()
}
return {
'candidates_by_id': candidates_by_id,
'drafts_by_id': drafts_by_id,
'intakes_by_no': intakes_by_no,
'jobs_by_ref': jobs_by_ref,
'jobs_by_prefix': jobs_by_prefix,
'executions_by_case_id': executions_by_case_id,
'gates_by_execution_id': gates_by_execution_id,
'latest_attempt_by_id': latest_attempt_by_id,
}
def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str, Any]:
"""返回会话级文件当前队列;Run/Case 历史均不参与主队列平铺。"""
if not runs:
return {'conversation_id': None, 'summary': {'total': 0, 'needs_action': 0, 'processing': 0, 'completed': 0}, 'items': []}
conversation_id = str(runs[0].conversation_id)
owner_ids = {int(run.user_id) for run in runs if run.user_id is not None}
query = (
db.session.query(ShippingOrderReviewStream, ShippingOrderReviewCase, ShippingOrderProcessingRun)
.join(ShippingOrderReviewCase, ShippingOrderReviewCase.id == ShippingOrderReviewStream.current_case_id)
.join(ShippingOrderProcessingRun, ShippingOrderProcessingRun.id == ShippingOrderReviewCase.run_id)
.filter(ShippingOrderProcessingRun.conversation_id == conversation_id)
.filter(ShippingOrderReviewCase.status != 'superseded')
.options(
Load(ShippingOrderReviewCase).load_only(
ShippingOrderReviewCase.id,
ShippingOrderReviewCase.stream_id,
ShippingOrderReviewCase.revision_no,
ShippingOrderReviewCase.case_no,
ShippingOrderReviewCase.run_id,
ShippingOrderReviewCase.document_id,
ShippingOrderReviewCase.candidate_id,
ShippingOrderReviewCase.current_draft_id,
ShippingOrderReviewCase.confirmed_task_id,
ShippingOrderReviewCase.status,
ShippingOrderReviewCase.disposition,
),
Load(ShippingOrderProcessingRun).load_only(
ShippingOrderProcessingRun.id,
ShippingOrderProcessingRun.run_no,
ShippingOrderProcessingRun.conversation_id,
ShippingOrderProcessingRun.user_id,
ShippingOrderProcessingRun.schema_version_id,
ShippingOrderProcessingRun.input_snapshot_json,
),
)
)
if owner_ids:
query = query.filter(ShippingOrderReviewStream.owner_user_id.in_(owner_ids))
rows = query.order_by(ShippingOrderReviewStream.updated_at.desc(), ShippingOrderReviewStream.id.desc()).all()
batch = _load_review_case_summary_batch([(case, run) for _, case, run in rows])
previous_cache = db.session.info.get('shipping_conversation_projection_read_cache')
cache = dict(previous_cache) if isinstance(previous_cache, dict) else {}
cache['stp_jobs_by_ref'] = {**cache.get('stp_jobs_by_ref', {}), **jobs_by_ref}
cache['stp_jobs_by_prefix'] = {**cache.get('stp_jobs_by_prefix', {}), **jobs_by_prefix}
cache['execution_by_case_id'] = {**cache.get('execution_by_case_id', {}), **executions_by_case_id}
cache['gates_by_execution_id'] = {**cache.get('gates_by_execution_id', {}), **gates_by_execution_id}
cache['latest_attempt_by_id'] = {**cache.get('latest_attempt_by_id', {}), **latest_attempt_by_id}
cache['stp_jobs_by_ref'] = {**cache.get('stp_jobs_by_ref', {}), **batch['jobs_by_ref']}
cache['stp_jobs_by_prefix'] = {**cache.get('stp_jobs_by_prefix', {}), **batch['jobs_by_prefix']}
cache['execution_by_case_id'] = {**cache.get('execution_by_case_id', {}), **batch['executions_by_case_id']}
cache['gates_by_execution_id'] = {**cache.get('gates_by_execution_id', {}), **batch['gates_by_execution_id']}
cache['latest_attempt_by_id'] = {**cache.get('latest_attempt_by_id', {}), **batch['latest_attempt_by_id']}
db.session.info['shipping_conversation_projection_read_cache'] = cache
try:
items = [{
**_serialize_review_case_summary(
case,
run=run,
candidates_by_id=candidates_by_id,
intakes_by_no=intakes_by_no,
drafts_by_id=drafts_by_id,
candidates_by_id=batch['candidates_by_id'],
intakes_by_no=batch['intakes_by_no'],
drafts_by_id=batch['drafts_by_id'],
),
'stream_id': int(stream.id),
'stream_state': stream.state,
@@ -884,6 +884,40 @@ def sync_fulfillment_gates_from_task(
mapping_confirmed = bool(inv_file is not None and bool(getattr(inv_file, 'mapping_confirmed', False)))
# [STEP 1] 优先读匹配/短缺实体;阶段由领域事实推导。
done_statuses = {'uploaded', 'closed'}
# [STEP 1A] 已上传/已关闭是终态事实:直接收口 RPA 与人工交接 Gate 后返回,
# 禁止再用当前库存不足/匹配缺失重算前置 Gate(否则已上传任务会被 gate 16
# 倒打回 blocked_manual,execution.current_gate 回退、OT 阶段与前端状态横跳)。
if status in done_statuses:
# 人工确认已上传 = 覆盖前序预警门禁(含短路时的 blocked_manual 短缺门禁),
# 使 Execution 全部通过并进入 completed;短缺事实仍保留在 Gate 审计 effective_result。
mark_gates_passed_through(
execution=execution,
through_gate_code='manual_upload_handoff',
actor_type=actor_type,
actor_id=actor_id,
reason='task_uploaded',
)
apply_gate_outcome(
execution=execution,
gate_code='freight_upload_rpa',
passed=True,
effective_result={'derived_fulfillment_status': status, 'findings': []},
actor_type=actor_type,
actor_id=actor_id,
idempotency_key=f'fulfill:freight_rpa:{execution.execution_no}:{status}:passed',
force=True,
)
apply_gate_outcome(
execution=execution,
gate_code='manual_upload_handoff',
passed=True,
effective_result={'derived_fulfillment_status': status, 'findings': []},
actor_type=actor_type,
actor_id=actor_id,
idempotency_key=f'fulfill:upload:{execution.execution_no}:{status}:passed',
force=True,
)
return
post_inventory = {'inventory_ready', 'matched', 'waiting_upload', 'upload_failed', *done_statuses}
sufficiency_ok = match_completed(task)
shortage = (not sufficiency_ok) and (
@@ -1085,7 +1085,9 @@ def _handle_recheck_inventory_sufficiency(
) -> dict[str, Any]:
"""独立库存满足性复核:读取 match_status / shortage_json,不重跑匹配。"""
from app.models import ShippingNotice
from app.services.shipping_notice.fulfillment_workflow import match_completed
from app.services.shipping_notice.fulfillment_workflow import (
recompute_task_fulfillment_state,
)
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
@@ -1097,6 +1099,16 @@ def _handle_recheck_inventory_sufficiency(
'effective_result_json': {'findings': []},
'output_snapshot': {'action_code': 'recheck_inventory_sufficiency'},
}
# [BE-满足性复盘] 复核先按当前放行/匹配事实重算任务级履约态,避免"Gate 认为满足、
# 任务却仍标 unfulfillable/shortage"的旧状态残留。仅在确有匹配行时重算(空事实不误标缺货)。
from app.models import ShippingNoticeLineInventoryMatch as _MatchRow
if getattr(task, 'id', None) is not None and (
_MatchRow.query.filter_by(task_id=int(task.id), is_current=True).first() is not None
):
recompute_task_fulfillment_state(task)
from app.services.shipping_notice.fulfillment_workflow import match_completed
sufficient = match_completed(task)
shortage = task.shortage_json if isinstance(task.shortage_json, (dict, list)) else None
apply_gate_outcome(
@@ -328,6 +328,32 @@ def serialize_process_execution(
.order_by(ShippingProcessGate.sequence_no.asc())
.all()
)
# [BE-性能] ui_state 等工作台路径不预置 conversation 投影缓存,导致 serialize_process_gate
# 对每个 Gate 各做一次 latest_attempt_id 的 query.get()(N+1)。此处批量加载本 Execution 的
# 全部 LatestAttempt 并写入会话缓存,缓存生效后逐 Gate 命中、不再逐条查询。
previous_cache = db.session.info.get('shipping_conversation_projection_read_cache')
merged_cache = dict(previous_cache) if isinstance(previous_cache, dict) else {}
latest_attempt_ids = [
int(gate.latest_attempt_id)
for gate in gates
if gate.latest_attempt_id is not None
]
if latest_attempt_ids:
attempt_by_id = {
int(a.id): a
for a in ShippingProcessGateAttempt.query.filter(
ShippingProcessGateAttempt.id.in_(latest_attempt_ids),
).all()
}
merged_cache['latest_attempt_by_id'] = {
**((merged_cache.get('latest_attempt_by_id') or {})),
**attempt_by_id,
}
merged_cache['gates_by_execution_id'] = {
**((merged_cache.get('gates_by_execution_id') or {})),
**{int(execution.id): gates},
}
db.session.info['shipping_conversation_projection_read_cache'] = merged_cache
serialized = [
serialize_process_gate(gate, include_diagnostics=include_diagnostics)
for gate in gates
@@ -245,6 +245,7 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
execution.responsible_party = None
if execution.status not in {'cancelled', 'failed'}:
execution.status = 'completed'
_sync_order_task_stage_after_gate_refresh(execution)
return
execution.current_gate_code = current.gate_code
execution.primary_next_action_code = current.next_action_code
@@ -258,6 +259,24 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
execution.status = 'active'
else:
execution.status = 'active'
# [OT SYNC] Gate 指针刷新后回写挂接 OT 的 stage/status,避免主卡/批次只读
# 投影停留在技术阶段(如 excel_generating),与当前 Gate 事实分叉。
# 仅已绑定任务时同步;建单前执行(无 task_id)自然跳过。延迟导入避免循环依赖。
_sync_order_task_stage_after_gate_refresh(execution)
def _sync_order_task_stage_after_gate_refresh(execution: ShippingProcessExecution) -> None:
"""Gate 指针刷新后回写挂接 OT 的 stage/status(completed 与阻断两个出口共用)。"""
if getattr(execution, 'task_id', None) is None:
return
from app.models import ShippingNotice
from app.services.shipping_notice.order_task_stage_machine import (
sync_order_task_stage_for_notice,
)
notice = db.session.get(ShippingNotice, int(execution.task_id))
if notice is not None:
sync_order_task_stage_for_notice(notice)
def ensure_execution_for_workflow_version(
@@ -792,8 +792,11 @@ def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
"""
投影发货通知列表需要的项次、料号、数量与当前库存事实。
核心逻辑:Notice 行定义“本通知包含哪些业务行”;当前库存只读取同 Notice、
`is_current=true` 的匹配事实。未找到匹配事实时明确返回 null,禁止由前端估算库存。
核心逻辑:Notice 行定义“本通知包含哪些业务行”;项次(line_no)经
order_line_no_resolver 统一解析(字段真实值 → 客户 PO 行号 → 展示序号),
并附 line_no_source 标注,禁止前端按 position 或序号自行推导业务项次。
当前库存只读取同 Notice、`is_current=true` 的匹配事实;未找到匹配事实时明确
返回 null,禁止由前端估算库存。
"""
if task.id is None:
return []
@@ -808,8 +811,18 @@ def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
rows = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by(
ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(),
).all()
from app.services.shipping_notice.order_line_no_resolver import (
notice_line_field_id_map,
resolve_order_line_no_projection,
)
field_id_by_code = notice_line_field_id_map(task)
return [{
'line_no': (item.field_values_json or {}).get('line_no') or item.position,
**resolve_order_line_no_projection(
field_values=item.field_values_json,
field_id_by_code=field_id_by_code,
fallback_sequence=(int(item.position) + 1) if item.position is not None else None,
),
'part_number': item.part_number,
'customer_part_number': (item.field_values_json or {}).get('customer_part_number'),
'reservation_id': item.reservation_id,
@@ -889,6 +902,7 @@ def _enrich_task_center_fields(
*,
viewer_user_id: int | None = None,
is_admin: bool = False,
include_stage_context: bool = False,
) -> dict[str, Any]:
"""
为 SUMMARY/DETAIL 投影补充任务中心字段(就地写入并返回 data)。
@@ -896,12 +910,15 @@ def _enrich_task_center_fields(
核心逻辑:todo_category / created_by 始终写入;viewer 给定时写入 can_handle;
recent_event / artifact_summary / ui_state 懒加载同源状态;
注入 shipping_processing_status / progress_version / order_task_no(统一进度)。
``include_stage_context`` 直接透传给 ``build_task_ui_state``,使 DETAIL 一次投影即可携带
工作面只读事实,避免调用方在同一请求里再 build 一次被覆盖。
Args:
task: 源任务。
data: 已构建的序列化字典。
viewer_user_id: 当前查看者;为 None 时省略 can_handle。
is_admin: 是否管理员视图(仅影响 can_handle 调用签名,不开放代操作)。
include_stage_context: 是否让内嵌 ui_state 附带 stage_context。
Returns:
同一 data 引用(已 enrich)。
@@ -918,7 +935,7 @@ def _enrich_task_center_fields(
# [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。
from app.services.shipping_notice.ui_state import build_task_ui_state
data["ui_state"] = build_task_ui_state(task)
data["ui_state"] = build_task_ui_state(task, include_stage_context=include_stage_context)
_inject_unified_processing_fields(task, data)
# [BE-06] WorkflowItem 账本已下线;固定为 None,禁止前端再当 OT 身份源。
data['workflow_item'] = None
@@ -950,6 +967,7 @@ def serialize_task_detail(
*,
viewer_user_id: int | None = None,
is_admin: bool = False,
include_stage_context: bool = False,
) -> dict[str, Any]:
"""
工作台任务详情用的 DETAIL 投影(含 lines、events 与任务中心 enrich)。
@@ -958,10 +976,12 @@ def serialize_task_detail(
task: 源任务。
viewer_user_id: 当前查看者;用于 can_handle。
is_admin: 是否管理员视图。
include_stage_context: 是否让内嵌 ui_state 附带 stage_context(避免调用方重复 build)。
"""
data = serialize_task(task, TaskProjection.DETAIL)
return _enrich_task_center_fields(
task, data, viewer_user_id=viewer_user_id, is_admin=is_admin,
include_stage_context=include_stage_context,
)
@@ -1123,17 +1143,19 @@ def list_freight_notice_groups_for_task(
if not business_no:
continue
# [STEP] 主区单条菜单只消费服务端已裁决的 Notice 动作,禁止按 upload_status 猜测。
from app.services.shipping_notice.ui_state import build_task_ui_state
actions = (build_task_ui_state(notice).get('actions') or {})
available_actions = [
str(action.get('code')).strip()
for action in [actions.get('primary'), *(actions.get('secondary') or [])]
if isinstance(action, dict) and action.get('enabled') is True and str(action.get('code') or '').strip()
]
# 轻量投影仅返回动作码,避免逐张 Notice 跑完整 build_task_ui_state 造成 N 倍放大。
from app.services.shipping_notice.ui_state import project_notice_available_actions
available_actions = project_notice_available_actions(notice)
items.append({
'business_no': business_no,
'po_number': po_number,
'upload_status': notice.upload_status,
'upload_mode': notice.upload_mode,
'upload_attempt': notice.upload_attempt,
'upload_error_code': notice.upload_error_code,
# 逐单失败原因:优先取最近一次上传的错误正文,回退到任务级 error_message。
'upload_error_message': (notice.upload_error_message or notice.error_message or '')[:500] or None,
'pending_human_reason': notice.pending_human_reason,
'export_file_name': notice.export_file_name,
'available_actions': available_actions,
'lines': _notice_line_summary_for_task(notice),
@@ -92,10 +92,22 @@ def invalidate_inventory_downstream(
upload.invalidated_at = now
upload.invalidation_reason = action_code
result['uploads'].append(int(upload.id))
if task is not None and action_code in {'retry_inventory_preparation', 'retry_inventory_from_preparation'}:
if task is not None and action_code in {
'retry_inventory_preparation',
'retry_inventory_from_preparation',
'retry_inventory_from_field_mapping',
'retry_inventory_from_matching',
}:
# [BE-放行-恢复] 本动作已把当前匹配行置 is_current=False(上方),必须同步清空任务级
# 派生状态,否则 UI 与 Gate 在下一轮重匹配前仍读到旧 match_status/shortage/line_results,
# 出现"已重试却仍显示旧缺货"的矛盾。
task.match_status = None
task.shortage_json = None
task.line_results_json = None
if task is not None and (
action_code in {'retry_inventory_preparation', 'retry_inventory_from_preparation'}
):
# 仅库存文件级重试才清空导出指针;匹配/字段映射级重试只作废匹配,不改已生成文件。
task.export_file_path = None
task.export_file_name = None
db.session.flush()
+59 -8
View File
@@ -11,6 +11,7 @@ from __future__ import annotations
import json
import os
import shutil
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any
@@ -259,36 +260,86 @@ def write_inventory_export_trigger_for_task(
)
def write_upload_trigger(task_no: str, export_file_path: str, payload: dict[str, Any] | None = None) -> tuple[str | None, str | None]:
def write_upload_trigger(
task_no: str,
export_file_path: str,
payload: dict[str, Any] | None = None,
*,
attempt_id: int | None = None,
artifact_id: int | None = None,
connector_type: str | None = None,
upload_config: dict[str, Any] | None = None,
upload_config_hash: str | None = None,
login_url: str | None = None,
credential_envelope: dict[str, Any] | None = None,
callback_id: str | None = None,
business_no: str | None = None,
) -> tuple[str | None, str | None, str | None]:
"""
复制 Excel 至上传队列并写入 RPA 上传触发 JSON。
复制发货 Excel 至共享上传队列,并以原子发布方式写入 RPA 上传触发 JSON。
【AI 触发时机】:upload_to_freight(mode=auto|retry_upload) 触发货代上传时调用。
触发文件固化本次上传契约快照,Worker 据此进入 DSV/Crane 受控流程:
schema_version / task_no / attempt_id / artifact_id / callback_id(非空)/
connector_type / upload_config(本次快照 + upload_config_hash)/ login_url / credential_envelope / file_path。
平台差异(文件选择器、提交与结果判定)由 Worker 的受控 Adapter 按 upload_config 执行。
写入复用“临时文件 + fsync + os.replace”原子方式,避免 Worker 读取半写 JSON。
Args:
task_no: 发货任务号。
export_file_path: 待上传发货 Excel 的服务端路径。
payload: 附加字段(如 mode),与下列具名参数合并。
attempt_id: 本次 Upload Attempt 主键。
artifact_id: 当前上传目标 Artifact 主键。
connector_type: 业务连接类型(dbs / crane)。
upload_config: 本次上传使用的连接级受控配置快照(enabled/entry_url/selector 等)。
upload_config_hash: 该快照的 sha256,用于审计关联。
login_url: 该连接登录地址(先登录,再访问 upload_config.entry_url 进入上传页)。
credential_envelope: 连接凭据密文信封(Worker 据此登录)。
callback_id: 回调幂等 ID;为空时自动生成,保证非空。
business_no: 发货通知对外业务编号(业务单号),用于精简上传文件名;为空时回退 task_no。
Returns:
tuple[str | None, str | None]: (queue 文件路径, trigger 文件路径);失败时 (None, None)。
tuple[str | None, str | None, str | None]: (queue 文件路径, trigger 文件路径, callback_id);
失败时 (None, None, None)。
"""
queue = upload_queue_dir()
trigger_dir = upload_trigger_dir()
if not queue or not trigger_dir:
return None, None
return None, None, None
queue.mkdir(parents=True, exist_ok=True)
trigger_dir.mkdir(parents=True, exist_ok=True)
src = Path(export_file_path)
if not src.is_file():
return None, None
dest = queue / f"{task_no}_{src.name}"
return None, None, None
# [STEP] 精简上传文件名:仅用业务编号(业务单号),避免 task_no 与导出文件名重复拼接过长;
# 业务编号为空时回退到内部任务号,扩展名沿用源文件(无扩展名时按 xlsx 兜底)。
emit_no = str(business_no or '').strip() or task_no
suffix = str(src.suffix or '.xlsx').lower()
dest = queue / f"{emit_no}{suffix}"
shutil.copy2(src, dest)
resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}'
body = {
"action": "shipment_upload",
"schema_version": "shipping_notice_upload_rpa.v1",
"task_no": task_no,
"attempt_id": attempt_id,
"artifact_id": artifact_id,
"callback_id": resolved_callback_id,
"connector_type": str(connector_type or '').strip() or None,
"upload_config": upload_config,
"upload_config_hash": upload_config_hash,
"login_url": login_url,
"credential_envelope": credential_envelope,
"file_path": str(dest),
"requested_at": datetime.utcnow().isoformat(),
**(payload or {}),
}
trigger_path = trigger_dir / f"upload_{task_no}.json"
trigger_path.write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8")
return str(dest), str(trigger_path)
_write_trigger_json_atomic(trigger_path, body)
return str(dest), str(trigger_path), resolved_callback_id
def find_latest_inventory_file() -> Path | None:
@@ -1588,7 +1588,23 @@ def _project_order_task_work_item(
active_execution = db.session.get(ShippingProcessExecution, int(active_execution_id))
active_gate = str(getattr(active_execution, 'current_gate_code', '') or '').strip().lower()
active_status = str(getattr(active_execution, 'status', '') or '').strip().lower()
if active_status != 'superseded' and active_gate in SHIPPING_PROCESSING_STAGES:
# [BE-10] 正式 Execution 的当前 Gate 只允许把阶段「向前抬起」,严禁把阶段回退。
# 人工确认上传后 Notice 已进入 upload 终态事实(OT.stage/project_stage_for_task 可能已
# 是 freight_uploading/completed),但 Execution 前置履约 Gate 若因 upload_status 未到位
# 而未被 STEP 1A 收口,仍会停在 inventory_sufficiency 等前置 Gate。此时若用 active_gate
# 无条件覆盖 stage,批次中心/对话卡会被回退成「通知准备」,与工作台的「通知完成」分叉。
# 只在 active_gate 不落后于 Notice 当前阶段时才覆盖。
from app.services.shipping_notice.processing_projection_invariants import (
shipping_processing_stage_index,
)
current_stage_idx = shipping_processing_stage_index(stage)
active_gate_idx = shipping_processing_stage_index(active_gate)
if (
active_status != 'superseded'
and active_gate in SHIPPING_PROCESSING_STAGES
and active_gate_idx is not None
and (current_stage_idx is None or active_gate_idx >= current_stage_idx)
):
stage = active_gate
stage_label_key = active_gate
# order_creating 无共享投影时仍统一用户文案键。
@@ -1345,6 +1345,11 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
task.review_status = None
task.pending_human_reason = None
task.error_message = None
# [BE-放行-重试] 重试应重新评估当前库存事实:清空旧匹配结果,强制 orchest 在下一轮
# 重新匹配,而不是带着旧的 unfulfillable/shortage 直接跳到步骤(避免旧缺货残留)。
task.match_status = None
task.line_results_json = None
task.shortage_json = None
try:
order_lines = current_line_field_values(task)
@@ -610,6 +610,12 @@ def _build_stage_context(
}
# 冻结订单与库存匹配是不同事实:库存文件尚未准备好时,用户仍必须能核对
# 已冻结的预约号、料号和需求数量。禁止用“是否有匹配结果”决定订单行是否展示。
from app.services.shipping_notice.order_line_no_resolver import (
notice_line_field_id_map,
resolve_order_line_no_projection,
)
line_no_field_id_by_code = notice_line_field_id_map(task)
frozen_order_lines: list[dict[str, Any]] = []
preparation_lines: list[dict[str, Any]] = []
notice_lines = (
@@ -619,6 +625,11 @@ def _build_stage_context(
for line in notice_lines:
frozen_order_lines.append({
'line_key': getattr(line, 'line_key', None),
**resolve_order_line_no_projection(
field_values=dict(getattr(line, 'field_values_json', None) or {}),
field_id_by_code=line_no_field_id_by_code,
fallback_sequence=(int(line.position) + 1) if line.position is not None else None,
),
'reservation_id': getattr(line, 'reservation_id', None),
'part_number': getattr(line, 'part_number', None),
'required_qty': str(getattr(line, 'required_qty', None)) if getattr(line, 'required_qty', None) is not None else None,
@@ -660,6 +671,11 @@ def _build_stage_context(
shortage_qty = result.get('shortage_qty', source.get('shortage_qty', verification.get('shortage_qty')))
preparation_lines.append({
'line_key': getattr(line, 'line_key', None) or source.get('line_key'),
**resolve_order_line_no_projection(
field_values=dict(getattr(line, 'field_values_json', None) or {}) if line is not None else None,
field_id_by_code=line_no_field_id_by_code,
fallback_sequence=index + 1,
),
'reservation_id': result.get('reservation_id') or source.get('effective_reservation_id') or source.get('reservation_id') or getattr(line, 'reservation_id', None),
'part_number': result.get('part_number') or source.get('part_number') or getattr(line, 'part_number', None),
'required_qty': required_qty,
@@ -672,7 +688,7 @@ def _build_stage_context(
has_match_result = bool(current_match_rows or raw_rows or any(
row.get('matched_qty') is not None
or row.get('shortage_qty') is not None
or str(row.get('disposition') or '').lower() in {'ok', 'partial', 'shortage'}
or str(row.get('disposition') or '').lower() in {'ok', 'partial', 'shortage', 'released'}
for row in fact_rows if isinstance(row, dict)
))
gate = process_gate if isinstance(process_gate, dict) else {}
@@ -930,3 +946,31 @@ def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any]
)
def project_notice_available_actions(task: ShippingNotice) -> list[str]:
"""轻量投影单张 Notice 的已授权动作码,供货代上传面板按 business_no 展示单条菜单。
核心逻辑:与 ``build_task_ui_state`` 的 actions 同源(Gate 摘要 + 统一动作 + 已验证
Excel 下载授权),但**不**构建 stage_context / summary / steps / progress_nodes 等昂贵
重活。list_freight_notice_groups_for_task 会遍历同 PO 的多张 Notice,逐张调用完整
``build_task_ui_state`` 会造成 N 倍放大;此处只返回动作码,用于面板首屏即可。
Returns:
已启用动作码列表(primary + secondary + 已验证下载)。
"""
process_gate = _process_gate_user_summary_for_task(task)
actions = _unified_actions(process_gate=process_gate)
codes = [
str(item.get('code') or '').strip()
for item in [actions.get('primary'), *(actions.get('secondary') or [])]
if isinstance(item, dict) and item.get('enabled') is True and str(item.get('code') or '').strip()
]
# 与 build_task_ui_state 同款下载授权:Artifact 已验证后补入只读下载。
from app.services.shipping_notice.query_service import resolve_task_export_download
if resolve_task_export_download(task) is not None:
download_code = 'download_excel'
if download_code not in codes:
codes.append(download_code)
return codes
@@ -112,11 +112,44 @@ def has_verified_upload_success(task: ShippingNotice) -> bool:
).first() is not None
def _normalize_callback_result(result: str | None, success: bool) -> str:
"""将回调结果归一化为三态 success / failed / unknown。
result 显式给定则按其校验;否则由 success 布尔推导(success→success,其余→failed)。
"""
if result is not None:
normalized = str(result or '').strip().lower()
if normalized not in {'success', 'failed', 'unknown'}:
raise ValidationError(
'result must be success, failed or unknown',
code='SHIPPING.UPLOAD_RESULT_INVALID',
)
return normalized
return 'success' if success else 'failed'
def complete_attempt(
attempt: ShippingUploadAttempt, *, success: bool, callback_id: str,
freight_ref_no: str | None = None, error_message: str | None = None,
result: str | None = None,
) -> ShippingUploadAttempt:
"""幂等落库 RPA 回调;失败或过期 Attempt 绝不能覆盖已经成功的 Artifact。"""
"""幂等落库 RPA 回调;失败或过期 Attempt 绝不能覆盖已经成功的 Artifact。
Args:
attempt: 本次上传尝试。
success: 兼容布尔标记;schema 迁移期仍保留,由 result 优先。
callback_id: 回调幂等键(唯一)。
freight_ref_no: 成功时货代回执号。
error_message: 失败/未知时的脱敏错误信息。
result: 三态结果 success / failed / unknown;三态与布尔推导见 _normalize_callback_result。
Returns:
ShippingUploadAttempt: 已更新状态的 Attob。
Raises:
ConflictError: 回调身份冲突、过期回调或不可接受的 Attempt 状态。
ValidationError: 缺 callback_id / artifact / 非法 result。
"""
callback = str(callback_id or '').strip()
if not callback:
raise ValidationError('callback_id is required', code='SHIPPING.UPLOAD_CALLBACK_REQUIRED')
@@ -134,10 +167,11 @@ def complete_attempt(
raise ConflictError('Late callback cannot overwrite uploaded artifact', code='SHIPPING.UPLOAD_CALLBACK_STALE')
if attempt.status not in {'pending', 'running', 'timed_out', 'unknown'}:
raise ConflictError('Callback is not valid for this attempt', code='SHIPPING.UPLOAD_CALLBACK_STALE')
result_status = _normalize_callback_result(result, success)
attempt.callback_id = callback
attempt.finished_at = datetime.utcnow()
task = db.session.get(ShippingNotice, artifact.task_id)
if success:
if result_status == 'success':
attempt.status = 'succeeded'
attempt.freight_ref_no = str(freight_ref_no or '').strip() or None
artifact.status = 'uploaded'
@@ -153,9 +187,20 @@ def complete_attempt(
else:
# A missing callback may conceal a completed freight submission. A late
# transport error is not enough to safely release or retry that Artifact.
if attempt.status in {'timed_out', 'unknown'} and not str(error_message or '').strip().lower().startswith('freight_rejected:'):
# unknown 结果既不允许自动重试,也不强制改 upload_status(迟到的成功回调可解除)。
already_unknown_before = attempt.status in {'timed_out', 'unknown'}
if result_status == 'unknown' or (
already_unknown_before
and not str(error_message or '').strip().lower().startswith('freight_rejected:')
):
attempt.status = 'unknown'
attempt.error_code = 'UPLOAD_RESULT_UNKNOWN'
attempt.error_message = str(error_message or 'Upload result remains unknown')[:500]
# 逐单状态展示:未知结果仍须在 Notice 上保留失败原因(不强制改 upload_status,
# 因为迟到的成功回调仍可解除该未知态)。
if task is not None:
task.upload_error_code = attempt.error_code
task.upload_error_message = attempt.error_message
db.session.flush()
return attempt
attempt.status = 'failed'
@@ -165,6 +210,9 @@ def complete_attempt(
artifact.status = 'ready'
if task is not None:
task.upload_status = 'failed'
# 逐单状态展示:把失败原因落到 Notice,供「按发货通知单展示状态」读取。
task.upload_error_code = attempt.error_code
task.upload_error_message = message
db.session.flush()
return attempt
@@ -0,0 +1,212 @@
"""
services/shipping_notice/upload_config_validation.py
用途:对连接级“发货 Excel 自动上传”配置做后端严格白名单校验,产出受限 JSON。
依赖:app.core.errors.ValidationError;仅标准库,不引入第三方。
逻辑:配置由管理端表单编辑,但后端只接受本模块允许的字段、枚举与安全边界;
禁止自由 JavaScript、脚本、URL 模板、Cookie 或任意浏览器动作落库。
upload_config 是“这次上传到底用了什么”的快照来源,不做版本管理(见技术文档)。
"""
from __future__ import annotations
import hashlib
import json
from typing import Any
from app.core.errors import ValidationError
# 连接类型与各平台已审核域名(主机名白名单,后缀匹配以覆盖同域子站)。
ALLOWED_CONNECTOR_TYPES = frozenset({'dbs', 'crane'})
ALLOWED_PLATFORM_DOMAINS: dict[str, tuple[str, ...]] = {
'dbs': ('dbschenker.com',),
'crane': ('craneww.com',),
}
ALLOWED_SUBMIT_MODES = frozenset({'auto_after_file', 'click_submit'})
ALLOWED_RESULT_MODES = frozenset({'page_notice', 'history_record'})
# 字段白名单:禁止把额外键(模板、Cookie、脚本)混入配置。
ALLOWED_KEYS = frozenset({
'enabled', 'entry_url', 'file_input_selector',
'submit_mode', 'submit_selector',
'result_mode', 'result_selector', 'success_texts', 'timeout_seconds',
})
MAX_ENTRY_URL_LENGTH = 500
MAX_SELECTOR_LENGTH = 200
MAX_SUCCESS_TEXTS = 10
MAX_SUCCESS_TEXT_LENGTH = 200
MIN_TIMEOUT_SECONDS = 1
MAX_TIMEOUT_SECONDS = 600
DEFAULT_TIMEOUT_SECONDS = 120
# 复用的字符黑名单:任何脚本/表达式/注入语义都拒绝。
_BLOCKED_SELECTOR_MARKERS = (
'javascript:', '<script', 'expression(', 'onclick=', 'onload=', 'onerror=',
'onmouseover=', 'onmouseout=', 'onfocus=', 'onblur=', 'onchange=', 'oninput=',
)
_BLOCKED_SELECTOR_CHARS = ('(', ')', '{', '}', ';', '<', '>', '`', '\\', '\n', '\r')
def _reject(message: str, *, field: str) -> None:
raise ValidationError(message, code='SHIPPING.UPLOAD_CONFIG_INVALID', details={'field': field})
def _normalize_text(value: Any) -> str:
return str(value or '').strip()
def _validate_entry_url(connector_type: str, value: Any, *, required: bool = True) -> str | None:
"""校验上传入口为 HTTPS 且主机名属于已审核平台域名。"""
url = _normalize_text(value)
if not url:
if required:
_reject('entry_url is required', field='entry_url')
return None
if len(url) > MAX_ENTRY_URL_LENGTH:
_reject('entry_url is too long', field='entry_url')
if not url.lower().startswith('https://'):
_reject('entry_url must be HTTPS', field='entry_url')
# 简单主机名解析:仅定位 host:port 部分,禁止 userinfo/query 进入主机判断。
scheme_rest = url[8:]
authority = scheme_rest.split('/', 1)[0].split('?', 1)[0].split('#', 1)[0]
host = authority.split('@')[-1].split(':')[0].strip().lower()
if not host:
_reject('entry_url host is invalid', field='entry_url')
allowed = ALLOWED_PLATFORM_DOMAINS.get(connector_type, ())
if not any(host == domain or host.endswith('.' + domain) for domain in allowed):
_reject(
f'entry_url host not allowed for {connector_type}',
field='entry_url',
)
return url
def _validate_css_selector(value: Any, *, field: str, required: bool) -> str | None:
"""校验普通 CSS selector:限制长度、拒绝脚本及表达式语义。"""
selector = _normalize_text(value)
if not selector:
if required:
_reject(f'{field} is required', field=field)
return None
if len(selector) > MAX_SELECTOR_LENGTH:
_reject(f'{field} is too long', field=field)
lowered = selector.lower()
for marker in _BLOCKED_SELECTOR_MARKERS:
if marker in lowered:
_reject(f'{field} contains script semantics', field=field)
for char in _BLOCKED_SELECTOR_CHARS:
if char in selector:
_reject(f'{field} contains an invalid character', field=field)
return selector
def _validate_success_texts(value: Any) -> list[str]:
if value in (None, ''):
return []
if not isinstance(value, list):
_reject('success_texts must be a list', field='success_texts')
if len(value) > MAX_SUCCESS_TEXTS:
_reject('success_texts is too long', field='success_texts')
result: list[str] = []
for item in value:
text = _normalize_text(item)
if not text or len(text) > MAX_SUCCESS_TEXT_LENGTH:
_reject('success_texts contains an invalid item', field='success_texts')
if text not in result:
result.append(text)
return result
def validate_upload_config(connector_type: str, raw: Any) -> dict[str, Any] | None:
"""白名单校验连接级上传配置,返回规范化 JSON;raw 为空/None 表示未配置(返回 None)。
Args:
connector_type: 连接类型,仅允许 dbs / crane。
raw: 管理端提交的原始上传配置对象。
Returns:
dict | None: 规范化受限 JSON;未配置时返回 None。
Raises:
ValidationError: 含未知字段/非法枚举/不安全 selector/非 HTTPS 或非法域名/
enabled=true 但缺少上传或结果判定所需字段。
"""
normalized_connector = _normalize_text(connector_type).lower()
if normalized_connector not in ALLOWED_CONNECTOR_TYPES:
_reject('connector_type must be dbs or crane', field='connector_type')
if raw in (None, ''):
return None
if not isinstance(raw, dict):
_reject('upload_config must be an object', field='upload_config_json')
unknown = set(raw) - ALLOWED_KEYS
if unknown:
_reject(f'upload_config contains unsupported fields: {sorted(unknown)}', field='upload_config_json')
enabled = raw.get('enabled') is True
config: dict[str, Any] = {
'enabled': enabled,
'entry_url': _validate_entry_url(normalized_connector, raw.get('entry_url'), required=enabled),
'file_input_selector': _validate_css_selector(
raw.get('file_input_selector'), field='file_input_selector', required=enabled,
),
'submit_mode': _normalize_text(raw.get('submit_mode')),
'submit_selector': _validate_css_selector(
raw.get('submit_selector'), field='submit_selector', required=False,
),
'result_mode': _normalize_text(raw.get('result_mode')),
'result_selector': _validate_css_selector(
raw.get('result_selector'), field='result_selector', required=False,
),
'success_texts': _validate_success_texts(raw.get('success_texts')),
'timeout_seconds': raw.get('timeout_seconds', DEFAULT_TIMEOUT_SECONDS),
}
if config['submit_mode'] not in ALLOWED_SUBMIT_MODES:
_reject('submit_mode must be auto_after_file or click_submit', field='submit_mode')
if config['result_mode'] not in ALLOWED_RESULT_MODES:
_reject('result_mode must be page_notice or history_record', field='result_mode')
if config['submit_mode'] == 'auto_after_file':
# auto_after_file 由页面在选文件后自动提交,不应同时配置提交按钮选择器。
config['submit_selector'] = None
try:
timeout = int(config['timeout_seconds'])
except (TypeError, ValueError):
_reject('timeout_seconds must be an integer', field='timeout_seconds')
if timeout < MIN_TIMEOUT_SECONDS or timeout > MAX_TIMEOUT_SECONDS:
_reject(
f'timeout_seconds must be within [{MIN_TIMEOUT_SECONDS}, {MAX_TIMEOUT_SECONDS}]',
field='timeout_seconds',
)
config['timeout_seconds'] = timeout
if enabled:
# 完成一次上传所需的公共字段由上述必填校验覆盖;此处补齐连接差异。
if not config['file_input_selector']:
_reject('enabled upload requires file_input_selector', field='file_input_selector')
if config['submit_mode'] == 'click_submit' and not config['submit_selector']:
_reject('enabled click_submit upload requires submit_selector', field='submit_selector')
# 结果判定:dbs(DSV) 使用代码内置的受控成功流(History 绿状态/页面证据),
# 不强制 admin 填写结果字段;crane 必须由 admin 补全提交/结果判定字段后才可启用。
if normalized_connector == 'crane':
if config['result_mode'] == 'page_notice':
if not config['result_selector'] or not config['success_texts']:
_reject(
'enabled crane page_notice upload requires result_selector and success_texts',
field='result_selector',
)
elif config['result_mode'] == 'history_record' and not config['result_selector']:
_reject('enabled crane history_record upload requires result_selector', field='result_selector')
# 未启用时仍保存规范化的受限 JSON,方便 admin 预填后续补全。
return config
def compute_upload_config_hash(config: dict[str, Any] | None) -> str | None:
"""对规范化上传配置计算稳定 sha256;供审计关联每次上传所用的确切快照。"""
if not config:
return None
payload = json.dumps(config, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
return hashlib.sha256(payload.encode('ascii')).hexdigest()