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}
|
||||
@@ -0,0 +1,39 @@
|
||||
"""
|
||||
backend/migrations/versions/rc3c4d5e6f7a_allow_null_receipt_unit_schedule_run.py
|
||||
|
||||
用途:收料 RPA 执行单元 schedule_run_id 改为可空,支持无排程的按需触发。
|
||||
依赖:Alembic revision rc2b3c4d5e6f;shipping_receipt_rpa_unit_runs 已存在。
|
||||
逻辑:调拨重试/预检补抓按需触发不产生 ScheduleRun,原 NOT NULL+FK 下只能写
|
||||
0 占位并被 PostgreSQL 外键拒绝(0 不在 schedule_runs);改为 NULL 表示无排程。
|
||||
降级前必须先确认表内不存在 schedule_run_id 为 NULL 的行。
|
||||
|
||||
Revision ID: rc3c4d5e6f7a
|
||||
Revises: rc2b3c4d5e6f
|
||||
Create Date: 2026-09-21 09:00:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "rc3c4d5e6f7a"
|
||||
down_revision = "rc2b3c4d5e6f"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""放开 shipping_receipt_rpa_unit_runs.schedule_run_id 的 NOT NULL 约束。"""
|
||||
op.alter_column(
|
||||
'shipping_receipt_rpa_unit_runs', 'schedule_run_id',
|
||||
existing_type=sa.Integer(), nullable=True,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""恢复 NOT NULL;执行前必须清理 schedule_run_id 为 NULL 的按需触发单元行。"""
|
||||
op.alter_column(
|
||||
'shipping_receipt_rpa_unit_runs', 'schedule_run_id',
|
||||
existing_type=sa.Integer(), nullable=False,
|
||||
)
|
||||
@@ -95,15 +95,42 @@ def test_trigger_receipt_rpa_creates_unit_run_before_writing_trigger(app, receip
|
||||
assert outcome["ok"] is True
|
||||
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one()
|
||||
assert unit.status == "awaiting_rpa"
|
||||
assert unit.schedule_run_id == 0 # 调拨触发无排程 run,沿用 0 占位约定
|
||||
# [断言意图] 按需触发无排程 run,schedule_run_id 必须为 NULL——
|
||||
# PostgreSQL 上 FK 禁止 0 占位(SQLite 测试库不强制 FK,需显式守住列可空契约)。
|
||||
assert unit.schedule_run_id is None
|
||||
assert ShippingReceiptRpaUnitRun.__table__.columns['schedule_run_id'].nullable is True
|
||||
assert captured["units"][0]["unit_run_id"] == unit.id
|
||||
assert unit.trigger_snapshot_json["callback_id"] == unit.callback_id
|
||||
|
||||
|
||||
def _bind_published_movement_profile(config: ShippingReceiptReportConfig) -> None:
|
||||
"""给收料配置绑定一条已发布 movement 规则(仅满足守卫校验,不参与解析)。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryParsingProfile
|
||||
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
purpose='movement', profile_code='MOVE_TRIGGER_STD', display_name='收料异动规则',
|
||||
version=1, status='published', file_format='xlsx',
|
||||
definition_json={'sheet_name': None, 'header_row_index': 1,
|
||||
'field_mapping': {'doc_no': '单据编号', 'material_code': '料号',
|
||||
'quantity': '数量', 'movement_date': '异动日期'},
|
||||
'match_keys': []},
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.flush()
|
||||
config.parsing_profile_id = profile.id
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_path, monkeypatch):
|
||||
"""deps 默认触发器必须真写 trigger 文件,不得只查配置就返回 ok=True(B1 断线根因)。"""
|
||||
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
|
||||
|
||||
with app.app_context():
|
||||
config = ShippingReceiptReportConfig.query.filter_by(
|
||||
inventory_source_id=receipt_source.id).one()
|
||||
_bind_published_movement_profile(config)
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
|
||||
outcome = _DefaultRpaTrigger().trigger(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17", reason="precheck_missing_ready_file",
|
||||
@@ -113,6 +140,20 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p
|
||||
assert list(tmp_path.glob("receipt_export_batch_*.json")), "trigger file not written"
|
||||
|
||||
|
||||
def test_default_trigger_fails_closed_when_movement_profile_missing(app, receipt_source, tmp_path, monkeypatch):
|
||||
"""收料配置存在但未绑已发布 movement 规则 → ok=False 且不写 trigger(防徒劳抓取)。"""
|
||||
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
|
||||
outcome = _DefaultRpaTrigger().trigger(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17", reason="precheck_missing_ready_file",
|
||||
)
|
||||
# [断言意图] 未绑规则时抓回文件也无法解析复用,必须 fail-closed 且不落 trigger 文件。
|
||||
assert outcome["ok"] is False
|
||||
assert outcome["error_code"] == "RPA_RECEIPT_MOVEMENT_PROFILE_MISSING"
|
||||
assert list(tmp_path.glob("receipt_export_batch_*.json")) == []
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source):
|
||||
"""trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。"""
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
标准异动字段目录接口测试。
|
||||
|
||||
用途:验证 GET /api/admin/shipping-notice/movement-fields 下发只读领域契约。
|
||||
依赖:Flask 管理 API、movement_contract 契约常量。
|
||||
逻辑:字段目录是 immutable 常量的投影——码/类型/必填/身份标记与契约逐项一致,
|
||||
不提供任何增删改入口,字段 label 由前端 i18n 渲染。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.conftest import parse_api_data
|
||||
|
||||
|
||||
def _headers() -> dict[str, str]:
|
||||
"""构造管理 API 身份 Header(与收料配置接口测试同款)。"""
|
||||
return {'X-Username': 'movement-admin', 'X-Role': 'admin', 'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
def test_movement_fields_returns_fixed_catalog(app, client):
|
||||
"""标准异动字段目录:10 个定死字段、顺序稳定、必填/身份标记与契约一致。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
from app.models import User
|
||||
from app import db
|
||||
db.session.add(User(username='movement-admin', email='movement-admin@example.com', role='admin', status='active'))
|
||||
db.session.commit()
|
||||
|
||||
response = client.get('/api/admin/shipping-notice/movement-fields', headers=_headers())
|
||||
assert response.status_code == 200
|
||||
data = parse_api_data(response.get_json())
|
||||
# [断言意图] 字段码与顺序是前后端共同契约——后端 movement_contract 变更必须显式同步本断言。
|
||||
assert [field['code'] for field in data] == [
|
||||
'doc_no', 'line_no', 'in_out_flag', 'material_code', 'material_name',
|
||||
'warehouse_code', 'storage_code', 'lot_no', 'quantity', 'movement_date',
|
||||
]
|
||||
required = {field['code'] for field in data if field['required']}
|
||||
assert required == {'doc_no', 'material_code', 'quantity', 'movement_date'}
|
||||
identity = {field['code'] for field in data if field['is_identity']}
|
||||
assert identity == {'doc_no', 'material_code', 'movement_date'}
|
||||
assert {field['value_type'] for field in data} <= {'text', 'decimal', 'date'}
|
||||
|
||||
|
||||
def test_movement_fields_rejects_non_admin(app, client):
|
||||
"""字段目录是管理端配置资产,非 admin 角色 403。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import User
|
||||
db.session.add(User(username='movement-user', email='movement-user@example.com', role='user', status='active'))
|
||||
db.session.commit()
|
||||
|
||||
response = client.get('/api/admin/shipping-notice/movement-fields', headers={
|
||||
'X-Username': 'movement-user', 'X-Role': 'user', 'Content-Type': 'application/json',
|
||||
})
|
||||
assert response.status_code == 403
|
||||
@@ -166,6 +166,102 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
|
||||
def _create_movement_profile(profile_code: str, *, status: str, purpose: str):
|
||||
"""创建异动/库存解析 Profile 种子;定义仅用于绑定校验,不参与解析。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryParsingProfile
|
||||
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
purpose=purpose, profile_code=profile_code, display_name=f'{profile_code} 规则',
|
||||
version=1, status=status, file_format='xlsx',
|
||||
definition_json={'sheet_name': 'Movement', 'header_row_index': 1,
|
||||
'field_mapping': {'doc_no': '单据编号', 'material_code': '料号',
|
||||
'quantity': '数量', 'movement_date': '异动日期'},
|
||||
'match_keys': []},
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.commit()
|
||||
return profile
|
||||
|
||||
|
||||
def test_receipt_config_binds_published_movement_profile(app, client):
|
||||
"""绑定已发布 movement 规则 → 保存成功,payload 携带 parsing_profile_id 与摘要,审计留痕。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source_id = source.id
|
||||
profile = _create_movement_profile('CRANE_MOVE_STD', status='published', purpose='movement')
|
||||
profile_id = profile.id
|
||||
|
||||
payload = {**_dbs_payload(), 'parsing_profile_id': profile_id}
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
json=payload, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
config = parse_api_data(response.get_json())
|
||||
# 关键断言:绑定 id 与规则摘要(码/版本/状态)必须回显,供抽屉展示当前绑定。
|
||||
assert config['parsing_profile_id'] == profile_id
|
||||
assert config['parsing_profile']['profile_code'] == 'CRANE_MOVE_STD'
|
||||
assert config['parsing_profile']['status'] == 'published'
|
||||
|
||||
from app.models import ShippingAuditEvent
|
||||
audit = ShippingAuditEvent.query.filter_by(
|
||||
event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id),
|
||||
).order_by(ShippingAuditEvent.id.desc()).first()
|
||||
assert audit.metadata_json['parsing_profile_id'] == profile_id
|
||||
|
||||
|
||||
def test_receipt_config_rejects_draft_or_non_movement_profile(app, client):
|
||||
"""draft/库存用途/不存在 的规则一律拒绝,防止误绑导致预检无法解析收料文件。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source_id = source.id
|
||||
draft = _create_movement_profile('MOVE_DRAFT', status='draft', purpose='movement')
|
||||
inventory_profile = _create_movement_profile('INV_PUBLISHED', status='published', purpose='inventory')
|
||||
cases = [draft.id, inventory_profile.id, 999999]
|
||||
|
||||
for profile_id in cases:
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
json={**_dbs_payload(), 'parsing_profile_id': profile_id},
|
||||
headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400, f'profile_id={profile_id}'
|
||||
# 关键断言:非"已发布 movement"绑定必须走统一错误码,fail-closed。
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_receipt_config_empty_profile_id_unbinds(app, client):
|
||||
"""parsing_profile_id 传 None → 解绑(置空),不做校验也不报错。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source_id = source.id
|
||||
profile = _create_movement_profile('MOVE_UNBIND', status='published', purpose='movement')
|
||||
profile_id = profile.id
|
||||
|
||||
bound = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
json={**_dbs_payload(), 'parsing_profile_id': profile_id},
|
||||
headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert bound.status_code == 200
|
||||
|
||||
unbound = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
json={**_dbs_payload(), 'parsing_profile_id': None},
|
||||
headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert unbound.status_code == 200
|
||||
# 关键断言:None 表示显式解绑,payload 的绑定字段回到空值。
|
||||
assert parse_api_data(unbound.get_json())['parsing_profile_id'] is None
|
||||
|
||||
|
||||
def test_crane_receipt_config_rejects_query_parameters(app, client):
|
||||
"""Crane 固定使用页面默认值直接 Run Report,管理员不能维护查询条件。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
|
||||
@@ -281,3 +281,42 @@ def test_sample_analysis_rejects_invalid_file(app, tmp_path):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
inventory_structure_analysis.create_sample_upload(upload, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID'
|
||||
|
||||
|
||||
def test_profile_draft_purpose_passthrough_creates_movement_profile(app, tmp_path):
|
||||
"""purpose='movement' 必须透传到解析规则:异动草稿不依赖库存字段目录与匹配键。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
# 关键断言:movement 映射直接用定死领域字段码作键,不需要订单匹配键。
|
||||
profile = inventory_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
'profile_code': 'MOVE_STD', 'display_name': '收料异动标准', 'purpose': 'movement',
|
||||
'sheet_name': 'Inventory', 'header_row_index': 3,
|
||||
'field_mapping': {'doc_no': 'Supplier Sku', 'material_code': 'Reservation ID',
|
||||
'quantity': 'Qty Available', 'movement_date': 'Warehouse ID'},
|
||||
'match_keys': None,
|
||||
}, actor_id=None)
|
||||
assert profile['purpose'] == 'movement'
|
||||
assert profile['definition']['match_keys'] == []
|
||||
assert set(profile['definition']['field_mapping']) == {'doc_no', 'material_code', 'quantity', 'movement_date'}
|
||||
|
||||
|
||||
def test_publish_movement_profile_skips_order_match_key_contract(app, tmp_path):
|
||||
"""发布 movement 规则不需要订单匹配键:其端点契约是定死异动字段,不是订单 Schema。"""
|
||||
from app.services.shipping_notice import inventory_parsing_profile
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
profile = inventory_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
'profile_code': 'MOVE_PUB', 'display_name': '收料异动发布', 'purpose': 'movement',
|
||||
'sheet_name': 'Inventory', 'header_row_index': 3,
|
||||
'field_mapping': {'doc_no': 'Supplier Sku', 'material_code': 'Reservation ID',
|
||||
'quantity': 'Qty Available', 'movement_date': 'Warehouse ID'},
|
||||
'match_keys': None,
|
||||
}, actor_id=None)
|
||||
# 关键断言:movement 草稿必须能直接发布(有样本证据即可),match_keys 为空是合法契约。
|
||||
published = inventory_parsing_profile.publish(profile['id'], actor_id=None)
|
||||
assert published['status'] == 'published'
|
||||
assert published['checksum']
|
||||
assert published['definition']['match_keys'] == []
|
||||
Reference in new issue
Block a user