feat(freight-rpa): 增加出站报表配置与回调支持,重构相关服务
- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。 - 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。 - 更新 ORM 模型,增加出站报表相关的持久化模型。 - 统一命名规范,确保在手、入站与出站的概念一致性。
This commit is contained in:
1 parent
39fe3c05f2
commit
911afa0f73
152 files changed
+9861
-2984
No files matched your search
@@ -1,100 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/inbound_report_access.py
|
||||
|
||||
用途:收料归档文件的授权列表与受控下载。
|
||||
依赖:FreightRpaInboundReportFile(仅查询/取回行,供授权与审计)、当前用户、
|
||||
freight_rpa/reports.read_inbound_file_bytes(归档字节唯一读取入口)。
|
||||
逻辑:工作台 /api/workspace/inbound-report-files 调用本模块;下载地址只返回受控 API 路径。
|
||||
阶段 B Task 5 起下载字节改经 freight_rpa/reports 只读函数取得,禁止本模块
|
||||
自持模型 + 对象存储双跳读字节。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ForbiddenError, NotFoundError
|
||||
from app.models import FreightRpaInboundReportFile, User
|
||||
from app.services.freight_rpa.reports import read_inbound_file_bytes
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def _is_admin(user: User) -> bool:
|
||||
"""判断用户是否为收料报表管理角色。"""
|
||||
return bool(user.is_platform_admin())
|
||||
|
||||
|
||||
def can_download_receipt_report_file(report_file: FreightRpaInboundReportFile, user: User) -> bool:
|
||||
"""仅允许管理员或所属排程通知接收人读取收料归档。"""
|
||||
if _is_admin(user):
|
||||
return True
|
||||
run = report_file.unit_run.schedule_run
|
||||
task = run.task if run is not None else None
|
||||
return task is not None and int(user.id) in {
|
||||
int(value) for value in (task.notify_user_ids_json or []) if str(value).isdigit()
|
||||
}
|
||||
|
||||
|
||||
def _serialize_receipt_report_file(report_file: FreightRpaInboundReportFile) -> dict[str, Any]:
|
||||
"""输出可下载收料文件的脱敏列表投影,永不暴露对象存储 bucket 或 key。"""
|
||||
unit = report_file.unit_run
|
||||
run = unit.schedule_run if unit is not None else None
|
||||
return {
|
||||
'id': report_file.id,
|
||||
'original_filename': report_file.original_filename,
|
||||
'content_type': report_file.content_type,
|
||||
'file_size': report_file.file_size,
|
||||
'sha256': report_file.sha256,
|
||||
'source_code': unit.source_code if unit is not None else None,
|
||||
'warehouse_id': unit.warehouse_id if unit is not None else None,
|
||||
'schedule_run_no': run.run_no if run is not None else None,
|
||||
'archive_expires_at': report_file.archive_expires_at.isoformat() if report_file.archive_expires_at else None,
|
||||
'created_at': report_file.created_at.isoformat() if report_file.created_at else None,
|
||||
'download_url': f'/api/workspace/inbound-report-files/{report_file.id}/download',
|
||||
}
|
||||
|
||||
|
||||
def list_receipt_report_files(user: User, *, limit: int = 100) -> list[dict[str, Any]]:
|
||||
"""列出管理员或当前排程接收人可见的未清理收料归档,并留存读取审计。"""
|
||||
bounded_limit = max(1, min(int(limit), 200))
|
||||
rows = FreightRpaInboundReportFile.query.filter(
|
||||
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
|
||||
).order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc()).all()
|
||||
# 先按授权过滤再截断:不能因为前 100 条属于其他排程而遗漏当前接收人的历史文件。
|
||||
visible = [item for item in rows if can_download_receipt_report_file(item, user)][:bounded_limit]
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_inbound_report_files_listed', aggregate_type='shipping_inbound_file_collection',
|
||||
aggregate_id=str(user.id), actor_type='user', actor_id=user.id, owner_user_id=user.id,
|
||||
result='success', after={'visible_count': len(visible), 'limit': bounded_limit},
|
||||
metadata={'surface': 'workspace_receipt_report_files'},
|
||||
)
|
||||
db.session.commit()
|
||||
return [_serialize_receipt_report_file(item) for item in visible]
|
||||
|
||||
|
||||
def resolve_receipt_report_download(file_id: int, user: User) -> tuple[BytesIO, str, str | None]:
|
||||
"""授权读取私有对象并记录允许或拒绝的下载审计。"""
|
||||
report_file = db.session.get(FreightRpaInboundReportFile, file_id)
|
||||
if report_file is None or report_file.archive_deleted_at is not None:
|
||||
raise NotFoundError('Receipt report file not found', code='SHIPPING.RECEIPT_REPORT_FILE_NOT_FOUND')
|
||||
if not can_download_receipt_report_file(report_file, user):
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_inbound_report_download_rejected', aggregate_type='shipping_inbound_file',
|
||||
aggregate_id=str(report_file.id), actor_type='user', actor_id=user.id, owner_user_id=user.id,
|
||||
unit_id=report_file.unit_run_id, result='rejected', reason_code='recipient_not_authorized',
|
||||
after={'status': 'rejected', 'owner_user_id': user.id}, artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
)
|
||||
db.session.commit()
|
||||
raise ForbiddenError('You are not authorized to download this receipt report')
|
||||
# [STEP] 阶段 B Task 5:归档字节统一经 freight_rpa/reports 只读函数读取(对象存储 key 不外泄、不双跳)。
|
||||
data = read_inbound_file_bytes(file_id)
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_inbound_report_downloaded', aggregate_type='shipping_inbound_file',
|
||||
aggregate_id=str(report_file.id), actor_type='user', actor_id=user.id, owner_user_id=user.id,
|
||||
unit_id=report_file.unit_run_id, result='success',
|
||||
after={'status': 'downloaded', 'owner_user_id': user.id}, artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
)
|
||||
db.session.commit()
|
||||
return BytesIO(data), report_file.original_filename, report_file.content_type
|
||||
@@ -1,122 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/inbound_report_storage.py
|
||||
|
||||
收料 RPA callback 的域内业务桥与终态收尾(shipping_notice 留守侧)。
|
||||
|
||||
用途:批次 R Task 10 拆分后,本模块只留守「业务桥」——收料终态落库后推进在途调拨的
|
||||
waiting_rpa_callback 来源任务(B3 接线)、success 终态的调拨证据同步,以及排程
|
||||
终态归集(finalize)调用;原样归档/三年保留/resend/通知投递等 RPA 产物事实能力
|
||||
已下沉 freight_rpa.inbound.report_archive(函数名 receipt 词根→inbound)。
|
||||
依赖:freight_rpa.inbound.report_archive(归档能力,经 ingest_receipt_callback 委托)、
|
||||
in_transit_transfer.inbound_callback_bridge / evidence_sync(惰性导入,仅桥),
|
||||
schedule.freight_rpa_inbound_finalize(惰性导入,仅 finalize)。
|
||||
逻辑:ingest_receipt_callback 仍是本域回调入口(rpa_sinks 以 {'success':True,'data':...}
|
||||
envelope 注册为 inbound-batch-ready sink):委托 report_archive.ingest_inbound_callback
|
||||
归档(各终态分支各自 commit 后投递 ReportFact——批次 B Task 6 起归档入口不再收
|
||||
on_terminal 钩子)。生产链路的终态收尾自 Task 7 起由调拨侧处理函数
|
||||
in_transit_transfer.inbound_report_handler.handle_inbound_report 承担(rpa_sinks 经
|
||||
register_report_handler 注册);本模块的 _finish_inbound_callback_terminal +
|
||||
_advance_transfer_source_job 留守为回归测试桥(tests/test_freight_receipt_rpa_callback.
|
||||
py 经 register_report_handler 注入复刻拆分前终态收尾),其中桥推进失败
|
||||
【不再吞异常】(Task 7 移除 except Exception: logger.warning——失败必须外抛,
|
||||
避免把调拨推进失败再次吞掉;吞异常仅保留在证据同步双保险分支)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.models import FreightRpaInboundUnitRun
|
||||
|
||||
|
||||
def _advance_transfer_source_job(
|
||||
unit: 'FreightRpaInboundUnitRun', *, ok: bool,
|
||||
file_no: str | None = None, file_sha256: str | None = None,
|
||||
error_code: str | None = None, error_message: str | None = None,
|
||||
) -> None:
|
||||
"""收料回调终态推进调拨来源任务并提交;失败外抛(Task 7 起不再吞异常)。
|
||||
|
||||
Args:
|
||||
unit: 已落终态的收料单元行(用其 source_code 定位调拨任务)。
|
||||
ok: 回调是否成功(True 仅在 success 且带 file_no 时推进 file_ready)。
|
||||
file_no / file_sha256: success 时绑定的归档文件号与指纹。
|
||||
error_code / error_message: 失败时的错误码与描述。
|
||||
Raises:
|
||||
Exception: 桥推进/提交失败原样外抛(Task 7 移除 except 吞异常——
|
||||
生产链路的推进失败改由调拨侧处理函数承担并外抛供 Worker 重试;
|
||||
本函数留守为回归测试桥,同样不再吞失败)。
|
||||
"""
|
||||
from app import db
|
||||
from app.services.in_transit_transfer.inbound_callback_bridge import advance_source_job_from_inbound_callback
|
||||
advanced = advance_source_job_from_inbound_callback(
|
||||
source_code=unit.source_code, file_no=file_no, file_sha256=file_sha256,
|
||||
callback_ok=ok, error_code=error_code, error_message=error_message,
|
||||
)
|
||||
if advanced is not None:
|
||||
# 桥内只 flush 不 commit;empty/failed 且 finalize 提前返回时无人提交,
|
||||
# 必须在此 commit,否则请求结束回滚会丢掉已推进的任务(B3 持久性)。
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _finish_inbound_callback_terminal(
|
||||
unit: 'FreightRpaInboundUnitRun', *, ok: bool,
|
||||
file_no: str | None = None, file_sha256: str | None = None,
|
||||
error_code: str | None = None, error_message: str | None = None,
|
||||
) -> None:
|
||||
"""终态归档 commit 之后的业务收尾(留守测试桥),顺序与拆分前逐点一致。
|
||||
|
||||
定位(Task 7 起):生产链路的终态收尾已由调拨侧处理函数
|
||||
in_transit_transfer.inbound_report_handler.handle_inbound_report 承担
|
||||
(rpa_sinks 经 register_report_handler 注册);本函数留守为回归测试桥
|
||||
(tests/test_freight_receipt_rpa_callback.py 经 register_report_handler 注入),
|
||||
复刻拆分前的桥推进(不再吞异常)+ 证据同步 + 排程收口三段语义。
|
||||
|
||||
核心逻辑:[STEP 1] 推进在途调拨来源任务(_advance_transfer_source_job,原 B3 接线);
|
||||
[STEP 2] 仅 success 终态触发调拨证据同步(桥模式失败仅日志,绝不影响收料归档主链路,
|
||||
语义见 in_transit_transfer/evidence_sync.sync_and_commit_for_callback);[STEP 3] 有排程
|
||||
run 时回写进度并归集终态(按需触发单元 schedule_run_id 为 NULL,跳过排程终态归集;
|
||||
文件通知不在此逐文件发送:统一由排程终态归集后一次性推送,与库存 RPA 同构)。
|
||||
"""
|
||||
_advance_transfer_source_job(
|
||||
unit, ok=ok, file_no=file_no, file_sha256=file_sha256,
|
||||
error_code=error_code, error_message=error_message,
|
||||
)
|
||||
if ok:
|
||||
# [调拨证据同步·主链路] success 终态文件落地即解析写调拨待办(本分支专属;
|
||||
# empty/failed 分支不触发同步)。
|
||||
try:
|
||||
from datetime import datetime as _dt
|
||||
|
||||
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
|
||||
|
||||
sync_and_commit_for_callback(
|
||||
source_code=unit.source_code, business_date=str(_dt.utcnow().date()), now=_dt.utcnow(),
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 —— 双保险:桥内部已吞异常
|
||||
current_app.logger.warning('[receipt-callback] transfer evidence sync failed: %s', exc)
|
||||
from app.services.schedule.freight_rpa_inbound_finalize import (
|
||||
finalize_receipt_schedule_run_if_complete,
|
||||
refresh_receipt_schedule_run_progress,
|
||||
)
|
||||
if unit.schedule_run_id:
|
||||
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
|
||||
|
||||
def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""幂等接收单个收料单元回调:委托 report_archive 原样归档(终态后投递事实)。
|
||||
|
||||
Args:
|
||||
payload: Worker 回调载荷;schema_version 必须等于 freight_rpa.inbound.v1。
|
||||
Returns:
|
||||
dict: unit_run_id/status[/file_id/idempotent],与拆分前逐键一致(API envelope 契约)。
|
||||
业务顺序(Task 6 起):归档各终态 commit 后由 report_archive 直接投递
|
||||
ReportFact(dispatch_report_fact);本域桥/finalize 收尾改经
|
||||
register_report_handler 注册的处理函数承担(Task 7 接线),不再走
|
||||
on_terminal 钩子。
|
||||
"""
|
||||
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
|
||||
|
||||
return ingest_inbound_callback(payload)
|
||||
@@ -514,7 +514,7 @@ def confirm_test_profile(source_id: int, run_no: str, profile_id: int, *, actor_
|
||||
|
||||
adopt_published_profile(run.analysis_id, profile_id)
|
||||
# s18 起解析绑定写 onhand_report_config 配置行(无则插入),站点行不再承载该外键;
|
||||
# 与 shipping_onhand_admin_service.bind_source_parsing_profile 的批量绑定写序保持同构。
|
||||
# 与 freight_rpa_source_admin_service.bind_source_parsing_profile 的批量绑定写序保持同构。
|
||||
config = source.onhand_report_config
|
||||
if config is None:
|
||||
config = FreightRpaOnhandReportConfig(source=source)
|
||||
|
||||
@@ -689,7 +689,7 @@ def parse_inventory_snapshot_file(inv_file: FreightRpaOnhandReportFile) -> tuple
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"未找到库存快照文件 {inv_file.onhand_file_no}")
|
||||
from app.models import FreightRpaSource
|
||||
from app.services.shipping_notice.onhand_parsing_profile import require_source_profile
|
||||
from app.services.freight_rpa.parsing_profile import require_source_profile
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
source = FreightRpaSource.query.filter_by(source_code=inv_file.source_code).first()
|
||||
|
||||
@@ -1,355 +0,0 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/onhand_parsing_profile.py
|
||||
|
||||
用途:管理可跨库存源复用的版本化库存解析 Profile,并为运行期提供确定性解析定义。
|
||||
依赖:FreightRpaParsingProfile、FreightRpaOnhandReportConfig(s18 起站点绑定归配置行)、FreightRpaInboundReportConfig、ShippingOrderField、onhand_mapping。
|
||||
逻辑:管理员保存草稿并发布不可变版本;库存源仅绑定 published Profile,解析链直接使用定义中的列映射与订单字段匹配键。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
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 (
|
||||
FreightRpaOnhandField,
|
||||
FreightRpaOnhandReportConfig,
|
||||
FreightRpaParsingProfile,
|
||||
FreightRpaOnhandStructureAnalysis,
|
||||
ShippingOrderField,
|
||||
FreightRpaInboundReportConfig,
|
||||
)
|
||||
|
||||
|
||||
def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, FreightRpaOnhandField]:
|
||||
"""解析字段目录 ID 并确认均为可用于新方案的启用库存业务字段。"""
|
||||
field_ids: list[int] = []
|
||||
for raw_id in field_mapping:
|
||||
try:
|
||||
field_id = int(raw_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') from exc
|
||||
if field_id <= 0:
|
||||
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
field_ids.append(field_id)
|
||||
rows = FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(set(field_ids))).all() if field_ids else []
|
||||
fields = {str(row.id): row for row in rows if row.status == 'active'}
|
||||
if len(fields) != len(set(str(item) for item in field_ids)):
|
||||
raise ValidationError('Parsing profile inventory field is unavailable', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
return fields
|
||||
|
||||
|
||||
def _required_catalog_field_ids(fields: dict[str, FreightRpaOnhandField]) -> set[str]:
|
||||
"""校验解析方案具备匹配与库存数量能力,不限定字段名称。"""
|
||||
match_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'match_identity'}
|
||||
quantity_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'inventory_quantity'}
|
||||
if not match_ids or len(quantity_ids) != 1:
|
||||
raise ValidationError(
|
||||
'Parsing profile requires at least one match field and exactly one inventory quantity field',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
return match_ids | quantity_ids
|
||||
|
||||
|
||||
# 入站(inbound)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。
|
||||
def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]:
|
||||
"""校验 inbound 用途的解析定义只引用定死领域字段,且必需字段齐全。"""
|
||||
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
|
||||
|
||||
movement_codes = {field.code for field in MOVEMENT_FIELDS}
|
||||
mapping = definition.get('field_mapping') or {}
|
||||
mapped_codes = {str(code) for code in mapping.keys() if str(code).strip()}
|
||||
unknown = mapped_codes - movement_codes
|
||||
if unknown:
|
||||
raise ValidationError(
|
||||
f'Movement parsing profile references unknown field: {sorted(unknown)}',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
missing = {code for code in ('doc_no', 'material_code', 'quantity', 'movement_date') if code not in mapped_codes}
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
f'Movement parsing profile requires doc_no/material_code/quantity/movement_date: {sorted(missing)}',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
return mapped_codes
|
||||
|
||||
|
||||
def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any]:
|
||||
"""校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。
|
||||
|
||||
Args:
|
||||
raw: 解析定义对象。
|
||||
purpose: 'onhand'/'outbound'(沿用库存字段目录与 match_keys)或
|
||||
'inbound'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。
|
||||
"""
|
||||
if not isinstance(raw, dict):
|
||||
raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
field_mapping = raw.get('field_mapping')
|
||||
if not isinstance(field_mapping, dict) or not field_mapping:
|
||||
raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
if any(not str(value or '').strip() for value in field_mapping.values()):
|
||||
raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
header_row_index = raw.get('header_row_index')
|
||||
if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1):
|
||||
raise ValidationError('header_row_index is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
|
||||
if purpose == 'inbound':
|
||||
_required_movement_field_ids(raw)
|
||||
return {
|
||||
'sheet_name': str(raw.get('sheet_name') or '').strip() or None,
|
||||
'header_row_index': header_row_index,
|
||||
'field_mapping': {str(key).strip(): str(value).strip() for key, value in field_mapping.items()},
|
||||
'match_keys': [],
|
||||
}
|
||||
|
||||
catalog_fields = _catalog_fields(field_mapping)
|
||||
_required_catalog_field_ids(catalog_fields)
|
||||
match_keys = raw.get('match_keys')
|
||||
if not isinstance(match_keys, list) or not match_keys:
|
||||
raise ValidationError('Parsing profile requires match keys', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
normalized_keys: list[dict[str, str]] = []
|
||||
seen_order_fields: set[str] = set()
|
||||
seen_inventory_fields: set[str] = set()
|
||||
for item in match_keys:
|
||||
field = db.session.get(ShippingOrderField, str(item.get('order_field_id') or '')) if isinstance(item, dict) else None
|
||||
inventory_field = str(item.get('inventory_field_id') or item.get('inventory_field') or '') if isinstance(item, dict) else ''
|
||||
inventory = catalog_fields.get(inventory_field)
|
||||
if (
|
||||
field is None or field.status != 'active' or field.scope != 'line'
|
||||
or inventory is None or inventory.usage_type != 'match_identity'
|
||||
):
|
||||
raise ValidationError('Parsing profile match key is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
if field.id in seen_order_fields or inventory_field in seen_inventory_fields:
|
||||
raise ValidationError('Parsing profile match keys must be unique', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
seen_order_fields.add(field.id)
|
||||
seen_inventory_fields.add(inventory_field)
|
||||
normalized_keys.append({'order_field_id': field.id, 'inventory_field_id': inventory_field})
|
||||
return {
|
||||
'sheet_name': str(raw.get('sheet_name') or '').strip() or None,
|
||||
'header_row_index': header_row_index,
|
||||
'field_mapping': {str(int(key)): str(value).strip() for key, value in field_mapping.items()},
|
||||
'match_keys': normalized_keys,
|
||||
}
|
||||
|
||||
|
||||
def _require_sample_evidence(
|
||||
sample_analysis_id: Any,
|
||||
definition: dict[str, Any],
|
||||
*,
|
||||
file_format: str,
|
||||
) -> FreightRpaOnhandStructureAnalysis:
|
||||
"""校验草稿仅能使用已持久化样本证据中的工作表、表头和来源栏位。"""
|
||||
try:
|
||||
analysis_id = int(sample_analysis_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Parsing profile requires sample analysis evidence',
|
||||
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED',
|
||||
) from exc
|
||||
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id)
|
||||
if analysis is None or analysis.analysis_status != 'ready' or analysis.file_format != file_format:
|
||||
raise ValidationError(
|
||||
'Parsing profile sample analysis evidence is unavailable',
|
||||
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED',
|
||||
)
|
||||
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
|
||||
candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else []
|
||||
selected = next((candidate for candidate in candidates if isinstance(candidate, dict)
|
||||
and candidate.get('sheet_name') == definition.get('sheet_name')
|
||||
and candidate.get('header_row_index') == definition.get('header_row_index')), None)
|
||||
if not isinstance(selected, dict):
|
||||
raise ValidationError(
|
||||
'Parsing profile worksheet or header row is not present in sample evidence',
|
||||
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
|
||||
)
|
||||
headers = {str(header).strip() for header in selected.get('headers', []) if str(header).strip()}
|
||||
if any(str(header or '').strip() not in headers for header in (definition.get('field_mapping') or {}).values()):
|
||||
raise ValidationError(
|
||||
'Parsing profile mapping is not present in sample evidence',
|
||||
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
|
||||
)
|
||||
duplicates = {
|
||||
str(column.get('header') or '').strip()
|
||||
for column in selected.get('columns', []) if isinstance(column, dict) and column.get('duplicate')
|
||||
}
|
||||
if any(str(header).strip() in duplicates for header in (definition.get('field_mapping') or {}).values()):
|
||||
raise ValidationError(
|
||||
'Parsing profile mapping uses duplicate sample headers',
|
||||
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
|
||||
)
|
||||
return analysis
|
||||
|
||||
|
||||
def payload(profile: FreightRpaParsingProfile) -> dict[str, Any]:
|
||||
"""序列化解析 Profile 管理 DTO。"""
|
||||
sample_analysis = profile.sample_analysis
|
||||
return {
|
||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'purpose': profile.purpose, 'version': profile.version, 'status': profile.status, 'file_format': profile.file_format,
|
||||
'definition': profile.definition_json or {}, 'checksum': profile.checksum,
|
||||
'published_at': profile.published_at.isoformat() if profile.published_at else None,
|
||||
'source_count': len(profile.sources),
|
||||
'sample_analysis_id': profile.sample_analysis_id,
|
||||
'sample_evidence_history': profile.sample_evidence_history_json or [],
|
||||
'sample_evidence': {
|
||||
'id': sample_analysis.id,
|
||||
'source_file_name': sample_analysis.source_file_name,
|
||||
'file_checksum': sample_analysis.file_checksum,
|
||||
'file_format': sample_analysis.file_format,
|
||||
'structure': sample_analysis.structure_json or {},
|
||||
'sample_rows': sample_analysis.sample_rows_json or [],
|
||||
'validation_summary': sample_analysis.validation_summary_json or {},
|
||||
'created_at': sample_analysis.created_at.isoformat() if sample_analysis.created_at else None,
|
||||
} if sample_analysis is not None else None,
|
||||
}
|
||||
|
||||
|
||||
def list_profiles() -> list[dict[str, Any]]:
|
||||
"""列出全部解析 Profile 版本。"""
|
||||
return [payload(item) for item in FreightRpaParsingProfile.query.order_by(
|
||||
FreightRpaParsingProfile.profile_code, FreightRpaParsingProfile.version.desc(),
|
||||
).all()]
|
||||
|
||||
|
||||
def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
|
||||
"""创建或更新解析 Profile 草稿;必须绑定样本证据,published 版本不可原地修改。"""
|
||||
profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile_id else None
|
||||
if profile_id and profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile is not None and profile.status != 'draft':
|
||||
raise ConflictError('Published parsing profile is immutable', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE')
|
||||
code = str(data.get('profile_code') or '').strip().upper()
|
||||
if not code:
|
||||
raise ValidationError('profile_code is required', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
if profile is not None and code != profile.profile_code:
|
||||
raise ConflictError('Draft profile_code is immutable', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE')
|
||||
if profile is None:
|
||||
next_version = int(db.session.query(func.max(FreightRpaParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
|
||||
profile = FreightRpaParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
|
||||
db.session.add(profile)
|
||||
purpose = str(data.get('purpose') or profile.purpose or 'onhand').strip().lower()
|
||||
if purpose not in {'onhand', 'inbound', 'outbound'}:
|
||||
raise ValidationError('purpose is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
if profile_id and purpose != profile.purpose:
|
||||
raise ValidationError(
|
||||
'Draft parsing profile purpose is immutable',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
profile.purpose = purpose
|
||||
profile.display_name = str(data.get('display_name') or code).strip()
|
||||
requested_file_format = str(data.get('file_format') or 'xlsx').lower()
|
||||
if requested_file_format not in {'xls', 'xlsx', 'csv'}:
|
||||
raise ValidationError('file_format is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
if profile_id and requested_file_format != profile.file_format:
|
||||
raise ValidationError(
|
||||
'Draft parsing profile file format is immutable',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
profile.file_format = requested_file_format
|
||||
definition = _validate_definition(data.get('definition'), purpose=purpose)
|
||||
if profile.file_format == 'csv' and definition.get('sheet_name'):
|
||||
raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
sample_analysis = _require_sample_evidence(
|
||||
data.get('sample_analysis_id', profile.sample_analysis_id), definition, file_format=profile.file_format,
|
||||
)
|
||||
if profile.sample_analysis_id and profile.sample_analysis_id != sample_analysis.id:
|
||||
if not bool(data.get('confirm_sample_replacement')):
|
||||
raise ValidationError(
|
||||
'Replacing inventory sample evidence requires confirmation',
|
||||
code='SHIPPING.ONHAND_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED',
|
||||
)
|
||||
history = list(profile.sample_evidence_history_json or [])
|
||||
history.append({
|
||||
'previous_analysis_id': profile.sample_analysis_id,
|
||||
'replacement_analysis_id': sample_analysis.id,
|
||||
'replaced_at': datetime.utcnow().isoformat(),
|
||||
'replaced_by': actor_id,
|
||||
})
|
||||
profile.sample_evidence_history_json = history
|
||||
profile.definition_json = definition
|
||||
profile.sample_analysis = sample_analysis
|
||||
db.session.commit()
|
||||
return payload(profile)
|
||||
|
||||
|
||||
def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""发布解析 Profile;既有 published 版本继续供已绑定库存源稳定使用。"""
|
||||
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'draft':
|
||||
raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID')
|
||||
_require_sample_evidence(
|
||||
profile.sample_analysis_id, profile.definition_json or {}, file_format=profile.file_format,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
# inbound 用途无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;onhand/outbound 维持原约束。
|
||||
referenced_field_ids = {
|
||||
str(item.get('order_field_id') or '')
|
||||
for item in (profile.definition_json or {}).get('match_keys', [])
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
if profile.purpose != 'inbound':
|
||||
published_field_ids = {
|
||||
str(item.get('field_id') or '')
|
||||
for item in order_schema_service.get_published_contract().get('fields', [])
|
||||
}
|
||||
if not referenced_field_ids or not referenced_field_ids <= published_field_ids:
|
||||
raise ValidationError(
|
||||
'Parsing profile match keys must reference the current published order schema',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
encoded = json.dumps(profile.definition_json, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
profile.checksum = hashlib.sha256(encoded).hexdigest()
|
||||
profile.status = 'published'
|
||||
profile.published_by = actor_id
|
||||
profile.published_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return payload(profile)
|
||||
|
||||
|
||||
def retire(profile_id: int) -> dict[str, Any]:
|
||||
"""退役无库存源/收料报表配置引用的 published Profile,避免使现有绑定静默失效。"""
|
||||
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'published':
|
||||
raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_INVALID')
|
||||
# s18 起库存站点绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载该外键。
|
||||
bound_sources = FreightRpaOnhandReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
|
||||
# 收料报表配置(FreightRpaInboundReportConfig)同样绑定解析 Profile:退役前必须一并核查,
|
||||
# 否则入站文件解析链(inbound purpose)会静默失去规则。
|
||||
bound_receipt_configs = FreightRpaInboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
|
||||
if bound_sources or bound_receipt_configs:
|
||||
raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED')
|
||||
profile.status = 'retired'
|
||||
db.session.commit()
|
||||
return payload(profile)
|
||||
|
||||
|
||||
def delete_draft(profile_id: int) -> None:
|
||||
"""删除从未发布的解析 Profile 草稿。"""
|
||||
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'draft':
|
||||
raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.ONHAND_PARSING_PROFILE_DELETE_BLOCKED')
|
||||
db.session.delete(profile)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def require_source_profile(source: Any) -> FreightRpaParsingProfile:
|
||||
"""读取库存源绑定的 published 解析 Profile;缺失或非发布状态时阻断自动解析。"""
|
||||
# s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。
|
||||
config = getattr(source, 'onhand_report_config', None)
|
||||
profile = config.parsing_profile if config is not None else None
|
||||
if profile is None or profile.status != 'published':
|
||||
raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
|
||||
return profile
|
||||
@@ -10,7 +10,8 @@ services/shipping_notice/onhand_report_handler.py
|
||||
require_report_kind——只消费事实契约,不 import freight_rpa 工作流)、
|
||||
onhand_recovery_service(候选准备 settle/聚合/等待任务反查)、
|
||||
process_gate_bridge(门禁同步)。
|
||||
逻辑:由组合根(app.create_app → shipping_notice.rpa_sinks.register_onhand_sinks)
|
||||
逻辑:由组合根(app.create_app → shipping_notice.rpa_sinks.register_onhand_sinks;
|
||||
入站/出站另见 in_transit_transfer.rpa_sinks)
|
||||
注册为 'onhand' kind 处理函数;onhand_rpa_workflow 的单回调
|
||||
(rpa_report_inventory)与批量 worker(process_rpa_report_inventory_batch)
|
||||
在文件行 commit 后逐文件投递 ok=True 事实(先 commit 再投递——Task 7 修复轮
|
||||
@@ -100,7 +101,7 @@ def handle_onhand_report(fact: ReportFact) -> None:
|
||||
if kind != 'onhand':
|
||||
raise ValidationError(
|
||||
f"handle_onhand_report only accepts onhand facts, got: {kind!r}",
|
||||
code='SHIPPING.RECEIPT_CALLBACK_INVALID',
|
||||
code='SHIPPING.INBOUND_CALLBACK_INVALID',
|
||||
details={'report_kind': fact.report_kind},
|
||||
)
|
||||
|
||||
|
||||
@@ -448,7 +448,7 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in
|
||||
}
|
||||
if any(str(value or '').strip() in duplicates for value in mapping.values()):
|
||||
raise ValidationError('Parsing field mapping cannot use duplicate headers', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID')
|
||||
from app.services.shipping_notice import onhand_parsing_profile
|
||||
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
|
||||
|
||||
saved = onhand_parsing_profile.save_draft({
|
||||
'profile_code': data.get('profile_code'),
|
||||
|
||||
@@ -525,7 +525,7 @@ def create_parsing_profile_draft_from_temporary_session(
|
||||
if existing_draft_id:
|
||||
existing_draft = db.session.get(FreightRpaParsingProfile, existing_draft_id)
|
||||
if existing_draft is not None:
|
||||
from app.services.shipping_notice.onhand_parsing_profile import payload as profile_payload
|
||||
from app.services.freight_rpa.parsing_profile import payload as profile_payload
|
||||
|
||||
return profile_payload(existing_draft)
|
||||
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
|
||||
@@ -1,23 +1,14 @@
|
||||
"""
|
||||
services/shipping_notice/rpa_sinks.py
|
||||
|
||||
用途:onhand(在手库存)与 inbound(入站,原收料)RPA 回调的业务 sink 注册适配层——把
|
||||
/api/freight-rpa/* 蓝图的 dispatch_sink kind 接到真实业务处理器,并把文件/报表
|
||||
事实 kind 接到 reports.dispatch 的处理函数(阶段 B Task 7)。
|
||||
依赖:freight_rpa.common.callback_sinks(register_sink——进度类回调注册表)、
|
||||
freight_rpa.reports.dispatch(register_report_handler——文件/报表事实处理函数注册表)、
|
||||
onhand_rpa_workflow(快照落盘/批量 ingest)、per_source_rpa_service(Attempt 认领)、
|
||||
onhand_configuration_test(配置测试)、inbound_report_storage(inbound 归档入口 +
|
||||
业务桥留守)、in_transit_transfer.inbound_report_handler / onhand_report_handler
|
||||
(Task 7 的两个文件事实处理函数)、schedule.freight_rpa_inbound_finalize
|
||||
(inbound 进度/领取处理器,Task 11 已随排程壳平移改名)。
|
||||
逻辑:由组合根(app.create_app)调用 register_onhand_sinks() / register_inbound_sinks() 完成
|
||||
注册(幂等,重复注册覆盖)。进度类 sink 仅做两件事:① 复刻旧 shipping-notice rpa
|
||||
回调端点的响应 envelope(逐 kind 对齐,禁止统一 envelope);② 对 onhand-repair 注入
|
||||
旧路由等价的 payload['repair']=True。文件事实处理函数经 register_report_handler 注册
|
||||
(Task 7:inbound→handle_inbound_report、onhand→handle_onhand_report)——归档入口
|
||||
终态 commit 后经 dispatch_report_fact 投递 ReportFact 调入;业务事务边界完全由被
|
||||
包装的域内函数保持,本层只做接线,不碰 db。
|
||||
用途:onhand(在手库存)RPA 回调与报表事实的组合根注册——把 /api/freight-rpa/onhand-*
|
||||
接到发货域业务处理器。入站 / 出站注册见 in_transit_transfer.rpa_sinks。
|
||||
依赖:freight_rpa.common.callback_sinks、freight_rpa.reports.dispatch、
|
||||
onhand_rpa_workflow、per_source_rpa_service、onhand_configuration_test、
|
||||
onhand_report_handler。
|
||||
逻辑:由 app.create_app 调用 register_onhand_sinks()(幂等)。进度类 sink 复刻旧
|
||||
shipping-notice rpa 回调 envelope;onhand-repair 注入 payload['repair']=True;
|
||||
文件事实经 register_report_handler('onhand', handle_onhand_report) 注册。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -64,11 +55,9 @@ def register_onhand_sinks() -> None:
|
||||
"""组合根入口:注册全部 onhand 回调 sink 与 onhand 事实处理函数(幂等;create_app 每次启动调用)。
|
||||
|
||||
核心逻辑:进度类 kind 命名 = /api/freight-rpa/* 回调路由名去前缀,被包装函数全部住在
|
||||
shipping_notice(业务落盘留守域),与 Task 4 裁定一致——认领(claim_inventory_batch)
|
||||
与批量编排留 per_source_rpa_service,本层只做 envelope 复刻与分发接线;
|
||||
文件事实处理函数走 reports.dispatch(Task 7):'onhand' kind 经
|
||||
register_report_handler 注册 handle_onhand_report(在手文件归档终态 commit 后由
|
||||
dispatch_report_fact 调入),进度类 sink 仍走 register_sink、envelope 不变。
|
||||
shipping_notice(业务落盘留守域)——认领(claim_inventory_batch)与批量编排留
|
||||
per_source_rpa_service,本层只做 envelope 复刻与分发接线;文件事实处理函数走
|
||||
reports.dispatch:'onhand' kind 注册 handle_onhand_report。
|
||||
"""
|
||||
from app.services.freight_rpa.common.callback_sinks import register_sink
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
@@ -93,35 +82,4 @@ def register_onhand_sinks() -> None:
|
||||
_ok_data_envelope(onhand_configuration_test.report_batch_test_exports),
|
||||
)
|
||||
register_sink('onhand-repair', _onhand_repair_sink)
|
||||
# [STEP Task 7] 文件事实处理函数注册:onhand 归档终态 commit 后经
|
||||
# dispatch_report_fact 投递 ReportFact(report_kind='onhand')到本处理函数。
|
||||
register_report_handler('onhand', handle_onhand_report)
|
||||
|
||||
|
||||
def register_inbound_sinks() -> None:
|
||||
"""组合根入口:注册全部 inbound(收料)回调 sink 与 inbound 事实处理函数(幂等;create_app 每次启动调用)。
|
||||
|
||||
核心逻辑:进度类 kind 命名 = /api/freight-rpa/* 回调路由名去前缀。inbound-batch-ready 的
|
||||
业务处理器 = inbound_report_storage.ingest_receipt_callback(归档能力下沉
|
||||
freight_rpa.inbound.report_archive 后的域内入口;批次 B Task 6 起归档入口不再收
|
||||
on_terminal 钩子——终态 commit 后由 report_archive 直接投递 ReportFact);
|
||||
unit/batch-progress 处理器仍住排程壳
|
||||
(Task 11 已平移改名为 schedule.freight_rpa_inbound_finalize),按「处理函数住在哪个包」
|
||||
由本层接注册表。三个进度类 kind 旧端点 envelope 均为 {'success':True,'data':...},逐字复刻。
|
||||
文件事实处理函数走 reports.dispatch(Task 7):'inbound' kind 经 register_report_handler
|
||||
注册 in_transit_transfer.handle_inbound_report(调拨推进/证据同步/排程收口均由该
|
||||
处理函数承担,freight_rpa 不 import 桥与 finalize),进度类 sink 仍走 register_sink、
|
||||
envelope 不变。
|
||||
"""
|
||||
from app.services.freight_rpa.common.callback_sinks import register_sink
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
|
||||
from app.services.schedule import freight_rpa_inbound_finalize
|
||||
from app.services.shipping_notice import inbound_report_storage
|
||||
|
||||
register_sink('inbound-batch-ready', _success_data_envelope(inbound_report_storage.ingest_receipt_callback))
|
||||
register_sink('inbound-unit-progress', _success_data_envelope(freight_rpa_inbound_finalize.mark_receipt_unit_processing))
|
||||
register_sink('inbound-batch-progress', _success_data_envelope(freight_rpa_inbound_finalize.report_receipt_batch_progress))
|
||||
# [STEP Task 7] 文件事实处理函数注册:inbound 归档各终态 commit 后经
|
||||
# dispatch_report_fact 投递 ReportFact(report_kind='inbound')到调拨侧处理函数。
|
||||
register_report_handler('inbound', handle_inbound_report)
|
||||
Reference in new issue
Block a user