feat(shipping-notice): 收料异动解析配置闭环与按需触发FK违例修复
- 收料单元 schedule_run_id 改可空,修复按需触发 FK 违例 - 收料配置绑定已发布异动解析规则(校验/回显/审计快照) - 预检未绑异动规则 fail-closed,不再徒劳触发 RPA - 标准异动字段目录只读接口;解析规则用途切换与批号映射表单(四语言) - movement 解析规则可发布(跳过订单匹配键校验);站点启停门禁仅限库存站点页签 - 只读映射卡三列布局修复
This commit is contained in:
1 parent
ab57ab3b1f
commit
20835dcfc0
28 files changed
+987
-73
No files matched your search
@@ -428,6 +428,21 @@ def get_shipping_inventory_configuration_catalog():
|
||||
})
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/movement-fields', methods=['GET'])
|
||||
@require_admin
|
||||
def list_movement_fields():
|
||||
"""标准异动字段目录(只读领域契约,供收料异动解析规则映射表单;禁止增删)。"""
|
||||
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
|
||||
|
||||
return _ok([
|
||||
{
|
||||
'code': field.code, 'value_type': str(field.value_type),
|
||||
'required': bool(field.required), 'is_identity': bool(field.is_identity),
|
||||
}
|
||||
for field in MOVEMENT_FIELDS
|
||||
])
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_parsing_profiles():
|
||||
|
||||
@@ -160,9 +160,13 @@ class ShippingInventorySourceParsingBindingAudit(Base):
|
||||
class ShippingInventoryParsingProfile(Base):
|
||||
"""可跨源复用的通用文件解析规则(库存/异动按 purpose 区分)。
|
||||
|
||||
注意:表名中的 inventory 是历史命名——本表实为"通用文件解析规则表",
|
||||
用途以 purpose 字段为准,勿按表名推断只服务库存。
|
||||
purpose='inventory':端点用 ShippingInventoryField 库存字段目录(既有语义);
|
||||
purpose='movement':端点用定死领域字段(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date),
|
||||
供收料/异动文件映射,不依赖库存字段目录。校验逻辑按 purpose 分支。
|
||||
绑定入口:库存站点 ShippingInventorySource.parsing_profile_id /
|
||||
收料配置 ShippingReceiptReportConfig.parsing_profile_id(后者必须 purpose='movement')。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_parsing_profiles'
|
||||
|
||||
@@ -52,7 +52,10 @@ class ShippingReceiptReportConfig(Base):
|
||||
|
||||
|
||||
class ShippingReceiptRpaUnitRun(Base):
|
||||
"""一次收料排程内的站点或站点-Warehouse 不可重复执行单元。"""
|
||||
"""一次收料执行的站点或站点-Warehouse 不可重复执行单元。
|
||||
|
||||
schedule_run_id 指向排程 run;调拨按需触发(重试/预检补抓)无排程,保持 NULL。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_receipt_rpa_unit_runs'
|
||||
__table_args__ = (
|
||||
@@ -66,7 +69,7 @@ class ShippingReceiptRpaUnitRun(Base):
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schedule_run_id: Mapped[int] = mapped_column(ForeignKey('schedule_runs.id'), nullable=False, index=True)
|
||||
schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True, index=True)
|
||||
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
|
||||
retry_of_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=True, index=True,
|
||||
@@ -85,7 +88,7 @@ class ShippingReceiptRpaUnitRun(Base):
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
schedule_run: Mapped['ScheduleRun'] = relationship(foreign_keys=[schedule_run_id])
|
||||
schedule_run: Mapped[Optional['ScheduleRun']] = relationship(foreign_keys=[schedule_run_id])
|
||||
inventory_source: Mapped['ShippingInventorySource'] = relationship()
|
||||
retry_of: Mapped[Optional['ShippingReceiptRpaUnitRun']] = relationship(remote_side=[id])
|
||||
files: Mapped[list['ShippingReceiptReportFile']] = relationship(
|
||||
|
||||
@@ -255,15 +255,43 @@ def _source_payload(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
|
||||
def _receipt_report_config_payload(config: ShippingReceiptReportConfig) -> dict[str, Any]:
|
||||
"""序列化独立收料配置,禁止把库存路径或凭据透传至管理端。"""
|
||||
profile = config.parsing_profile
|
||||
return {
|
||||
'id': config.id, 'inventory_source_id': config.inventory_source_id,
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': config.query_parameters_json or [],
|
||||
# 异动解析绑定:供抽屉回显当前规则;摘要只取展示字段,不透传定义。
|
||||
'parsing_profile_id': config.parsing_profile_id,
|
||||
'parsing_profile': ({
|
||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'version': profile.version, 'status': profile.status,
|
||||
} if profile else None),
|
||||
'config_version': config.config_version,
|
||||
'created_at': _iso(config.created_at), 'updated_at': _iso(config.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _validate_movement_profile_binding(profile_id: Any) -> int | None:
|
||||
"""校验收料配置绑定的异动解析规则:必须已发布且 purpose='movement';空值表示解绑。
|
||||
|
||||
Args:
|
||||
profile_id: 请求中的 parsing_profile_id;None/空串表示解绑。
|
||||
Returns:
|
||||
规整后的规则 id 或 None。
|
||||
Raises:
|
||||
ValidationError: 规则不存在/未发布/用途不是 movement(fail-closed,防误绑库存规则)。
|
||||
"""
|
||||
if profile_id is None or str(profile_id).strip() == '':
|
||||
return None
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, int(profile_id))
|
||||
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
|
||||
raise ValidationError(
|
||||
'Receipt movement parsing profile must be published with purpose movement',
|
||||
code='SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID',
|
||||
)
|
||||
return profile.id
|
||||
|
||||
|
||||
def _validate_receipt_report_config(
|
||||
source: ShippingInventorySource, data: dict[str, Any],
|
||||
) -> tuple[dict[str, str], list[dict[str, Any]]]:
|
||||
@@ -328,6 +356,7 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
|
||||
config.config_version += 1
|
||||
config.report_path_json = path
|
||||
config.query_parameters_json = parameters
|
||||
config.parsing_profile_id = _validate_movement_profile_binding(data.get('parsing_profile_id'))
|
||||
config.updated_by = actor_id
|
||||
db.session.flush()
|
||||
after = _receipt_report_config_payload(config)
|
||||
@@ -335,7 +364,8 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
|
||||
event_type='shipping_receipt_report_config_saved', aggregate_type='shipping_receipt_report_config',
|
||||
aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update',
|
||||
result='success', before=before, after=after,
|
||||
metadata={'inventory_source_id': source.id, 'connector_type': source.connector_type},
|
||||
metadata={'inventory_source_id': source.id, 'connector_type': source.connector_type,
|
||||
'parsing_profile_id': config.parsing_profile_id},
|
||||
)
|
||||
db.session.commit()
|
||||
return after
|
||||
|
||||
@@ -81,11 +81,25 @@ class _DefaultRpaTrigger:
|
||||
|
||||
真实链路 = 落单元行 + 原子写 trigger 文件;来源/收料配置缺失或 trigger
|
||||
目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。
|
||||
另在本类前置守卫:收料配置存在但未绑定已发布 movement 解析规则时
|
||||
直接返回 RPA_RECEIPT_MOVEMENT_PROFILE_MISSING,不触发徒劳抓取。
|
||||
"""
|
||||
|
||||
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
|
||||
|
||||
# [守卫] 收料配置存在但未绑定已发布 movement 解析规则时,触发 RPA 必然徒劳:
|
||||
# 抓回的文件无法被 latest_ready_file 复用,预检会反复重抓。fail-closed 返回明确错误码。
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is not None:
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
|
||||
if config is not None:
|
||||
profile = config.parsing_profile
|
||||
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
|
||||
return {'ok': False, 'error_code': 'RPA_RECEIPT_MOVEMENT_PROFILE_MISSING'}
|
||||
|
||||
outcome = trigger_receipt_rpa(source_code=source_code, business_date=business_date, reason=reason)
|
||||
return {
|
||||
"ok": bool(outcome.get("ok")),
|
||||
|
||||
@@ -96,7 +96,7 @@ def trigger_receipt_rpa(
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=0, # 调拨触发无 ScheduleRun,沿用 0 占位约定
|
||||
# 按需触发无 ScheduleRun:schedule_run_id 保持 NULL(列可空;FK 禁止 0 占位)。
|
||||
inventory_source_id=unit_payload['inventory_source_id'],
|
||||
source_code=unit_payload['source_code'],
|
||||
connector_type=unit_payload['connector_type'],
|
||||
|
||||
@@ -32,7 +32,10 @@ def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource,
|
||||
return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted]
|
||||
|
||||
|
||||
def _build_unit(source: ShippingInventorySource, config: ShippingReceiptReportConfig, warehouse_id: str | None) -> ShippingReceiptRpaUnitRun:
|
||||
def _build_unit(
|
||||
source: ShippingInventorySource, config: ShippingReceiptReportConfig,
|
||||
warehouse_id: str | None, schedule_run_id: int,
|
||||
) -> ShippingReceiptRpaUnitRun:
|
||||
"""冻结可审计的收料执行单元;DBS 日期字段不进入查询快照。"""
|
||||
callback_id = f'receipt:{uuid.uuid4().hex}'
|
||||
snapshot = {
|
||||
@@ -41,7 +44,7 @@ def _build_unit(source: ShippingInventorySource, config: ShippingReceiptReportCo
|
||||
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
|
||||
}
|
||||
return ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=0, inventory_source_id=source.id, source_code=source.source_code,
|
||||
schedule_run_id=schedule_run_id, inventory_source_id=source.id, source_code=source.source_code,
|
||||
connector_type=source.connector_type, warehouse_id=warehouse_id, callback_id=callback_id,
|
||||
status='awaiting_rpa', config_snapshot_json=snapshot,
|
||||
)
|
||||
@@ -81,9 +84,7 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
# Warehouse 条件即逐仓拆分维度:运行时从条件派生仓库清单,不读取持久化列表。
|
||||
warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None]
|
||||
for warehouse_id in warehouses:
|
||||
unit = _build_unit(source, config, str(warehouse_id) if warehouse_id else None)
|
||||
unit.schedule_run_id = run.id
|
||||
units.append(unit)
|
||||
units.append(_build_unit(source, config, str(warehouse_id) if warehouse_id else None, run.id))
|
||||
if not units:
|
||||
return 0, 0, 0, 1, [], ['no enabled receipt report sources'], [{'step': 'freight_receipt_rpa', 'status': 'skipped'}]
|
||||
db.session.add_all(units)
|
||||
|
||||
@@ -289,20 +289,22 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
published_field_ids = {
|
||||
str(item.get('field_id') or '')
|
||||
for item in order_schema_service.get_published_contract().get('fields', [])
|
||||
}
|
||||
# movement 用途无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;inventory 维持原约束。
|
||||
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 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.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
if profile.purpose != 'movement':
|
||||
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.INVENTORY_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'
|
||||
|
||||
@@ -453,6 +453,8 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in
|
||||
saved = inventory_parsing_profile.save_draft({
|
||||
'profile_code': data.get('profile_code'),
|
||||
'display_name': data.get('display_name'),
|
||||
# 用途随请求透传(缺省沿用既有草稿/默认 inventory):movement 草稿端点为定死领域字段。
|
||||
'purpose': data.get('purpose'),
|
||||
'file_format': analysis.file_format,
|
||||
'sample_analysis_id': analysis.id,
|
||||
'confirm_sample_replacement': bool(data.get('confirm_sample_replacement')),
|
||||
|
||||
@@ -94,7 +94,9 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
db.session.commit()
|
||||
_advance_transfer_source_job(unit, ok=False, error_code='RPA_RECEIPT_EMPTY', error_message='receipt export empty')
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
|
||||
if unit.schedule_run_id:
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
return {'unit_run_id': unit.id, 'status': 'empty'}
|
||||
if status != 'success':
|
||||
unit.status = 'failed'; unit.error_code = str(payload.get('error_code') or 'RPA.RECEIPT_EXPORT_FAILED')[:64]; unit.error_message = str(payload.get('error_message') or 'receipt export failed')[:2000]; unit.finished_at = datetime.utcnow()
|
||||
@@ -108,7 +110,9 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
db.session.commit()
|
||||
_advance_transfer_source_job(unit, ok=False, error_code=unit.error_code, error_message=unit.error_message)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
|
||||
if unit.schedule_run_id:
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
return {'unit_run_id': unit.id, 'status': 'failed'}
|
||||
data = _read_receipt_callback_file(str(payload.get('file_path') or ''))
|
||||
sha256 = hashlib.sha256(data).hexdigest()
|
||||
@@ -128,8 +132,9 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
append_shipping_audit_event(event_type='shipping_receipt_report_archived', aggregate_type='shipping_receipt_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'receipt_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3})
|
||||
db.session.commit()
|
||||
_advance_transfer_source_job(unit, ok=True, file_no=str(record.id), file_sha256=sha256)
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
||||
deliver_receipt_file(record.id)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
|
||||
# 文件通知不在此处逐文件发送:统一由排程终态归集后一次性推送(与库存 RPA 同构)。
|
||||
if unit.schedule_run_id:
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
return {'unit_run_id': unit.id, 'status': 'success', 'file_id': record.id, 'idempotent': False}
|
||||
Reference in new issue
Block a user