diff --git a/backend/app/api/admin/shipping_inventory.py b/backend/app/api/admin/shipping_inventory.py index 2787bbb2..27b77bfd 100644 --- a/backend/app/api/admin/shipping_inventory.py +++ b/backend/app/api/admin/shipping_inventory.py @@ -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(): diff --git a/backend/app/models/shipping_inventory_config.py b/backend/app/models/shipping_inventory_config.py index 5831deea..bb9ae94b 100644 --- a/backend/app/models/shipping_inventory_config.py +++ b/backend/app/models/shipping_inventory_config.py @@ -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' diff --git a/backend/app/models/shipping_receipt_report.py b/backend/app/models/shipping_receipt_report.py index 1df4c202..ce4c3ae0 100644 --- a/backend/app/models/shipping_receipt_report.py +++ b/backend/app/models/shipping_receipt_report.py @@ -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( diff --git a/backend/app/services/admin/shipping_inventory_service.py b/backend/app/services/admin/shipping_inventory_service.py index c86555ab..bd735572 100644 --- a/backend/app/services/admin/shipping_inventory_service.py +++ b/backend/app/services/admin/shipping_inventory_service.py @@ -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 diff --git a/backend/app/services/in_transit_transfer/deps.py b/backend/app/services/in_transit_transfer/deps.py index 9acc536a..59ab4917 100644 --- a/backend/app/services/in_transit_transfer/deps.py +++ b/backend/app/services/in_transit_transfer/deps.py @@ -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")), diff --git a/backend/app/services/in_transit_transfer/receipt_trigger_service.py b/backend/app/services/in_transit_transfer/receipt_trigger_service.py index 183f8e86..7cdcf44e 100644 --- a/backend/app/services/in_transit_transfer/receipt_trigger_service.py +++ b/backend/app/services/in_transit_transfer/receipt_trigger_service.py @@ -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'], diff --git a/backend/app/services/schedule/freight_receipt_rpa_job.py b/backend/app/services/schedule/freight_receipt_rpa_job.py index b842a61f..5efe7bdd 100644 --- a/backend/app/services/schedule/freight_receipt_rpa_job.py +++ b/backend/app/services/schedule/freight_receipt_rpa_job.py @@ -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) diff --git a/backend/app/services/shipping_notice/inventory_parsing_profile.py b/backend/app/services/shipping_notice/inventory_parsing_profile.py index f36fe1ca..12b048b0 100644 --- a/backend/app/services/shipping_notice/inventory_parsing_profile.py +++ b/backend/app/services/shipping_notice/inventory_parsing_profile.py @@ -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' diff --git a/backend/app/services/shipping_notice/inventory_structure_analysis.py b/backend/app/services/shipping_notice/inventory_structure_analysis.py index 51f69c89..bf08b51b 100644 --- a/backend/app/services/shipping_notice/inventory_structure_analysis.py +++ b/backend/app/services/shipping_notice/inventory_structure_analysis.py @@ -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')), diff --git a/backend/app/services/shipping_notice/receipt_report_storage.py b/backend/app/services/shipping_notice/receipt_report_storage.py index 5722af8a..07cac19b 100644 --- a/backend/app/services/shipping_notice/receipt_report_storage.py +++ b/backend/app/services/shipping_notice/receipt_report_storage.py @@ -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} diff --git a/backend/migrations/versions/rc3c4d5e6f7a_allow_null_receipt_unit_schedule_run.py b/backend/migrations/versions/rc3c4d5e6f7a_allow_null_receipt_unit_schedule_run.py new file mode 100644 index 00000000..593970ea --- /dev/null +++ b/backend/migrations/versions/rc3c4d5e6f7a_allow_null_receipt_unit_schedule_run.py @@ -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, + ) diff --git a/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py b/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py index 8a0ed9d6..9d1111bc 100644 --- a/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py +++ b/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py @@ -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 diff --git a/backend/tests/test_admin_movement_fields.py b/backend/tests/test_admin_movement_fields.py new file mode 100644 index 00000000..c909f548 --- /dev/null +++ b/backend/tests/test_admin_movement_fields.py @@ -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 diff --git a/backend/tests/test_admin_shipping_receipt_config.py b/backend/tests/test_admin_shipping_receipt_config.py index 8540b73a..4207a5e1 100644 --- a/backend/tests/test_admin_shipping_receipt_config.py +++ b/backend/tests/test_admin_shipping_receipt_config.py @@ -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 diff --git a/backend/tests/test_inventory_structure_analysis.py b/backend/tests/test_inventory_structure_analysis.py index d73bd77b..d7131525 100644 --- a/backend/tests/test_inventory_structure_analysis.py +++ b/backend/tests/test_inventory_structure_analysis.py @@ -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'] == [] diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 557751c7..a6619dbf 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -2946,6 +2946,7 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui - 货代上传 SOP + 正式上传模板列映射 - 生产 Windows RPA 脚本 - 上传成功 / 失败回执样例 +- CRANE「Inbound Details」真实收料样本文件(用于建立异动解析规则的字段映射) ### 1.9 收料报表 RPA 共享部署(Windows RPA + Ubuntu 后端) @@ -3871,3 +3872,32 @@ inventory_preparation Gate - 左侧文件队列图标五态口径(`ReviewDocumentNavigation.vue` 的 `navIconKind`,优先级命中即停):失败 ✗ → 需人工 ⚠(`issue_count>0` 或 `needs_attention`,以及 `draft`/`ready`/`unreviewed`/`quality_issue`/`pending_review`/`waiting_review`)→ 终态绿勾 ✓(`lifecycle_stage=upload_complete` 或 `closed`/`completed`)→ 系统在办蓝转圈(`confirmed`/`confirming`/`processing`/`reparse_pending`/`queued`)→ 中性灰圈(`non_order`/`cancelled`/`superseded`)→ 兜底转圈。绿勾不再被「已创建任务」等中间态占用;选中态仅由行高亮表达。 - 队列 `summary` 三桶与图标同口径(`_queue_summary_bucket`):`quality_issue` 归 needs_action;`confirmed` 归 processing;仅终态归 completed。前端当前未消费三桶,属契约纠偏。 - 已知边界(fail-safe):队列 `lifecycle_stage` 为轻量投影,极端场景会偏早(兜回 `intake_parse`),后果是完成单暂不亮绿勾;反向(未完成亮绿勾)不可能——`upload_complete` 仅由已持久化 `OT.stage=completed` 驱动。 + +## 收料异动解析规则配置闭环(2026-09-21) + +> 背景:调拨按需触发/预检复用链路依赖「收料配置绑定异动解析规则」,本节记录 2026-09-21 补齐的配置闭环与守卫语义。解析规则复用 `ShippingInventoryParsingProfile`(表名 inventory 为历史命名,用途以 `purpose` 为准)。 + +### 标准异动字段目录(只读契约,共 10 项) + +| code | 中文 | 类型 | 必填 | 身份字段 | 备注 | +| --- | --- | --- | --- | --- | --- | +| `doc_no` | 单号 | text | ✅ | ✅ | 幂等/汇总键 | +| `line_no` | 项次 | text | — | — | 行溯源 | +| `in_out_flag` | 进出库别 | text | — | — | 方向过滤 | +| `material_code` | 料号 | text | ✅ | ✅ | 与发货通知行匹配 | +| `material_name` | 品名 | text | — | — | 展示核对 | +| `warehouse_code` | 仓库 | text | — | — | 仓库维度核对 | +| `storage_code` | 储位 | text | — | — | 储位维度核对 | +| `lot_no` | 批号 | text | — | — | 批次核对 | +| `quantity` | 数量 | decimal | ✅ | — | 严格数量匹配 | +| `movement_date` | 异动日期 | date | ✅ | ✅ | 成熟过滤 | + +- 唯一事实源:`movement_contract.MOVEMENT_FIELDS`;管理端经 `GET /api/admin/shipping-notice/movement-fields` 只读下发(code/value_type/required/is_identity),label 由前端 i18n(`admin.shippingInventory.movementFields.*`)渲染。禁止新增自定义字段。 +- 规则创建走既有「样本上传 → 结构分析 → 字段映射 → 发布」流程,新建弹窗新增「规则用途」(inventory/movement,创建后不可变);movement 弹窗渲染 10 行固定映射,隐藏库存字段目录与订单匹配键。`create_profile_draft` 透传 `purpose`。 + +### 绑定闭环与守卫语义 + +- `ShippingReceiptReportConfig.parsing_profile_id` 绑定已发布 movement 规则:保存接口校验(非 published 或用途非 movement → `SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID`),绑定进前后快照审计;抽屉「异动解析规则」下拉只列 published+movement 规则。 +- 预检触发守卫(`_DefaultRpaTrigger`):收料配置存在但未绑/规则未发布/用途不符 → `RPA_RECEIPT_MOVEMENT_PROFILE_MISSING`,不写 trigger(防徒劳抓取循环);无收料配置仍走既有 `RPA_RECEIPT_CONFIG_MISSING`。 +- 站点库存解析绑定(`ShippingInventorySource.parsing_profile_id`,站点表单与批量绑定弹窗)只列 `purpose==='inventory'` 的已发布规则,防止误绑异动规则。 +- `movement_file_repository.latest_ready_file` 复用条件不变:归档文件存在且绑定规则就绪;无排程按需触发的单元行 `schedule_run_id` 为 NULL(FK 禁止 0 占位)。 diff --git a/docs/funclist.md b/docs/funclist.md index 1709083b..41dc833f 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -781,3 +781,6 @@ | Admin API | 后端已实现 | `/api/integration-connector/*`(配置 CRUD + 能力清单/调用 + 连接测试;拒绝 interface_id;require_admin) | | 调拨 query_inventory 接线 | 后端已实现 | `services/in_transit_transfer/gateway_adapter.py` 把 ERP 访问收敛到 gateway(P1 用默认绑定,来源专属绑定待 P2/P3) | | 配置作业 UI / MCP / Dify 暴露 / RPA/SQL 传输 | 待实施 | 属 P2/P3(AI 只暴露 Capability;RPA 为独立异步 Transport) | +| 收料异动解析规则(标准字段目录 + 规则用途) | 后端+管理端已实现 | purpose='movement' 解析规则创建/发布;`GET /api/admin/shipping-notice/movement-fields` 只读目录(10 定死字段,禁自定义);movement 映射表单(前端 `admin/shipping-notice` 解析模块) | +| 收料配置绑定异动解析规则 | 后端+管理端已实现 | 收料配置保存/回显 `parsing_profile_id`(校验 published+movement,`SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID`);抽屉绑定选择器;审计快照含绑定 | +| 预检未绑异动规则守卫 | 后端已实现 | 收料配置存在但未绑已发布 movement 规则 → `RPA_RECEIPT_MOVEMENT_PROFILE_MISSING`,fail-closed 不触发徒劳抓取 | diff --git a/docs/plans/2026-09-21-receipt-movement-parsing-module.md b/docs/plans/2026-09-21-receipt-movement-parsing-module.md new file mode 100644 index 00000000..8a924610 --- /dev/null +++ b/docs/plans/2026-09-21-receipt-movement-parsing-module.md @@ -0,0 +1,295 @@ +# 收料文件解析模块(异动解析规则)实施计划 + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 补齐收料异动解析规则的配置闭环:管理端可创建/发布 purpose='movement' 解析规则(基于只读标准异动字段目录),收料配置可绑定该规则,预检在未绑定规则时不再徒劳触发 RPA。 + +**Architecture:** 后端复用既有 `ShippingInventoryParsingProfile.purpose='movement'` 校验分支与 `ShippingReceiptReportConfig.parsing_profile_id` 字段(零模型变更、零迁移),只补 API 字段与守卫;前端参考库存解析模块在 `ShippingInventoryPage.vue` 内扩展用途切换与映射表单。标准字段目录以后端 `movement_contract.MOVEMENT_FIELDS` 为唯一事实源,经只读接口下发 code,文案由前端 i18n 四语言渲染(字段不允许用户自定义)。 + +**Tech Stack:** Flask blueprint(`app/api/admin/shipping_inventory.py`)+ SQLAlchemy 2.0(无迁移);Vue 3 Composition API + `@/shared/api/client requestJson` + Pinia 既有 admin 模块;pytest / vitest。 + +**Spec:** 本文件 §"标准异动字段清单(已确认)" 即字段契约 spec;模块行为设计要点已并入各 Task 的 Interfaces 说明。设计讨论结论:①参考库存解析模块增加收料文件解析能力;②不引入自定义字段,只提供标准异动字段(业务领域字段不允许用户自定义);③最小清单 10 字段,不过度设计(非重做 ERP)。 + +## 标准异动字段清单(已确认,2026-09-21) + +| # | code | 中文 | 类型 | 必填 | 身份字段 | T100 inaj_t 对应(仅备注,不入库) | +| --- | --- | --- | --- | --- | --- | --- | +| 1 | doc_no | 单号 | text | ✅ | ✅ | inaj001 單據編號(幂等/汇总键) | +| 2 | line_no | 项次 | text | — | — | inaj002 項次(行溯源) | +| 3 | in_out_flag | 进出库别 | text | — | — | inaj004 出入庫碼(方向过滤) | +| 4 | material_code | 料号 | text | ✅ | ✅ | inaj005 料件編號(匹配身份) | +| 5 | material_name | 品名 | text | — | — | —(料件主档带出,展示核对) | +| 6 | warehouse_code | 仓库 | text | — | — | inaj008 庫位編號 | +| 7 | storage_code | 储位 | text | — | — | inaj009 儲位編號 | +| 8 | lot_no | 批号 | text | — | — | inaj010 批號(批次核对) | +| 9 | quantity | 数量 | decimal | ✅ | — | inaj011 交易數量(严格数量匹配) | +| 10 | movement_date | 异动日期 | date | ✅ | ✅ | inaj024 單據扣帳日期(成熟过滤) | + +唯一事实源:`backend/app/services/in_transit_transfer/movement_contract.py:44` 的 `MOVEMENT_FIELDS`(code/label/value_type/is_identity/required 已全部定义)。**禁止**在前后端任何位置出现第 11 个异动字段码。 + +## Global Constraints + +- 提交信息符合 Conventional Commits:`type(shipping-notice): 中文主题`(type ∈ feat/test/docs/refactor),中文祈使语气、≤100 字符。 +- i18n 红线:前端新增文案同步 `frontend/src/locales/{zh-CN,zh-TW,en,th}/admin.json` 的 `admin.shippingInventory.*` 命名空间,四语言齐全,禁止硬编码中文。 +- 不新增第三方依赖;不改 `models.py`;无 Alembic 迁移(两个模型字段均已存在)。 +- 后端新逻辑遵守统一错误契约:业务失败 `raise ValidationError(..., code='SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID')`,不新写 jsonify error。 +- 前端 HTTP 统一 `@/shared/api/client` 的 `requestJson`;新注释遵守 AGENTS.md §5(文件块注释 + 函数 docstring/JSDoc)。 +- 测试命令:后端 `cd backend && .venv/Scripts/python.exe -m pytest -q`;前端 `cd frontend && npm run test:unit -- `、构建 `npm run build`(改动 frontend 后必须 build 通过)。 +- 站点行内的"绑定解析规则"下拉(`ShippingInventoryPage.vue:127`、批量绑定弹窗 `:426`)是**库存**解析绑定(`ShippingInventorySource.parsing_profile_id`),本计划**不改**它;收料异动绑定只进收料配置抽屉,防止两个语义混淆。 + +--- + +### Task 1: 后端 — 收料配置支持绑定异动解析规则 + +**Files:** +- Modify: `backend/app/services/admin/shipping_inventory_service.py`(`_receipt_report_config_payload`:256、`save_receipt_report_config`:314、文件顶部 import) +- Test: `backend/tests/test_admin_shipping_receipt_config.py` + +**Interfaces:** +- Consumes: `ShippingReceiptReportConfig.parsing_profile`(relationship,已存在,`movement_file_repository.py:46` 同款用法)、`ShippingInventoryParsingProfile(status/purpose)`。 +- Produces: `_receipt_report_config_payload` 返回新增 `parsing_profile_id: int | None` 与 `parsing_profile: {id, profile_code, display_name, version, status} | None`;`save_receipt_report_config(source_id, data, actor_id)` 接受 `data['parsing_profile_id']`(None/空串=解绑)。新校验失败码 `SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID`。 + +- [ ] **Step 1: 写失败测试**(追加到 `backend/tests/test_admin_shipping_receipt_config.py`,沿用该文件既有 app/种子 fixture 与登录风格;若该文件用 `client` fixture 直接照抄相邻用例的请求写法,以下断言为核心) + +```python +def test_save_receipt_config_binds_published_movement_profile(app, ...): + """绑定已发布 movement 规则 → 保存成功且 get 返回 parsing_profile_id 与摘要。""" + # 种子:enabled 来源 + published 且 purpose='movement' 的 ShippingInventoryParsingProfile + resp = client.put(f"/api/admin/shipping-notice/sources/{source_id}/receipt-report-config", + json={"report_path_json": {...}, "query_parameters_json": [...], + "parsing_profile_id": profile.id}) + assert resp.status_code == 200 + body = resp.get_json()["data"] + assert body["parsing_profile_id"] == profile.id + assert body["parsing_profile"]["profile_code"] == profile.profile_code + +def test_save_receipt_config_rejects_draft_profile(...): + """draft 规则不可绑定 → 400 SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID。""" + # status='draft' 的 profile,断言 resp.status_code == 400 且 error.code == 'SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID' + +def test_save_receipt_config_rejects_inventory_purpose_profile(...): + """purpose='inventory' 的已发布规则不可绑定 → 同错误码(防误绑库存规则)。""" + +def test_save_receipt_config_empty_profile_id_unbinds(...): + """parsing_profile_id 传 None → 解绑,payload 返回 None;审计 metadata 含 parsing_profile_id=None。""" +``` + +- [ ] **Step 2: 跑测试确认失败**:`.venv/Scripts/python.exe -m pytest tests/test_admin_shipping_receipt_config.py -q` → 新增用例 FAIL(payload 无 parsing_profile_id 键 / 400 未返回新错误码)。 + +- [ ] **Step 3: 最小实现**(`shipping_inventory_service.py`): + +```python +def _validate_movement_profile_binding(profile_id: Any) -> int | None: + """校验收料配置绑定的异动解析规则:必须已发布且 purpose='movement';空值=解绑。 + + Args: + profile_id: 请求里的 parsing_profile_id(None/空串表示解绑)。 + Returns: + 规整后的 profile id 或 None。 + Raises: + ValidationError: 规则不存在/未发布/用途不是 movement(SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID)。 + """ + 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 +``` + +`save_receipt_report_config` 在 `_validate_receipt_report_config` 之后追加一行 `config.parsing_profile_id = _validate_movement_profile_binding(data.get('parsing_profile_id'))`,审计 `metadata` 增加 `'parsing_profile_id': config.parsing_profile_id`;`_receipt_report_config_payload` 追加: + +```python +profile = config.parsing_profile +... +'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), +``` + +顶部 import 确认含 `ShippingInventoryParsingProfile`、`ValidationError`(文件内已有同款用法)。 + +- [ ] **Step 4: 跑测试确认通过**(同 Step 2 命令,预期全 PASS;连带跑 `tests/services/in_transit_transfer/test_movement_file_repository.py` 确认无回归)。 + +- [ ] **Step 5: Commit**:`git add backend/app/services/admin/shipping_inventory_service.py backend/tests/test_admin_shipping_receipt_config.py && git commit -m "feat(shipping-notice): 收料配置支持绑定已发布异动解析规则"` + +--- + +### Task 2: 后端 — 预检止血:未绑异动规则不再徒劳触发 RPA + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/deps.py:86`(`_DefaultRpaTrigger.trigger`) +- Test: `backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py` + +**Interfaces:** +- Consumes: Task 1 的绑定字段;`trigger_receipt_rpa` 现有 `RPA_RECEIPT_CONFIG_MISSING` fail-closed。 +- Produces: `_DefaultRpaTrigger.trigger` 新返回错误码 `RPA_RECEIPT_MOVEMENT_PROFILE_MISSING`(ok=False,不写 trigger 文件、不落单元行)。语义矩阵:来源停用/无收料配置 → 委托既有链路返回 `RPA_RECEIPT_CONFIG_MISSING`;有配置但规则未绑/未发布/用途不对 → 新守卫;已正确绑定 → 正常触发。 + +- [ ] **Step 1: 写失败测试**(追加到 `test_receipt_trigger_service.py`) + +```python +def test_default_trigger_fails_closed_when_movement_profile_missing(app, receipt_source): + """收料配置存在但未绑已发布 movement 规则 → ok=False 且不写 trigger(防徒劳抓取)。""" + from app.services.in_transit_transfer.deps import _DefaultRpaTrigger + import tempfile + with tempfile.TemporaryDirectory() as trigger_dir: + monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', trigger_dir) + outcome = _DefaultRpaTrigger().trigger( + source_code=receipt_source.source_code, business_date='2026-09-21', reason='precheck_missing_ready_file') + assert outcome['ok'] is False + assert outcome['error_code'] == 'RPA_RECEIPT_MOVEMENT_PROFILE_MISSING' + assert not list(pathlib.Path(trigger_dir).glob('receipt_export_batch_*.json')) +``` + +(`receipt_source` fixture 建 config 但不绑 profile,恰好就是守卫场景;再补一条正例:给 config.parsing_profile_id 绑上 Task 1 同款 published movement profile 后 trigger ok=True。`monkeypatch` 用例内加 `request` 参数。) + +- [ ] **Step 2: 跑测试确认失败**:`.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_receipt_trigger_service.py -q` → 新用例 FAIL(当前返回 ok=True 并写文件)。 + +- [ ] **Step 3: 实现**(`deps.py` `_DefaultRpaTrigger.trigger` 开头插入守卫,注释遵守 §5 写明【触发时机】): + +```python +# [守卫] 收料配置存在但未绑定已发布异动解析规则时,触发 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'} +``` + +- [ ] **Step 4: 跑测试确认通过**(同 Step 2,全量 PASS;`test_default_rpa_trigger_writes_real_trigger_file` 需按正例补 profile 绑定后保持 PASS)。 + +- [ ] **Step 5: Commit**:`git commit -m "fix(shipping-notice): 未绑异动解析规则时预检触发fail-closed防徒劳抓取"` + +--- + +### Task 3: 后端 — 标准异动字段目录只读接口 + +**Files:** +- Modify: `backend/app/api/admin/shipping_inventory.py`(新增路由,放在 parsing-profiles 路由附近 `:431`) +- Test: 新建 `backend/tests/test_admin_movement_fields.py`(仿 `test_admin_shipping_receipt_config.py` 的 admin 鉴权 fixture 风格) + +**Interfaces:** +- Consumes: `movement_contract.MOVEMENT_FIELDS`(`MovementFieldValueType` 为 StrEnum,直接 `str()` 得 "text"/"decimal"/"date")。 +- Produces: `GET /api/admin/shipping-notice/movement-fields` → `{success, data: [{code, value_type, required, is_identity}]}`(10 条,顺序=契约顺序;**不返回 label**,文案走前端 i18n)。 + +- [ ] **Step 1: 写失败测试** + +```python +def test_movement_fields_returns_fixed_catalog(client): + """标准异动字段目录:10 个定死字段、顺序稳定、含必填/身份标记,不含可配置项。""" + resp = client.get('/api/admin/shipping-notice/movement-fields') + data = resp.get_json()['data'] + assert [f['code'] for f in data] == [ + 'doc_no', 'line_no', 'in_out_flag', 'material_code', 'material_name', + 'warehouse_code', 'storage_code', 'lot_no', 'quantity', 'movement_date'] + required = {f['code'] for f in data if f['required']} + assert required == {'doc_no', 'material_code', 'quantity', 'movement_date'} + identity = {f['code'] for f in data if f['is_identity']} + assert identity == {'doc_no', 'material_code', 'movement_date'} + assert {f['value_type'] for f in data} <= {'text', 'decimal', 'date'} +``` + +- [ ] **Step 2: 跑测试确认失败**:`pytest tests/test_admin_movement_fields.py -q` → 404/FAIL。 + +- [ ] **Step 3: 实现路由** + +```python +@admin_bp.route('/shipping-notice/movement-fields', methods=['GET']) +@admin_required +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 + ]) +``` + +(装饰器/`_ok` 用法照抄同文件相邻路由 `:431` 的 `list_shipping_inventory_parsing_profiles`。) + +- [ ] **Step 4: 跑测试确认通过**。 +- [ ] **Step 5: Commit**:`git commit -m "feat(shipping-notice): 暴露标准异动字段目录只读接口"` + +--- + +### Task 4: 前端 — 解析规则模块支持收料异动用途 + +**Files:** +- Modify: `frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue`(`parsing` reactive `:620`;编辑弹窗 `:216-260`;解析卡片列表;保存 payload 组装处) +- Modify: `frontend/src/features/admin/api/admin.api.ts`(`saveShippingInventoryParsingProfile` `:270` 附近新增 `fetchMovementFields`) +- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/admin.json` +- Test: `frontend/src/features/admin/modules/shipping-inventory/movementParsingProfileForm.spec.ts`(新建,仿 `receiptReportConfigForm.spec.ts` 风格;映射组装逻辑抽成纯函数 `movementParsingProfileForm.ts` 便于测试) + +**Interfaces:** +- Consumes: Task 3 `GET /movement-fields`;既有 `saveShippingInventoryParsingProfile(payload, id?)`(payload 已支持 `purpose`/`definition.field_mapping` 字符串键,后端 `save_draft:235` 校验)。 +- Produces: `fetchMovementFields(): Promise`,`MovementFieldDef = {code: string; value_type: 'text'|'decimal'|'date'; required: boolean; is_identity: boolean}`;`buildMovementDefinition(mappings, sheetName, headerRowIndex)` 返回 `{sheet_name, header_row_index, field_mapping: Record}`。 + +- [ ] **Step 1: 写失败测试**(`movementParsingProfileForm.spec.ts`):断言 `buildMovementDefinition` 把 `[{code:'doc_no',alias:'单据编号'},…]` 组装为 `field_mapping` 字符串键对象、空 alias 的**非必填**字段被剔除、必填字段(doc_no/material_code/quantity/movement_date)缺 alias 时抛出带字段 code 的错误、`header_row_index` 空串归一为 undefined。 + +- [ ] **Step 2: 跑测试确认失败**:`npm run test:unit -- movementParsingProfileForm` → 模块不存在 FAIL。 + +- [ ] **Step 3: 实现 `movementParsingProfileForm.ts`**(文件头块注释:用途/依赖/逻辑;导出 `buildMovementDefinition` + `REQUIRED_MOVEMENT_FIELD_CODES = ['doc_no','material_code','quantity','movement_date']` 常量)。 + +- [ ] **Step 4: 页面接入**(`ShippingInventoryPage.vue`,全部为局部改动): + 1. `:620` `parsing` reactive 增加 `purpose: 'inventory' as 'inventory' | 'movement'` 与 `movement_mappings: [] as {code: string; alias: string}[]`;打开新建弹窗时重置 purpose='inventory' 并拉取 movement-fields 填充 movement_mappings(10 行,alias 全空)。 + 2. 编辑弹窗 `:216` 附近: purpose 下拉(库存解析/收料异动);编辑既有规则时 disabled(后端规定 purpose 草稿也不可变,`save_draft:238`)。 + 3. `purpose==='movement'` 分支:隐藏库存字段映射行与"订单字段与库存字段匹配键"区(`:251-260` 的 matchKeys 模板加 `v-if="parsing.purpose === 'inventory'"`);渲染 10 行固定映射表(标准字段名走 i18n `admin.shippingInventory.movementFields.`,必填列标 ✱,身份列标 🔑,alias 输入);保存 payload:`{profile_code, display_name, file_format, purpose, sample_analysis_id, confirm_sample_replacement?, definition: buildMovementDefinition(...)}`(样本上传/结构分析流程原样复用)。 + 4. 只读详情区(`:203` matchKeys 同款):movement 规则展示 10 行映射只读卡,隐藏 matchKeys。 + 5. 解析规则卡片列表(parsingProfiles 卡片 v-for)加用途徽标:`t('admin.shippingInventory.parsingPurpose.' + row.purpose)`;库存绑定下拉(`:127`、`:426`)**保持只列 `purpose==='inventory'`** 的已发布规则(现无过滤,补 `.filter(row => row.purpose === 'inventory')`,防止异动规则被误绑到库存站点)。 + +- [ ] **Step 5: i18n 四语言**(`admin.json` → `admin.shippingInventory` 命名空间,四文件键一致):`parsingPurpose.inventory/parsingPurpose.movement`、`movementPurposeLabel`、`movementFields.doc_no/line_no/in_out_flag/material_code/material_name/warehouse_code/storage_code/lot_no/quantity/movement_date`、`movementFieldAlias`、`movementRequiredMark`、`movementIdentityMark`。zh-TW 用繁体、en/th 用英文/泰文对应译文。 + +- [ ] **Step 6: 跑测试 + 构建**:`npm run test:unit -- movementParsingProfileForm` PASS;`npm run build` 通过。 + +- [ ] **Step 7: Commit**:`git commit -m "feat(shipping-notice): 解析规则模块支持收料异动用途与标准字段映射"` + +--- + +### Task 5: 前端 — 收料配置抽屉异动规则选择器 + +**Files:** +- Modify: `frontend/src/features/admin/modules/shipping-inventory/receiptReportConfigForm.ts`(类型 + payload) +- Modify: `frontend/src/features/admin/modules/shipping-inventory/receiptReportConfigForm.spec.ts` +- Modify: `frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue`(收料配置抽屉 `:159` 附近) +- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/admin.json` + +**Interfaces:** +- Consumes: Task 1 GET payload(`parsing_profile_id`/`parsing_profile`);Task 4 的 `parsingProfiles`(过滤 `status==='published' && purpose==='movement'`)。 +- Produces: `buildReceiptReportConfigPayload` 输出含 `parsing_profile_id: number | null`;抽屉显示当前绑定规则名与版本。 + +- [ ] **Step 1: 写失败测试**(追加 spec):payload 含 parsing_profile_id(null 归一);回填函数从 GET payload 恢复该字段。 +- [ ] **Step 2: 跑测试确认失败**:`npm run test:unit -- receiptReportConfigForm`。 +- [ ] **Step 3: 实现**:form 类型与 `buildReceiptReportConfigPayload` 增加 `parsing_profile_id`(0/undefined→null);抽屉模板在查询条件区下加"异动解析规则"下拉:`` + `parsingProfiles.filter(published && purpose==='movement')` 选项,下方展示已绑规则的 `parsing_profile.profile_code V{{version}}`;保存/回填走 Task 1 payload。 +- [ ] **Step 4: i18n 四语言**:`movementBindingLabel`(异动解析规则)、`movementBindingNone`(未绑定)、`movementBindingHint`(说明:绑定后预检将复用归档文件,未绑定时预检不触发抓取)。 +- [ ] **Step 5: 跑测试 + build 通过**。 +- [ ] **Step 6: Commit**:`git commit -m "feat(shipping-notice): 收料配置抽屉支持绑定异动解析规则"` + +--- + +### Task 6: 文档同步 + +**Files:** +- Modify: `docs/features/shipping-notice/technical.md`(收料 RPA 章节,约 `:2952` 起的部署手册附近,补"异动解析规则"小节:标准字段 10 项表、绑定闭环、预检守卫语义矩阵) +- Modify: `docs/funclist.md`(功能清单追加:收料异动解析规则管理 + 收料配置绑定) +- Modify: `docs/demand.md`(如调拨章节有收料文件前置描述则同步一句,无则跳过) + +- [ ] **Step 1:** 按上述内容更新文档(字段表直接复制本计划"标准异动字段清单"节)。 +- [ ] **Step 2: Commit**:`git commit -m "docs(shipping-notice): 补收料异动解析规则配置闭环文档"` + +--- + +### Task 7: 全量自检 + +- [ ] **Step 1: 后端相关域全量**:`cd backend && .venv/Scripts/python.exe -m pytest tests/test_admin_shipping_receipt_config.py tests/test_admin_movement_fields.py tests/services/in_transit_transfer/ tests/test_freight_receipt_rpa_schedule.py tests/test_freight_receipt_rpa_callback.py -q` → 全 PASS。 +- [ ] **Step 2: 前端**:`cd frontend && npm run test:unit && npm run build` → 全 PASS。 +- [ ] **Step 3: 手工链路验证**(本地 dev,Postgres 已跑):管理端建 CRANE movement 规则(上传 CRANE Inbound Details 样本)→ 发布 → 收料配置抽屉绑定 → `/in-transit` 来源页 CRANE 点重试 RPA 正常 → 点"确认范围并预检"不再触发新 RPA 且预检复用文件(file_pending→file_ready)。此步需要真实样本文件,若样本未备齐,标记为"待运营样本"并在交付说明中注明。 +- [ ] **Step 4: Commit**(如有零星修复):`fix(shipping-notice): ...` diff --git a/frontend/src/features/admin/api/admin.api.ts b/frontend/src/features/admin/api/admin.api.ts index 8a2efff0..50c2edc8 100644 --- a/frontend/src/features/admin/api/admin.api.ts +++ b/frontend/src/features/admin/api/admin.api.ts @@ -288,6 +288,10 @@ export const createShippingInventoryStructureAnalysis = (file: File) => { method: 'POST', body: form, ...auth(), }); }; +/** 读取标准异动字段目录(只读领域契约,供收料异动解析规则映射表单)。 */ +export const fetchMovementFields = () => requestJson>( + '/api/admin/shipping-notice/movement-fields', auth(), +); /** 用已分析的真实栏位创建库存文件解析方案草稿。 */ export const createShippingInventoryParsingDraftFromAnalysis = (id: number, payload: Record) => requestJson( `/api/admin/shipping-notice/inventory-structure-analyses/${id}/create-profile-draft`, diff --git a/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue b/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue index e2866898..0334f9f0 100644 --- a/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue +++ b/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue @@ -124,7 +124,7 @@ - + @@ -178,6 +178,7 @@

{{ t('admin.shippingInventory.receiptCraneFixedPath') }}

+ @@ -185,21 +186,32 @@ @@ -333,7 +355,7 @@
{{ t('admin.shippingInventory.enabled') }}
-
+