diff --git a/backend/app/api/admin/shipping_order_document_profiles.py b/backend/app/api/admin/shipping_order_document_profiles.py index 2b576115..2595d09c 100644 --- a/backend/app/api/admin/shipping_order_document_profiles.py +++ b/backend/app/api/admin/shipping_order_document_profiles.py @@ -63,6 +63,14 @@ def get_order_document_profile_sample_status(intake_no: str): return _ok(service.get_sample_intake_status(intake_no, actor_id=_actor_id())) +@admin_bp.route('/shipping-notice/order-document-profile-samples/intakes/', methods=['DELETE']) +@require_admin +def delete_order_document_profile_sample(intake_no: str): + """删除未进入盲测且已结束解析的专用模板样本。""" + service.delete_sample_intake(intake_no, actor_id=_actor_id()) + return '', 204 + + @admin_bp.route('/shipping-notice/order-document-profile-samples//tables', methods=['GET']) @require_admin def get_order_document_profile_sample_tables(document_id: int): @@ -70,6 +78,30 @@ def get_order_document_profile_sample_tables(document_id: int): return _ok(service.get_sample_tables(document_id)) +@admin_bp.route('/shipping-notice/order-document-profile-samples/coordinate-reconstruction-preview', methods=['POST']) +@require_admin +def preview_order_document_profile_coordinate_reconstruction(): + """根据管理员确认的相对列边界返回只读坐标重建候选。""" + return _ok(service.preview_coordinate_reconstruction(request.get_json(silent=True) or {}, actor_id=_actor_id())) + + +@admin_bp.route('/shipping-notice/order-document-profile-samples/coordinate-reconstruction-suggestion', methods=['POST']) +@require_admin +def suggest_order_document_profile_coordinate_reconstruction(): + """根据冻结字符坐标自动建议动态物理行和列边界,结果仍需管理员确认。""" + return _ok(service.suggest_coordinate_reconstruction(request.get_json(silent=True) or {}, actor_id=_actor_id())) + + +@admin_bp.route('/shipping-notice/order-document-profile-samples/ocr-coordinate-evidence', methods=['POST']) +@require_admin +def generate_order_document_profile_ocr_coordinate_evidence(): + """为无文字层 PDF 的当前样本表格生成受控 OCR 坐标证据。""" + data = request.get_json(silent=True) or {} + return _ok(service.generate_ocr_coordinate_evidence( + document_id=data.get('document_id'), table_id=str(data.get('table_id') or ''), actor_id=_actor_id(), + )) + + @admin_bp.route('/shipping-notice/order-document-profiles/from-sample', methods=['POST']) @require_admin def create_order_document_profile_from_sample(): diff --git a/backend/app/api/admin/shipping_order_schema.py b/backend/app/api/admin/shipping_order_schema.py index f8b5c754..eacb3185 100644 --- a/backend/app/api/admin/shipping_order_schema.py +++ b/backend/app/api/admin/shipping_order_schema.py @@ -14,6 +14,7 @@ from app.api.admin.blueprint import admin_bp from app.core.decorators import require_admin from app.core.response import ok from app.services.shipping_notice.order_schema import service +from app.services.shipping_notice import fulfillment_policy_registry def _actor_id() -> int | None: @@ -42,6 +43,25 @@ def shipping_order_auto_creation_policy(): return _ok(service.save_auto_creation_policy(request.get_json(silent=True) or {}, actor_id=_actor_id())) +@admin_bp.route('/shipping-fulfillment-policies', methods=['GET', 'POST']) +@require_admin +def shipping_fulfillment_policies(): + """读取策略能力目录或创建新的货代履约策略草稿。""" + if request.method == 'GET': + return _ok(fulfillment_policy_registry.get_state()) + return _ok(fulfillment_policy_registry.create_draft(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/shipping-fulfillment-policies//publish', methods=['POST']) +@require_admin +def publish_shipping_fulfillment_policy(policy_id: int): + """发布指定货代履约策略版本并退役当前版本。""" + payload = request.get_json(silent=True) or {} + return _ok(fulfillment_policy_registry.publish( + policy_id, actor_id=_actor_id(), expected_lock_version=payload.get('expected_lock_version'), + )) + + @admin_bp.route('/shipping-order-schema', methods=['POST']) @require_admin def initialize_shipping_order_schema(): diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index 1e9122f0..a557b7e8 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -39,6 +39,7 @@ from app.models.shipping_fulfillment import ( ShippingReservation, ShippingUploadAttempt, ) +from app.models.shipping_fulfillment_policy import ShippingFulfillmentPolicy from app.models.shipping_order_schema import ( ShippingOrderExtraction, ShippingOrderSchemaAuditEvent, @@ -218,6 +219,7 @@ __all__ = [ 'ShippingInventoryVerificationLine', 'ShippingExportArtifactLine', 'ShippingUploadAttempt', + 'ShippingFulfillmentPolicy', 'ShippingNoticeIntake', 'ShippingNoticeDocument', 'ShippingNoticeCandidate', diff --git a/backend/app/models/shipping_fulfillment.py b/backend/app/models/shipping_fulfillment.py index a3de3845..e409c9ee 100644 --- a/backend/app/models/shipping_fulfillment.py +++ b/backend/app/models/shipping_fulfillment.py @@ -19,11 +19,11 @@ from app.models.base import Base class ShippingReservation(Base): - """预约单当前履约注册表;同一预约号与内部料号在当前版本只能有一条事实。""" + """预约单当前履约注册表;Reservation ID 全局只能归属一个采购单。""" __tablename__ = 'shipping_reservations' __table_args__ = ( - UniqueConstraint('reservation_id', 'part_number', name='uq_shipping_reservations_reservation_part'), + UniqueConstraint('reservation_id', name='uq_shipping_reservations_reservation_id'), CheckConstraint( "status IN ('pending', 'available', 'artifact_reserved', 'uploaded', 'external_change_required')", name='ck_shipping_reservations_status', @@ -35,6 +35,7 @@ class ShippingReservation(Base): task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False) snapshot_line_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_snapshot_lines.id'), nullable=False) reservation_id: Mapped[str] = mapped_column(String(64), nullable=False) + po_number_normalized: Mapped[str] = mapped_column(String(255), nullable=False) part_number: Mapped[str] = mapped_column(String(255), nullable=False) required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False) status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending') diff --git a/backend/app/models/shipping_fulfillment_policy.py b/backend/app/models/shipping_fulfillment_policy.py new file mode 100644 index 00000000..526c1852 --- /dev/null +++ b/backend/app/models/shipping_fulfillment_policy.py @@ -0,0 +1,48 @@ +""" +models/shipping_fulfillment_policy.py + +用途:保存货代字段能力绑定和不可变履约策略版本。 +依赖:订单 Schema、users 与 SQLAlchemy Base。 +逻辑:Schema 负责字段目录;本模型以稳定 field_id 将字段绑定到货代履约能力,并只允许一个 published 策略。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text +from sqlalchemy.orm import Mapped, mapped_column + +from app.models.base import Base + + +class ShippingFulfillmentPolicy(Base): + """货代履约策略版本;published 版本不可修改且由冻结 Snapshot 引用。""" + + __tablename__ = 'shipping_fulfillment_policies' + __table_args__ = ( + UniqueConstraint('schema_id', 'policy_code', 'version', name='uq_shipping_fulfillment_policies_version'), + CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_fulfillment_policies_status'), + Index( + 'uq_shipping_fulfillment_policy_one_published', 'schema_id', unique=True, + postgresql_where=text("status = 'published'"), sqlite_where=text("status = 'published'"), + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + schema_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=False) + policy_code: Mapped[str] = mapped_column(String(64), nullable=False) + version: Mapped[int] = mapped_column(Integer, nullable=False) + status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft') + definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') + change_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + source_policy_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_fulfillment_policies.id'), nullable=True) + created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + published_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + retired_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) diff --git a/backend/app/models/shipping_inventory_config.py b/backend/app/models/shipping_inventory_config.py index 1e52e3f5..45db4253 100644 --- a/backend/app/models/shipping_inventory_config.py +++ b/backend/app/models/shipping_inventory_config.py @@ -344,14 +344,14 @@ class ShippingInventoryExternalMapping(Base): __tablename__ = 'shipping_inventory_external_mappings' __table_args__ = ( Index( - 'uq_shipping_inventory_external_mappings_source_default_enabled', + 'uq_shipping_inv_ext_map_src_default_enabled', 'inventory_source_id', unique=True, postgresql_where=text('freight_warehouse_id IS NULL AND enabled = true'), sqlite_where=text('freight_warehouse_id IS NULL AND enabled = 1'), ), Index( - 'uq_shipping_inventory_external_mappings_source_warehouse_enabled', + 'uq_shipping_inv_ext_map_src_wh_enabled', 'inventory_source_id', 'freight_warehouse_id', unique=True, diff --git a/backend/app/models/shipping_order_snapshot.py b/backend/app/models/shipping_order_snapshot.py index 20c74354..2e864897 100644 --- a/backend/app/models/shipping_order_snapshot.py +++ b/backend/app/models/shipping_order_snapshot.py @@ -38,7 +38,7 @@ class ShippingOrderSnapshot(Base): # 保留所有已发布 Header 字段;核心字段同时写入下方强类型列,扩展字段由业务配置按 field_id 消费。 header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) - po_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + customer_po_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) customer_code: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) customer_name: Mapped[Optional[str]] = mapped_column(Text, nullable=True) bill_to_customer: Mapped[Optional[str]] = mapped_column(Text, nullable=True) @@ -80,7 +80,6 @@ class ShippingOrderSnapshotLine(Base): line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) customer_part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) - aws_part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) reservation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True) uom: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) diff --git a/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py b/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py index 74f4b540..0120feb1 100644 --- a/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py +++ b/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py @@ -17,8 +17,8 @@ from app.services.shipping_notice.document_layout.contracts import LayoutBBox from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter -_LINE_NUMBER_PATTERN = re.compile(r'^0{2,}\d+$') -_DELETED_PATTERN = re.compile(r'^\*+\s*item\s+deleted\s*\*+$', re.IGNORECASE) +_LINE_NUMBER_PATTERN = re.compile(r'^(?:0{2,}\d+|\d{1,6})$') +_DELETED_PATTERN = re.compile(r'^\*+itemdeleted\*+$', re.IGNORECASE) class CoordinateReconstructionModel(BaseModel): @@ -32,6 +32,7 @@ class CoordinateColumnAnchor(CoordinateReconstructionModel): column_index: int = Field(ge=0) bbox: LayoutBBox + field_code: str | None = None class ReconstructedCell(CoordinateReconstructionModel): @@ -44,10 +45,10 @@ class ReconstructedCell(CoordinateReconstructionModel): class ReconstructedRow(CoordinateReconstructionModel): - """一个 y-band 形成的视觉行;删除标记只能附着在前一强锚定行。""" + """一个 y-band 形成的视觉行;其角色供后续逻辑明细合并使用。""" row_index: int = Field(ge=0) - role: Literal['data', 'continuation', 'deleted', 'needs_review'] + role: Literal['data', 'continuation', 'deleted', 'header', 'summary', 'needs_review'] cells: list[ReconstructedCell] = Field(min_length=1) @model_validator(mode='after') @@ -67,11 +68,128 @@ class CoordinateTableReconstruction(CoordinateReconstructionModel): issues: list[str] = Field(default_factory=list) +_HEADER_TERMS = frozenset({ + 'item', 'material', 'description', 'date', 'price', 'quantity', 'amount', + 'brand', 'manufacturer', 'delivery', 'shipping', 'drawing', 'rev', +}) +_SUMMARY_PATTERN = re.compile( + r'(?:total\s*amount|incl\.?\s*tax|subtotal|invoice\s*bill|terms?\s*and\s*conditions?)', + re.IGNORECASE, +) + + +class CoordinateSubrowLayout(CoordinateReconstructionModel): + """一条逻辑明细内某类物理子行的独立列边界与固定字段语义。""" + + role: Literal['main', 'continuation'] + row_offset: int = Field(ge=0) + column_boundaries: list[float] = Field(min_length=2) + column_field_codes: list[str | None] + + @model_validator(mode='after') + def validate_layout(self) -> 'CoordinateSubrowLayout': + """确保子行边界覆盖整表,且每个区间恰好对应一个字段或忽略项。""" + if self.column_boundaries[0] != 0 or self.column_boundaries[-1] != 1: + raise ValueError('coordinate subrow boundaries must start at 0 and end at 1') + if any(left >= right for left, right in zip(self.column_boundaries, self.column_boundaries[1:])): + raise ValueError('coordinate subrow boundaries must be strictly increasing') + if len(self.column_field_codes) != len(self.column_boundaries) - 1: + raise ValueError('coordinate subrow field codes must match column count') + return self + + +class ReconstructedLogicalRow(CoordinateReconstructionModel): + """多子行版式合并后的单条逻辑订单明细及来源物理行。""" + + role: Literal['data', 'deleted'] + fields: dict[str, str] = Field(default_factory=dict) + source_row_indices: list[int] = Field(min_length=1) + + +class CoordinateSubrowSuggestion(CoordinateReconstructionModel): + """从实际字符坐标生成的单种物理行版式建议,不包含绝对坐标。""" + + role: Literal['main', 'continuation'] + row_offset: int = Field(ge=0) + column_boundaries: list[float] = Field(min_length=2) + column_samples: list[list[str]] + suggested_field_codes: list[str | None] + + +def suggest_multi_subrow_layouts( + *, + characters: list[PositionedCharacter | dict[str, Any]], + table_bbox: LayoutBBox | dict[str, Any], +) -> list[CoordinateSubrowSuggestion]: + """ + 从实际物理行和文本起始位置自动建议动态多行版式。 + + AI/调用方触发时机:管理员打开坐标重建且不清楚相对边界时调用。算法只负责把 + 同一明细中的第 1..N 行分组并建议列区间;除可确定的 ``line_no`` 外不猜业务字段, + 建议结果仍须管理员结合示例文字确认。 + + Args: + characters: 当前表格冻结的 PDF 原生或 OCR 字符坐标。 + table_bbox: 当前数据表范围。 + Returns: + 按 row_offset 排列的动态行建议;找不到可靠主行时返回空列表。 + """ + bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox) + glyphs = _table_glyphs(characters, bbox) + if not glyphs: + return [] + bands = _group_visual_rows(glyphs) + groups: list[list[list[tuple[int, PositionedCharacter]]]] = [] + current: list[list[tuple[int, PositionedCharacter]]] | None = None + for band in bands: + text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip() + compact = re.sub(r'\s+', '', text) + if _SUMMARY_PATTERN.search(text): + if current: + groups.append(current) + break + if _DELETED_PATTERN.fullmatch(compact): + if current: + groups.append(current) + current = None + continue + if _band_starts_item(band, bbox): + if current: + groups.append(current) + current = [band] + elif current is not None: + current.append(band) + if current: + groups.append(current) + if not groups: + return [] + + max_rows = max(len(group) for group in groups) + suggestions: list[CoordinateSubrowSuggestion] = [] + for row_offset in range(max_rows): + samples = [group[row_offset] for group in groups if row_offset < len(group)] + boundaries, column_samples, line_column = _suggest_band_boundaries( + samples, bbox, detect_line_number=row_offset == 0, + ) + suggestions.append(CoordinateSubrowSuggestion( + role='main' if row_offset == 0 else 'continuation', + row_offset=row_offset, + column_boundaries=boundaries, + column_samples=column_samples, + suggested_field_codes=[ + 'line_no' if row_offset == 0 and index == line_column else None + for index in range(len(boundaries) - 1) + ], + )) + return suggestions + + def reconstruct_table_from_positioned_text( *, characters: list[PositionedCharacter | dict[str, Any]], table_bbox: LayoutBBox, column_anchors: list[CoordinateColumnAnchor | dict[str, Any]], + line_start_column_index: int = 0, ) -> CoordinateTableReconstruction: """ 以 x 列锚点、y 视觉行和内容/邻接辅助规则重建保守候选。 @@ -83,7 +201,8 @@ def reconstruct_table_from_positioned_text( Args: characters: 表格范围内外的 PDF 原生字符及 source_index。 table_bbox: 当前表格的真实页面范围。 - column_anchors: 从可信表头得到的列区间,至少两列且不可重叠。 + column_anchors: 管理员确认的列区间及可选固定字段编码,至少两列且不可重叠。 + line_start_column_index: 出现有效行号时代表新明细的列,默认第一列。 Returns: 带 glyph 索引的视觉行候选;status 始终为 needs_review。 """ @@ -95,14 +214,19 @@ def reconstruct_table_from_positioned_text( issues: set[str] = set() rows: list[ReconstructedRow] = [] previous_has_line_number = False + data_region_started = False for row_index, band in enumerate(_group_visual_rows(glyphs)): cells: dict[int, list[tuple[int, PositionedCharacter]]] = {} - for glyph_index, glyph in band: - column = _assign_column(glyph.bbox, anchors) + previous_column: int | None = None + for text_run in _group_text_runs(band): + run_bbox = _run_bbox(text_run) + run_text = ''.join(glyph.text for _, glyph in text_run).strip() + column = _assign_column(run_bbox, run_text, anchors, previous_column=previous_column) if column is None: issues.add('coordinate_reconstruction_column_ambiguous') continue - cells.setdefault(column, []).append((glyph_index, glyph)) + cells.setdefault(column, []).extend(text_run) + previous_column = column if not cells: continue rebuilt = [ @@ -110,27 +234,225 @@ def reconstruct_table_from_positioned_text( for column, value in sorted(cells.items()) ] text = ' '.join(cell.text for cell in rebuilt) - has_line_number = any(_LINE_NUMBER_PATTERN.fullmatch(cell.text.replace(' ', '')) for cell in rebuilt) - if _DELETED_PATTERN.fullmatch(text.strip()): - role: Literal['data', 'continuation', 'deleted', 'needs_review'] = ( + has_line_number = any( + cell.column_index == line_start_column_index + and _LINE_NUMBER_PATTERN.fullmatch(cell.text.replace(' ', '')) + for cell in rebuilt + ) + compact_text = re.sub(r'\s+', '', text) + if _SUMMARY_PATTERN.search(text): + role: Literal['data', 'continuation', 'deleted', 'header', 'summary', 'needs_review'] = 'summary' + previous_has_line_number = False + elif _DELETED_PATTERN.fullmatch(compact_text): + role = ( 'deleted' if previous_has_line_number else 'needs_review' ) if role == 'needs_review': issues.add('coordinate_reconstruction_deleted_row_unattached') elif has_line_number: role = 'data' + data_region_started = True + elif not data_region_started and _looks_like_header(text): + role = 'header' else: role = 'continuation' if previous_has_line_number else 'needs_review' if role == 'needs_review': issues.add('coordinate_reconstruction_row_unanchored') rows.append(ReconstructedRow(row_index=row_index, role=role, cells=rebuilt)) - previous_has_line_number = has_line_number or (role == 'continuation' and previous_has_line_number) + previous_has_line_number = has_line_number or (role in {'continuation', 'deleted'} and previous_has_line_number) if not rows: issues.add('coordinate_reconstruction_rows_missing') return CoordinateTableReconstruction(rows=rows, issues=sorted(issues)) +def reconstruct_multi_subrow_table( + *, + characters: list[PositionedCharacter | dict[str, Any]], + table_bbox: LayoutBBox, + subrow_layouts: list[CoordinateSubrowLayout | dict[str, Any]], + line_start_field_code: str = 'line_no', +) -> list[ReconstructedLogicalRow]: + """ + 使用每种子行的独立边界,将重叠版式的多条物理行合并为订单明细。 + + 核心逻辑:每个视觉行先按主行布局寻找行号;命中后开始新明细。后续物理行按 + ``row_offset`` 选择第 2..N 行布局,将值直接合并到固定字段,而不是沿用首行列号。 + + Args: + characters: 表格范围内的原生或 OCR 字符坐标。 + table_bbox: 当前数据表页面范围。 + subrow_layouts: 主行、补充行和属性行的独立边界及字段映射。 + line_start_field_code: 标记新明细的固定字段,默认 ``line_no``。 + Returns: + 合并后的逻辑明细;纯表头、说明和合计区域不会返回。 + """ + layouts = [ + item if isinstance(item, CoordinateSubrowLayout) else CoordinateSubrowLayout.model_validate(item) + for item in subrow_layouts + ] + by_offset = {item.row_offset: item for item in layouts} + main = by_offset.get(0) + if main is None or not any(code == line_start_field_code for code in main.column_field_codes): + raise ValueError('multi-subrow reconstruction requires a main row line-start field') + glyphs = _table_glyphs(characters, table_bbox) + if not glyphs: + return [] + anchors = {item.row_offset: _layout_anchors(item, table_bbox) for item in layouts} + max_offset = max(by_offset) + logical_rows: list[ReconstructedLogicalRow] = [] + current_fields: dict[str, str] | None = None + current_sources: list[int] = [] + continuation_offset = 0 + current_deleted = False + + def flush() -> None: + """将当前已聚合子行固化为一条逻辑明细。""" + nonlocal current_fields, current_sources, current_deleted + if current_fields is not None and current_sources: + logical_rows.append(ReconstructedLogicalRow( + role='deleted' if current_deleted else 'data', + fields=current_fields, + source_row_indices=current_sources, + )) + current_fields = None + current_sources = [] + current_deleted = False + + for row_index, band in enumerate(_group_visual_rows(glyphs)): + raw_text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip() + compact_text = re.sub(r'\s+', '', raw_text) + if _SUMMARY_PATTERN.search(raw_text): + flush() + break + if _DELETED_PATTERN.fullmatch(compact_text): + if current_fields is not None: + current_deleted = True + current_sources.append(row_index) + continue + + main_values = _band_field_values(band, anchors[0]) + line_value = re.sub(r'\s+', '', main_values.get(line_start_field_code, '')) + if _LINE_NUMBER_PATTERN.fullmatch(line_value): + flush() + current_fields = main_values + current_sources = [row_index] + continuation_offset = 0 + continue + if current_fields is None: + continue + + continuation_offset += 1 + selected_offset = continuation_offset if continuation_offset in by_offset else max_offset + values = _band_field_values(band, anchors[selected_offset]) + for field_code, value in values.items(): + previous = current_fields.get(field_code, '').strip() + current_fields[field_code] = f'{previous} {value}'.strip() + current_sources.append(row_index) + + flush() + return logical_rows + + +def _layout_anchors(layout: CoordinateSubrowLayout, table_bbox: LayoutBBox) -> list[CoordinateColumnAnchor]: + """将子行相对边界转换为当前表格绝对列区间。""" + width = table_bbox.x1 - table_bbox.x0 + return [CoordinateColumnAnchor( + column_index=index, + field_code=layout.column_field_codes[index], + bbox=LayoutBBox( + x0=table_bbox.x0 + width * layout.column_boundaries[index], y0=table_bbox.y0, + x1=table_bbox.x0 + width * layout.column_boundaries[index + 1], y1=table_bbox.y1, + ), + ) for index in range(len(layout.column_field_codes))] + + +def _band_field_values( + band: list[tuple[int, PositionedCharacter]], + anchors: list[CoordinateColumnAnchor], +) -> dict[str, str]: + """先形成独立文本片段,再以片段中心落入子行区间,避免字段在边界处被拆字。""" + values: dict[str, str] = {} + for text_run in _group_text_runs(band): + bbox = _run_bbox(text_run) + center = (bbox.x0 + bbox.x1) / 2 + candidates = [ + anchor.column_index for anchor in anchors + if anchor.bbox.x0 <= center <= anchor.bbox.x1 + ] + if len(candidates) != 1: + continue + column = candidates[0] + field_code = anchors[column].field_code + text = ''.join(glyph.text for _, glyph in text_run).strip() + if not field_code or not text: + continue + previous = values.get(field_code, '').strip() + values[field_code] = f'{previous} {text}'.strip() + return values + + +def _looks_like_header(text: str) -> bool: + """以有限英文表头词识别数据区之前的多层表头,避免把表头并入首条明细。""" + words = set(re.findall(r'[a-z]+', text.lower())) + return len(words & _HEADER_TERMS) >= 2 + + +def _band_starts_item( + band: list[tuple[int, PositionedCharacter]], table_bbox: LayoutBBox, +) -> bool: + """以左侧文本片段的行号形态识别新明细,不依赖已经配置的列边界。""" + width = table_bbox.x1 - table_bbox.x0 + for run in _group_text_runs(band): + bbox = _run_bbox(run) + relative_center = ((bbox.x0 + bbox.x1) / 2 - table_bbox.x0) / width + text = re.sub(r'\s+', '', ''.join(glyph.text for _, glyph in run)) + if relative_center <= 0.25 and _LINE_NUMBER_PATTERN.fullmatch(text): + return True + return False + + +def _suggest_band_boundaries( + bands: list[list[tuple[int, PositionedCharacter]]], + table_bbox: LayoutBBox, + *, + detect_line_number: bool, +) -> tuple[list[float], list[list[str]], int | None]: + """聚合相同 row_offset 的文本起始位置,以相邻列中心中点生成稳定相对边界。""" + width = table_bbox.x1 - table_bbox.x0 + runs: list[tuple[float, str, bool]] = [] + for band in bands: + for run in _group_text_runs(band): + bbox = _run_bbox(run) + center = max(0.0, min(1.0, ((bbox.x0 + bbox.x1) / 2 - table_bbox.x0) / width)) + text = ''.join(glyph.text for _, glyph in run).strip() + if text: + runs.append((center, text, bool(_LINE_NUMBER_PATTERN.fullmatch(re.sub(r'\s+', '', text))))) + if not runs: + return [0.0, 1.0], [[]], None + + centers: list[float] = [] + clusters: list[list[tuple[float, str, bool]]] = [] + for item in sorted(runs, key=lambda value: value[0]): + nearest = min(range(len(centers)), key=lambda index: abs(centers[index] - item[0])) if centers else None + if nearest is not None and abs(centers[nearest] - item[0]) <= 0.045: + clusters[nearest].append(item) + centers[nearest] = median(value[0] for value in clusters[nearest]) + else: + centers.append(item[0]) + clusters.append([item]) + ordered = sorted(zip(centers, clusters), key=lambda item: item[0]) + centers = [item[0] for item in ordered] + clusters = [item[1] for item in ordered] + boundaries = [0.0] + [round((left + right) / 2, 4) for left, right in zip(centers, centers[1:])] + [1.0] + column_samples = [list(dict.fromkeys(value[1] for value in cluster))[:3] for cluster in clusters] + line_column = next(( + index for index, cluster in enumerate(clusters) + if detect_line_number and any(value[2] for value in cluster) + ), None) + return boundaries, column_samples, line_column + + def _validated_anchors(raw: list[CoordinateColumnAnchor | dict[str, Any]]) -> list[CoordinateColumnAnchor]: """校验列锚点数量、排序与不重叠,防止错误表头诱导列归属。""" anchors = sorted( @@ -175,16 +497,87 @@ def _group_visual_rows(glyphs: list[tuple[int, PositionedCharacter]]) -> list[li return bands -def _assign_column(bbox: LayoutBBox, anchors: list[CoordinateColumnAnchor]) -> int | None: - """优先最大 x-overlap,只有唯一最佳候选才允许归属;中心距离仅作无重叠时的后备。""" +def _group_text_runs( + band: list[tuple[int, PositionedCharacter]], +) -> list[list[tuple[int, PositionedCharacter]]]: + """将同一视觉行的相邻字符组成文本片段,使字段格式评分可看到完整值。""" + ordered = sorted(band, key=lambda item: (item[1].bbox.x0, item[0])) + widths = [glyph.bbox.x1 - glyph.bbox.x0 for _, glyph in ordered] + gap_limit = max(2.0, median(widths) * 1.8) + runs: list[list[tuple[int, PositionedCharacter]]] = [] + for item in ordered: + if runs and item[1].bbox.x0 - runs[-1][-1][1].bbox.x1 <= gap_limit: + runs[-1].append(item) + else: + runs.append([item]) + return runs + + +def _run_bbox(run: list[tuple[int, PositionedCharacter]]) -> LayoutBBox: + """汇总文本片段 bbox,供列重叠与中心距离共同评分。""" + boxes = [glyph.bbox for _, glyph in run] + return LayoutBBox( + x0=min(item.x0 for item in boxes), y0=min(item.y0 for item in boxes), + x1=max(item.x1 for item in boxes), y1=max(item.y1 for item in boxes), + ) + + +def _assign_column( + bbox: LayoutBBox, + text: str, + anchors: list[CoordinateColumnAnchor], + *, + previous_column: int | None, +) -> int | None: + """以 x-overlap 为主,字段格式和同行从左到右顺序只辅助边界歧义。""" overlaps = [max(0.0, min(bbox.x1, item.bbox.x1) - max(bbox.x0, item.bbox.x0)) for item in anchors] best_overlap = max(overlaps) - if best_overlap > 0 and overlaps.count(best_overlap) == 1: - return anchors[overlaps.index(best_overlap)].column_index + if best_overlap > 0: + candidates = [index for index, overlap in enumerate(overlaps) if overlap >= best_overlap * 0.8] + if len(candidates) == 1: + return anchors[candidates[0]].column_index + scores = [] + for index in candidates: + adjacency = 0.0 + if previous_column is not None: + if anchors[index].column_index < previous_column: + adjacency = -1.0 + elif anchors[index].column_index in {previous_column, previous_column + 1}: + adjacency = 0.25 + scores.append( + overlaps[index] + + _field_content_score(text, anchors[index].field_code) * max(bbox.x1 - bbox.x0, 1.0) * 0.25 + + adjacency + ) + best_score = max(scores) + return anchors[candidates[scores.index(best_score)]].column_index if scores.count(best_score) == 1 else None center = (bbox.x0 + bbox.x1) / 2 distances = [abs(center - (item.bbox.x0 + item.bbox.x1) / 2) for item in anchors] nearest = min(distances) - return anchors[distances.index(nearest)].column_index if distances.count(nearest) == 1 else None + candidates = [index for index, distance in enumerate(distances) if distance == nearest] + if previous_column is not None: + ordered_candidates = [index for index in candidates if anchors[index].column_index >= previous_column] + candidates = ordered_candidates or candidates + return anchors[candidates[0]].column_index if len(candidates) == 1 else None + + +def _field_content_score(text: str, field_code: str | None) -> float: + """对固定订单字段执行有限格式评分;未知字段不影响几何归列。""" + value = str(text or '').strip() + if not value or not field_code: + return 0.0 + compact = value.replace(',', '').replace(' ', '') + if field_code == 'line_no': + return 1.0 if _LINE_NUMBER_PATTERN.fullmatch(compact) else -1.0 + if field_code in {'qty', 'unit_price', 'amount'}: + return 1.0 if re.fullmatch(r'[-+]?\d+(?:\.\d+)?', compact) else -1.0 + if field_code == 'uom': + return 1.0 if re.fullmatch(r'[A-Za-z]{1,6}', compact) else -0.5 + if field_code == 'required_date': + return 1.0 if re.fullmatch(r'\d{1,4}[-/]\d{1,2}[-/]\d{1,4}', compact) else -0.5 + if field_code in {'part_number', 'customer_part_number', 'aws_part_number'}: + return 0.75 if re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._/-]{2,}', compact) else 0.0 + return 0.0 def _cell_from_glyphs(column_index: int, glyphs: list[tuple[int, PositionedCharacter]]) -> ReconstructedCell: diff --git a/backend/app/services/shipping_notice/document_layout/order_profile.py b/backend/app/services/shipping_notice/document_layout/order_profile.py index 35fb0b3f..ba575930 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile.py @@ -3,12 +3,13 @@ backend/app/services/shipping_notice/document_layout/order_profile.py 用途:定义订单文档模板级解析 Profile 纯契约,覆盖全局 Schema 无法表达的模板列语义。 依赖:Pydantic、HTML 网格、订单字段规则和既有 TEMP 复合料号规则。 -逻辑:Profile 只在精确结构指纹命中时按固定列执行注册解析器;行结构已丢失的模板显式阻断,不做相似匹配。 +逻辑:普通 Profile 按精确表头指纹匹配;坐标 Profile 先合并物理续行并生成稳定虚拟表头,再按固定列执行注册解析器。 """ from __future__ import annotations import hashlib +import html import json import re from decimal import Decimal @@ -17,6 +18,7 @@ from typing import Any, Literal from pydantic import BaseModel, ConfigDict, Field, model_validator from app.core.errors import ValidationError +from app.services.shipping_notice.document_layout.contracts import LayoutBBox from app.services.shipping_notice.document_layout.html_table import HtmlGrid, parse_html_grid from app.services.shipping_notice.notice_line_values import parse_number from app.services.shipping_notice.notice_lines import resolve_composite_part_numbers @@ -66,6 +68,45 @@ class OrderProfileColumnRule(OrderProfileModel): return self +class CoordinateReconstructionProfile(OrderProfileModel): + """冻结管理员确认的相对列边界;同版 PDF 表格据此重建并仍受 Profile 精确指纹门禁。""" + + method: Literal['native_pdf_coordinates.v1', 'ocr_pdf_coordinates.v1'] = 'native_pdf_coordinates.v1' + column_boundaries: list[float] = Field(default_factory=list) + column_field_codes: list[str | None] = Field(default_factory=list) + line_start_column_index: int = Field(default=0, ge=0) + subrow_layouts: list[dict[str, Any]] = Field(default_factory=list) + + @model_validator(mode='after') + def validate_boundaries(self) -> 'CoordinateReconstructionProfile': + """边界须覆盖整表且严格递增,禁止由错误 HTML 反向猜列。""" + if self.subrow_layouts: + from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import CoordinateSubrowLayout + + layouts = [CoordinateSubrowLayout.model_validate(item) for item in self.subrow_layouts] + offsets = [item.row_offset for item in layouts] + roles = [item.role for item in layouts] + if len(offsets) != len(set(offsets)) or sorted(offsets) != list(range(len(offsets))) or roles.count('main') != 1: + raise ValueError('coordinate subrow layouts require contiguous offsets and one main row') + if next(item for item in layouts if item.role == 'main').row_offset != 0: + raise ValueError('coordinate main row must use offset zero') + if any(item.row_offset > 0 and item.role != 'continuation' for item in layouts): + raise ValueError('coordinate rows after the main row must be continuations') + return self + if len(self.column_boundaries) < 3: + raise ValueError('coordinate reconstruction requires column boundaries') + if self.column_boundaries[0] != 0 or self.column_boundaries[-1] != 1: + raise ValueError('coordinate reconstruction boundaries must start at 0 and end at 1') + if any(left >= right for left, right in zip(self.column_boundaries, self.column_boundaries[1:])): + raise ValueError('coordinate reconstruction boundaries must be strictly increasing') + column_count = len(self.column_boundaries) - 1 + if self.column_field_codes and len(self.column_field_codes) != column_count: + raise ValueError('coordinate reconstruction field codes must match column count') + if self.line_start_column_index >= column_count: + raise ValueError('coordinate reconstruction line start column is out of range') + return self + + class OrderDocumentProfile(OrderProfileModel): """保存不可变模板结构、列覆盖、数据起始行和质量策略。""" @@ -77,6 +118,7 @@ class OrderDocumentProfile(OrderProfileModel): data_start_row_index: int = Field(ge=1) row_structure: Literal['preserved', 'unsupported_row_structure'] = 'preserved' column_rules: list[OrderProfileColumnRule] = Field(default_factory=list) + coordinate_reconstruction: CoordinateReconstructionProfile | None = None drop_zero_qty: bool = True @model_validator(mode='after') @@ -171,6 +213,104 @@ def order_profile_structure_fingerprint( return hashlib.sha256(encoded).hexdigest() +def reconstruct_order_profile_html( + *, characters: list[dict[str, Any]], table_bbox: dict[str, Any], + reconstruction: CoordinateReconstructionProfile, +) -> str: + """ + 利用冻结坐标证据生成带稳定虚拟表头的逻辑明细 HTML。 + + 核心逻辑:先按 x/y 重建物理行,再将 continuation 按列并入最近 data 行;deleted + 回写最近明细状态,summary 终止数据区。虚拟表头只表达列序,不依赖数据页表头是否完整。 + + Args: + characters: 当前表格 bbox 内的原生或 OCR 字符坐标。 + table_bbox: 当前表格页面坐标。 + reconstruction: 管理员确认的相对列边界。 + Returns: + 可由既有 Profile 解析器消费的 HTML;行角色保存在 ``data-row-role`` 属性中。 + """ + from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import ( + CoordinateColumnAnchor, + reconstruct_multi_subrow_table, + reconstruct_table_from_positioned_text, + ) + + bbox = LayoutBBox.model_validate(table_bbox) + if reconstruction.subrow_layouts: + logical_rows = reconstruct_multi_subrow_table( + characters=characters, + table_bbox=bbox, + subrow_layouts=reconstruction.subrow_layouts, + ) + field_codes = [] + for layout in reconstruction.subrow_layouts: + for code in layout.get('column_field_codes') or []: + if code and code not in field_codes: + field_codes.append(code) + header = '' + ''.join( + f'{html.escape(code)}' for code in field_codes + ) + '' + body = ''.join( + '{}'.format( + row.role, ','.join(str(index) for index in row.source_row_indices), + ''.join(f'{html.escape(row.fields.get(code, ""))}' for code in field_codes), + ) + for row in logical_rows + ) + return f'{header}{body}
' + boundaries = reconstruction.column_boundaries + width = bbox.x1 - bbox.x0 + anchors = [CoordinateColumnAnchor( + column_index=index, + field_code=(reconstruction.column_field_codes[index] if reconstruction.column_field_codes else None), + bbox=LayoutBBox( + x0=bbox.x0 + width * boundaries[index], y0=bbox.y0, + x1=bbox.x0 + width * boundaries[index + 1], y1=bbox.y1, + ), + ) for index in range(len(boundaries) - 1)] + result = reconstruct_table_from_positioned_text( + characters=characters, table_bbox=bbox, column_anchors=anchors, + line_start_column_index=reconstruction.line_start_column_index, + ) + if not result.rows: + raise ValidationError( + 'No coordinate reconstruction rows were produced', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE', + ) + logical_rows: list[dict[str, Any]] = [] + for row in result.rows: + values = {cell.column_index: cell.text for cell in row.cells} + if row.role == 'data': + logical_rows.append({'role': 'data', 'values': values, 'source_rows': [row.row_index]}) + elif row.role == 'continuation' and logical_rows: + current = logical_rows[-1] + for column_index, value in values.items(): + previous = str(current['values'].get(column_index) or '').strip() + current['values'][column_index] = f'{previous} {value}'.strip() + current['source_rows'].append(row.row_index) + elif row.role == 'deleted' and logical_rows: + logical_rows[-1]['role'] = 'deleted' + logical_rows[-1]['source_rows'].append(row.row_index) + elif row.role == 'summary': + break + + header = '' + ''.join( + f'coordinate_column_{index + 1}' for index in range(len(anchors)) + ) + '' + body = ''.join( + '{}'.format( + row['role'], ','.join(str(index) for index in row['source_rows']), + ''.join( + f'{html.escape(str(row["values"].get(index, "")))}' + for index in range(len(anchors)) + ), + ) + for row in logical_rows + ) + return f'{header}{body}
' + + def parse_html_table_with_order_profile( html: str, *, @@ -210,15 +350,19 @@ def parse_html_table_with_order_profile( profile_version=profile.version, issues=['order_profile_column_out_of_range'], ) + row_roles = _profile_html_row_roles(html) rows = [ _parse_profile_row( grid, row_index=index, profile=profile, contract=contract, + source_role=row_roles[index] if index < len(row_roles) else 'data', ) for index in range(profile.data_start_row_index, grid.row_count) ] + if not rows: + return OrderProfileParseResult(matched=False) return OrderProfileParseResult( matched=True, profile_code=profile.profile_code, @@ -233,8 +377,9 @@ def _parse_profile_row( row_index: int, profile: OrderDocumentProfile, contract: TableHeaderContract, + source_role: str = 'data', ) -> OrderProfileRowResult: - """执行一条 preserved 模板行;零 Qty 删除,非法字段保留机器问题码。""" + """执行一条逻辑模板行;坐标重建删除状态和零 Qty 均映射为 deleted。""" fields: dict[str, Any] = {} issues: list[str] = [] explicit_qty: float | None = None @@ -258,7 +403,7 @@ def _parse_profile_row( issues.append(f'order_profile_field_invalid:{code}') continue fields[code] = _profile_json_value(value) - if profile.drop_zero_qty and explicit_qty == 0: + if source_role == 'deleted' or (profile.drop_zero_qty and explicit_qty == 0): return OrderProfileRowResult(row_index=row_index, status='deleted') required_build = {'part_number', 'qty'} if not required_build.issubset(fields): @@ -271,6 +416,16 @@ def _parse_profile_row( ) +def _profile_html_row_roles(source_html: str) -> list[str]: + """读取坐标重建写入的受控行角色;普通 MinerU HTML 默认按 data 处理。""" + from bs4 import BeautifulSoup + + table = BeautifulSoup(source_html or '', 'html.parser').find('table') + if table is None: + return [] + return [str(row.get('data-row-role') or 'data') for row in table.find_all('tr')] + + def _apply_profile_extractor(extractor_key: str, raw: str) -> dict[str, Any]: """执行代码注册的有限解析器;未知 key 不允许运行。""" if extractor_key == 'temp_internal_parts': @@ -289,11 +444,16 @@ def _apply_profile_extractor(extractor_key: str, raw: str) -> dict[str, Any]: def _normalize_profile_value(raw: Any, config: dict[str, Any] | None) -> Any: - """按冻结 Schema 类型和 validator 规范化模板字段;非法值返回 None。""" + """按冻结 Schema 类型和 validator 规范化模板字段;模板日期兼容常见美式订单格式。""" if config is None: return None value_type = str(config.get('value_type') or 'string') candidate = raw + if value_type == 'date': + text = str(raw or '').strip() + matched = re.fullmatch(r'(\d{1,2})/(\d{1,2})/(\d{4})', text) + if matched: + candidate = f'{matched.group(3)}-{int(matched.group(1)):02d}-{int(matched.group(2)):02d}' if value_type in {'decimal', 'integer'}: candidate = parse_number(raw) if candidate is None: diff --git a/backend/app/services/shipping_notice/document_layout/runtime.py b/backend/app/services/shipping_notice/document_layout/runtime.py index f390fe8e..dc873bbd 100644 --- a/backend/app/services/shipping_notice/document_layout/runtime.py +++ b/backend/app/services/shipping_notice/document_layout/runtime.py @@ -167,6 +167,7 @@ def build_mineru_table_snapshot( try: from app.services.shipping_notice.document_layout.native_pdf import ( build_native_pdf_layout_candidate, + extract_native_pdf_pages, ) layout = build_native_pdf_layout_candidate( @@ -174,6 +175,10 @@ def build_mineru_table_snapshot( content=content, mineru=candidate, ) snapshot['layout_candidate'] = layout.model_dump(mode='json') + # 仅保存表格范围内的原生字符坐标,供管理员确认后的坐标模板在 Run 冻结快照中复现。 + snapshot['coordinate_evidence'] = _table_coordinate_evidence( + content=content, tables=tables, + ) except Exception: snapshot['issues'] = sorted(set( list(snapshot['issues']) + ['native_pdf_layout_candidate_invalid'], @@ -181,6 +186,34 @@ def build_mineru_table_snapshot( return snapshot +def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]]) -> dict[str, Any]: + """按 MinerU 整表 bbox 截取 PDF 字符证据;非表格正文与页面图像绝不持久化。""" + from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages + + pages = {item.page_no: item for item in extract_native_pdf_pages(content)} + evidence: dict[str, list[dict[str, Any]]] = {} + for table in tables: + table_id = str(table.get('table_id') or '') + raw_bbox = table.get('bbox') + page = pages.get(int(table.get('page_no') or 0)) + if not table_id or page is None or not isinstance(raw_bbox, dict): + continue + try: + x0, y0 = float(raw_bbox['x0']), float(raw_bbox['y0']) + x1, y1 = float(raw_bbox['x1']), float(raw_bbox['y1']) + except (KeyError, TypeError, ValueError): + continue + glyphs = [] + for item in page.characters: + center_x = (item.bbox.x0 + item.bbox.x1) / 2 + center_y = (item.bbox.y0 + item.bbox.y1) / 2 + if x0 <= center_x <= x1 and y0 <= center_y <= y1: + glyphs.append(item.model_dump(mode='json')) + if glyphs: + evidence[table_id] = glyphs + return {'version': 'shipping_order_coordinate_evidence.v1', 'tables': evidence} + + def attach_mineru_layout_snapshots(result: Any, *, root_asset_bytes: bytes | None = None) -> None: """就地为 NoticeIntakeResult 的根文件或 EML 附件补充布局快照,失败不阻断文本解析。""" meta = result.meta if isinstance(getattr(result, 'meta', None), dict) else {} diff --git a/backend/app/services/shipping_notice/document_profile_quality_service.py b/backend/app/services/shipping_notice/document_profile_quality_service.py index fc0c00a7..f309ca75 100644 --- a/backend/app/services/shipping_notice/document_profile_quality_service.py +++ b/backend/app/services/shipping_notice/document_profile_quality_service.py @@ -22,7 +22,10 @@ from app.models import ( ) from app.services.shipping_notice.document_layout.html_table import parse_html_grid from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot -from app.services.shipping_notice.document_layout.order_profile import parse_html_table_with_order_profile +from app.services.shipping_notice.document_layout.order_profile import ( + parse_html_table_with_order_profile, + reconstruct_order_profile_html, +) from app.services.shipping_notice.order_document_profile_service import _definition_contract from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract @@ -109,8 +112,25 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]: failures: list[str] = [] passed = 0 for sample in suite.samples: + html = _table_html(sample.document_id, sample.table_id) + if parser.coordinate_reconstruction is not None: + document = db.session.get(ShippingNoticeDocument, sample.document_id) + layout = current_layout_snapshot(document) if document is not None else None + raw_table = next(( + item for item in (layout or {}).get('tables') or [] + if isinstance(item, dict) and str(item.get('table_id') or '') == sample.table_id + ), None) + evidence = (layout or {}).get('coordinate_evidence') if isinstance((layout or {}).get('coordinate_evidence'), dict) else {} + characters = (evidence.get('tables') or {}).get(sample.table_id) if isinstance(evidence.get('tables'), dict) else None + if not isinstance(raw_table, dict) or not isinstance(raw_table.get('bbox'), dict) or not isinstance(characters, list): + failures.append(f'sample:{sample.id}:coordinate_evidence_missing') + continue + html = reconstruct_order_profile_html( + characters=[item for item in characters if isinstance(item, dict)], + table_bbox=raw_table['bbox'], reconstruction=parser.coordinate_reconstruction, + ) parsed = parse_html_table_with_order_profile( - _table_html(sample.document_id, sample.table_id), table_id=sample.table_id, + html, table_id=sample.table_id, profile=parser, contract=contract, ) actual = [dict(row.fields) for row in parsed.rows if row.status == 'parsed'] diff --git a/backend/app/services/shipping_notice/duplicate_detection.py b/backend/app/services/shipping_notice/duplicate_detection.py index 0bfc3dc3..c3d8e387 100644 --- a/backend/app/services/shipping_notice/duplicate_detection.py +++ b/backend/app/services/shipping_notice/duplicate_detection.py @@ -20,6 +20,7 @@ from app.models import ( ShippingNoticeCandidate, ShippingNoticeDocument, ShippingNoticeIntake, + ShippingOrderSnapshot, ShippingTask, ) from app.services.shipping_notice.business_fingerprint import ( @@ -28,6 +29,7 @@ from app.services.shipping_notice.business_fingerprint import ( build_business_fingerprint, build_content_fingerprint, ) +from app.services.shipping_notice.reservation_id import validated_reservation_id # 与 state_machine 主路径对齐的活跃/完成/关闭态(禁止 needs_review/matching/export_ready 等非主状态) _ACTIVE_PROCESS_STATUSES = frozenset( @@ -82,6 +84,36 @@ def _match_payload(task: ShippingTask, *, match_type: str, matched_fields: list[ } +def _reservation_differences(task: ShippingTask, summary: dict[str, Any]) -> list[dict[str, Any]]: + """比较候选与目标冻结订单的同 Reservation 行,供人工修订确认前展示。""" + snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None + if snapshot is None: + return [] + proposed = { + validated_reservation_id(str(line.get('reservation_id') or '')): line + for line in summary.get('lines') or [] + if isinstance(line, dict) and validated_reservation_id(str(line.get('reservation_id') or '')) + } + differences: list[dict[str, Any]] = [] + for line in snapshot.lines: + reservation_id = validated_reservation_id(line.reservation_id) + candidate_line = proposed.get(reservation_id) + if not reservation_id or candidate_line is None: + continue + previous = {'part_number': str(line.part_number or '').strip(), 'qty': str(line.qty)} + proposed_value = { + 'part_number': str(candidate_line.get('part_number') or '').strip(), + 'qty': str(candidate_line.get('qty') or '').strip(), + } + if previous != proposed_value: + differences.append({ + 'reservation_id': reservation_id, + 'previous': previous, + 'proposed': proposed_value, + }) + return differences + + def _allowed_actions_for( *, status: str, @@ -245,6 +277,10 @@ def detect_duplicates_for_intake( } if strength == 'unavailable' and status == 'none': blocking = False + for match in matches: + task = db.session.query(ShippingTask).filter_by(task_no=match['task_no']).one_or_none() + if task is not None: + match['reservation_differences'] = _reservation_differences(task, summary) return { 'status': status, @@ -569,6 +605,10 @@ def detect_duplicates_for_candidate( } if strength == 'unavailable' and status == 'none': blocking = False + for match in matches: + task = db.session.query(ShippingTask).filter_by(task_no=match['task_no']).one_or_none() + if task is not None: + match['reservation_differences'] = _reservation_differences(task, summary) return { 'status': status, diff --git a/backend/app/services/shipping_notice/fulfillment_policy_registry.py b/backend/app/services/shipping_notice/fulfillment_policy_registry.py new file mode 100644 index 00000000..55d3a495 --- /dev/null +++ b/backend/app/services/shipping_notice/fulfillment_policy_registry.py @@ -0,0 +1,204 @@ +""" +services/shipping_notice/fulfillment_policy_registry.py + +用途:管理货代字段能力绑定与版本化滚动履约策略。 +依赖:订单 Schema、履约策略模型与统一 AppError。 +逻辑:策略使用稳定 field_id 绑定货代能力;冻结只消费当前 published 策略,历史 Snapshot 保存完整策略事实。 +""" + +from __future__ import annotations + +import hashlib +import json +from datetime import datetime +from typing import Any + +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.extensions import db +from app.models import ShippingFulfillmentPolicy, ShippingOrderField, ShippingOrderSchema, ShippingOrderSchemaVersion + + +SHIP_AVAILABLE_ROLLING_V1 = 'SHIP_AVAILABLE_ROLLING_V1' +_CAPABILITIES = { + 'fulfillment.reservation_identity': {'scope': 'line', 'value_type': 'string', 'required': True}, + 'fulfillment.part_number': {'scope': 'line', 'value_type': 'string', 'required': True}, + 'fulfillment.quantity': {'scope': 'line', 'value_type': 'decimal', 'required': True}, + 'routing.inventory_source_hint': {'scope': 'line', 'value_type': 'string', 'required': False}, +} +_REQUIRED_CAPABILITIES = frozenset({ + 'fulfillment.reservation_identity', 'fulfillment.part_number', 'fulfillment.quantity', +}) +_CANONICAL_FIELD_CODES = { + 'fulfillment.reservation_identity': 'reservation_id', + 'fulfillment.part_number': 'part_number', + 'fulfillment.quantity': 'qty', + 'routing.inventory_source_hint': 'inventory_source_hint', +} + + +def capability_catalog() -> list[dict[str, Any]]: + """返回货代专用能力目录;管理员不能配置自由代码、SQL 或脚本。""" + return [{'capability_code': code, **spec} for code, spec in sorted(_CAPABILITIES.items())] + + +def _schema() -> ShippingOrderSchema: + schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none() + if schema is None: + raise NotFoundError('Shipping order schema is not initialized', code='SHIPPING.ORDER_SCHEMA_NOT_FOUND') + return schema + + +def _checksum(definition: dict[str, Any]) -> str: + """为策略定义计算稳定摘要,供冻结与审计比对。""" + return hashlib.sha256(json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()).hexdigest() + + +def _field_bindings(raw: Any, *, schema_id: int) -> list[dict[str, Any]]: + """校验能力与稳定 field_id 的一对一绑定,拒绝 scope/type 漂移。""" + if not isinstance(raw, list): + raise ValidationError('field_bindings must be a list', code='SHIPPING.FULFILLMENT_POLICY_INVALID') + seen_capabilities: set[str] = set() + seen_fields: set[str] = set() + bindings: list[dict[str, Any]] = [] + for item in raw: + if not isinstance(item, dict): + raise ValidationError('field binding is invalid', code='SHIPPING.FULFILLMENT_POLICY_INVALID') + capability = str(item.get('capability_code') or '').strip() + field_id = str(item.get('field_id') or '').strip() + spec = _CAPABILITIES.get(capability) + field = db.session.get(ShippingOrderField, field_id) if field_id else None + if ( + spec is None or field is None or field.schema_id != schema_id or field.status != 'active' + or field.scope != spec['scope'] or field.value_type != spec['value_type'] + or capability in seen_capabilities or field_id in seen_fields + ): + raise ValidationError('field capability binding is invalid', code='SHIPPING.FULFILLMENT_POLICY_INVALID') + seen_capabilities.add(capability) + seen_fields.add(field_id) + bindings.append({ + 'capability_code': capability, + 'field_id': field.id, + 'field_code': field.field_code, + 'scope': field.scope, + 'value_type': field.value_type, + }) + if _REQUIRED_CAPABILITIES - seen_capabilities: + raise ValidationError( + 'required fulfillment capability bindings are missing', + code='SHIPPING.FULFILLMENT_POLICY_INVALID', + details={'capabilities': sorted(_REQUIRED_CAPABILITIES - seen_capabilities)}, + ) + return sorted(bindings, key=lambda item: item['capability_code']) + + +def _definition(raw: dict[str, Any], *, schema_id: int) -> dict[str, Any]: + """生成可发布的受控策略定义,策略仅支持滚动发货语义。""" + policy_code = str(raw.get('policy_code') or SHIP_AVAILABLE_ROLLING_V1).strip() + if policy_code != SHIP_AVAILABLE_ROLLING_V1: + raise ValidationError('unsupported fulfillment policy', code='SHIPPING.FULFILLMENT_POLICY_INVALID') + return { + 'policy_code': policy_code, + 'fulfillment_mode': 'ship_available_rolling', + 'requires_confirmed_customer': True, + 'allows_partial_reservation': False, + 'field_bindings': _field_bindings(raw.get('field_bindings'), schema_id=schema_id), + } + + +def _payload(policy: ShippingFulfillmentPolicy) -> dict[str, Any]: + """序列化策略版本,前端只能拿到已验证定义与版本状态。""" + return { + 'id': policy.id, 'policy_code': policy.policy_code, 'version': policy.version, 'status': policy.status, + 'definition': dict(policy.definition_json or {}), 'checksum': policy.checksum, + 'lock_version': policy.lock_version, 'change_note': policy.change_note, + 'published_at': policy.published_at.isoformat() if policy.published_at else None, + } + + +def get_state() -> dict[str, Any]: + """读取货代履约策略管理状态及当前发布版本。""" + schema = _schema() + policies = ShippingFulfillmentPolicy.query.filter_by(schema_id=schema.id).order_by(ShippingFulfillmentPolicy.version.desc()).all() + return {'capabilities': capability_catalog(), 'policies': [_payload(item) for item in policies]} + + +def create_draft(raw: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """创建下一策略草稿;未发布策略不得参与冻结。""" + schema = _schema() + latest = db.session.query(ShippingFulfillmentPolicy.version).filter_by(schema_id=schema.id).order_by(ShippingFulfillmentPolicy.version.desc()).first() + definition = _definition(raw, schema_id=schema.id) + policy = ShippingFulfillmentPolicy( + schema_id=schema.id, policy_code=definition['policy_code'], version=(int(latest[0]) + 1 if latest else 1), + definition_json=definition, change_note=str(raw.get('change_note') or '').strip() or None, created_by_id=actor_id, + ) + db.session.add(policy) + db.session.commit() + return _payload(policy) + + +def publish(policy_id: int, *, actor_id: int | None, expected_lock_version: int | None) -> dict[str, Any]: + """发布策略并退役旧版本;策略字段必须存在于当前发布 Schema。""" + policy = db.session.get(ShippingFulfillmentPolicy, policy_id) + if policy is None: + raise NotFoundError('Fulfillment policy not found', code='SHIPPING.FULFILLMENT_POLICY_NOT_FOUND') + if policy.status != 'draft' or expected_lock_version != policy.lock_version: + raise ConflictError('Fulfillment policy has changed', code='SHIPPING.FULFILLMENT_POLICY_CONFLICT') + definition = _definition(dict(policy.definition_json or {}), schema_id=policy.schema_id) + published_schema = ShippingOrderSchemaVersion.query.filter_by( + schema_id=policy.schema_id, status='published', + ).one_or_none() + if published_schema is not None: + enabled_field_ids = { + str(config.get('field_id')) + for config in (published_schema.definition_json or {}).get('fields') or [] + if config.get('enabled', True) + } + missing_field_ids = sorted( + str(binding['field_id']) + for binding in definition['field_bindings'] + if str(binding['field_id']) not in enabled_field_ids + ) + if missing_field_ids: + raise ValidationError( + 'Fulfillment policy fields must be included in the published schema', + code='SHIPPING.FULFILLMENT_POLICY_INVALID', + details={'field_ids': missing_field_ids}, + ) + current = ShippingFulfillmentPolicy.query.filter_by(schema_id=policy.schema_id, status='published').one_or_none() + now = datetime.utcnow() + if current is not None: + current.status, current.retired_at = 'retired', now + policy.definition_json = definition + policy.checksum = _checksum(definition) + policy.status, policy.published_by_id, policy.published_at = 'published', actor_id, now + db.session.commit() + return _payload(policy) + + +def published_policy() -> ShippingFulfillmentPolicy: + """取得当前可执行策略;没有发布版本时 fail closed。""" + schema = _schema() + policy = ShippingFulfillmentPolicy.query.filter_by(schema_id=schema.id, status='published').one_or_none() + if policy is None: + raise ConflictError('No published fulfillment policy', code='SHIPPING.FULFILLMENT_POLICY_NOT_PUBLISHED') + return policy + + +def required_field_configs(definition: dict[str, Any], policy: ShippingFulfillmentPolicy) -> dict[str, dict[str, Any]]: + """把已发布策略的能力绑定解析为冻结字段配置,并拒绝 Schema 版本漂移。""" + by_id = {str(item.get('field_id')): item for item in definition.get('fields') or [] if item.get('enabled', True)} + selected: dict[str, dict[str, Any]] = {} + bound_capabilities: set[str] = set() + for binding in (policy.definition_json or {}).get('field_bindings') or []: + capability = str(binding.get('capability_code') or '') + config = by_id.get(str(binding.get('field_id') or '')) + spec = _CAPABILITIES.get(capability) + if config is None and spec is not None and not spec['required']: + continue + if config is None or spec is None or config.get('scope') != spec['scope'] or config.get('value_type') != spec['value_type']: + raise ValidationError('Frozen order schema does not satisfy the fulfillment policy', code='SHIPPING.ORDER_CONTRACT_INVALID') + selected[_CANONICAL_FIELD_CODES[capability]] = config + bound_capabilities.add(capability) + if _REQUIRED_CAPABILITIES - bound_capabilities: + raise ValidationError('Fulfillment policy bindings are incomplete', code='SHIPPING.ORDER_CONTRACT_INVALID') + return selected diff --git a/backend/app/services/shipping_notice/order_document_profile_service.py b/backend/app/services/shipping_notice/order_document_profile_service.py index a1a2c15c..43af1a9c 100644 --- a/backend/app/services/shipping_notice/order_document_profile_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_service.py @@ -19,17 +19,22 @@ from sqlalchemy import func from app.core.errors import ConflictError, NotFoundError, ValidationError from app.extensions import db from app.models import ( + FileAsset, + ShippingDocumentProfileTestSample, ShippingNoticeDocument, ShippingNoticeIntake, ShippingOrderDocumentProfile, ShippingOrderSchemaVersion, ) from app.services.shipping_notice.document_layout.html_table import parse_html_grid +from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import suggest_multi_subrow_layouts from app.services.shipping_notice.document_layout.order_profile import ( + CoordinateReconstructionProfile, OrderDocumentProfile, OrderProfileColumnRule, diagnose_order_profile_header, order_profile_structure_fingerprint, + reconstruct_order_profile_html, ) @@ -72,7 +77,15 @@ def _require_schema_version(raw_id: Any) -> ShippingOrderSchemaVersion: def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersion) -> dict[str, Any]: - """校验纯 Profile 契约并把每个目标字段冻结为 field_id + field_code。""" + """ + 校验 Profile 契约、冻结字段 ID,并确保坐标辅助规则与实际列映射一致。 + + Args: + raw: 管理端提交的模板定义;禁止信任浏览器生成的字段辅助数组。 + schema_version: 当前模板绑定的不可变订单字段版本。 + Returns: + 可持久化的标准定义;坐标列字段和新行列均由列规则重新计算。 + """ if not isinstance(raw, dict): raise ValidationError( 'Order profile definition must be an object', @@ -104,6 +117,56 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio for code in rule.target_field_codes ], }) + raw_reconstruction = raw.get('coordinate_reconstruction') + if isinstance(raw_reconstruction, dict): + raw_subrows = raw_reconstruction.get('subrow_layouts') + if isinstance(raw_subrows, list) and raw_subrows: + normalized_subrows: list[dict[str, Any]] = [] + output_field_codes: list[str] = [] + for raw_subrow in raw_subrows: + if not isinstance(raw_subrow, dict): + raise ValidationError( + 'Coordinate subrow layout is invalid', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID', + ) + codes = raw_subrow.get('column_field_codes') + if not isinstance(codes, list) or any( + code is not None and str(code).strip() not in fields for code in codes + ): + raise ValidationError( + 'Coordinate subrow target field is unavailable', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID', + ) + normalized_subrows.append({ + **raw_subrow, + 'column_field_codes': [str(code).strip() if code is not None else None for code in codes], + }) + for code in codes: + normalized = str(code).strip() if code is not None else '' + if normalized and normalized not in output_field_codes: + output_field_codes.append(normalized) + normalized_rules = [{ + **OrderProfileColumnRule( + column_index=index, extractor_key='direct', target_field_codes=[code], + ).model_dump(), + 'target_fields': [{'field_id': str(fields[code]['field_id']), 'field_code': code}], + } for index, code in enumerate(output_field_codes)] + raw_reconstruction = {**raw_reconstruction, 'subrow_layouts': normalized_subrows} + else: + column_count = len(raw_reconstruction.get('column_boundaries') or []) - 1 + field_codes: list[str | None] = [None] * max(column_count, 0) + for rule in normalized_rules: + column_index = int(rule['column_index']) + if column_index < len(field_codes): + field_codes[column_index] = str(rule['target_field_codes'][0]) + line_start_column_index = next( + (index for index, code in enumerate(field_codes) if code == 'line_no'), 0, + ) + raw_reconstruction = { + **raw_reconstruction, + 'column_field_codes': field_codes, + 'line_start_column_index': line_start_column_index, + } try: contract = OrderDocumentProfile( profile_code='VALIDATION_PROFILE', @@ -115,6 +178,7 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio column_rules=[OrderProfileColumnRule(**{ key: value for key, value in item.items() if key != 'target_fields' }) for item in normalized_rules], + coordinate_reconstruction=raw_reconstruction, drop_zero_qty=raw.get('drop_zero_qty', True), ) except (TypeError, ValueError) as exc: @@ -128,6 +192,10 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio 'data_start_row_index': contract.data_start_row_index, 'row_structure': contract.row_structure, 'column_rules': normalized_rules, + 'coordinate_reconstruction': ( + contract.coordinate_reconstruction.model_dump() + if contract.coordinate_reconstruction else None + ), 'drop_zero_qty': contract.drop_zero_qty, } @@ -145,6 +213,7 @@ def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderDocument column_rules=[OrderProfileColumnRule(**{ key: value for key, value in rule.items() if key != 'target_fields' }) for rule in definition.get('column_rules') or [] if isinstance(rule, dict)], + coordinate_reconstruction=definition.get('coordinate_reconstruction'), drop_zero_qty=definition.get('drop_zero_qty', True), ) @@ -194,6 +263,102 @@ def _document_layout(document: ShippingNoticeDocument) -> dict[str, Any]: return layout +def _coordinate_characters(layout: dict[str, Any], table_id: str) -> list[dict[str, Any]]: + """读取当前布局冻结的整表原生字符;向浏览器只返回重建后的网格,不泄露坐标。""" + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {} + characters = tables.get(table_id) if isinstance(tables.get(table_id), list) else [] + return [item for item in characters if isinstance(item, dict)] + + +def generate_ocr_coordinate_evidence(*, document_id: int, table_id: str, actor_id: int | None) -> dict[str, Any]: + """为无文字层 PDF 的指定表格生成 OCR 坐标证据;仅管理员审核后的模板可使用。""" + document = db.session.get(ShippingNoticeDocument, int(document_id)) + if document is None or not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'): + raise ValidationError('OCR coordinate reconstruction requires a PDF sample', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') + layout = _document_layout(document) + raw_table = next(( + item for item in layout.get('tables') or [] + if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id or '').strip() + ), None) + if raw_table is None or not isinstance(raw_table.get('bbox'), dict): + raise ValidationError('Selected sample table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') + asset = db.session.get(FileAsset, document.asset_id) + if asset is None: + raise ValidationError('Sample file is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') + from app.services.file_assets.service import read_asset_bytes + from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot + from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages + from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines + + try: + page = next( + item for item in extract_native_pdf_pages(read_asset_bytes(asset)) + if item.page_no == int(raw_table.get('page_no') or 0) + ) + lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height) + characters = _ocr_lines_to_characters(lines=lines, table_bbox=raw_table['bbox']) + except Exception as exc: + raise ValidationError('OCR coordinate reconstruction is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc + if not characters: + raise ValidationError('OCR found no usable table text', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') + next_snapshot = dict(layout) + evidence = dict(next_snapshot.get('coordinate_evidence') or {}) + evidence_tables = dict(evidence.get('tables') or {}) + evidence_tables[str(raw_table['table_id'])] = characters + next_snapshot['coordinate_evidence'] = { + 'version': 'shipping_order_coordinate_evidence.v1', 'tables': evidence_tables, + 'sources': {**dict(evidence.get('sources') or {}), str(raw_table['table_id']): 'ocr'}, + } + next_snapshot['issues'] = sorted(set(list(next_snapshot.get('issues') or []) + ['coordinate_evidence_ocr_needs_review'])) + record_inline_layout_snapshot( + document, next_snapshot, + parser_key='mineru-pipeline+rapidocr:shipping_order_coordinate_evidence.v1', + ) + db.session.commit() + return {'document_id': document.id, 'table_id': str(raw_table['table_id']), 'source': 'ocr'} + + +def _ocr_lines_to_characters(*, lines: list[Any], table_bbox: dict[str, Any]) -> list[dict[str, Any]]: + """把 OCR 行等宽拆为字符坐标并限制在整表范围;OCR 误差继续由人工审核兜底。""" + bbox = table_bbox + result: list[dict[str, Any]] = [] + source_index = 0 + for line in lines: + text = str(line.text or '').strip() + line_bbox = line.bbox + if not text or not (bbox['x0'] <= (line_bbox.x0 + line_bbox.x1) / 2 <= bbox['x1'] and bbox['y0'] <= (line_bbox.y0 + line_bbox.y1) / 2 <= bbox['y1']): + continue + width = (line_bbox.x1 - line_bbox.x0) / len(text) + for index, character in enumerate(text): + if not character.strip(): + continue + result.append({'text': character, 'source_index': source_index, 'bbox': { + 'x0': line_bbox.x0 + index * width, 'y0': line_bbox.y0, + 'x1': line_bbox.x0 + (index + 1) * width, 'y1': line_bbox.y1, + }}) + source_index += 1 + return result + + +def _reconstructed_table_html(*, layout: dict[str, Any], raw_table: dict[str, Any], raw_settings: Any) -> str: + """从持久化坐标证据和管理员确认的边界生成可审核重建表,缺任一条件均拒绝。""" + try: + settings = CoordinateReconstructionProfile.model_validate(raw_settings) + except (TypeError, ValueError) as exc: + raise ValidationError('Coordinate reconstruction settings are invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID') from exc + table_id = str(raw_table.get('table_id') or '') + characters = _coordinate_characters(layout, table_id) + if not characters or not isinstance(raw_table.get('bbox'), dict): + raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') + try: + return reconstruct_order_profile_html( + characters=characters, table_bbox=raw_table['bbox'], reconstruction=settings, + ) + except (TypeError, ValueError) as exc: + raise ValidationError('Coordinate reconstruction could not produce a table', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID') from exc + + def list_sample_documents(*, limit: int = 50) -> list[dict[str, Any]]: """列出最近含 ready MinerU 表格的订单附件;不返回正文、HTML 或原始布局。""" safe_limit = max(1, min(int(limit), 100)) @@ -212,21 +377,93 @@ def list_sample_documents(*, limit: int = 50) -> list[dict[str, Any]]: tables = layout.get('tables') if isinstance(layout.get('tables'), list) else [] if layout.get('status') != 'ready' or not tables: continue + intake = db.session.get(ShippingNoticeIntake, document.intake_id) + if intake is None: + continue + is_template_sample = intake.purpose == 'order_document_profile_sample' + is_test_sample = ShippingDocumentProfileTestSample.query.filter_by(document_id=document.id).first() is not None result.append({ 'document_id': document.id, 'intake_id': document.intake_id, - 'filename': document.filename, + 'intake_no': intake.intake_no, + 'filename': document.filename, 'content_hash': document.content_hash, 'provider': layout.get('provider'), 'provider_version': layout.get('provider_version'), 'table_count': len(tables), 'created_at': document.created_at.isoformat() if document.created_at else None, + 'purpose': intake.purpose, + 'parse_status': intake.parse_status, + 'is_template_sample': is_template_sample, + 'can_delete': is_template_sample and not is_test_sample, + 'delete_block_reason': ( + 'blind_test_referenced' if is_template_sample and is_test_sample else None + ), }) if len(result) >= safe_limit: break return result +def delete_sample_intake(intake_no: str, *, actor_id: int | None) -> None: + """删除管理员自己的专用模板样本;业务附件、解析中样本和盲测证据一律保留。""" + if actor_id is None: + raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') + intake = ShippingNoticeIntake.query.filter_by( + intake_no=str(intake_no or '').strip().upper(), user_id=int(actor_id), + purpose='order_document_profile_sample', + ).first() + if intake is None: + raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') + if intake.parse_status != 'parsed': + raise ConflictError( + 'Template sample is still being parsed', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED', + ) + + documents = ShippingNoticeDocument.query.filter_by(intake_id=intake.id).all() + document_ids = [document.id for document in documents] + if document_ids and ShippingDocumentProfileTestSample.query.filter( + ShippingDocumentProfileTestSample.document_id.in_(document_ids), + ).first() is not None: + raise ConflictError( + 'Template sample is referenced by a blind test', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED', + ) + + # Intake creation owns exactly one root-asset reference. Do not delete files shared by another flow. + asset = db.session.get(FileAsset, intake.asset_id) + asset_ids = {int(asset.id)} if asset is not None else set() + asset_ids.update(int(document.asset_id) for document in documents if document.asset_id) + assets = [db.session.get(FileAsset, asset_id) for asset_id in sorted(asset_ids)] + if asset is None or int(asset.reference_count or 0) != 1 or any( + item is None or (item.id != asset.id and int(item.reference_count or 0) != 1) + for item in assets + ): + raise ConflictError( + 'Template sample asset is referenced elsewhere', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED', + ) + for document in documents: + db.session.delete(document) + db.session.flush() + db.session.delete(intake) + db.session.flush() + for item in assets: + if item is not None: + item.reference_count = 0 + item.lifecycle_status = 'temporary' + item.expires_at = None + db.session.commit() + + # Storage deletion is delegated to the established asset lifecycle service after FK rows are gone. + from app.services.file_assets.service import delete_temporary_asset + + for item in assets: + if item is not None: + delete_temporary_asset(asset_no=item.asset_no, user_id=int(actor_id)) + + def create_sample_intake(*, asset_no: str, actor_id: int | None) -> dict[str, Any]: """从模板页已上传的私有 PDF/EML 创建隔离样本 Intake,不生成履约业务数据。""" if actor_id is None: @@ -290,6 +527,8 @@ def get_sample_tables(document_id: int) -> dict[str, Any]: ], 'issues': issues, 'profile_creation_allowed': not issues, + 'coordinate_reconstruction_available': bool(_coordinate_characters(layout, table_id)) and isinstance(raw.get('bbox'), dict), + 'ocr_coordinate_reconstruction_available': not bool(_coordinate_characters(layout, table_id)) and bool(document.asset_id) and str(document.filename or '').lower().endswith('.pdf') and isinstance(raw.get('bbox'), dict), }) return { 'document': { @@ -302,6 +541,106 @@ def get_sample_tables(document_id: int) -> dict[str, Any]: } +def preview_coordinate_reconstruction(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """ + 生成不含坐标的逻辑明细候选,并返回行角色及来源物理行供管理员复核。 + + Args: + data: document_id、table_id 和受控坐标重建参数。 + actor_id: 当前管理员 ID;样本文档仍由既有权限边界保护。 + Returns: + 稳定虚拟表头、合并后的逻辑明细、删除状态及来源物理行索引。 + """ + try: + document_id = int(data.get('document_id')) + except (TypeError, ValueError) as exc: + raise ValidationError('document_id is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') from exc + document = db.session.get(ShippingNoticeDocument, document_id) + if document is None: + raise NotFoundError('Order profile sample document not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') + layout = _document_layout(document) + table_id = str(data.get('table_id') or '').strip() + raw_table = next((item for item in layout.get('tables') or [] if isinstance(item, dict) and str(item.get('table_id') or '') == table_id), None) + if raw_table is None: + raise ValidationError('Selected sample table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') + rebuilt_html = _reconstructed_table_html( + layout=layout, raw_table=raw_table, raw_settings=data.get('coordinate_reconstruction'), + ) + grid = parse_html_grid(rebuilt_html, table_id=f'{table_id}:coordinate-review') + from bs4 import BeautifulSoup + + table = BeautifulSoup(rebuilt_html, 'html.parser').find('table') + html_rows = table.find_all('tr') if table is not None else [] + return { + 'table_id': table_id, + 'row_count': grid.row_count, + 'column_count': grid.column_count, + 'rows': [[slot.text if slot is not None else '' for slot in row] for row in grid.rows], + 'row_roles': [str(row.get('data-row-role') or 'data') for row in html_rows], + 'source_row_indices': [ + [int(value) for value in str(row.get('data-source-rows') or '').split(',') if value.isdigit()] + for row in html_rows + ], + 'status': 'needs_review', + } + + +def suggest_coordinate_reconstruction(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """ + 根据冻结字符坐标返回全部或指定物理行的相对列边界建议。 + + Args: + data: document_id、table_id,以及可选的非负 row_offset。省略 row_offset 时建议全部行。 + actor_id: 当前管理员 ID;保留与预览接口一致的授权边界。 + Returns: + 仅含相对边界、少量列示例及确定性 line_no 建议的待审核配置;指定行时只返回该行。 + """ + try: + document_id = int(data.get('document_id')) + except (TypeError, ValueError) as exc: + raise ValidationError('document_id is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') from exc + document = db.session.get(ShippingNoticeDocument, document_id) + if document is None: + raise NotFoundError('Order profile sample document not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') + layout = _document_layout(document) + table_id = str(data.get('table_id') or '').strip() + raw_table = next(( + item for item in layout.get('tables') or [] + if isinstance(item, dict) and str(item.get('table_id') or '') == table_id + ), None) + characters = _coordinate_characters(layout, table_id) + if raw_table is None or not characters or not isinstance(raw_table.get('bbox'), dict): + raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') + suggestions = suggest_multi_subrow_layouts( + characters=characters, table_bbox=raw_table['bbox'], + ) + if not suggestions: + raise ValidationError('No item rows could be detected', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID') + raw_row_offset = data.get('row_offset') + if raw_row_offset is not None: + try: + row_offset = int(raw_row_offset) + except (TypeError, ValueError) as exc: + raise ValidationError( + 'row_offset is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID', + ) from exc + if row_offset < 0: + raise ValidationError( + 'row_offset is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID', + ) + suggestions = [item for item in suggestions if item.row_offset == row_offset] + if not suggestions: + raise ValidationError( + 'Requested physical row could not be detected', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID', + ) + return { + 'table_id': table_id, + 'subrow_layouts': [item.model_dump() for item in suggestions], + 'status': 'needs_review', + } + + def create_draft_from_sample( data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None, ) -> dict[str, Any]: @@ -340,7 +679,13 @@ def create_draft_from_sample( raise ValidationError( 'Sample row selection is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID', ) from exc - grid = parse_html_grid(str(raw_table.get('html') or ''), table_id=table_id) + coordinate_reconstruction = data.get('coordinate_reconstruction') + source_html = str(raw_table.get('html') or '') + if coordinate_reconstruction is not None: + source_html = _reconstructed_table_html( + layout=layout, raw_table=raw_table, raw_settings=coordinate_reconstruction, + ) + grid = parse_html_grid(source_html, table_id=table_id) if ( header_row_index < 0 or header_row_index >= grid.row_count or data_start_row_index <= header_row_index or data_start_row_index >= grid.row_count @@ -364,6 +709,7 @@ def create_draft_from_sample( 'data_start_row_index': data_start_row_index, 'row_structure': str(data.get('row_structure') or 'preserved'), 'column_rules': data.get('column_rules'), + 'coordinate_reconstruction': coordinate_reconstruction, 'drop_zero_qty': data.get('drop_zero_qty', True), } return save_draft({ diff --git a/backend/app/services/shipping_notice/order_extraction_workflow.py b/backend/app/services/shipping_notice/order_extraction_workflow.py index 0e421889..f62652c4 100644 --- a/backend/app/services/shipping_notice/order_extraction_workflow.py +++ b/backend/app/services/shipping_notice/order_extraction_workflow.py @@ -21,6 +21,7 @@ from app.services.shipping_notice.document_layout.order_profile import ( OrderDocumentProfile, OrderProfileColumnRule, parse_html_table_with_order_profile, + reconstruct_order_profile_html, ) from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract @@ -245,6 +246,24 @@ def _profile_snapshot_targets_valid(raw: dict[str, Any], *, contract: Any) -> bo return True +def _reconstructed_profile_html(*, layout: dict[str, Any], raw_table: dict[str, Any], profile: OrderDocumentProfile) -> str | None: + """从 Run 已冻结的坐标证据重建 HTML;证据缺失时绝不回读可变资产或降级猜测。""" + if profile.coordinate_reconstruction is None: + return str(raw_table.get('html') or '') + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {} + characters = tables.get(str(raw_table.get('table_id') or '')) + if not isinstance(characters, list) or not isinstance(raw_table.get('bbox'), dict): + return None + try: + return reconstruct_order_profile_html( + characters=[item for item in characters if isinstance(item, dict)], + table_bbox=raw_table['bbox'], reconstruction=profile.coordinate_reconstruction, + ) + except (TypeError, ValueError): + return None + + def _dify_profile_candidates(tables: list[dict[str, Any]]) -> list[dict[str, Any]]: """剥离内部 field_code,只向 Dify 暴露稳定 field_id、值和短逐字证据。""" result: list[dict[str, Any]] = [] @@ -301,10 +320,15 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]: issues.append('order_profile_snapshot_field_mismatch') continue try: + profile = _frozen_order_profile(raw_profile) + source_html = _reconstructed_profile_html(layout=layout, raw_table=raw_table, profile=profile) + if source_html is None: + issues.append('order_profile_coordinate_reconstruction_unavailable') + continue parsed = parse_html_table_with_order_profile( - str(raw_table['html']), + source_html, table_id=table_id, - profile=_frozen_order_profile(raw_profile), + profile=profile, contract=contract, ) except (TypeError, ValueError): @@ -322,7 +346,12 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]: if parsed.issues: issues.extend(parsed.issues) continue - grid = parse_html_grid(str(raw_table['html']), table_id=table_id) + profile = _frozen_order_profile(raw_profile) + source_html = _reconstructed_profile_html(layout=layout, raw_table=raw_table, profile=profile) + if source_html is None: + issues.append('order_profile_coordinate_reconstruction_unavailable') + continue + grid = parse_html_grid(source_html, table_id=table_id) compact_rows: list[dict[str, Any]] = [] for row in parsed.rows: if row.status == 'deleted': diff --git a/backend/app/services/shipping_notice/order_field_purposes.py b/backend/app/services/shipping_notice/order_field_purposes.py index 262f7231..d06cdfca 100644 --- a/backend/app/services/shipping_notice/order_field_purposes.py +++ b/backend/app/services/shipping_notice/order_field_purposes.py @@ -1,9 +1,9 @@ """ services/shipping_notice/order_field_purposes.py -用途:将冻结订单 Snapshot 按冻结 Schema 业务用途投影给履约链。 -依赖:order_schema.service、export.order_field_id_values、ShippingTask。 -逻辑:路由、门禁、匹配和展示只通过发布快照中的 business_purpose 定位稳定 field_id,禁止读取任务行固定业务列。 +用途:将冻结订单 Snapshot 按冻结货代策略能力投影给履约链。 +依赖:冻结履约策略、export.order_field_id_values、ShippingTask。 +逻辑:路由、门禁、匹配和展示只通过策略冻结的 stable field_id 定位字段,禁止读取 Schema business_purpose 或任务行固定列。 """ from __future__ import annotations @@ -15,19 +15,33 @@ from app.models import ShippingOrderSnapshot, ShippingTask from app.services.shipping_notice.export import order_field_id_values +_PURPOSE_BY_CAPABILITY = { + 'fulfillment.reservation_identity': 'reservation_id', + 'fulfillment.part_number': 'part_number', + 'fulfillment.quantity': 'quantity', + 'routing.inventory_source_hint': 'inventory_source_hint', +} + + def task_line_purpose_field_ids(task: ShippingTask, *, required: set[str] | None = None) -> dict[str, str]: - """读取冻结快照的行级用途与字段 ID,防止后续发布版本重解释履约任务。""" + """读取冻结策略能力与字段 ID,防止 Schema 或策略后续发布重解释任务。""" snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None if snapshot is None: raise ValueError('任务没有可用于履约的冻结订单快照') + policy = (snapshot.rule_versions_json or {}).get('fulfillment_policy') + definition = policy.get('definition') if isinstance(policy, dict) else None + bindings = definition.get('field_bindings') if isinstance(definition, dict) else None purposes = { - str(config.get('business_purpose')): str(config.get('field_id')) - for config in (snapshot.schema_version.definition_json or {}).get('fields') or [] - if config.get('scope') == 'line' and config.get('business_purpose') not in (None, '', 'general') + purpose: str(binding.get('field_id')) + for binding in bindings or [] + if isinstance(binding, dict) + and binding.get('scope') == 'line' + and (purpose := _PURPOSE_BY_CAPABILITY.get(str(binding.get('capability_code') or ''))) + and binding.get('field_id') } missing = sorted((required or set()) - set(purposes)) if missing: - raise ValueError(f'已发布订单 Schema 缺少业务用途:{", ".join(missing)}') + raise ValueError(f'冻结履约策略缺少字段能力:{", ".join(missing)}') return purposes diff --git a/backend/app/services/shipping_notice/order_freeze_service.py b/backend/app/services/shipping_notice/order_freeze_service.py index 5f2e204c..be2b3787 100644 --- a/backend/app/services/shipping_notice/order_freeze_service.py +++ b/backend/app/services/shipping_notice/order_freeze_service.py @@ -26,20 +26,32 @@ from app.models import ( ShippingOrderSnapshotLine, ShippingTask, ) +from app.services.shipping_notice.fulfillment_policy_registry import ( + published_policy, + required_field_configs, +) -HEADER_FIELDS = ( - 'po_number', 'customer_code', 'customer_name', 'bill_to_customer', 'bill_to_address', - 'ship_to_customer', 'ship_to_address', 'destination', 'currency', 'incoterm', 'required_date', - 'order_date', 'payment_term', -) -LINE_FIELDS = ( - 'line_no', 'part_number', 'customer_part_number', 'aws_part_number', 'reservation_id', 'qty', 'uom', - 'unit_price', 'amount', 'warehouse', 'inventory_source_hint', 'remark', -) -CRITICAL_FIELDS = frozenset({'part_number', 'reservation_id', 'qty', 'po_number'}) -DECIMAL_FIELDS = frozenset({'qty', 'unit_price', 'amount'}) -DATE_FIELDS = frozenset({'required_date', 'order_date'}) +# 强类型列只是既有查询/导出投影;56 项标准字段的完整事实始终写在 field_id JSON。 +HEADER_FIELD_PROJECTIONS = { + 'customer_po_number': 'customer_po_number', 'customer_code': 'customer_code', 'customer_name': 'customer_name', + 'bill_to_customer': 'bill_to_customer', 'bill_to_address': 'bill_to_address', + 'ship_to_customer': 'ship_to_customer', 'ship_to_address': 'ship_to_address', + 'destination': 'destination', 'currency': 'currency', 'incoterm': 'incoterm', + 'order_date': 'order_date', 'payment_term': 'payment_term', +} +LINE_FIELD_PROJECTIONS = { + 'line_no': 'line_no', 'part_number': 'part_number', 'customer_part_number': 'customer_part_number', + 'reservation_id': 'reservation_id', 'qty': 'qty', 'uom': 'uom', 'unit_price': 'unit_price', + 'line_amount_with_tax': 'amount', 'requested_warehouse_code': 'warehouse', + 'inventory_source_hint': 'inventory_source_hint', 'line_remark': 'remark', +} +CRITICAL_FIELDS = frozenset({'part_number', 'reservation_id', 'qty', 'customer_po_number'}) +DECIMAL_FIELDS = frozenset({ + 'qty', 'reference_qty', 'pricing_qty', 'unit_price', 'line_amount_before_tax', + 'line_tax_amount', 'line_amount_with_tax', 'tax_rate', +}) +DATE_FIELDS = frozenset({'order_date', 'required_date', 'requested_receipt_date'}) def freeze_order_snapshot( @@ -79,7 +91,7 @@ def freeze_order_snapshot( details={'expected': expected_order_data_version, 'actual': actual_version}, ) extraction = _accepted_extraction(task) - configs = _fixed_configs(extraction) + policy, configs = _policy_configs(extraction) _assert_llm_review_gate(extraction, configs) header_values, line_values = _extraction_values(extraction, configs) customer_match = _confirmed_ordering_customer(extraction) @@ -94,6 +106,14 @@ def freeze_order_snapshot( order_data_version=actual_version, rule_versions_json={ **dict(rule_versions or {}), + 'fulfillment_policy': { + 'id': policy.id, + 'code': policy.policy_code, + 'version': policy.version, + 'checksum': policy.checksum, + 'definition': dict(policy.definition_json or {}), + 'required_field_ids': {code: config['field_id'] for code, config in configs.items()}, + }, 'ordering_customer': { 'match_id': customer_match.id, 'identity_fingerprint': customer_match.identity_fingerprint, @@ -105,7 +125,7 @@ def freeze_order_snapshot( }, frozen_by_id=actor_id, header_values_json=_field_id_values(header_values, configs), - **{field: _coerce_value(header_values.get(field), field) for field in HEADER_FIELDS}, + **_project_values(header_values, HEADER_FIELD_PROJECTIONS), ) db.session.add(snapshot) db.session.flush() @@ -114,7 +134,7 @@ def freeze_order_snapshot( snapshot_id=snapshot.id, position=position, field_values_json=_field_id_values(source, configs), - **{field: _coerce_value(source.get(field), field) for field in LINE_FIELDS}, + **_project_values(source, LINE_FIELD_PROJECTIONS), )) task.order_snapshot_id = snapshot.id ShippingOrderReviewEvent.query.filter_by( @@ -154,36 +174,17 @@ def _confirmed_ordering_customer(extraction: ShippingOrderExtraction) -> Shippin return row -def _fixed_configs(extraction: ShippingOrderExtraction) -> dict[str, dict[str, Any]]: - """验证预置核心字段存在且类型正确;扩展字段由已发布业务配置决定是否参与履约。""" - configs = { - str(item.get('field_code')): item - for item in (extraction.schema_version.definition_json or {}).get('fields') or [] +def _policy_configs(extraction: ShippingOrderExtraction) -> tuple[Any, dict[str, dict[str, Any]]]: + """按已发布货代策略验证冻结契约,Schema 只继续承担字段目录职责。""" + definition = extraction.schema_version.definition_json or {} + policy = published_policy() + required = required_field_configs(definition, policy) + all_configs = { + str(item.get('field_code') or ''): item + for item in definition.get('fields') or [] if item.get('enabled', True) } - expected = set(HEADER_FIELDS) | set(LINE_FIELDS) - missing = expected - set(configs) - if missing: - raise ValidationError( - 'Frozen order schema is missing required core fields', - code='SHIPPING.ORDER_CONTRACT_INVALID', - details={'missing': sorted(missing)}, - ) - wrong_scope = [ - code for code, config in configs.items() if code in expected - if str(config.get('scope')) != ('header' if code in HEADER_FIELDS else 'line') - ] - if wrong_scope: - raise ValidationError('Frozen order schema has invalid field scope', code='SHIPPING.ORDER_CONTRACT_INVALID', details={'fields': wrong_scope}) - wrong_type = [ - code for code, config in configs.items() if code in expected - if str(config.get('value_type')) != ( - 'date' if code in DATE_FIELDS else 'decimal' if code in DECIMAL_FIELDS else 'string' - ) - ] - if wrong_type: - raise ValidationError('Frozen order schema has invalid core field type', code='SHIPPING.ORDER_CONTRACT_INVALID', details={'fields': wrong_type}) - return configs + return policy, all_configs | required def _assert_llm_review_gate(extraction: ShippingOrderExtraction, configs: dict[str, dict[str, Any]]) -> None: @@ -196,7 +197,7 @@ def _assert_llm_review_gate(extraction: ShippingOrderExtraction, configs: dict[s int(item.id): item for item in ShippingOrderFieldObservation.query.filter_by(extraction_id=extraction.id).all() } - field_codes = {str(config['field_id']): code for code, config in configs.items()} + field_codes = {str(config['field_id']): code for code, config in configs.items() if config.get('field_id')} blocked: list[dict[str, Any]] = [] for decision in decisions.values(): code = field_codes.get(str(decision.field_id)) @@ -248,6 +249,14 @@ def _field_id_values(values: dict[str, Any], configs: dict[str, dict[str, Any]]) } +def _project_values(values: dict[str, Any], projections: dict[str, str]) -> dict[str, Any]: + """将标准字段的兼容投影写入旧强类型列,不把目录扩展为物理列。""" + return { + column: _coerce_value(values.get(field_code), field_code) + for field_code, column in projections.items() + } + + def _coerce_value(value: Any, field_code: str) -> Any: """将动态 JSON 值安全写入强类型快照;数量为 Decimal,日期为 date,标识符为字符串。""" if value in (None, ''): diff --git a/backend/app/services/shipping_notice/order_schema/runtime.py b/backend/app/services/shipping_notice/order_schema/runtime.py index 13269a07..290813cb 100644 --- a/backend/app/services/shipping_notice/order_schema/runtime.py +++ b/backend/app/services/shipping_notice/order_schema/runtime.py @@ -386,8 +386,7 @@ def _associated_backend_rows(raw_fields: list[Any], configs: dict[str, dict[str, rows: list[dict[str, Any]]) -> list[dict[str, Any]]: """仅用同 Document 的强身份字段关联 layout 行,禁止 Qty 等常见值导致跨文档串行。""" strong_codes = { - 'part_number', 'customer_part_number', 'aws_part_number', - 'reservation_id', 'line_no', 'po_number', + 'part_number', 'customer_part_number', 'reservation_id', 'line_no', 'customer_po_number', } signatures: list[tuple[str, Any, int]] = [] for raw in raw_fields: @@ -604,9 +603,6 @@ def persist_dynamic_order( 'required_key_field_codes': sorted({ str(item['field_code']) for item in all_configs.values() - if item.get('required') and ( - item.get('business_purpose') in {'part_number', 'quantity', 'reservation_id'} - or item.get('field_code') == 'po_number' - ) + if item.get('required') or item.get('field_code') == 'customer_po_number' }), } diff --git a/backend/app/services/shipping_notice/order_schema/service.py b/backend/app/services/shipping_notice/order_schema/service.py index 87188050..13d63fbe 100644 --- a/backend/app/services/shipping_notice/order_schema/service.py +++ b/backend/app/services/shipping_notice/order_schema/service.py @@ -66,34 +66,67 @@ DIFY_EXPOSURE_POLICY_ORDER = ('never', 'redacted', 'confirmed_readonly') DIFY_EXPOSURE_POLICIES = frozenset(DIFY_EXPOSURE_POLICY_ORDER) SENSITIVITY_LEVELS = frozenset({'low', 'personal', 'confidential'}) -# 阶段 1:这 26 个字段是预置强类型履约核心。扩展字段也可由已发布业务配置纳入履约, +# 这 57 个字段是预置标准字段目录。扩展字段也可由已发布业务配置纳入履约, # 并在 Snapshot 中按稳定 field_id 冻结,避免字段重命名影响历史履约事实。 -FIXED_CORE_FIELD_SPECS: dict[str, tuple[str, str]] = { - 'po_number': ('header', 'string'), +STANDARD_ORDER_FIELD_SPECS: dict[str, tuple[str, str]] = { + # 客户订单事实:customer_po_number 是外部客户 PO;内部 ERP 单号属于系统事实。 + 'customer_po_number': ('header', 'string'), + 'order_date': ('header', 'date'), + 'source_order_number': ('header', 'string'), + 'contract_number': ('header', 'string'), + 'order_type': ('header', 'string'), + 'sales_channel': ('header', 'string'), 'customer_code': ('header', 'string'), 'customer_name': ('header', 'string'), 'bill_to_customer': ('header', 'string'), 'bill_to_address': ('header', 'string'), 'ship_to_customer': ('header', 'string'), 'ship_to_address': ('header', 'string'), + 'end_customer': ('header', 'string'), + 'customer_contact': ('header', 'string'), + 'ship_from_organization': ('header', 'string'), 'destination': ('header', 'string'), 'currency': ('header', 'string'), 'incoterm': ('header', 'string'), - 'required_date': ('header', 'date'), - 'order_date': ('header', 'date'), 'payment_term': ('header', 'string'), + 'mark_number': ('header', 'string'), + 'direct_ship_required': ('header', 'boolean'), + 'urgent_order': ('header', 'boolean'), + 'order_remark': ('header', 'string'), 'line_no': ('line', 'string'), - 'part_number': ('line', 'string'), - 'customer_part_number': ('line', 'string'), - 'aws_part_number': ('line', 'string'), 'reservation_id': ('line', 'string'), + 'part_number': ('line', 'string'), + 'product_revision': ('line', 'string'), + 'customer_part_number': ('line', 'string'), + 'customer_po_line_no': ('line', 'string'), + 'product_feature': ('line', 'string'), 'qty': ('line', 'decimal'), 'uom': ('line', 'string'), + 'reference_qty': ('line', 'decimal'), + 'reference_uom': ('line', 'string'), + 'pricing_qty': ('line', 'decimal'), + 'pricing_uom': ('line', 'string'), + 'required_date': ('line', 'date'), + 'requested_receipt_date': ('line', 'date'), 'unit_price': ('line', 'decimal'), - 'amount': ('line', 'decimal'), - 'warehouse': ('line', 'string'), + 'line_amount_before_tax': ('line', 'decimal'), + 'line_tax_amount': ('line', 'decimal'), + 'line_amount_with_tax': ('line', 'decimal'), + 'tax_category': ('line', 'string'), + 'tax_rate': ('line', 'decimal'), + 'ship_from_site': ('line', 'string'), + 'line_ship_to_address': ('line', 'string'), + 'requested_warehouse_code': ('line', 'string'), + 'storage_location_code': ('line', 'string'), + 'lot_number': ('line', 'string'), 'inventory_source_hint': ('line', 'string'), - 'remark': ('line', 'string'), + 'partial_delivery_allowed': ('line', 'boolean'), + 'bonded_flag': ('line', 'boolean'), + 'package_type': ('line', 'string'), + 'project_code': ('line', 'string'), + 'wbs_code': ('line', 'string'), + 'activity_code': ('line', 'string'), + 'line_remark': ('line', 'string'), } @@ -650,7 +683,7 @@ def get_extraction_audit(extraction_id: int) -> dict[str, Any]: def initialize_schema(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: - """初始化全局唯一订单 Schema 并预置 26 个履约核心字段;仍允许新增扩展字段。""" + """初始化全局唯一订单 Schema 并预置 57 个标准字段;仍允许新增扩展字段。""" if ShippingOrderSchema.query.count(): raise ConflictError('Only one shipping order schema is allowed', code='SHIPPING.ORDER_SCHEMA_EXISTS') display_name = str(data.get('display_name') or '').strip() @@ -665,7 +698,7 @@ def initialize_schema(data: dict[str, Any], *, actor_id: int | None) -> dict[str ) db.session.add(schema) db.session.flush() - for sequence, (field_code, (scope, value_type)) in enumerate(FIXED_CORE_FIELD_SPECS.items(), start=1): + for sequence, (field_code, (scope, value_type)) in enumerate(STANDARD_ORDER_FIELD_SPECS.items(), start=1): db.session.add(ShippingOrderField( schema_id=schema.id, field_code=field_code, @@ -676,6 +709,20 @@ def initialize_schema(data: dict[str, Any], *, actor_id: int | None) -> dict[str display_sequence=sequence, created_by_id=actor_id, )) + db.session.flush() + # 初始化仅预置策略草稿;管理员发布 Schema 后须显式确认并发布,避免未审核配置参与冻结。 + from app.services.shipping_notice.fulfillment_policy_registry import create_draft + + fields_by_code = {item.field_code: item for item in ShippingOrderField.query.filter_by(schema_id=schema.id).all()} + draft = create_draft({ + 'field_bindings': [ + {'capability_code': 'fulfillment.reservation_identity', 'field_id': fields_by_code['reservation_id'].id}, + {'capability_code': 'fulfillment.part_number', 'field_id': fields_by_code['part_number'].id}, + {'capability_code': 'fulfillment.quantity', 'field_id': fields_by_code['qty'].id}, + {'capability_code': 'routing.inventory_source_hint', 'field_id': fields_by_code['inventory_source_hint'].id}, + ], + 'change_note': '初始化货代滚动履约策略', + }, actor_id=actor_id) db.session.commit() return get_state() @@ -684,7 +731,7 @@ def save_field( data: dict[str, Any], *, actor_id: int | None, field_id: str | None = None, request_id: str | None = None, ) -> dict[str, Any]: - """创建或更新字段;核心 26 字段身份不可变,扩展字段仍可按既有治理规则维护。""" + """创建或更新字段;标准字段身份不可变,扩展字段仍可按既有治理规则维护。""" schema = _require_schema() field = db.session.get(ShippingOrderField, field_id) if field_id else None if field_id and (field is None or field.schema_id != schema.id): @@ -696,7 +743,7 @@ def save_field( collection_mode = str(data.get('collection_mode') or 'llm_extraction').strip() if not FIELD_CODE_RE.fullmatch(code): raise ValidationError('field_code must use lower snake_case', code='SHIPPING.ORDER_FIELD_INVALID') - fixed_shape = FIXED_CORE_FIELD_SPECS.get(code) + fixed_shape = STANDARD_ORDER_FIELD_SPECS.get(code) # 预置核心字段在 Schema 初始化时已存在。历史调用方重复声明相同契约时 # 只返回既有字段,绝不能再插入一条同名记录;形状不一致仍是硬错误。 if field is None and fixed_shape is not None: @@ -705,7 +752,7 @@ def save_field( if (scope, value_type) != fixed_shape: raise ConflictError('Core order field identity is immutable', code='SHIPPING.ORDER_FIELD_IMMUTABLE') return _field_payload(existing_core) - if field is not None and field.field_code in FIXED_CORE_FIELD_SPECS: + if field is not None and field.field_code in STANDARD_ORDER_FIELD_SPECS: if field.field_code != code or (scope, value_type) != fixed_shape: raise ConflictError('Core order field identity is immutable', code='SHIPPING.ORDER_FIELD_IMMUTABLE') if scope not in FIELD_SCOPES or value_type not in FIELD_TYPES: @@ -873,7 +920,7 @@ def _field_runtime_references(field_id: str) -> list[str]: """返回字段仍被哪些可运行下游配置引用,供退役与 Schema 发布共用。""" from app.models import ( ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingOrderDocumentProfile, - ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, + ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingFulfillmentPolicy, ) references: list[str] = [] if db.session.query(ShippingInventoryRoutingRuleCondition).join(ShippingInventoryRoutingRule).filter( @@ -912,6 +959,15 @@ def _field_runtime_references(field_id: str) -> list[str]: ) if template_reference: references.append('excel_template') + field = db.session.get(ShippingOrderField, field_id) + policy_reference = any( + any(str(item.get('field_id') or '') == field_id for item in (policy.definition_json or {}).get('field_bindings', [])) + for policy in ShippingFulfillmentPolicy.query.filter_by( + schema_id=field.schema_id if field is not None else None, status='published', + ).all() + ) + if policy_reference: + references.append('fulfillment_policy') # 识别定义同样消费稳定订单字段;字段退役或发布移除前必须先完成规则替换/退役。 from app.services.shipping_notice.identity_rules.service import active_definition_field_references references.extend(active_definition_field_references(field_id)) diff --git a/backend/app/services/shipping_notice/order_schema/table_contract.py b/backend/app/services/shipping_notice/order_schema/table_contract.py index 9b72c9a5..5dbc9a92 100644 --- a/backend/app/services/shipping_notice/order_schema/table_contract.py +++ b/backend/app/services/shipping_notice/order_schema/table_contract.py @@ -17,9 +17,13 @@ from app.core.errors import ValidationError TABLE_FIELD_CODES = frozenset({ - 'line_no', 'part_number', 'qty', 'unit_price', 'amount', 'currency', - 'reservation_id', 'required_date', 'customer_part_number', - 'aws_part_number', 'uom', 'remark', 'po_number', 'inventory_source_hint', + 'line_no', 'reservation_id', 'part_number', 'product_revision', 'customer_part_number', + 'customer_po_line_no', 'product_feature', 'qty', 'uom', 'reference_qty', 'reference_uom', + 'pricing_qty', 'pricing_uom', 'required_date', 'requested_receipt_date', 'unit_price', + 'line_amount_before_tax', 'line_tax_amount', 'line_amount_with_tax', 'tax_category', 'tax_rate', + 'ship_from_site', 'line_ship_to_address', 'requested_warehouse_code', 'storage_location_code', + 'lot_number', 'inventory_source_hint', 'partial_delivery_allowed', 'bonded_flag', 'package_type', + 'project_code', 'wbs_code', 'activity_code', 'line_remark', }) # 这些技术/业务标识与 Reservation ID 语义不同,管理员配置不得覆盖安全边界。 diff --git a/backend/app/services/shipping_notice/reservation_service.py b/backend/app/services/shipping_notice/reservation_service.py index 856a58cf..4b4f5391 100644 --- a/backend/app/services/shipping_notice/reservation_service.py +++ b/backend/app/services/shipping_notice/reservation_service.py @@ -22,6 +22,9 @@ from app.models import ( ShippingReservation, ShippingTask, ) +from app.services.shipping_notice.po_number import normalize_po_number +from app.services.shipping_notice.reservation_id import validated_reservation_id +from app.services.shipping_notice.tool_common import log_task_event def _decimal(value: Any) -> Decimal: @@ -36,40 +39,105 @@ def _decimal(value: Any) -> Decimal: def ensure_task_reservations(task: ShippingTask) -> list[ShippingReservation]: - """由冻结 Snapshot 注册预约单;历史上传或占用记录不允许被新快照静默覆盖。""" + """由冻结 Snapshot 注册全局预约号;同 PO 的变更只能作为人工修订候选。""" snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None if snapshot is None: raise ValidationError('Frozen order snapshot is required', code='SHIPPING.ORDER_SNAPSHOT_REQUIRED') + po_number = normalize_po_number(snapshot.customer_po_number).upper() registered: list[ShippingReservation] = [] + seen: set[str] = set() for line in snapshot.lines: - reservation_id = str(line.reservation_id or '').strip() + reservation_id = validated_reservation_id(line.reservation_id) part_number = str(line.part_number or '').strip() if not reservation_id or not part_number or line.qty is None: raise ValidationError('Reservation id, part number and quantity are required', code='SHIPPING.RESERVATION_INVALID') - row = ShippingReservation.query.filter_by(reservation_id=reservation_id, part_number=part_number).one_or_none() + if reservation_id in seen: + raise ConflictError('Reservation is duplicated in the frozen order', code='SHIPPING.RESERVATION_DUPLICATED_IN_ORDER') + seen.add(reservation_id) + row = ShippingReservation.query.filter_by(reservation_id=reservation_id).one_or_none() if row is None: row = ShippingReservation( task_id=task.id, snapshot_line_id=line.id, reservation_id=reservation_id, - part_number=part_number, required_qty=_decimal(line.qty), status='pending', + po_number_normalized=po_number, part_number=part_number, required_qty=_decimal(line.qty), status='pending', ) db.session.add(row) - elif row.task_id != task.id or row.snapshot_line_id != line.id: - raise ConflictError( - 'Reservation is already registered by another order version', - code='SHIPPING.RESERVATION_ALREADY_REGISTERED', + elif not po_number: + raise ValidationError( + 'Purchase order is required when a reservation is already registered', + code='SHIPPING.RESERVATION_PO_REQUIRED', ) + elif row.po_number_normalized != po_number: + raise ConflictError( + 'Reservation is already registered by a different purchase order', + code='SHIPPING.RESERVATION_PO_CONFLICT', + details={'reservation_id': reservation_id, 'registered_po_number': row.po_number_normalized}, + ) + elif row.task_id != task.id or row.snapshot_line_id != line.id: + if row.current_artifact_id is not None or row.status in {'artifact_reserved', 'uploaded'}: + raise ConflictError('Reservation cannot be revised after export or upload', code='SHIPPING.RESERVATION_REVISION_LOCKED') + if row.part_number != part_number or row.required_qty != _decimal(line.qty): + if task.supersedes_task_id == row.task_id: + _transfer_confirmed_revision(row, task=task, line=line, part_number=part_number) + registered.append(row) + continue + raise ConflictError( + 'Reservation revision requires human confirmation', + code='SHIPPING.RESERVATION_REVISION_REVIEW_REQUIRED', + details={ + 'reservation_id': reservation_id, + 'registered_task_id': row.task_id, + 'previous': {'part_number': row.part_number, 'qty': str(row.required_qty)}, + 'proposed': {'part_number': part_number, 'qty': str(_decimal(line.qty))}, + }, + ) + raise ConflictError('Reservation is already registered by another order version', code='SHIPPING.RESERVATION_ALREADY_REGISTERED') registered.append(row) db.session.flush() return registered +def _transfer_confirmed_revision( + reservation: ShippingReservation, + *, task: ShippingTask, + line: Any, + part_number: str, +) -> None: + """仅允许已确认的直接修订后继接替未履约 Reservation,并追加双向审计。""" + previous = { + 'task_id': reservation.task_id, + 'snapshot_line_id': reservation.snapshot_line_id, + 'part_number': reservation.part_number, + 'qty': str(reservation.required_qty), + } + reservation.task_id = task.id + reservation.snapshot_line_id = line.id + reservation.part_number = part_number + reservation.required_qty = _decimal(line.qty) + reservation.status = 'pending' + reservation.current_artifact_id = None + details = { + 'reservation_id': reservation.reservation_id, + 'previous': previous, + 'proposed': { + 'task_id': task.id, + 'snapshot_line_id': line.id, + 'part_number': part_number, + 'qty': str(reservation.required_qty), + }, + } + log_task_event(task, 'reservation_revision_confirmed', details) + parent = db.session.get(ShippingTask, task.supersedes_task_id) + if parent is not None: + log_task_event(parent, 'reservation_revision_superseded', details) + + def record_inventory_verification( task: ShippingTask, *, inventory_snapshot_id: int | None, source_config_version: str | None, line_results: list[dict[str, Any]], ) -> ShippingInventoryVerification: """把一轮库存匹配追加为核验事实,并仅将完整满足的 pending 预约单标记 available。""" reservations = ensure_task_reservations(task) - by_key = {(row.reservation_id, row.part_number): row for row in reservations} + by_key = {row.reservation_id: row for row in reservations} verification = ShippingInventoryVerification( task_id=task.id, inventory_snapshot_id=inventory_snapshot_id, source_config_version=source_config_version, status='completed', result_json={'line_count': len(line_results)}, @@ -78,10 +146,10 @@ def record_inventory_verification( db.session.flush() available_count = 0 for item in line_results: - reservation_id = str(item.get('reservation_id') or '').strip() + reservation_id = validated_reservation_id(item.get('reservation_id')) part_number = str(item.get('part_number') or '').strip() - reservation = by_key.get((reservation_id, part_number)) - if reservation is None: + reservation = by_key.get(reservation_id) + if reservation is None or reservation.part_number != part_number: raise ValidationError('Inventory result does not map to a frozen reservation', code='SHIPPING.RESERVATION_MISMATCH') required = _decimal(item.get('required_qty')) available = _decimal(item.get('available_qty')) if Decimal(str(item.get('available_qty') or 0)) > 0 else Decimal('0') diff --git a/backend/migrations/versions/025b6c7d8e9f_make_shipping_reservation_globally_unique.py b/backend/migrations/versions/025b6c7d8e9f_make_shipping_reservation_globally_unique.py new file mode 100644 index 00000000..1f04d3ec --- /dev/null +++ b/backend/migrations/versions/025b6c7d8e9f_make_shipping_reservation_globally_unique.py @@ -0,0 +1,34 @@ +"""make shipping reservation globally unique + +Revision ID: 025b6c7d8e9f +Revises: 024a5b6c7d8e +Create Date: 2026-07-23 00:00:00.000000 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = '025b6c7d8e9f' +down_revision = '024a5b6c7d8e' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """将预约号改为单列全局唯一,并保存首次注册时的标准 PO。""" + with op.batch_alter_table('shipping_reservations') as batch: + batch.add_column(sa.Column('po_number_normalized', sa.String(length=255), nullable=True)) + batch.drop_constraint('uq_shipping_reservations_reservation_part', type_='unique') + batch.create_unique_constraint('uq_shipping_reservations_reservation_id', ['reservation_id']) + op.execute("UPDATE shipping_reservations SET po_number_normalized = '' WHERE po_number_normalized IS NULL") + with op.batch_alter_table('shipping_reservations') as batch: + batch.alter_column('po_number_normalized', existing_type=sa.String(length=255), nullable=False) + + +def downgrade() -> None: + """恢复旧的 Reservation 与料号联合唯一约束。""" + with op.batch_alter_table('shipping_reservations') as batch: + batch.drop_constraint('uq_shipping_reservations_reservation_id', type_='unique') + batch.create_unique_constraint('uq_shipping_reservations_reservation_part', ['reservation_id', 'part_number']) + batch.drop_column('po_number_normalized') diff --git a/backend/migrations/versions/026c7d8e9f0a_add_shipping_fulfillment_policies.py b/backend/migrations/versions/026c7d8e9f0a_add_shipping_fulfillment_policies.py new file mode 100644 index 00000000..870e31cd --- /dev/null +++ b/backend/migrations/versions/026c7d8e9f0a_add_shipping_fulfillment_policies.py @@ -0,0 +1,48 @@ +"""add shipping fulfillment policies + +Revision ID: 026c7d8e9f0a +Revises: 025b6c7d8e9f +Create Date: 2026-07-23 00:00:00.000000 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = '026c7d8e9f0a' +down_revision = '025b6c7d8e9f' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """建立货代专用策略版本表;不影响已冻结的历史 Snapshot。""" + op.create_table( + 'shipping_fulfillment_policies', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('schema_id', sa.Integer(), sa.ForeignKey('shipping_order_schemas.id'), nullable=False), + sa.Column('policy_code', sa.String(length=64), nullable=False), + sa.Column('version', sa.Integer(), nullable=False), + sa.Column('status', sa.String(length=16), nullable=False, server_default='draft'), + sa.Column('definition_json', sa.JSON(), nullable=False), + sa.Column('checksum', sa.String(length=64)), + sa.Column('lock_version', sa.Integer(), nullable=False, server_default='1'), + sa.Column('change_note', sa.Text()), + sa.Column('source_policy_id', sa.Integer(), sa.ForeignKey('shipping_fulfillment_policies.id')), + sa.Column('created_by_id', sa.Integer(), sa.ForeignKey('users.id')), + sa.Column('published_by_id', sa.Integer(), sa.ForeignKey('users.id')), + sa.Column('published_at', sa.DateTime()), sa.Column('retired_at', sa.DateTime()), + sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('schema_id', 'policy_code', 'version', name='uq_shipping_fulfillment_policies_version'), + sa.CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_fulfillment_policies_status'), + ) + op.create_index( + 'uq_shipping_fulfillment_policy_one_published', 'shipping_fulfillment_policies', ['schema_id'], unique=True, + postgresql_where=sa.text("status = 'published'"), sqlite_where=sa.text("status = 'published'"), + ) + + +def downgrade() -> None: + """移除尚未被 Snapshot 外键引用的策略表。""" + op.drop_index('uq_shipping_fulfillment_policy_one_published', table_name='shipping_fulfillment_policies') + op.drop_table('shipping_fulfillment_policies') diff --git a/backend/migrations/versions/027d8e9f0a1b_expand_shipping_standard_field_catalog.py b/backend/migrations/versions/027d8e9f0a1b_expand_shipping_standard_field_catalog.py new file mode 100644 index 00000000..e74f7c1e --- /dev/null +++ b/backend/migrations/versions/027d8e9f0a1b_expand_shipping_standard_field_catalog.py @@ -0,0 +1,172 @@ +"""expand shipping standard field catalog + +Revision ID: 027d8e9f0a1b +Revises: 026c7d8e9f0a +Create Date: 2026-07-23 00:00:00.000000 + +用途:以 57 项标准字段目录重建 shipping_order_fields,并清理依赖旧 field_id 的未投产数据。 +依赖:shipping_order_schemas / shipping_order_fields 及相关履约、库存配置表。 +逻辑:先按外键安全顺序清空受影响事实表,再重插标准字段;含解析绑定审计表须先于 parsing_profiles 删除。 +""" + +from __future__ import annotations + +import uuid + +from alembic import op +import sqlalchemy as sa + + +revision = '027d8e9f0a1b' +down_revision = '026c7d8e9f0a' +branch_labels = None +depends_on = None + + +STANDARD_FIELDS = ( + ('customer_po_number', 'header', 'string'), ('order_date', 'header', 'date'), + ('source_order_number', 'header', 'string'), ('contract_number', 'header', 'string'), + ('order_type', 'header', 'string'), ('sales_channel', 'header', 'string'), + ('customer_code', 'header', 'string'), ('customer_name', 'header', 'string'), + ('bill_to_customer', 'header', 'string'), ('bill_to_address', 'header', 'string'), + ('ship_to_customer', 'header', 'string'), ('ship_to_address', 'header', 'string'), + ('end_customer', 'header', 'string'), ('customer_contact', 'header', 'string'), + ('ship_from_organization', 'header', 'string'), ('destination', 'header', 'string'), + ('currency', 'header', 'string'), ('incoterm', 'header', 'string'), + ('payment_term', 'header', 'string'), ('mark_number', 'header', 'string'), + ('direct_ship_required', 'header', 'boolean'), ('urgent_order', 'header', 'boolean'), + ('order_remark', 'header', 'string'), ('line_no', 'line', 'string'), + ('reservation_id', 'line', 'string'), ('part_number', 'line', 'string'), + ('product_revision', 'line', 'string'), ('customer_part_number', 'line', 'string'), + ('customer_po_line_no', 'line', 'string'), ('product_feature', 'line', 'string'), + ('qty', 'line', 'decimal'), ('uom', 'line', 'string'), ('reference_qty', 'line', 'decimal'), + ('reference_uom', 'line', 'string'), ('pricing_qty', 'line', 'decimal'), + ('pricing_uom', 'line', 'string'), ('required_date', 'line', 'date'), + ('requested_receipt_date', 'line', 'date'), ('unit_price', 'line', 'decimal'), + ('line_amount_before_tax', 'line', 'decimal'), ('line_tax_amount', 'line', 'decimal'), + ('line_amount_with_tax', 'line', 'decimal'), ('tax_category', 'line', 'string'), + ('tax_rate', 'line', 'decimal'), ('ship_from_site', 'line', 'string'), + ('line_ship_to_address', 'line', 'string'), ('requested_warehouse_code', 'line', 'string'), + ('storage_location_code', 'line', 'string'), ('lot_number', 'line', 'string'), + ('inventory_source_hint', 'line', 'string'), ('partial_delivery_allowed', 'line', 'boolean'), + ('bonded_flag', 'line', 'boolean'), ('package_type', 'line', 'string'), + ('project_code', 'line', 'string'), ('wbs_code', 'line', 'string'), + ('activity_code', 'line', 'string'), ('line_remark', 'line', 'string'), +) + + +def upgrade() -> None: + """清理未投产旧配置/订单事实后,以 57 项目录重新建立字段身份。""" + bind = op.get_bind() + tables = set(sa.inspect(bind).get_table_names()) + _reset_affected_shipping_order_data(bind, tables) + if 'shipping_order_snapshots' in tables: + columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_order_snapshots')} + with op.batch_alter_table('shipping_order_snapshots') as batch: + if 'po_number' in columns: + batch.alter_column('po_number', new_column_name='customer_po_number') + if 'shipping_order_snapshot_lines' in tables: + columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_order_snapshot_lines')} + if 'aws_part_number' in columns: + with op.batch_alter_table('shipping_order_snapshot_lines') as batch: + batch.drop_column('aws_part_number') + + if not {'shipping_order_schemas', 'shipping_order_fields'} <= tables: + return + schema = bind.execute(sa.text("SELECT id FROM shipping_order_schemas WHERE schema_code = 'SHIPPING_ORDER'")).mappings().first() + if not schema: + return + schema_id = schema['id'] + # 业务未投产,旧 field_id 不可安全重解释为新语义,因此一律重新建立。 + bind.execute(sa.text("DELETE FROM shipping_order_fields WHERE schema_id = :schema_id"), {'schema_id': schema_id}) + for sequence, (field_code, scope, value_type) in enumerate(STANDARD_FIELDS, start=1): + bind.execute(sa.text(""" + INSERT INTO shipping_order_fields + (id, schema_id, field_code, scope, value_type, field_category, collection_mode, + display_sequence, status, published_once, created_at, updated_at) + VALUES + (:id, :schema_id, :field_code, :scope, :value_type, :field_category, + 'llm_extraction', :sequence, 'active', false, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) + """), { + 'id': str(uuid.uuid4()), 'schema_id': schema_id, 'field_code': field_code, + 'scope': scope, 'value_type': value_type, + 'field_category': 'order_header' if scope == 'header' else 'order_line', + 'sequence': sequence, + }) + + +def _reset_affected_shipping_order_data(bind: sa.Connection, tables: set[str]) -> None: + """删除依赖旧字段身份的未投产配置和履约数据,并解除任务引用。 + + 核心逻辑:先解绑任务/库存源外键,再按依赖末端→前端顺序 DELETE; + parsing_binding_audits 必须早于 parsing_profiles,避免 FK 阻断。 + """ + if 'shipping_tasks' in tables: + columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_tasks')} + resets = [] + if 'current_order_extraction_id' in columns: + resets.append('current_order_extraction_id = NULL') + if 'order_snapshot_id' in columns: + resets.append('order_snapshot_id = NULL') + if 'source_candidate_id' in columns: + resets.append('source_candidate_id = NULL') + if resets: + bind.execute(sa.text(f"UPDATE shipping_tasks SET {', '.join(resets)}")) + if 'agent_runtime_bindings' in tables: + columns = {item['name'] for item in sa.inspect(bind).get_columns('agent_runtime_bindings')} + if 'quality_batch_id' in columns: + bind.execute(sa.text('UPDATE agent_runtime_bindings SET quality_batch_id = NULL')) + if 'shipping_inventory_sources' in tables: + columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_inventory_sources')} + resets = [name for name in ('parsing_profile_id', 'previous_parsing_profile_id', 'excel_template_id') if name in columns] + if resets: + assignments = [f'{name} = NULL' for name in resets] + if 'enabled' in columns: + assignments.append('enabled = false') + bind.execute(sa.text(f"UPDATE shipping_inventory_sources SET {', '.join(assignments)}")) + # 由最末端向 Schema/Field 反向清理,确保不同部署阶段缺表时也可安全升级。 + affected_tables = ( + 'shipping_notice_candidates', 'shipping_excel_templates', + 'shipping_upload_attempts', 'shipping_export_artifact_lines', + 'shipping_inventory_verification_lines', 'shipping_reservations', + 'shipping_inventory_verifications', 'shipping_export_artifacts', + 'shipping_order_review_events', 'shipping_order_snapshot_lines', 'shipping_order_snapshots', + 'shipping_order_customer_matches', 'shipping_order_field_values', + 'shipping_order_field_decisions', 'shipping_order_field_observations', + 'shipping_order_lines', 'shipping_order_extractions', + 'shipping_order_extraction_quality_labels', 'shipping_order_extraction_progress_events', + 'shipping_order_extraction_diagnostic_audits', 'shipping_order_extraction_units', + 'shipping_order_extraction_plans', 'shipping_order_extraction_run_intakes', + 'shipping_order_extraction_runs', 'shipping_order_extraction_quality_batches', + 'shipping_customer_shadow_matches', 'shipping_customer_shadow_resolutions', + 'shipping_document_profile_test_runs', 'shipping_document_profile_test_samples', + 'shipping_document_profile_test_suites', 'shipping_order_document_profiles', + 'shipping_inventory_routing_rule_versions', 'shipping_inventory_routing_rule_conditions', + 'shipping_inventory_routing_rules', + # [STEP] 先清绑定审计,再删 parsing_profiles,避免 previous/current 外键挡住删除。 + 'shipping_inventory_source_parsing_binding_audits', + 'shipping_inventory_parsing_profiles', + 'shipping_identity_evidences', 'shipping_identity_rule_audit_events', + 'shipping_identity_rule_sets', 'shipping_identity_definitions', + 'shipping_fulfillment_policies', 'shipping_order_schema_audit_events', + 'shipping_order_schema_versions', + ) + for table in affected_tables: + if table in tables: + bind.execute(sa.text(f'DELETE FROM {table}')) + + +def downgrade() -> None: + """仅恢复已重命名/移除的物理兼容列;字段目录按发布记录仍不可无损回退。""" + bind = op.get_bind() + tables = set(sa.inspect(bind).get_table_names()) + if 'shipping_order_snapshot_lines' in tables: + columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_order_snapshot_lines')} + if 'aws_part_number' not in columns: + with op.batch_alter_table('shipping_order_snapshot_lines') as batch: + batch.add_column(sa.Column('aws_part_number', sa.String(length=255), nullable=True)) + if 'shipping_order_snapshots' in tables: + columns = {item['name'] for item in sa.inspect(bind).get_columns('shipping_order_snapshots')} + if 'customer_po_number' in columns: + with op.batch_alter_table('shipping_order_snapshots') as batch: + batch.alter_column('customer_po_number', new_column_name='po_number') diff --git a/backend/migrations/versions/2b3c4d5e6f7a_add_shipping_inventory_configuration.py b/backend/migrations/versions/2b3c4d5e6f7a_add_shipping_inventory_configuration.py index 9e9581bc..f95baacc 100644 --- a/backend/migrations/versions/2b3c4d5e6f7a_add_shipping_inventory_configuration.py +++ b/backend/migrations/versions/2b3c4d5e6f7a_add_shipping_inventory_configuration.py @@ -135,7 +135,7 @@ def upgrade() -> None: ) op.create_index('ix_shipping_inventory_external_mappings_inventory_source_id', 'shipping_inventory_external_mappings', ['inventory_source_id']) op.create_index( - 'uq_shipping_inventory_external_mappings_source_default_enabled', + 'uq_shipping_inv_ext_map_src_default_enabled', 'shipping_inventory_external_mappings', ['inventory_source_id'], unique=True, @@ -143,7 +143,7 @@ def upgrade() -> None: sqlite_where=sa.text('freight_warehouse_id IS NULL AND enabled = 1'), ) op.create_index( - 'uq_shipping_inventory_external_mappings_source_warehouse_enabled', + 'uq_shipping_inv_ext_map_src_wh_enabled', 'shipping_inventory_external_mappings', ['inventory_source_id', 'freight_warehouse_id'], unique=True, diff --git a/backend/migrations/versions/ad2e3f4a5b6c_migrate_routing_rules_to_order_fields.py b/backend/migrations/versions/ad2e3f4a5b6c_migrate_routing_rules_to_order_fields.py index 784a4dc5..a64e91ea 100644 --- a/backend/migrations/versions/ad2e3f4a5b6c_migrate_routing_rules_to_order_fields.py +++ b/backend/migrations/versions/ad2e3f4a5b6c_migrate_routing_rules_to_order_fields.py @@ -51,7 +51,6 @@ def _published_purposes(bind) -> dict[str, str]: def upgrade() -> None: """仅迁移草稿规则;已发布规则若仍使用固定事实则阻断,禁止混合运行路径。""" bind = op.get_bind() - purposes = _published_purposes(bind) rules = sa.table( 'shipping_inventory_routing_rules', sa.column('id', sa.Integer()), sa.column('status', sa.String()), @@ -66,9 +65,13 @@ def upgrade() -> None: .join(rules, rules.c.id == conditions.c.rule_id) .where(conditions.c.system_fact_key.in_(tuple(_FACT_TO_PURPOSE))) ).mappings().all() + # 新库不存在旧固定事实条件,无需强制要求尚未配置的 published Schema。 + if not legacy: + return published = [row for row in legacy if row['status'] == 'published'] if published: raise RuntimeError('Published routing rules still use fixed system facts; retire and replace them before migration') + purposes = _published_purposes(bind) for row in legacy: if row['status'] != 'draft': continue diff --git a/backend/migrations/versions/b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields.py b/backend/migrations/versions/b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields.py index 2c021722..756ecffd 100644 --- a/backend/migrations/versions/b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields.py +++ b/backend/migrations/versions/b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields.py @@ -91,12 +91,18 @@ def _backfill_legacy_inventory_source() -> None: bind = op.get_bind() legacy_config_version = "legacy-unverified" - rows = bind.execute( - sa.text( - "SELECT id, step_payload_json, pending_human_reason FROM shipping_tasks " - "WHERE step_payload_json IS NOT NULL" - ) - ).fetchall() + # `step_payload_json` was introduced by a sibling historical migration, not + # this revision's ancestor chain. Fresh databases therefore have no legacy + # JSON to backfill, while upgraded legacy databases can still preserve it. + task_columns = {item["name"] for item in sa.inspect(bind).get_columns("shipping_tasks")} + rows = [] + if "step_payload_json" in task_columns: + rows = bind.execute( + sa.text( + "SELECT id, step_payload_json, pending_human_reason FROM shipping_tasks " + "WHERE step_payload_json IS NOT NULL" + ) + ).fetchall() for row in rows: payload = row.step_payload_json if not isinstance(payload, dict): @@ -175,36 +181,15 @@ def _backfill_legacy_inventory_source() -> None: }, ) if needs_review or status in {"ambiguous", "unresolved"}: - bind.execute( - sa.text( - "UPDATE shipping_tasks SET " - "pending_human_reason = 'inventory_source_unresolved', " - "current_step = 'step2_parse_confirm', " - "process_status = 'pending_review' " - "WHERE id = :task_id" - ), - {"task_id": row.id}, - ) + _mark_unresolved(bind, task_columns, "id = :task_id", {"task_id": row.id}) - bind.execute( - sa.text( - "UPDATE shipping_tasks SET " - "pending_human_reason = 'inventory_source_unresolved', " - "current_step = 'step2_parse_confirm', " - "process_status = 'pending_review' " - "WHERE inventory_source_status IN ('ambiguous', 'unresolved', 'conflicted', 'invalid') " - "AND (pending_human_reason IS NULL OR pending_human_reason = '')" - ) - ) - bind.execute( - sa.text( - "UPDATE shipping_tasks SET " - "pending_human_reason = 'inventory_source_unresolved', " - "current_step = 'step2_parse_confirm', " - "process_status = 'pending_review' " - "WHERE inventory_source_config_version = 'legacy-unverified'" - ) + _mark_unresolved( + bind, + task_columns, + "inventory_source_status IN ('ambiguous', 'unresolved', 'conflicted', 'invalid') " + "AND (pending_human_reason IS NULL OR pending_human_reason = '')", ) + _mark_unresolved(bind, task_columns, "inventory_source_config_version = 'legacy-unverified'") file_rows = bind.execute( sa.text("SELECT id, source_code, warehouse_id FROM shipping_inventory_files WHERE source_code IS NOT NULL") @@ -218,6 +203,21 @@ def _backfill_legacy_inventory_source() -> None: ) +def _mark_unresolved( + bind: sa.Connection, + task_columns: set[str], + where_clause: str, + params: dict[str, object] | None = None, +) -> None: + """回填旧状态时只写当前历史分支实际拥有的任务列。""" + assignments = ["pending_human_reason = 'inventory_source_unresolved'"] + if "current_step" in task_columns: + assignments.append("current_step = 'step2_parse_confirm'") + if "process_status" in task_columns: + assignments.append("process_status = 'pending_review'") + bind.execute(sa.text(f"UPDATE shipping_tasks SET {', '.join(assignments)} WHERE {where_clause}"), params or {}) + + def downgrade(): """Remove inventory source gate columns.""" with op.batch_alter_table("shipping_task_inventory_links", schema=None) as batch_op: diff --git a/backend/migrations/versions/d38f4a5b6c7d_rename_erp_mappings_to_external_mappings.py b/backend/migrations/versions/d38f4a5b6c7d_rename_erp_mappings_to_external_mappings.py index ca8fe61c..944728f4 100644 --- a/backend/migrations/versions/d38f4a5b6c7d_rename_erp_mappings_to_external_mappings.py +++ b/backend/migrations/versions/d38f4a5b6c7d_rename_erp_mappings_to_external_mappings.py @@ -12,6 +12,7 @@ Create Date: 2026-07-17 10:28:00.000000 from __future__ import annotations +import sqlalchemy as sa from alembic import op @@ -23,6 +24,10 @@ depends_on = None def upgrade() -> None: """将 shipping_inventory_erp_mappings 重命名为 shipping_inventory_external_mappings。""" + tables = set(sa.inspect(op.get_bind()).get_table_names()) + # 空库链已由 2b3c 直接创建 external 表;只有历史库保留 erp 表时才需要重命名。 + if 'shipping_inventory_erp_mappings' not in tables: + return # [STEP 1] 表名 op.rename_table('shipping_inventory_erp_mappings', 'shipping_inventory_external_mappings') @@ -60,11 +65,11 @@ def upgrade() -> None: ) op.execute( 'ALTER INDEX IF EXISTS uq_shipping_inventory_erp_mappings_source_default_enabled ' - 'RENAME TO uq_shipping_inventory_external_mappings_source_default_enabled' + 'RENAME TO uq_shipping_inv_ext_map_src_default_enabled' ) op.execute( 'ALTER INDEX IF EXISTS uq_shipping_inventory_erp_mappings_source_warehouse_enabled ' - 'RENAME TO uq_shipping_inventory_external_mappings_source_warehouse_enabled' + 'RENAME TO uq_shipping_inv_ext_map_src_wh_enabled' ) op.execute( 'ALTER INDEX IF EXISTS shipping_inventory_erp_mappings_pkey ' @@ -74,16 +79,19 @@ def upgrade() -> None: def downgrade() -> None: """回滚为 erp_* 表与列名。""" + tables = set(sa.inspect(op.get_bind()).get_table_names()) + if 'shipping_inventory_external_mappings' not in tables: + return op.execute( 'ALTER INDEX IF EXISTS shipping_inventory_external_mappings_pkey ' 'RENAME TO shipping_inventory_erp_mappings_pkey' ) op.execute( - 'ALTER INDEX IF EXISTS uq_shipping_inventory_external_mappings_source_warehouse_enabled ' + 'ALTER INDEX IF EXISTS uq_shipping_inv_ext_map_src_wh_enabled ' 'RENAME TO uq_shipping_inventory_erp_mappings_source_warehouse_enabled' ) op.execute( - 'ALTER INDEX IF EXISTS uq_shipping_inventory_external_mappings_source_default_enabled ' + 'ALTER INDEX IF EXISTS uq_shipping_inv_ext_map_src_default_enabled ' 'RENAME TO uq_shipping_inventory_erp_mappings_source_default_enabled' ) op.execute( diff --git a/backend/migrations/versions/d6e7f8a9b0c1_add_rpa_callback_idempotency_fields.py b/backend/migrations/versions/d6e7f8a9b0c1_add_rpa_callback_idempotency_fields.py index e4cbf07c..47a38783 100644 --- a/backend/migrations/versions/d6e7f8a9b0c1_add_rpa_callback_idempotency_fields.py +++ b/backend/migrations/versions/d6e7f8a9b0c1_add_rpa_callback_idempotency_fields.py @@ -38,6 +38,9 @@ def _json_consumed_run_no_expr(dialect_name: str) -> str: def _backfill_consumed_run_no(bind) -> None: """将历史 step_payload_json 中的消费轮次回填到独立列。""" + task_columns = {item["name"] for item in sa.inspect(bind).get_columns("shipping_tasks")} + if "step_payload_json" not in task_columns: + return expr = _json_consumed_run_no_expr(bind.dialect.name) bind.execute( sa.text( diff --git a/backend/tests/services/shipping_notice/test_shipping_order_snapshot.py b/backend/tests/services/shipping_notice/test_shipping_order_snapshot.py index ac399fe1..93503960 100644 --- a/backend/tests/services/shipping_notice/test_shipping_order_snapshot.py +++ b/backend/tests/services/shipping_notice/test_shipping_order_snapshot.py @@ -21,6 +21,7 @@ from app.models import ( ShippingOrderFieldDecision, ShippingOrderFieldObservation, ShippingOrderFieldValue, + ShippingFulfillmentPolicy, ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, @@ -30,28 +31,28 @@ from app.models import ( User, ) from app.services.shipping_notice.order_freeze_service import ( - HEADER_FIELDS, - LINE_FIELDS, + HEADER_FIELD_PROJECTIONS, + LINE_FIELD_PROJECTIONS, assert_task_order_is_editable, freeze_order_snapshot, ) -def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension: bool = False): +def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension: bool = False, suffix: str = '001'): """创建一份含预置核心字段的已接受解析;可加入扩展字段验证配置化履约。""" - user = User(username='snapshot-user', email='snapshot-user@example.test', password_hash='x') - task = ShippingTask(task_no='SN-SNAPSHOT-001', source_type='test', order_data_version=7) + user = User(username=f'snapshot-user-{suffix}', email=f'snapshot-user-{suffix}@example.test', password_hash='x') + task = ShippingTask(task_no=f'SN-SNAPSHOT-{suffix}', source_type='test', order_data_version=7) schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Frozen order') db.session.add_all([user, task, schema]) db.session.flush() definitions = [] fields: dict[str, ShippingOrderField] = {} - field_codes = [*HEADER_FIELDS, *LINE_FIELDS] + field_codes = [*HEADER_FIELD_PROJECTIONS, *LINE_FIELD_PROJECTIONS] if with_extension: field_codes.append('packing_reference') for position, code in enumerate(field_codes, start=1): - scope = 'header' if code in HEADER_FIELDS else 'line' - value_type = 'decimal' if code in {'qty', 'unit_price', 'amount'} else ('date' if code in {'required_date', 'order_date'} else 'string') + scope = 'header' if code in HEADER_FIELD_PROJECTIONS else 'line' + value_type = 'decimal' if code in {'qty', 'unit_price', 'line_amount_with_tax'} else ('date' if code in {'required_date', 'order_date'} else 'string') field = ShippingOrderField( schema_id=schema.id, field_code=code, scope=scope, value_type=value_type, field_category='order_header' if scope == 'header' else 'order_line', @@ -64,6 +65,27 @@ def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension: version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={'fields': definitions}, checksum='snapshot-test') db.session.add(version) db.session.flush() + bindings = [ + ('fulfillment.reservation_identity', 'reservation_id'), + ('fulfillment.part_number', 'part_number'), + ('fulfillment.quantity', 'qty'), + ('routing.inventory_source_hint', 'inventory_source_hint'), + ] + db.session.add(ShippingFulfillmentPolicy( + schema_id=schema.id, policy_code='SHIP_AVAILABLE_ROLLING_V1', version=1, status='published', + checksum='policy-test', definition_json={ + 'policy_code': 'SHIP_AVAILABLE_ROLLING_V1', 'fulfillment_mode': 'ship_available_rolling', + 'requires_confirmed_customer': True, 'allows_partial_reservation': False, + 'field_bindings': [ + { + 'capability_code': capability, 'field_id': fields[field_code].id, + 'field_code': field_code, 'scope': 'line', + 'value_type': 'decimal' if field_code == 'qty' else 'string', + } + for capability, field_code in bindings + ], + }, + )) extraction = ShippingOrderExtraction( task_id=task.id, schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted', ) @@ -73,15 +95,15 @@ def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension: db.session.add(line) db.session.flush() values = { - 'po_number': 'PO-0001', 'customer_code': 'C-001', 'customer_name': 'Customer', + 'customer_po_number': 'PO-0001', 'customer_code': 'C-001', 'customer_name': 'Customer', 'part_number': '000123', 'reservation_id': '0012345678', 'qty': Decimal('12.50'), - 'unit_price': Decimal('2.30'), 'amount': Decimal('28.75'), 'uom': 'PCS', + 'unit_price': Decimal('2.30'), 'line_amount_with_tax': Decimal('28.75'), 'uom': 'PCS', 'packing_reference': 'PK-0007', } for code, field in fields.items(): value = values.get(code) decision = ShippingOrderFieldDecision( - extraction_id=extraction.id, line_id=None if code in HEADER_FIELDS else line.id, + extraction_id=extraction.id, line_id=None if code in HEADER_FIELD_PROJECTIONS else line.id, field_id=field.id, decision_status='accepted', resolved_value_json=str(value) if isinstance(value, Decimal) else value, supporting_observation_ids_json=[], ) @@ -89,7 +111,7 @@ def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension: db.session.flush() if value is not None: db.session.add(ShippingOrderFieldValue( - extraction_id=extraction.id, line_id=None if code in HEADER_FIELDS else line.id, + extraction_id=extraction.id, line_id=None if code in HEADER_FIELD_PROJECTIONS else line.id, field_id=field.id, decision_id=decision.id, value_json=str(value) if isinstance(value, Decimal) else value, value_text=str(value) if isinstance(value, str) else None, value_decimal=value if isinstance(value, Decimal) else None, @@ -187,6 +209,38 @@ def test_freeze_rejects_core_field_type_drift(app): assert error.value.code == 'SHIPPING.ORDER_CONTRACT_INVALID' +def test_freeze_allows_schema_without_optional_standard_fields(app): + """关键断言:当前滚动发货策略只要求预约号、料号和正数数量,不要求全部标准字段。""" + with app.app_context(): + task, user = _build_accepted_order() + extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) + required = {'reservation_id', 'part_number', 'qty'} + extraction.schema_version.definition_json['fields'] = [ + item for item in extraction.schema_version.definition_json['fields'] + if item['field_code'] in required + ] + + snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7) + + assert snapshot.lines[0].reservation_id == '0012345678' + assert snapshot.currency is None + assert snapshot.rule_versions_json['fulfillment_policy']['code'] == 'SHIP_AVAILABLE_ROLLING_V1' + + +def test_freeze_rejects_when_no_fulfillment_policy_is_published(app): + """关键断言:Schema 已发布不等于可履约,未发布策略时必须在冻结入口阻断。""" + with app.app_context(): + task, user = _build_accepted_order() + ShippingFulfillmentPolicy.query.delete() + db.session.commit() + + with pytest.raises(ConflictError) as error: + freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7) + + assert error.value.code == 'SHIPPING.FULFILLMENT_POLICY_NOT_PUBLISHED' + assert task.order_snapshot_id is None + + def test_freeze_rejects_unconfirmed_or_caller_supplied_customer(app): """冻结只能采纳已确认订购客户,调用者传 customer_id 不能绕过该链路。""" with app.app_context(): diff --git a/backend/tests/test_shipping_coordinate_table_reconstruction.py b/backend/tests/test_shipping_coordinate_table_reconstruction.py index 18068095..583e2e25 100644 --- a/backend/tests/test_shipping_coordinate_table_reconstruction.py +++ b/backend/tests/test_shipping_coordinate_table_reconstruction.py @@ -10,7 +10,18 @@ from __future__ import annotations from app.services.shipping_notice.document_layout.contracts import LayoutBBox from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import ( reconstruct_table_from_positioned_text, + suggest_multi_subrow_layouts, ) +from app.services.shipping_notice.document_layout.order_profile import ( + CoordinateReconstructionProfile, + OrderDocumentProfile, + OrderProfileColumnRule, + order_profile_structure_fingerprint, + parse_html_table_with_order_profile, + reconstruct_order_profile_html, +) +from app.services.shipping_notice.document_layout.html_table import parse_html_grid +from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract def _glyphs(*rows: list[tuple[str, float]]) -> list[dict]: @@ -62,3 +73,229 @@ def test_coordinate_reconstruction_only_attaches_deleted_marker_to_prior_line(): assert attached.rows[1].role == 'deleted' assert unattached.rows[0].role == 'needs_review' assert unattached.issues == ['coordinate_reconstruction_deleted_row_unattached'] + + +def test_reconstructed_profile_html_uses_confirmed_relative_column_boundaries(): + """坐标模板用稳定虚拟表头并合并续行,不能回退到错误 HTML 的行列关系。""" + html = reconstruct_order_profile_html( + characters=_glyphs( + [('ITEM NO', 12), ('MATERIAL', 62)], + [('00010', 12), ('PART-A', 62)], + [('PART-A-DETAIL', 62)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 120, 'y1': 70}, + reconstruction=CoordinateReconstructionProfile(column_boundaries=[0, 0.4, 1]), + ) + assert 'coordinate_column_1' in html + assert 'ITEM NO' not in html + assert 'PART-A PART-A-DETAIL' in html + assert html.count(' None: """为导出测试建立冻结订单和可用库存核验,避免测试绕过正式履约门禁。""" + field_codes = { + str(item.get('field_id')): str(item.get('field_code') or '') + for item in (version.definition_json or {}).get('fields') or [] + } + po_number = next( + (str(value) for field_id, value in (header or {}).items() if field_codes.get(str(field_id)) == 'po_number'), + 'TEST-PO-001', + ) snapshot = ShippingOrderSnapshot( task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id, order_data_version=1, rule_versions_json={}, header_values_json={str(key): value for key, value in (header or {}).items()}, + customer_po_number=po_number, ) db.session.add(snapshot) db.session.flush() @@ -225,7 +234,7 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path): _freeze_export_snapshot( task, extraction, version, header={customer.id: 'acme', po_number.id: '16754796'}, - lines=[(1, part.id, 'PN-1', 1, 'RES-EXPORT-1')], + lines=[(1, part.id, 'PN-1', 1, '1000000001')], ) path, filename, artifact = generate_shipment_excel(task) @@ -409,8 +418,8 @@ def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path _freeze_export_snapshot( task, extraction, version, lines=[ - (1, part.id, 'PN-A', 1, 'RES-KEYED-A'), - (2, part.id, 'PN-B', 1, 'RES-KEYED-B'), + (1, part.id, 'PN-A', 1, '1000000002'), + (2, part.id, 'PN-B', 1, '1000000003'), ], ) @@ -579,7 +588,7 @@ def test_export_rejects_ambiguous_inventory_values_and_cleans_partial_file(app, db.session.add(task); db.session.flush() _freeze_export_snapshot( task, extraction, version, - lines=[(1, part.id, 'PN-A', 1, 'RES-AMBIGUOUS-A')], + lines=[(1, part.id, 'PN-A', 1, '1000000004')], ) with pytest.raises(ValueError, match='值不一致'): diff --git a/backend/tests/test_shipping_fulfillment_policy.py b/backend/tests/test_shipping_fulfillment_policy.py new file mode 100644 index 00000000..ac1dd0e2 --- /dev/null +++ b/backend/tests/test_shipping_fulfillment_policy.py @@ -0,0 +1,151 @@ +""" +tests/test_shipping_fulfillment_policy.py + +用途:验证货代字段能力绑定与版本化履约策略。 +依赖:订单 Schema 服务、履约策略注册表与测试数据库。 +逻辑:策略只允许受控能力绑定稳定 field_id;发布后冻结保存版本快照,错误类型或范围必须阻断。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.core.errors import ValidationError +from app.models import ShippingFulfillmentPolicy, ShippingOrderField +from app.services.shipping_notice.fulfillment_policy_registry import create_draft, get_state, publish +from app.services.shipping_notice.order_schema import service as schema_service + + +def _bindings() -> list[dict[str, str]]: + """以当前标准字段的稳定 ID 构造首个滚动履约策略绑定。""" + fields = {item.field_code: item for item in ShippingOrderField.query.filter_by(status='active').all()} + return [ + {'capability_code': 'fulfillment.reservation_identity', 'field_id': fields['reservation_id'].id}, + {'capability_code': 'fulfillment.part_number', 'field_id': fields['part_number'].id}, + {'capability_code': 'fulfillment.quantity', 'field_id': fields['qty'].id}, + {'capability_code': 'routing.inventory_source_hint', 'field_id': fields['inventory_source_hint'].id}, + ] + + +def _field_config(field_id: str, *, display_name: str, value_type: str = 'string') -> dict: + """构造可发布的最小字段配置,验证策略只能绑定当前已发布字段。""" + return { + 'field_id': field_id, 'display_name': display_name, 'business_purpose': 'general', + 'required': False, 'aliases': [], 'normalizer_key': 'decimal' if value_type == 'decimal' else 'uppercase_trim', + 'validator_keys': [], 'enum_options': [], + 'evidence_policy': { + 'required': True, 'source_precedence': ['attachment_table'], + 'conflict_policy': 'block', 'allow_single_source': True, + }, + 'relation_role': None, 'comparator_key': 'decimal' if value_type == 'decimal' else 'normalized_text', + } + + +def test_policy_initialization_and_publish_versions_are_isolated(app): + """初始化只创建待确认草稿;发布后新版本退役旧版且保留稳定字段绑定。""" + with app.app_context(): + schema_service.initialize_schema({'display_name': '货代字段'}, actor_id=None) + initial = ShippingFulfillmentPolicy.query.filter_by(status='draft').one() + assert initial.policy_code == 'SHIP_AVAILABLE_ROLLING_V1' + assert {item['capability_code'] for item in initial.definition_json['field_bindings']} >= { + 'fulfillment.reservation_identity', 'fulfillment.part_number', 'fulfillment.quantity', + } + + initial = publish(initial.id, actor_id=None, expected_lock_version=initial.lock_version) + assert initial['status'] == 'published' + + draft = create_draft({'field_bindings': _bindings(), 'change_note': '复核策略'}, actor_id=None) + released = publish(draft['id'], actor_id=None, expected_lock_version=draft['lock_version']) + + assert released['status'] == 'published' + assert ShippingFulfillmentPolicy.query.filter_by(status='retired').one().id == initial['id'] + assert len(get_state()['capabilities']) == 4 + + +def test_policy_rejects_scope_or_type_drift(app): + """能力绑定只能选择匹配 scope/value_type 的字段,不能借字段目录绕过履约契约。""" + with app.app_context(): + schema_service.initialize_schema({'display_name': '货代字段'}, actor_id=None) + bindings = _bindings() + wrong = next(item for item in ShippingOrderField.query.filter_by(field_code='customer_po_number').all()) + bindings[0]['field_id'] = wrong.id + + with pytest.raises(ValidationError) as exc_info: + create_draft({'field_bindings': bindings}, actor_id=None) + assert exc_info.value.code == 'SHIPPING.FULFILLMENT_POLICY_INVALID' + + +def test_policy_allows_a_custom_field_to_bind_a_compatible_capability(app): + """自定义字段只要 scope/type 匹配,即可经策略承担履约能力而不依赖字段编码。""" + with app.app_context(): + schema_service.initialize_schema({'display_name': '货代字段'}, actor_id=None) + custom = schema_service.save_field({ + 'field_code': 'customer_reservation_reference', 'scope': 'line', 'value_type': 'string', + }, actor_id=None) + bindings = _bindings() + bindings[0]['field_id'] = custom['id'] + + draft = create_draft({'field_bindings': bindings, 'change_note': '客户预约单字段'}, actor_id=None) + + reservation = next(item for item in draft['definition']['field_bindings'] + if item['capability_code'] == 'fulfillment.reservation_identity') + assert reservation['field_id'] == custom['id'] + assert reservation['field_code'] == 'customer_reservation_reference' + + +def test_policy_publish_rejects_an_active_field_omitted_from_published_schema(app): + """已有正式 Schema 后,API 不得发布绑定了目录中但未纳入版本的字段的策略。""" + with app.app_context(): + schema_service.initialize_schema({'display_name': '货代字段'}, actor_id=None) + fields = {item.field_code: item for item in ShippingOrderField.query.filter_by(status='active').all()} + draft = schema_service.create_draft({}, actor_id=None) + configs = [ + _field_config(fields['reservation_id'].id, display_name='预定单号'), + _field_config(fields['part_number'].id, display_name='料号'), + _field_config(fields['qty'].id, display_name='数量', value_type='decimal'), + _field_config(fields['inventory_source_hint'].id, display_name='库存源线索'), + ] + saved = schema_service.save_draft(draft['id'], { + 'fields': configs, 'expected_lock_version': draft['lock_version'], + }, actor_id=None) + schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) + custom = schema_service.save_field({ + 'field_code': 'unpublished_reservation_reference', 'scope': 'line', 'value_type': 'string', + }, actor_id=None) + bindings = _bindings() + bindings[0]['field_id'] = custom['id'] + policy_draft = create_draft({'field_bindings': bindings}, actor_id=None) + + with pytest.raises(ValidationError) as exc_info: + publish(policy_draft['id'], actor_id=None, expected_lock_version=policy_draft['lock_version']) + assert exc_info.value.code == 'SHIPPING.FULFILLMENT_POLICY_INVALID' + + +def test_schema_publish_cannot_omit_a_field_bound_by_published_policy(app): + """发布 Schema 时须反查当前策略,避免移除绑定字段后冻结阶段才失败。""" + with app.app_context(): + schema_service.initialize_schema({'display_name': '货代字段'}, actor_id=None) + fields = {item.field_code: item for item in ShippingOrderField.query.filter_by(status='active').all()} + first = schema_service.create_draft({}, actor_id=None) + first_fields = [ + _field_config(fields['reservation_id'].id, display_name='预定单号'), + _field_config(fields['part_number'].id, display_name='料号'), + _field_config(fields['qty'].id, display_name='数量', value_type='decimal'), + _field_config(fields['inventory_source_hint'].id, display_name='库存源线索'), + ] + saved = schema_service.save_draft(first['id'], { + 'fields': first_fields, 'expected_lock_version': first['lock_version'], + }, actor_id=None) + schema_service.publish(first['id'], actor_id=None, expected_lock_version=saved['lock_version']) + initial_policy = ShippingFulfillmentPolicy.query.filter_by(status='draft').one() + publish(initial_policy.id, actor_id=None, expected_lock_version=initial_policy.lock_version) + second = schema_service.create_draft({}, actor_id=None) + only_required = first_fields[:3] + saved = schema_service.save_draft(second['id'], { + 'fields': only_required, 'expected_lock_version': second['lock_version'], + }, actor_id=None) + + with pytest.raises(Exception) as exc_info: + schema_service.publish(second['id'], actor_id=None, expected_lock_version=saved['lock_version']) + assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_PUBLISH_DEPENDENCY_BLOCKED' diff --git a/backend/tests/test_shipping_inventory_routing_engine.py b/backend/tests/test_shipping_inventory_routing_engine.py index 028d0435..b2514f84 100644 --- a/backend/tests/test_shipping_inventory_routing_engine.py +++ b/backend/tests/test_shipping_inventory_routing_engine.py @@ -1,9 +1,9 @@ """ tests/test_shipping_inventory_routing_engine.py -用途:验证库存源路由只消费已发布订单 Schema 的已裁决字段值。 +用途:验证库存源路由只消费冻结订单 Snapshot 中的已裁决字段值。 依赖:订单 Schema service、库存路由模型、inventory_routing_engine。 -逻辑:测试以稳定 field_id 创建 FieldValue,确认库存源线索优先于预定单号兜底且不会读取固定任务行字段。 +逻辑:测试以稳定 field_id 创建冻结行事实,确认库存源线索优先于预定单号兜底且不会读取可变解析投影。 """ from __future__ import annotations @@ -11,48 +11,66 @@ from __future__ import annotations from app.extensions import db from app.models import ( ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderExtraction, - ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingTask, + ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot, + ShippingOrderSnapshotLine, ShippingTask, ) from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules from app.services.shipping_notice.order_schema import service as order_schema_service -def _field_config(field_id: str, *, name: str) -> dict: +def _field_config(field_id: str, *, name: str, value_type: str = 'string') -> dict: """构造最小可发布行字段配置;路由只依赖其稳定 field_id。""" return { 'field_id': field_id, 'display_name': name, 'required': False, 'aliases': [], - 'normalizer_key': 'uppercase_trim', 'validator_keys': [], 'enum_options': [], + 'normalizer_key': 'decimal' if value_type == 'decimal' else 'uppercase_trim', + 'comparator_key': 'decimal' if value_type == 'decimal' else 'normalized_text', 'evidence_policy': { 'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True, }, - 'relation_role': None, 'comparator_key': 'normalized_text', + 'relation_role': None, } def _published_line_fields() -> dict[str, str]: - """创建当前测试所需的预定单号和库存源线索字段,并发布其稳定契约。""" + """创建冻结履约所需字段及可选库存源线索,并发布其稳定契约。""" order_schema_service.initialize_schema({'display_name': '路由字段'}, actor_id=None) reservation = order_schema_service.save_field( {'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None, ) + part_number = order_schema_service.save_field( + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None, + ) + qty = order_schema_service.save_field( + {'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None, + ) source_hint = order_schema_service.save_field( {'field_code': 'inventory_source_hint', 'scope': 'line', 'value_type': 'string'}, actor_id=None, ) draft = order_schema_service.create_draft({}, actor_id=None) reservation_config = _field_config(reservation['id'], name='预定单号') reservation_config['business_purpose'] = 'reservation_id' + part_number_config = _field_config(part_number['id'], name='料号') + part_number_config['business_purpose'] = 'part_number' + qty_config = _field_config(qty['id'], name='数量', value_type='decimal') + qty_config['business_purpose'] = 'quantity' source_hint_config = _field_config(source_hint['id'], name='库存源线索') source_hint_config['business_purpose'] = 'inventory_source_hint' saved = order_schema_service.save_draft(draft['id'], { - 'fields': [reservation_config, source_hint_config], 'expected_lock_version': draft['lock_version'], + 'fields': [reservation_config, part_number_config, qty_config, source_hint_config], + 'expected_lock_version': draft['lock_version'], }, actor_id=None) order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) - return {'reservation_id': reservation['id'], 'inventory_source_hint': source_hint['id']} + return { + 'reservation_id': reservation['id'], 'part_number': part_number['id'], 'qty': qty['id'], + 'inventory_source_hint': source_hint['id'], + } -def _task_with_line_values(values: dict[str, tuple[str, str]]) -> tuple[ShippingTask, dict[str, int]]: - """保存当前解析的 FieldValue;测试断言路由只通过该审计投影读取值。""" +def _task_with_line_values( + fields: dict[str, str], values: dict[str, tuple[str, str]], +) -> tuple[ShippingTask, dict[str, int]]: + """创建冻结快照;路由测试只允许从该不可变事实读取字段。""" task = ShippingTask(task_no='SN-DYNAMIC-ROUTE', user_id=None, source_type='manual') db.session.add(task) db.session.flush() @@ -77,6 +95,23 @@ def _task_with_line_values(values: dict[str, tuple[str, str]]) -> tuple[Shipping value_text=value, value_json=value, )) task.current_order_extraction_id = extraction.id + snapshot_values = {field_id: value for field_id, (value, _purpose) in values.items()} + snapshot_values.setdefault(fields['part_number'], 'PN-ROUTE') + snapshot_values.setdefault(fields['qty'], '1') + snapshot = ShippingOrderSnapshot( + task_id=task.id, extraction_id=extraction.id, + schema_version_id=extraction.schema_version_id, order_data_version=1, + rule_versions_json={}, header_values_json={}, customer_po_number='ROUTE-PO-001', + ) + db.session.add(snapshot) + db.session.flush() + db.session.add(ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, position=0, + reservation_id=str(snapshot_values.get(fields['reservation_id']) or ''), + part_number=str(snapshot_values[fields['part_number']]), qty=snapshot_values[fields['qty']], + field_values_json=snapshot_values, + )) + task.order_snapshot_id = snapshot.id db.session.flush() return task, {'_position': 0} @@ -100,7 +135,7 @@ def test_reservation_prefix_rule_returns_ambiguous_source_candidates(app): """十位预定单号兜底只产生 DUB/RTM 候选,不在路由阶段擅自选择 Source。""" with app.app_context(): fields = _published_line_fields() - task, line = _task_with_line_values({fields['reservation_id']: ('1000123456', 'reservation_id')}) + task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')}) db.session.add(_rule( code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'], conditions=[(fields['reservation_id'], 'prefix', '1')], @@ -115,7 +150,7 @@ def test_inventory_source_hint_wins_over_reservation_fallback(app): """高优先级库存源线索必须覆盖预定单号兜底,体现明确订单事实优先。""" with app.app_context(): fields = _published_line_fields() - task, line = _task_with_line_values({ + task, line = _task_with_line_values(fields, { fields['reservation_id']: ('1000123456', 'reservation_id'), fields['inventory_source_hint']: ('VMI-FRA01', 'inventory_source_hint'), }) @@ -139,7 +174,7 @@ def test_crane_inventory_source_hint_wins_over_reservation_fallback(app): """Crane 邮件线索必须按高优先级规则命中,不依赖五位预定单号兜底。""" with app.app_context(): fields = _published_line_fields() - task, line = _task_with_line_values({ + task, line = _task_with_line_values(fields, { fields['reservation_id']: ('1000123456', 'reservation_id'), fields['inventory_source_hint']: ('LUK', 'inventory_source_hint'), }) @@ -166,7 +201,7 @@ def test_five_digit_reservation_rule_can_route_to_crane(app): """五位纯数字预定单号通过订单 FieldValue 路由 Crane,Warehouse 仍留给库存行匹配。""" with app.app_context(): fields = _published_line_fields() - task, line = _task_with_line_values({fields['reservation_id']: ('12345', 'reservation_id')}) + task, line = _task_with_line_values(fields, {fields['reservation_id']: ('12345', 'reservation_id')}) db.session.add(_rule( code='RSV_LENGTH_5', priority=200, sources=['CRANE'], conditions=[(fields['reservation_id'], 'numeric_length', 5)], diff --git a/backend/tests/test_shipping_inventory_source_gate_migration.py b/backend/tests/test_shipping_inventory_source_gate_migration.py new file mode 100644 index 00000000..dabf40a7 --- /dev/null +++ b/backend/tests/test_shipping_inventory_source_gate_migration.py @@ -0,0 +1,77 @@ +"""验证库存源独立字段迁移可在不存在旧 JSON 列的空库链上执行。""" + +from __future__ import annotations + +import importlib + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def test_inventory_source_gate_backfill_skips_absent_legacy_json_column(monkeypatch): + """关键断言:空库没有 sibling 迁移的 JSON 列时,回填不得查询不存在的列。""" + migration = importlib.import_module('migrations.versions.b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields') + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + sa.Table( + 'shipping_tasks', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('pending_human_reason', sa.String(64)), + sa.Column('inventory_source_status', sa.String(32)), + sa.Column('inventory_source_config_version', sa.String(32)), + ) + sa.Table( + 'shipping_inventory_files', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('source_code', sa.String(64)), + sa.Column('warehouse_id', sa.String(64)), + sa.Column('identity_status', sa.String(32)), + ) + with engine.begin() as connection: + metadata.create_all(connection) + monkeypatch.setattr(migration, 'op', Operations(MigrationContext.configure(connection))) + migration._backfill_legacy_inventory_source() + + +def test_rpa_consumed_run_backfill_skips_absent_legacy_json_column(monkeypatch): + """关键断言:后续幂等迁移在空库链中也不得读取 sibling JSON 列。""" + migration = importlib.import_module('migrations.versions.d6e7f8a9b0c1_add_rpa_callback_idempotency_fields') + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + sa.Table( + 'shipping_tasks', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('inventory_rpa_consumed_run_no', sa.String(128)), + ) + with engine.begin() as connection: + metadata.create_all(connection) + monkeypatch.setattr(migration, 'op', Operations(MigrationContext.configure(connection))) + migration._backfill_consumed_run_no(connection) + + +def test_external_mapping_rename_skips_empty_database_chain(monkeypatch): + """关键断言:新库已无 ERP 表时,兼容重命名迁移必须成为安全空操作。""" + migration = importlib.import_module('migrations.versions.d38f4a5b6c7d_rename_erp_mappings_to_external_mappings') + engine = sa.create_engine('sqlite:///:memory:') + with engine.begin() as connection: + monkeypatch.setattr(migration, 'op', Operations(MigrationContext.configure(connection))) + migration.upgrade() + + +def test_routing_rule_migration_skips_empty_configuration(monkeypatch): + """关键断言:没有旧路由条件的空库不得要求业务管理员预先发布 Schema。""" + migration = importlib.import_module('migrations.versions.ad2e3f4a5b6c_migrate_routing_rules_to_order_fields') + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + sa.Table('shipping_order_schema_versions', metadata, sa.Column('id', sa.Integer(), primary_key=True), sa.Column('status', sa.String()), sa.Column('definition_json', sa.JSON())) + sa.Table('shipping_inventory_routing_rules', metadata, sa.Column('id', sa.Integer(), primary_key=True), sa.Column('status', sa.String())) + sa.Table( + 'shipping_inventory_routing_rule_conditions', metadata, + sa.Column('id', sa.Integer(), primary_key=True), sa.Column('rule_id', sa.Integer()), + sa.Column('source_kind', sa.String()), sa.Column('order_field_id', sa.String()), sa.Column('system_fact_key', sa.String()), + ) + with engine.begin() as connection: + metadata.create_all(connection) + monkeypatch.setattr(migration, 'op', Operations(MigrationContext.configure(connection))) + migration.upgrade() diff --git a/backend/tests/test_shipping_notice_tools.py b/backend/tests/test_shipping_notice_tools.py index 6ece8efa..82c08d9a 100644 --- a/backend/tests/test_shipping_notice_tools.py +++ b/backend/tests/test_shipping_notice_tools.py @@ -82,7 +82,16 @@ def _attach_dynamic_order(task: ShippingTask, *, part_number: str, reservation_i # 建立最小履约真相,避免旧测试绕过阶段 1 门禁。 snapshot = ShippingOrderSnapshot( task_id=task.id, extraction_id=extraction.id, schema_version_id=published['id'], - order_data_version=task.order_data_version or 1, rule_versions_json={}, header_values_json={}, + order_data_version=task.order_data_version or 1, + rule_versions_json={'fulfillment_policy': { + 'code': 'SHIP_AVAILABLE_ROLLING_V1', 'version': 1, + 'definition': {'field_bindings': [ + {'capability_code': 'fulfillment.part_number', 'field_id': fields['part_number']['id'], 'scope': 'line'}, + {'capability_code': 'fulfillment.reservation_identity', 'field_id': fields['reservation_id']['id'], 'scope': 'line'}, + {'capability_code': 'fulfillment.quantity', 'field_id': fields['qty']['id'], 'scope': 'line'}, + ]}, + }}, + header_values_json={}, ) db.session.add(snapshot) db.session.flush() diff --git a/backend/tests/test_shipping_order_document_profile_service.py b/backend/tests/test_shipping_order_document_profile_service.py index 6a47e4b4..174ac685 100644 --- a/backend/tests/test_shipping_order_document_profile_service.py +++ b/backend/tests/test_shipping_order_document_profile_service.py @@ -17,6 +17,8 @@ from app.models import ( ShippingOrderDocumentProfile, ShippingNoticeDocument, ShippingNoticeIntake, + ShippingDocumentProfileTestSample, + ShippingDocumentProfileTestSuite, FileAsset, ShippingOrderSchema, ShippingOrderSchemaVersion, @@ -412,3 +414,269 @@ def test_profile_sample_intake_is_isolated_from_shipping_business_flow(app): with pytest.raises(Exception) as caught: create_order_document_profile_sample_intake(user_id=user.id, asset_no=invalid.asset_no) assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_FILE_TYPE_INVALID' + + +def test_profile_sample_delete_only_allows_unreferenced_dedicated_samples(app, monkeypatch): + """专用样本可回收;历史业务样本与盲测证据必须由删除门禁保留。""" + with app.app_context(): + user = User(username='sample-delete-admin', email='sample-delete@example.com', role='admin', status='active') + asset = FileAsset( + asset_no='FA-PROFILE-DELETE', owner_user_id=1, original_filename='delete.pdf', + storage_provider='minio', storage_bucket='test', storage_key='delete.pdf', + content_hash='1' * 64, file_size=100, mime_type='application/pdf', + upload_status='ready', lifecycle_status='referenced', reference_count=1, + ) + db.session.add(user) + db.session.flush() + asset.owner_user_id = user.id + db.session.add(asset) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no='SNI-PROFILE-DELETE', asset_id=asset.id, user_id=user.id, + purpose='order_document_profile_sample', parse_status='parsed', parser_version='v6', + ) + db.session.add(intake) + db.session.flush() + document = ShippingNoticeDocument( + intake_id=intake.id, asset_id=asset.id, document_type='attachment', + attachment_key='delete.pdf', filename='delete.pdf', content_hash='1' * 64, + classification='supporting', parse_status='parsed', + ) + db.session.add(document) + db.session.commit() + + deleted_assets: list[str] = [] + monkeypatch.setattr( + 'app.services.file_assets.service.delete_temporary_asset', + lambda *, asset_no, user_id: deleted_assets.append(asset_no), + ) + service.delete_sample_intake(intake.intake_no, actor_id=user.id) + assert ShippingNoticeIntake.query.filter_by(intake_no=intake.intake_no).first() is None + assert deleted_assets == ['FA-PROFILE-DELETE'] + + asset.reference_count = 1 + asset.lifecycle_status = 'referenced' + + protected_intake = ShippingNoticeIntake( + intake_no='SNI-PROFILE-BLIND', asset_id=asset.id, user_id=user.id, + purpose='order_document_profile_sample', parse_status='parsed', parser_version='v7', + ) + db.session.add(protected_intake) + db.session.flush() + protected_document = ShippingNoticeDocument( + intake_id=protected_intake.id, asset_id=asset.id, document_type='attachment', + attachment_key='blind.pdf', filename='blind.pdf', content_hash='2' * 64, + classification='supporting', parse_status='parsed', + ) + profile = ShippingOrderDocumentProfile( + profile_code='DELETE_TEST', display_name='Delete test', version=1, + status='published', schema_version_id=_schema_version().id, + structure_fingerprint='2' * 64, definition_json={}, checksum='2' * 64, + published_at=datetime.utcnow(), lock_version=1, + ) + db.session.add_all([protected_document, profile]) + db.session.flush() + suite = ShippingDocumentProfileTestSuite( + profile_id=profile.id, profile_checksum=profile.checksum, created_by_id=user.id, + ) + db.session.add(suite) + db.session.flush() + db.session.add(ShippingDocumentProfileTestSample( + suite_id=suite.id, document_id=protected_document.id, table_id='table-1', + expected_rows_json=[], created_by_id=user.id, + )) + db.session.commit() + with pytest.raises(Exception) as caught: + service.delete_sample_intake(protected_intake.intake_no, actor_id=user.id) + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED' + + +def test_profile_normalizes_coordinate_fields_from_column_rules(app): + """服务端必须覆盖浏览器伪造的坐标字段辅助数组和新行列。""" + with app.app_context(): + schema = _schema_version() + saved = service.save_draft({ + 'profile_code': 'COORDINATE_SAFE', 'display_name': 'Coordinate safe', + 'schema_version_id': schema.id, + 'definition': { + 'structure_fingerprint': 'a' * 64, + 'header_row_index': 0, 'data_start_row_index': 1, + 'row_structure': 'preserved', + 'column_rules': [ + {'column_index': 0, 'extractor_key': 'direct', 'target_field_codes': ['customer_part_number']}, + {'column_index': 1, 'extractor_key': 'direct', 'target_field_codes': ['part_number']}, + {'column_index': 2, 'extractor_key': 'direct', 'target_field_codes': ['qty']}, + ], + 'coordinate_reconstruction': { + 'column_boundaries': [0, 0.2, 0.8, 1], + 'column_field_codes': ['qty', 'qty', 'qty'], + 'line_start_column_index': 2, + }, + }, + }, actor_id=None) + + reconstruction = saved['definition']['coordinate_reconstruction'] + assert reconstruction['column_field_codes'] == ['customer_part_number', 'part_number', 'qty'] + assert reconstruction['line_start_column_index'] == 0 + + +def test_profile_accepts_schema_bound_multi_subrow_layouts(app): + """多子行允许重叠字段语义,但每个字段都必须来自绑定 Schema。""" + with app.app_context(): + schema = _schema_version() + saved = service.save_draft({ + 'profile_code': 'MULTI_SUBROW', 'display_name': 'Multi subrow', + 'schema_version_id': schema.id, + 'definition': { + 'structure_fingerprint': 'c' * 64, + 'header_row_index': 0, 'data_start_row_index': 1, + 'row_structure': 'preserved', + 'column_rules': [ + {'column_index': 0, 'extractor_key': 'direct', 'target_field_codes': ['customer_part_number']}, + {'column_index': 1, 'extractor_key': 'direct', 'target_field_codes': ['part_number']}, + {'column_index': 2, 'extractor_key': 'direct', 'target_field_codes': ['qty']}, + ], + 'coordinate_reconstruction': {'subrow_layouts': [ + {'role': 'main', 'row_offset': 0, 'column_boundaries': [0, 0.3, 0.7, 1], + 'column_field_codes': ['customer_part_number', 'part_number', 'qty']}, + {'role': 'continuation', 'row_offset': 1, 'column_boundaries': [0, 0.5, 1], + 'column_field_codes': [None, 'customer_part_number']}, + ]}, + }, + }, actor_id=None) + + subrows = saved['definition']['coordinate_reconstruction']['subrow_layouts'] + assert subrows[0]['column_field_codes'] == ['customer_part_number', 'part_number', 'qty'] + assert subrows[1]['column_field_codes'] == [None, 'customer_part_number'] + + +def test_coordinate_preview_reports_four_source_rows(app, monkeypatch): + """四行物理版式在管理端预览中必须合并为一条逻辑明细并保留全部来源行。""" + def characters(*rows: list[tuple[str, float]]) -> list[dict]: + """构造四条相互分离的坐标文本行,模拟持久化原生 PDF 字符证据。""" + result: list[dict] = [] + source_index = 0 + for row_index, row in enumerate(rows): + for text, x0 in row: + for character_index, character in enumerate(text): + result.append({ + 'text': character, + 'source_index': source_index, + 'bbox': { + 'x0': x0 + character_index * 5, + 'y0': 10 + row_index * 20, + 'x1': x0 + (character_index + 1) * 5, + 'y1': 20 + row_index * 20, + }, + }) + source_index += 1 + return result + + layout = { + 'tables': [{ + 'table_id': 'four-row', 'page_no': 1, + 'bbox': {'x0': 0, 'y0': 0, 'x1': 320, 'y1': 100}, + 'html': '
broken
', + }], + 'coordinate_evidence': {'tables': {'four-row': characters( + [('10', 12), ('PART-10', 100), ('3', 270)], + [('VENDOR-10', 180)], + [('05/05/2026', 180)], + [('R2_SA;HF_SA', 180)], + )}}, + } + monkeypatch.setattr(db.session, 'get', lambda model, object_id: object() if object_id == 101 else None) + monkeypatch.setattr(service, '_document_layout', lambda document: layout) + + with app.app_context(): + preview = service.preview_coordinate_reconstruction({ + 'document_id': 101, + 'table_id': 'four-row', + 'coordinate_reconstruction': {'subrow_layouts': [ + {'role': 'main', 'row_offset': 0, 'column_boundaries': [0, 0.25, 0.7, 1], + 'column_field_codes': ['line_no', 'part_number', 'qty']}, + {'role': 'continuation', 'row_offset': 1, 'column_boundaries': [0, 0.5, 1], + 'column_field_codes': [None, 'customer_part_number']}, + {'role': 'continuation', 'row_offset': 2, 'column_boundaries': [0, 0.5, 1], + 'column_field_codes': [None, 'required_date']}, + {'role': 'continuation', 'row_offset': 3, 'column_boundaries': [0, 0.5, 1], + 'column_field_codes': [None, 'part_number']}, + ]}, + }, actor_id=None) + + assert preview['row_count'] == 2 + assert preview['row_roles'] == ['header', 'data'] + assert preview['source_row_indices'] == [[], [0, 1, 2, 3]] + + +def test_coordinate_suggestion_returns_reviewable_dynamic_rows(app, monkeypatch): + """建议接口只返回相对边界和示例,并自动标出首行 line_no。""" + characters = [] + source_index = 0 + for row_index, row in enumerate([ + [('00020', 12), ('PART-20', 100), ('36', 270)], + [('VENDOR-20', 150)], + ]): + for text, x0 in row: + for character_index, character in enumerate(text): + characters.append({ + 'text': character, 'source_index': source_index, + 'bbox': { + 'x0': x0 + character_index * 5, 'y0': 10 + row_index * 20, + 'x1': x0 + (character_index + 1) * 5, 'y1': 20 + row_index * 20, + }, + }) + source_index += 1 + layout = { + 'tables': [{'table_id': 'suggest', 'bbox': {'x0': 0, 'y0': 0, 'x1': 320, 'y1': 70}, + 'html': '
broken
'}], + 'coordinate_evidence': {'tables': {'suggest': characters}}, + } + monkeypatch.setattr(db.session, 'get', lambda model, object_id: object() if object_id == 102 else None) + monkeypatch.setattr(service, '_document_layout', lambda document: layout) + + with app.app_context(): + result = service.suggest_coordinate_reconstruction( + {'document_id': 102, 'table_id': 'suggest'}, actor_id=None, + ) + + assert result['status'] == 'needs_review' + assert len(result['subrow_layouts']) == 2 + assert result['subrow_layouts'][0]['suggested_field_codes'][0] == 'line_no' + assert result['subrow_layouts'][1]['column_boundaries'] == [0.0, 1.0] + + +def test_coordinate_suggestion_can_return_only_requested_physical_row(app, monkeypatch): + """指定 row_offset 时只返回当前物理行,避免覆盖管理员已确认的其他行。""" + characters = [] + source_index = 0 + for row_index, row in enumerate([ + [('00020', 12), ('PART-20', 100), ('36', 270)], + [('VENDOR-20', 150)], + ]): + for value, x0 in row: + for character_index, character in enumerate(value): + characters.append({ + 'text': character, 'source_index': source_index, + 'bbox': { + 'x0': x0 + character_index * 5, 'y0': 10 + row_index * 20, + 'x1': x0 + (character_index + 1) * 5, 'y1': 20 + row_index * 20, + }, + }) + source_index += 1 + layout = { + 'tables': [{'table_id': 'suggest-one', 'bbox': {'x0': 0, 'y0': 0, 'x1': 320, 'y1': 70}, + 'html': '
broken
'}], + 'coordinate_evidence': {'tables': {'suggest-one': characters}}, + } + monkeypatch.setattr(db.session, 'get', lambda model, object_id: object() if object_id == 103 else None) + monkeypatch.setattr(service, '_document_layout', lambda document: layout) + + with app.app_context(): + result = service.suggest_coordinate_reconstruction( + {'document_id': 103, 'table_id': 'suggest-one', 'row_offset': 1}, actor_id=None, + ) + + # 当前行识别只返回 row_offset=1,首行建议不会混入响应。 + assert [item['row_offset'] for item in result['subrow_layouts']] == [1] + assert result['subrow_layouts'][0]['column_samples'] == [['VENDOR-20']] diff --git a/backend/tests/test_shipping_order_field_purposes.py b/backend/tests/test_shipping_order_field_purposes.py index 24b130aa..d74134c3 100644 --- a/backend/tests/test_shipping_order_field_purposes.py +++ b/backend/tests/test_shipping_order_field_purposes.py @@ -1,16 +1,17 @@ """ tests/test_shipping_order_field_purposes.py -用途:验证履约门禁从任务锁定的订单 Schema 快照和 FieldValue 读取业务字段。 -依赖:订单 Schema service/runtime 模型、reservation_gate。 -逻辑:当前任务不读取固定任务行投影;缺少用途或 Extraction 时必须明确阻断。 +用途:验证履约门禁只从冻结订单快照及其冻结策略读取预约单号。 +依赖:订单 Schema service、冻结快照模型、reservation_gate。 +逻辑:当前任务不得读取可变 FieldValue 或旧任务行投影;策略缺少能力时必须明确阻断。 """ from __future__ import annotations from app import db from app.models import ( - ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingTask, + ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, + ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingTask, ) from app.services.shipping_notice.order_schema import service from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues @@ -30,8 +31,8 @@ def _config(field_id: str) -> dict: } -def _task_with_reservation(value: str) -> ShippingTask: - """发布 Schema 并持久化当前 Extraction 的行级 FieldValue。""" +def _task_with_reservation(value: str, *, include_reservation_capability: bool = True) -> ShippingTask: + """创建冻结快照,策略绑定决定履约阶段如何定位预约单号。""" service.initialize_schema({'display_name': '用途测试'}, actor_id=None) field = service.save_field({'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None) draft = service.create_draft({}, actor_id=None) @@ -61,25 +62,47 @@ def _task_with_reservation(value: str) -> ShippingTask: value_text=value, value_json=value, )) task.current_order_extraction_id = extraction.id + bindings = [] + if include_reservation_capability: + bindings.append({ + 'capability_code': 'fulfillment.reservation_identity', + 'field_id': field['id'], + 'scope': 'line', + }) + snapshot = ShippingOrderSnapshot( + task_id=task.id, extraction_id=extraction.id, schema_version_id=published['id'], order_data_version=1, + customer_po_number='PURPOSE-PO-001', header_values_json={}, + rule_versions_json={'fulfillment_policy': { + 'code': 'SHIP_AVAILABLE_ROLLING_V1', 'version': 1, + 'definition': {'field_bindings': bindings}, + }}, + ) + db.session.add(snapshot) + db.session.flush() + db.session.add(ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, position=0, reservation_id=value, + field_values_json={field['id']: value}, + )) + task.order_snapshot_id = snapshot.id db.session.commit() return task -def test_task_reservation_gate_uses_current_field_value_not_task_line_projection(app): - """门禁以 FieldValue 的合法号码为准,即使旧任务行投影保存错误值也不得阻断。""" +def test_task_reservation_gate_uses_frozen_value_not_mutable_projection_or_field_value(app): + """门禁以冻结预约单为准,旧任务投影或后续 FieldValue 变化均不得重解释履约。""" with app.app_context(): task = _task_with_reservation('3000000001') + task.lines_json = [{'reservation_id': 'INVALID'}] + value = ShippingOrderFieldValue.query.filter_by(extraction_id=task.current_order_extraction_id).one() + value.value_text = 'INVALID' + value.value_json = 'INVALID' + db.session.commit() assert task_reservation_gate_issues(task) == [] -def test_task_reservation_gate_blocks_extraction_without_purpose(app): - """历史 Schema 未声明业务用途时不得猜测 field_code,必须阻断履约。""" +def test_task_reservation_gate_blocks_snapshot_without_reservation_capability(app): + """冻结策略缺少预约单能力时不得猜测 field_code,必须阻断履约。""" with app.app_context(): - task = _task_with_reservation('3000000001') - extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) - definition = dict(extraction.schema_version.definition_json) - definition['fields'] = [dict(item, business_purpose='general') for item in definition['fields']] - extraction.schema_version.definition_json = definition - db.session.commit() + task = _task_with_reservation('3000000001', include_reservation_capability=False) issues = task_reservation_gate_issues(task) assert issues[0]['reason'] == 'order_schema_unavailable' diff --git a/backend/tests/test_shipping_order_schema.py b/backend/tests/test_shipping_order_schema.py index cb927b90..bd79d453 100644 --- a/backend/tests/test_shipping_order_schema.py +++ b/backend/tests/test_shipping_order_schema.py @@ -16,6 +16,7 @@ from sqlalchemy.exc import IntegrityError from app import db from app.models import ( ShippingExcelTemplate, + ShippingFulfillmentPolicy, ShippingInventoryParsingProfile, ShippingOrderExtraction, ShippingOrderField, @@ -83,17 +84,19 @@ def _publish_draft(version_id: int) -> dict: return service.publish(version_id, actor_id=None, expected_lock_version=version.lock_version) -def test_order_schema_initializes_fixed_core_and_allows_extension_fields(app): - """关键断言:25 个预置业务核心不可变;扩展字段仍允许按业务治理新增。""" +def test_order_schema_initializes_standard_fields_and_allows_extension_fields(app): + """关键断言:57 个预置标准字段身份不可变;扩展字段仍允许按业务治理新增。""" with app.app_context(): service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) - core_codes = set(service.FIXED_CORE_FIELD_SPECS) + core_codes = set(service.STANDARD_ORDER_FIELD_SPECS) fields = ShippingOrderField.query.order_by(ShippingOrderField.display_sequence).all() - assert len(core_codes) == 25 + assert len(core_codes) == 57 assert {field.field_code for field in fields} == core_codes - assert service.FIXED_CORE_FIELD_SPECS['bill_to_address'] == ('header', 'string') - assert 'bill_to_customer_code' not in core_codes + assert service.STANDARD_ORDER_FIELD_SPECS['bill_to_address'] == ('header', 'string') + assert service.STANDARD_ORDER_FIELD_SPECS['product_revision'] == ('line', 'string') + assert 'po_number' not in core_codes + assert 'aws_part_number' not in core_codes bill_to_address = next(field for field in fields if field.field_code == 'bill_to_address') with pytest.raises(Exception) as error: @@ -281,6 +284,48 @@ def test_order_schema_admin_api_permissions_and_validation(app, client): assert parse_api_error(invalid.get_json())['code'] == 'SHIPPING.ORDER_FIELD_INVALID' +def test_fulfillment_policy_admin_api_requires_published_schema_and_admin(app, client): + """关键断言:策略仅由管理员发布,且绑定字段必须存在于当前 published Schema。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + _seed_users() + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + fields = {item.field_code: item for item in ShippingOrderField.query.filter_by(status='active').all()} + draft = service.create_draft({}, actor_id=None) + configs = [] + for code, name, value_type in ( + ('reservation_id', '预约单号', 'string'), + ('part_number', '料号', 'string'), + ('qty', '数量', 'decimal'), + ('inventory_source_hint', '库存源线索', 'string'), + ): + config = _field_config(fields[code].id, name=name) + config.update({ + 'aliases': [], + 'normalizer_key': 'decimal' if value_type == 'decimal' else 'uppercase_trim', + 'validator_keys': ['positive_decimal'] if value_type == 'decimal' else ['reservation_id'] if code == 'reservation_id' else [], + 'comparator_key': 'decimal' if value_type == 'decimal' else 'normalized_text', + }) + configs.append(config) + _save_draft(draft['id'], configs) + _publish_draft(draft['id']) + policy = ShippingFulfillmentPolicy.query.filter_by(status='draft').one() + + forbidden = client.post( + f'/api/admin/shipping-fulfillment-policies/{policy.id}/publish', + headers=_headers('schema-user', 'user'), json={'expected_lock_version': policy.lock_version}, + ) + assert forbidden.status_code == 403 + assert parse_api_error(forbidden.get_json())['code'] == 'AUTH.FORBIDDEN' + + published = client.post( + f'/api/admin/shipping-fulfillment-policies/{policy.id}/publish', + headers=_headers('schema-admin', 'admin'), json={'expected_lock_version': policy.lock_version}, + ) + assert published.status_code == 200 + assert parse_api_data(published.get_json())['status'] == 'published' + + def test_dynamic_header_field_value_is_unique(app): """Header 动态字段值必须按 extraction+field 唯一,避免 NULL 绕过唯一约束。""" with app.app_context(): @@ -354,7 +399,7 @@ def test_delete_unused_order_field_removes_draft_config_and_catalog_row(app): assert result == {'field_id': field['id'], 'action': 'deleted'} assert db.session.get(ShippingOrderField, field['id']) is None - assert {item['field_code'] for item in service.get_state()['fields']} == set(service.FIXED_CORE_FIELD_SPECS) + assert {item['field_code'] for item in service.get_state()['fields']} == set(service.STANDARD_ORDER_FIELD_SPECS) assert service.get_state()['versions'][0]['field_count'] == 0 @@ -376,7 +421,7 @@ def test_delete_historical_order_field_archives_and_hides_current_catalog(app): assert result == {'field_id': field['id'], 'action': 'archived'} assert db.session.get(ShippingOrderField, field['id']).status == 'retired' - assert {item['field_code'] for item in service.get_state()['fields']} == set(service.FIXED_CORE_FIELD_SPECS) + assert {item['field_code'] for item in service.get_state()['fields']} == set(service.STANDARD_ORDER_FIELD_SPECS) assert service.get_state()['versions'][0]['id'] == next_draft['id'] assert service.get_state()['versions'][0]['field_count'] == 0 @@ -436,7 +481,18 @@ def test_schema_publish_cannot_omit_field_referenced_by_downstream_config(app): first = service.create_draft({}, actor_id=None) referenced_config = _field_config(referenced['id']) referenced_config.update({'normalizer_key': 'trim', 'comparator_key': 'normalized_text', 'validator_keys': []}) - _save_draft(first['id'], [referenced_config]) + fields = {item.field_code: item for item in ShippingOrderField.query.filter_by(status='active').all()} + policy_configs = [] + for code in ('reservation_id', 'part_number', 'qty', 'inventory_source_hint'): + config = _field_config(fields[code].id, name=code) + config.update({ + 'aliases': [], 'extraction_instruction': '', + 'normalizer_key': 'decimal' if code == 'qty' else 'uppercase_trim', + 'validator_keys': ['positive_decimal'] if code == 'qty' else ['reservation_id'] if code == 'reservation_id' else [], + 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text', + }) + policy_configs.append(config) + _save_draft(first['id'], policy_configs) _publish_draft(first['id']) db.session.add(ShippingInventoryParsingProfile( profile_code='schema-gate', display_name='Schema Gate', status='published', @@ -453,7 +509,9 @@ def test_schema_publish_cannot_omit_field_referenced_by_downstream_config(app): with pytest.raises(Exception) as exc_info: _publish_draft(second['id']) assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_PUBLISH_DEPENDENCY_BLOCKED' - assert service.get_published_contract()['fields'][0]['field_id'] == referenced['id'] + assert referenced['id'] in { + field['field_id'] for field in service.get_published_contract()['fields'] + } def test_order_schema_rejects_type_incompatible_rules_and_can_delete_draft(app): @@ -539,7 +597,7 @@ def test_order_field_global_order_persists_without_schema_draft(app): refreshed = service.get_state() assert [item['id'] for item in refreshed['fields']][-2:] == [second['id'], first['id']] - assert [item['display_sequence'] for item in refreshed['fields']][-2:] == [26, 27] + assert [item['display_sequence'] for item in refreshed['fields']][-2:] == [58, 59] assert not any(item['status'] == 'draft' for item in refreshed['versions']) diff --git a/backend/tests/test_shipping_reservation_global_unique_migration.py b/backend/tests/test_shipping_reservation_global_unique_migration.py new file mode 100644 index 00000000..b8dbd15e --- /dev/null +++ b/backend/tests/test_shipping_reservation_global_unique_migration.py @@ -0,0 +1,41 @@ +""" +backend/tests/test_shipping_reservation_global_unique_migration.py + +用途:验证 Reservation 改为单列全局唯一后的数据库结构。 +依赖:Alembic Operations 与 SQLite 最小前置表。 +逻辑:先执行滚动履约初始迁移,再验证后继迁移替换唯一约束并增加 PO 快照。 +""" + +from __future__ import annotations + +import importlib + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def test_global_reservation_migration_replaces_composite_unique_constraint(monkeypatch): + """关键断言:Reservation 单列唯一且 PO 快照为必填,回滚可恢复旧约束。""" + initial = importlib.import_module('migrations.versions.022a3b4c5d6e_add_shipping_rolling_fulfillment') + migration = importlib.import_module('migrations.versions.025b6c7d8e9f_make_shipping_reservation_globally_unique') + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + for table in ('shipping_tasks', 'shipping_order_snapshot_lines', 'shipping_export_artifacts', 'shipping_inventory_files'): + sa.Table(table, metadata, sa.Column('id', sa.Integer(), primary_key=True)) + metadata.create_all(engine) + with engine.begin() as connection: + context = MigrationContext.configure(connection) + operations = Operations(context) + monkeypatch.setattr(initial, 'op', operations) + monkeypatch.setattr(migration, 'op', operations) + initial.upgrade() + migration.upgrade() + inspector = sa.inspect(connection) + columns = {item['name']: item for item in inspector.get_columns('shipping_reservations')} + constraints = inspector.get_unique_constraints('shipping_reservations') + assert columns['po_number_normalized']['nullable'] is False + assert any(item['name'] == 'uq_shipping_reservations_reservation_id' and item['column_names'] == ['reservation_id'] for item in constraints) + migration.downgrade() + constraints = sa.inspect(connection).get_unique_constraints('shipping_reservations') + assert any(item['name'] == 'uq_shipping_reservations_reservation_part' for item in constraints) diff --git a/backend/tests/test_shipping_rolling_fulfillment.py b/backend/tests/test_shipping_rolling_fulfillment.py index 48901739..d3a188c6 100644 --- a/backend/tests/test_shipping_rolling_fulfillment.py +++ b/backend/tests/test_shipping_rolling_fulfillment.py @@ -10,10 +10,14 @@ from __future__ import annotations from decimal import Decimal +import pytest + from app import db -from app.models import ShippingOrderSnapshotLine, ShippingReservation +from app.core.errors import ConflictError, ValidationError +from app.models import ShippingOrderExtraction, ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingReservation, ShippingTask from app.services.shipping_notice.reservation_service import ( current_available_snapshot_line_ids, + ensure_task_reservations, record_inventory_verification, ) from tests.services.shipping_notice.test_shipping_order_snapshot import _build_accepted_order @@ -79,3 +83,124 @@ def test_rolling_reservation_only_selects_unoccupied_lines_in_later_round(app): _verification, second_available = current_available_snapshot_line_ids(task) assert second.id > first.id assert second_available == {third_line.id} # C 后续补货,只能进入第二轮。 + + +def test_reservation_rejects_different_purchase_order_and_requires_review_for_same_po_change(app): + """关键断言:Reservation 全局归属首个 PO;同 PO 的料号或数量变化只能走人工修订。""" + with app.app_context(): + first_task, first_user = _build_accepted_order(suffix='101') + first_snapshot = freeze_order_snapshot(first_task, actor_id=first_user.id, expected_order_data_version=7) + ensure_task_reservations(first_task) + db.session.commit() + + second_task = ShippingTask(task_no='SN-SNAPSHOT-102', source_type='test') + db.session.add(second_task) + db.session.flush() + extraction = ShippingOrderExtraction( + task_id=second_task.id, schema_version_id=first_snapshot.schema_version_id, + input_snapshot_hash='b' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + second_snapshot = ShippingOrderSnapshot( + task_id=second_task.id, extraction_id=extraction.id, schema_version_id=first_snapshot.schema_version_id, + order_data_version=1, rule_versions_json={}, header_values_json={}, customer_po_number='PO-OTHER', + ) + db.session.add(second_snapshot) + db.session.flush() + db.session.add(ShippingOrderSnapshotLine( + snapshot_id=second_snapshot.id, position=0, reservation_id='0012345678', + part_number='000123', qty=Decimal('12.5'), field_values_json={}, + )) + second_task.order_snapshot_id = second_snapshot.id + db.session.flush() + with pytest.raises(ConflictError) as different_po: + ensure_task_reservations(second_task) + assert different_po.value.code == 'SHIPPING.RESERVATION_PO_CONFLICT' + db.session.rollback() + + # The first registration remains immutable after the rejected different-PO attempt. + assert first_snapshot.lines[0].reservation_id == '0012345678' + + +def test_confirmed_task_revision_transfers_unfulfilled_reservation_with_audit(app): + """已确认的直接后继可接替同 PO 的未履约 Reservation,且保留父子审计。""" + with app.app_context(): + first_task, first_user = _build_accepted_order(suffix='201') + first_snapshot = freeze_order_snapshot(first_task, actor_id=first_user.id, expected_order_data_version=7) + ensure_task_reservations(first_task) + db.session.flush() + original = ShippingReservation.query.filter_by(reservation_id=first_snapshot.lines[0].reservation_id).one() + + revision_task = ShippingTask( + task_no='SN-SNAPSHOT-202', source_type='test', supersedes_task_id=first_task.id, + ) + db.session.add(revision_task) + db.session.flush() + extraction = ShippingOrderExtraction( + task_id=revision_task.id, schema_version_id=first_snapshot.schema_version_id, + input_snapshot_hash='c' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + revision_snapshot = ShippingOrderSnapshot( + task_id=revision_task.id, extraction_id=extraction.id, + schema_version_id=first_snapshot.schema_version_id, order_data_version=2, + rule_versions_json={}, header_values_json={}, customer_po_number=first_snapshot.customer_po_number, + ) + db.session.add(revision_snapshot) + db.session.flush() + revision_line = ShippingOrderSnapshotLine( + snapshot_id=revision_snapshot.id, position=0, + reservation_id=first_snapshot.lines[0].reservation_id, + part_number='000123-REV', qty=Decimal('13.5'), field_values_json={}, + ) + db.session.add(revision_line) + revision_task.order_snapshot_id = revision_snapshot.id + db.session.flush() + + registered = ensure_task_reservations(revision_task) + + assert registered == [original] + assert original.task_id == revision_task.id + assert original.snapshot_line_id == revision_line.id + assert original.part_number == '000123-REV' + assert original.required_qty == Decimal('13.5') + assert {event.event_type for event in revision_task.events} == {'reservation_revision_confirmed'} + assert {event.event_type for event in first_task.events} == {'reservation_revision_superseded'} + + +def test_first_reservation_registration_allows_missing_po_but_repeat_requires_it(app): + """PO 不属于首次最小履约集;已有 Reservation 时缺 PO 必须阻断歧义修订。""" + with app.app_context(): + task, user = _build_accepted_order(suffix='301') + snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7) + snapshot.customer_po_number = None + ensure_task_reservations(task) + db.session.flush() + + repeat_task = ShippingTask(task_no='SN-SNAPSHOT-302', source_type='test') + db.session.add(repeat_task) + db.session.flush() + extraction = ShippingOrderExtraction( + task_id=repeat_task.id, schema_version_id=snapshot.schema_version_id, + input_snapshot_hash='d' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + repeat_snapshot = ShippingOrderSnapshot( + task_id=repeat_task.id, extraction_id=extraction.id, schema_version_id=snapshot.schema_version_id, + order_data_version=1, rule_versions_json={}, header_values_json={}, customer_po_number=None, + ) + db.session.add(repeat_snapshot) + db.session.flush() + db.session.add(ShippingOrderSnapshotLine( + snapshot_id=repeat_snapshot.id, position=0, reservation_id=snapshot.lines[0].reservation_id, + part_number=snapshot.lines[0].part_number, qty=snapshot.lines[0].qty, field_values_json={}, + )) + repeat_task.order_snapshot_id = repeat_snapshot.id + db.session.flush() + + with pytest.raises(ValidationError) as exc_info: + ensure_task_reservations(repeat_task) + assert exc_info.value.code == 'SHIPPING.RESERVATION_PO_REQUIRED' diff --git a/backend/tests/test_shipping_standard_field_catalog_migration.py b/backend/tests/test_shipping_standard_field_catalog_migration.py new file mode 100644 index 00000000..fe008797 --- /dev/null +++ b/backend/tests/test_shipping_standard_field_catalog_migration.py @@ -0,0 +1,48 @@ +"""验证货代标准字段目录扩展迁移。""" + +from __future__ import annotations + +import importlib + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def test_standard_field_catalog_migration_resets_old_schema_data(monkeypatch): + """关键断言:未投产旧字段身份被清空,客户 PO 与新目录重新建立。""" + migration = importlib.import_module('migrations.versions.027d8e9f0a1b_expand_shipping_standard_field_catalog') + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + schemas = sa.Table('shipping_order_schemas', metadata, sa.Column('id', sa.Integer(), primary_key=True), sa.Column('schema_code', sa.String(64))) + fields = sa.Table( + 'shipping_order_fields', metadata, sa.Column('id', sa.String(36), primary_key=True), + sa.Column('schema_id', sa.Integer()), sa.Column('field_code', sa.String(64)), + sa.Column('scope', sa.String(16)), sa.Column('value_type', sa.String(16)), + sa.Column('field_category', sa.String(32)), sa.Column('collection_mode', sa.String(32)), + sa.Column('display_sequence', sa.Integer()), sa.Column('status', sa.String(16)), + sa.Column('published_once', sa.Boolean()), sa.Column('created_at', sa.DateTime()), sa.Column('updated_at', sa.DateTime()), + ) + snapshots = sa.Table('shipping_order_snapshots', metadata, sa.Column('id', sa.Integer(), primary_key=True), sa.Column('po_number', sa.String(255))) + lines = sa.Table('shipping_order_snapshot_lines', metadata, sa.Column('id', sa.Integer(), primary_key=True), sa.Column('aws_part_number', sa.String(255))) + metadata.create_all(engine) + with engine.begin() as connection: + connection.execute(schemas.insert(), {'id': 1, 'schema_code': 'SHIPPING_ORDER'}) + connection.execute(fields.insert(), [ + {'id': 'po-id', 'schema_id': 1, 'field_code': 'po_number', 'scope': 'header', 'value_type': 'string', + 'field_category': 'order_header', 'collection_mode': 'llm_extraction', 'display_sequence': 1, + 'status': 'active', 'published_once': False}, + {'id': 'aws-id', 'schema_id': 1, 'field_code': 'aws_part_number', 'scope': 'line', 'value_type': 'string', + 'field_category': 'order_line', 'collection_mode': 'llm_extraction', 'display_sequence': 2, + 'status': 'active', 'published_once': False}, + ]) + operations = Operations(MigrationContext.configure(connection)) + monkeypatch.setattr(migration, 'op', operations) + migration.upgrade() + field_rows = connection.execute(sa.text('SELECT id, field_code, status FROM shipping_order_fields')).mappings().all() + by_code = {row['field_code']: row for row in field_rows} + assert by_code['customer_po_number']['id'] != 'po-id' + assert 'aws_part_number' not in by_code + assert len([row for row in field_rows if row['status'] == 'active']) == 57 + assert 'customer_po_number' in {item['name'] for item in sa.inspect(connection).get_columns('shipping_order_snapshots')} + assert 'aws_part_number' not in {item['name'] for item in sa.inspect(connection).get_columns('shipping_order_snapshot_lines')} diff --git a/backend/tests/test_shipping_task_parsed_projection.py b/backend/tests/test_shipping_task_parsed_projection.py index 0a2f246d..91c96fea 100644 --- a/backend/tests/test_shipping_task_parsed_projection.py +++ b/backend/tests/test_shipping_task_parsed_projection.py @@ -165,6 +165,7 @@ def test_serialize_task_detail_projects_fulfillment_timeline(app): ) reservation = ShippingReservation( task_id=task.id, snapshot_line_id=1, reservation_id='RES-TIMELINE-001', part_number='PN-TIMELINE', + po_number_normalized='PO-TIMELINE-001', required_qty=2, status='artifact_reserved', current_artifact_id=None, ) db.session.add_all([artifact, reservation]) diff --git a/backend/tests/test_shipping_upload_attempt.py b/backend/tests/test_shipping_upload_attempt.py index 6267f3af..3b6976b6 100644 --- a/backend/tests/test_shipping_upload_attempt.py +++ b/backend/tests/test_shipping_upload_attempt.py @@ -42,6 +42,7 @@ def _ready_artifact() -> tuple[ShippingTask, ShippingExportArtifact, ShippingRes db.session.add(artifact); db.session.flush() reservation = ShippingReservation( task_id=task.id, snapshot_line_id=1, reservation_id='RES-UPLOAD-1', part_number='PN-1', + po_number_normalized='PO-UPLOAD-1', required_qty=Decimal('1'), status='artifact_reserved', current_artifact_id=artifact.id, ) db.session.add(reservation); db.session.flush() diff --git a/docs/demand.md b/docs/demand.md index b776a5ff..39a0f803 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -121,6 +121,9 @@ - 扫描 PDF 的布局 OCR 必须保留 RapidOCR 原始多边形坐标和置信度,并且只有与严格有框网格及全部非空 cell 文本一致时才能生成 OCR cell 候选。EML HTML table 必须经主动内容/属性白名单清理后按 DOM 行列和跨度生成逻辑布局;原始 HTML 不得进入 Intake 摘要、Dify 或日志。两类结果在人工真值完成前均保持 `needs_review`。 - 冻结 Schema 映射必须直接消费 layout.v1 的真实 `cell_id/token_ids`,不得从 HTML 再生成第二套证据 ID。表头后置、重复列、零 Qty、类型与安全校验复用同一规则;跨页只接受显式 continuation。needs_review 映射只能冻结为内部 candidate,禁止进入 Dify、自动接受或跳过 Provider。 - 精确 Profile 命中后,模板语义优先于全局 Schema 别名。例如确认模板中的 `Part Number -> customer_part_number`、`Vendor Item# -> part_number` 是合法映射。只有唯一命中表且每个保留行都具备可信 `part_number + qty` 时,后端才可跳过该附件的 LLM;显式 Qty=0 行删除。Reservation 可由邮件或其他附件补充,最终缺失仍须阻断库存匹配和发货 Excel。 +- 对 MinerU 行列关系错误或数据页表头不完整的 PDF,管理员可基于原生/OCR 字符坐标确认相对列边界和固定字段映射。坐标模板不得依赖数据页完整表头:系统以行号列识别新明细,按纵坐标形成物理行,将无新行号的相邻行按列合并为续行,并将删除标记回写最近明细、在合计/说明起始行终止。几何位置是主证据,字段内容类型与同行左右顺序仅用于边界歧义辅助;重建结果必须在页面展示逻辑明细、删除状态和来源物理行,管理员确认后才可进入草稿与盲测。 +- 同一订单明细允许由任意连续 N 条物理行构成,不限定两行、三行或四行。管理员可动态增加/删除第 2..N 行版式,每行独立配置相对列边界和固定字段映射,横坐标区间允许跨行重叠;第 1 行必须包含 `line_no` 作为新明细锚点,后续行按 `row_offset` 合并到最近明细。 +- 管理员不得被要求从 PDF 截图手工计算 0..1 列边界。系统须基于冻结的 PDF/OCR 字符坐标自动建议物理行数量、每行列边界及列示例文字;人工只确认字段映射,并可在必要时使用高级边界校准。 - 阶段 2 创建 Run 时同步创建 `shipping_order_extraction` Job;Worker 按 Run 冻结快照调用 `shipping.order_extraction` 能力绑定的内部 Provider,并把 Dify 成功结果先于 HXOPS 订单落库独立提交,重试不得重复调用 Dify。 - 应用管理必须显式创建 `exposure_mode=internal` 的 Dify Workflow Provider,再由货代 Agent 绑定 `shipping.order_extraction`。业务代码只识别能力编码和数据库外键,禁止写死 App ID、按名称匹配或从环境变量静默回退;Dify 画布由管理员手工配置。 - Run 冻结 Provider App ID、Base URL 与执行参数;二者变更后旧 Run 必须失败并重新发起。API Key 不进入快照,允许在不重建 Run 的情况下安全轮换。 @@ -199,8 +202,10 @@ - **试点容量与恢复(阶段 7)**:批量通知文件数、单文件大小、EML 附件数量/单附件大小/总大小均须由环境变量限制,超限在解析和建单前返回明确业务错误;试点先以 3–5 个高频模板逐个完成独立盲测,再根据管理员健康接口记录的 P50/P95、失败率、积压与 RPA 耗时确定正式 SLA。Worker 重启恢复、同文件幂等重试和备份恢复演练均须留存环境、时间、操作者、结果与问题记录;演练失败不得启用自动建单或自动上传。 - 一个附件可形成一个业务任务,但一个任务可形成多份按时间顺序的 Excel Artifact。全部缺货时不得产生空 Excel;已成功上传的预约单永久不得再次制单;仅当任务全部当前有效预约单均上传成功时才完成。 - `FieldValue` 仅是解析阶段的 Observation/Decision 投影;人工复核和客户绑定完成后冻结 `OrderSnapshot` 及其行作为库存、制单、上传的正式业务真相。冻结快照不可编辑,后续客户修订必须形成新快照版本。 -- 预置核心字段同步保存为强类型列;管理员可新增扩展字段,已发布库存路由、Excel 模板或 RPA 配置需要使用时,Snapshot 按稳定 `field_id` 一并冻结并只由该快照提供值。扩展字段是否参与履约由业务配置决定,不得回读可变 `FieldValue`。 -- **字段计数校正**:预置业务核心为 13 个 Header 和 12 个 Line(共 25 个)。历史蓝图中的“26 个”包含已废弃的 `bill_to_customer_code`;该字段已按业务决定替换为 `bill_to_address`,不会重新引入。`position` 是明细行内部排序键,不是可抽取或可配置的业务字段。管理员仍可按治理规则新增扩展字段。 +- **字段分层与履约门禁(阶段 1)**:平台系统事实由代码和数据库固定;货代订单字段由“57 个可按版本启用的标准字段目录 + 自定义字段”组成,二者均以稳定 `field_id` 冻结。标准目录不是全部必填的固定核心字段。当前固定策略 `SHIP_AVAILABLE_ROLLING_V1` 只要求 Line 的 `reservation_id:string`、`part_number:string`、`qty:decimal > 0` 以及已人工确认的 Bill-to 客户;`uom` 暂不强制且不做单位换算。`inventory_source_hint` 仅是可选 Line 路由线索,不增加 `header.inventory_source_hint_default` 或 `shipping_method`。 +- **Reservation 全局唯一(阶段 1)**:`reservation_id` 单列全局唯一,同一 PO 内也不得重复。PO 比较只去除首尾空格并统一大写,保留前导零和中间字符;不同 PO 必须阻断为重复订单。相同 PO 但料号或数量变化仅返回包含前后差异的人工修订候选,存在有效 Excel Artifact 或已上传时直接阻断;PO 不属于首次履约最小字段,但 Reservation 已注册后若后续记录缺 PO 必须阻断,不能以空 PO 判断修订。 +- **客户 PO 与字段计数**:预置目录为 23 个 Header、34 个 Line(共 57 个)。`customer_po_number` 是客户 PO,对应 ERP `xmda033`;内部自动生成且全局唯一的 `erp_order_number` 是系统事实,不属于订单字段。`aws_part_number` 不在标准字段目录;`position` 只是明细排序键。管理员仍可按治理规则新增扩展字段。 +- **字段能力与策略版本**:字段目录只说明数据身份,字段能力绑定决定其在履约中的角色。货代仅允许代码注册的预约单身份、料号、数量和可选库存路由线索能力;按稳定 `field_id` 且严格按 scope/type 绑定。自定义字段满足约束时可绑定能力,不能按字段名称猜测。`SHIP_AVAILABLE_ROLLING_V1` 发布后冻结完整策略定义,后续策略发布不改变历史订单履约解释;Dify 不参与能力绑定或策略发布。 - 预约单以全局注册表管理,而非以历史订单行文本去重。唯一预约单在任一时刻只能处于 `pending`、`available`、`artifact_reserved`、`uploaded` 或 `external_change_required` 之一,并只允许归属一个有效 Artifact。 - Excel 文件名允许由已发布 Excel 模板的版本化命名规则定义;没有模板规则时可使用受控环境变量默认规则。后端必须校验规则、生成最终文件名并在 Artifact 冻结规则来源/版本、文件名和流水;前端、Dify 或普通用户不得提交任意文件名。 - Dify 仅生成候选 Observation,不能创建 Task、冻结 Snapshot、选择库存、生成 Excel 或触发上传。任何关键字段含未人工确认的 LLM fallback Observation 时,必须转人工复核并阻断自动冻结。 diff --git a/docs/features/shipping-notice/business.md b/docs/features/shipping-notice/business.md index 92b09415..636d11ad 100644 --- a/docs/features/shipping-notice/business.md +++ b/docs/features/shipping-notice/business.md @@ -632,6 +632,9 @@ A:Reservation ID(也可能叫 COM ID / Reservation Order / PR Number)是 **Q:Reservation ID 必须是数字吗?** A:必须。当前业务契约只接受 5 位或 10 位纯数字,例如 `12345` 或 `1000140351`;字母型编号、其他长度数字、32 位十六进制内部主键和 UUID 均会被拒绝。 +**Q:同一个 Reservation ID 再次出现时会怎样?** +A:系统按全局唯一处理,即使在同一 PO 中也不能重复。不同 PO 会作为重复订单阻断;相同 PO 但料号或数量不同,系统必须展示前后差异并由人工确认修订。已经生成有效 Excel 或已上传货代的 Reservation 不允许直接修订。 + **Q:单价、金额错了会影响能不能发货吗?** A:不会。库存匹配只看内部料号、Reservation ID、需求数量;但导出 Excel 前仍建议在解析确认阶段核对单价与金额。 diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 0e4dbc88..b9512da0 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -337,8 +337,26 @@ MinerU 服务地址、无认证方式和 OpenAPI 已确认,并已取得脱敏 **Profile 可视化治理 Review(2026-07-22)**:管理端 `/admin/shipping-order-document-profiles` 只展示 ready MinerU 样本文档及展开后的 cell 文本,不返回 HTML、bbox、全文或结构指纹。管理员选择表格、表头行、数据起始行、行结构和 Schema 明细字段;页面只允许 `direct` 与已注册 `temp_internal_parts` 解析器,阻止同一目标字段跨列重复映射。结构指纹始终由后端从持久化 HTML 计算,浏览器提交值无效。草稿支持乐观锁更新、发布、删除;不可变版本支持复制为下一草稿和退役。复制后的草稿必须选择样本重新确认映射才能更新,不允许直接编辑 JSON、HTML、正则、脚本或结构指纹。 +**多行表头配置 Review(2026-07-23)**:`header_row_index` 明确表示最后一条表头物理行,表头区域固定为 `0..header_row_index`,运行解析从 `data_start_row_index` 开始,不需要新增数据库字段。模板页按逻辑列合并表头区域内的非空文字并去除 rowspan/colspan 展开造成的重复标签,以独立虚拟列头映射区维护字段;所有表头物理行统一高亮,不再要求管理员只在最后一行表头上选字段。切换样本或表格会清理上一表的多物理行坐标状态,可直接配置的表格始终显示普通预览。多行表头与一条明细占多条物理行是两个独立配置维度,前者不得进入 `subrow_layouts`。 + +**模板样本治理与版本识别 Review(2026-07-23)**:样本文档按上传时间倒序显示,并在选择器中标明文件名、时间、解析状态和表格数,可按文件名搜索;同一 `profile_code` 的 `published` 版本显示“当前生效”和发布时间。模板页上传的专用样本 (`purpose=order_document_profile_sample`) 仅在已解析完成、未被独立盲测引用且其资产未被其他业务引用时允许删除;删除同时回收源文件和布局结果。历史 `shipping_notice` 业务附件及盲测证据始终不可在模板页删除。Profile 当前未持久化“创建时样本”外键,因此不得声称可以按该不存在的关系阻止删除;如需这一级审计保护,须另行设计字段、迁移和历史数据策略。 + **表头污染与坐标重建 Review(2026-07-22)**:若样本表头混入明显订单行值(例如 `ITEM NO 00010`),预览返回稳定诊断 `order_profile_header_contaminated_by_data` 并标记不可建 Profile;服务端也拒绝从该表创建草稿,避免浏览器绕过。Profile 页面不是手工修复原始网格的入口。对有 PDF 原生 glyph 坐标且已人工确认列锚点的文档,`coordinate_table_reconstruction` 仅输出 `needs_review` 候选:以 x-overlap/唯一中心距离归属列,以字体高度自适应 y-band 判断新视觉行,内容形态与相邻行连续性只作辅助;无强行号的行只能是续行或复核,`** Item deleted **` 只能附着前一强锚定明细。候选保留 glyph 索引,坐标不足、列归属并列或删除行无前序明细时一律复核,绝不自动接受、发布 Profile 或进入履约。 +**坐标逻辑明细闭环 Review(2026-07-23)**:坐标 Profile 不再依赖数据页自身的完整表头,而是按确认列数生成稳定虚拟表头并冻结列字段编码、新行起始列。字符先按 y-band 和横向间距组成文本片段,列归属仍以 x-overlap 为主,只在边界近似并列时使用字段格式(行号、数量/金额、单位、日期、料号)和同行从左到右顺序辅助。物理 `data/continuation/deleted/summary` 被保留到逻辑重建:续行按列并入最近明细,删除标记回写最近明细,合计/账单/条款起始行结束数据区;纯表头页因无逻辑明细不算 Profile 命中。管理页显示有效/删除状态和来源物理行,管理员确认后才可保存草稿,发布仍受盲测与自动建单质量门禁约束。 + +**动态 N 行明细 Review(2026-07-23)**:多行订单明细不预设“两行/三行/四行”数量,也不固定“补充/属性”业务角色。`subrow_layouts` 按连续 `row_offset=0..N-1` 保存任意 N 行;首行固定为 main 且必须映射 `line_no`,其余均为 continuation。每行独立配置列边界和字段编码,因此同一横坐标可在不同物理行表达不同字段。管理页支持动态增加/删除第 2..N 行,并在每次结构或映射变化后强制重新生成和审核最终逻辑明细。 + +**自动版式建议 Review(2026-07-23)**:管理员无需按截图手工换算 `0..1` 边界。建议器使用冻结 PDF/OCR 字符坐标按 y-band 形成物理行,以左侧行号切分逻辑明细,再将相同 `row_offset` 的文本片段按相对 x 中心聚类,并以相邻中心中点生成列边界。接口只返回相对边界、少量列示例和确定性的 `line_no` 建议,不返回绝对坐标;其他字段由管理员确认,结果始终保持 `needs_review`。单内容块续行允许使用边界 `[0, 1]`。 + +**映射工作台实时预览 Review(2026-07-23)**:多物理行坐标模板在同一工作台编辑字段,并在编辑区下方全宽显示最终逻辑明细候选。首行已映射 `line_no` 且各行边界有效时,字段或边界变化经 500ms 防抖自动调用既有只读重建接口;旧请求结果按请求序号丢弃,自动失败只在预览区提示,手动“重建表格候选”仍提供完整错误反馈。每个物理行独立显示按相对比例绘制的可拖拽边界尺,内部边界受相邻刻度约束,数字输入保留为精确校准入口。自动刷新不会自动勾选人工确认,保存草稿仍要求管理员确认当前候选。 + +**映射工作台交互收敛 Review(2026-07-23)**:工作台改为“左侧物理行列表 + 右侧当前行横向列配置 + 下方全宽实时候选”。原有全量建议保留并明确为“自动识别全部行”;建议接口新增可选 `row_offset`,用于“识别当前行”且只返回该行建议,前端按列位置保留已确认字段,不覆盖其他物理行。每个列卡片提供“后新增”,在该列区间中点插入边界并将空白新列插到当前列之后;不足 2% 的区间禁止继续拆分。删除列时合并相邻边界,字段与样例数组同步增删且至少保留一列。样本上传和删除按钮移到样本选择控件组,原独立上传框与样本操作卡片移除;表格、Schema、模板编码和名称按内容宽度排列,行结构与起始行归入高级设置,保存操作收敛到标题栏。 + +**坐标模板修复闭环 Review(2026-07-23)**:对于表头混入首条明细的 PDF,模板页显示“自动识别行版式”和“重建表格候选”。系统先建议从 `0` 到 `1` 严格递增的相对列边界,管理员按示例确认字段并可高级校准;系统仅使用同一 `ShippingDocumentLayoutVersion` 中表格 bbox 内的 PDF 原生字符重建网格。候选固定 `needs_review`,界面必须显式勾选审核确认后才可创建草稿。确认的边界随 Profile 定义冻结,Run 输入快照同时冻结对应的坐标证据;运行和盲测无法取得证据时阻断,不回读资产、不回退错误 MinerU 网格、不调用 Dify。坐标、页面图像、完整 PDF 正文和 MinerU 原始响应不返回浏览器或 Dify。 + +**模板页样本上传 Review(2026-07-23)**:管理员可直接在“订单文档模板”页上传 PDF 或 EML。文件先写入用户私有 `FileAsset`,再创建 purpose=`order_document_profile_sample` 的独立 Intake 并沿用异步预解析、EML 附件拆分和布局 Job;它不绑定 Chat 会话,预解析只落 Document/布局版本,禁止创建 Candidate、业务指纹、重复决策、Task 或 Dify 调用。PDF 可在原生 glyph 坐标可用时进入坐标重建候选;EML 可选择正文 HTML 或其中单个附件文档,附件不得自动合并。页面轮询仅返回状态和数量,不返回正文、HTML 或 bbox;仅 `parsed` 后的表格可选择字段映射。PDF/EML 以外的文件由前后端双重拒绝。 + MinerU 生产捕获固定使用 `pipeline`,通过 `/tasks` 异步提交、状态轮询和 `/result` 取回结果,不使用同步 `/file_parse` 长连接。Intake 不再内联调用 MinerU:它在持久化 Document/派生 FileAsset 后,同事务创建独立布局版本和 `shipping_document_layout` Job;布局 Worker 再读取对象存储并调用 Provider。`SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=false` 时不创建布局 Job;启用后只保存 `shipping_document_table_snapshot.v1` 的页/整表 bbox、HTML 表格与能力摘要,不保存 task 原响应、model output、content list 或非表格文本块。默认每个 Intake 最多 4 个支持文档;超量建立 `unsupported` 审计版本。所有 HTML/bbox 在 Dify Manifest 编译前剥离,仅 Profile 映射后的 `field_id/value/quote` 紧凑候选可进入 Dify。 ### L1 布局版本与独立任务生命周期 @@ -518,7 +536,7 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工 #### 待查看、管理诊断与保留 - 新功能上线后产生的 `completed/needs_review/failed` Run 创建待查看标记;用户进入对应会话且终态卡片成功加载后才确认已查看。会话历史显示未查看数量和严重级别;仅加载列表、后台预取或失败请求不得清除。 -- 管理入口固定为“货代发货通知 -> 订单识别运行”,所有现有管理员可只读访问;不新增权限点,不提供管理员重试、取消、强制完成、导出或状态修改。 +- 管理入口固定为“货代管理 → 订单识别 → 识别任务”,所有现有管理员可只读访问;不新增权限点,不提供管理员重试、取消、强制完成、导出或状态修改。 - 管理端访问记录订单域诊断审计:列表与详情访问分别记录一次;详情包含 Workflow Run ID、Job Attempt、节点时间线。审计仅保留筛选摘要,绝不保存正文或输入输出。 - 进度明细保留90天,Run摘要、阶段累计耗时、Job Attempt和最终错误码长期保留。默认排程 `shipping-order-extraction-progress-cleanup` 每日 03:15(Asia/Shanghai)分批清理明细;清理失败不得影响主链路并在下一次排程重试。 - **上传阶段不调用 LLM、不生成 Candidate、不判订单重复**:规则解析只作为 `rule_hints`,Candidate 只在后台 Workflow 结果通过 HXOPS 提交服务后生成。 @@ -879,7 +897,7 @@ SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/u 当前业务只有一组必须满足库存路由、匹配和发货 Excel 的订单字段,因此所有 EML 正文和 PDF/Word 附件共享唯一逻辑 Schema `SHIPPING_ORDER`。文件类型只影响文本提取方式,不选择不同字段配置。 -管理端入口:后台“货代配置”二级导航包含“库存配置”(`/admin/shipping-notice`)和“客户识别规则”(`/admin/shipping-identity-rules`);两页复用 `shipping_inventory` 管理权限,路由和后端 API 仍独立鉴权。订单字段位于库存配置页面的“订单字段”工作区,不再作为左侧一级菜单。主要接口: +管理端入口:后台“货代管理”按业务域组织二级导航。“订单识别”依次包含订单字段规则(`/admin/shipping-notice?section=orderSchema`)、订单文档模板、客户识别规则和识别任务;“库存管理”(`/admin/shipping-notice?section=parsing`)在综合工作台内按库存字段与解析、系统连接、库存站点、仓库映射、路由规则、发货模板排列,库存快照与导出记录归入“运行与审计”。各页面复用 `shipping_inventory` 管理权限,原有路由和后端 API 仍保持兼容并独立鉴权。主要接口: 管理界面以业务字段工作台呈现:管理员填写的“字段名称(系统标识)”就是 `field_code`,必须为小写下划线格式,例如 `part_number`、`reservation_id`、`request_qty`。系统不再生成随机字段编码;下游配置使用稳定 `field_id` 关联字段,发布快照同时冻结当时的 `field_code`,因此管理员可重命名系统标识且不会污染历史版本。字段首次发布后 `scope/value_type` 仍不可修改。字段清单与单字段规则编辑器分栏显示,避免字段数量增长时将全部规则纵向堆叠。 @@ -1007,7 +1025,7 @@ GET /api/admin/shipping-order-schema/published-contract # 发货 Excel 模板 -- 模板在“货代配置 → 发货模板”独立维护,状态为 `draft / published / retired`;库存站点只能绑定 published 版本。 +- 模板在“货代管理 → 库存管理 → 发货模板”独立维护,状态为 `draft / published / retired`;库存站点只能绑定 published 版本。 - 定义契约为 `filename_pattern + mappings[]`。每条 mapping 包含 `sheet`、`row_mode(header|line)`、`start_row`、`target_column`、`source_kind`、`source_key`、`formatter`。管理端上传模板时读取工作表与首行表头,管理员从实际工作表和目标列中选择,不要求记忆列序号。 - `filename_pattern` 是已发布模板可选的版本化规则;规则为空才使用 `SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN`。两种规则均只允许后端支持的变量和格式,Artifact 必须冻结实际来源、模板/环境规则版本、最终名称和不可复用流水,禁止客户端或 Dify 自定义名称。 - 文件名规则默认推荐 `{business_no}.xlsx`(例如 `WYC26060201.xlsx`)。可用变量必须在界面显式展示:`{business_no}`、`{customer_short_code}`、`{business_date}`(六位)、`{sequence}`(两位)、`{task_no}`、`{source_code}`、`{date}`(八位)、`{ts}`。业务单相关变量只读取 `ShippingCase` 已锁定的客户简称、业务日期和流水快照,保证重新导出与历史审计一致。 @@ -1868,7 +1886,7 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv ### 3.3 尚不能判定为已完全落地的项 -- **四语言验收**:货代配置、货代聊天和货代工作台三棵业务文案树已完成 `zh-CN / zh-TW / en-US / th-TH` 键集合一致性校验,并由 `shippingI18nParity.spec.ts` 持续验证。 +- **四语言验收**:货代管理、货代聊天和货代工作台三棵业务文案树已完成 `zh-CN / zh-TW / en-US / th-TH` 键集合一致性校验,并由 `shippingI18nParity.spec.ts` 持续验证。 - **库存自动抓取业务闭环**:代码层已具备后端库存准备、RPA 回调与自动推进入口,但是否达到真实业务可用,还依赖货代库存导出 SOP、正式 RPA 脚本和运行环境联调。 - **正式方案 P0 验收项**:从代码结构看已接近“对话主路径 + 轻量批次工作台”的目标要求,但像“不中断续办”“多票并行下的细粒度进度提示”“轻量工作台与对话聚焦任务的一致性”等,仍需要按原型测试用例逐项实测,而不能仅凭仓库代码直接视为全部完成。 @@ -2074,7 +2092,52 @@ API 层 6. **快照复用键**:`find_latest_ready_snapshot(source_code, warehouse_id)`;link 时做 identity check。 7. **迁移**:`2b3c4d5e6f7a_add_shipping_inventory_configuration`、`3c4d5e6f7a8b_remove_shipping_inventory_site_id`、`4c5d6e7f8a9_add_dynamic_inventory_snapshot_idempotency`。 -### 6.7 Bill-to / Ship-to 客户主数据匹配(2026-07) +### 6.7 字段分层、冻结策略与 Reservation 注册(2026-07-23) + +货代发货只采用单一订单字段族,结构为“平台系统事实(代码/数据库固定)→ 57 个标准字段目录(按 Schema 版本可选)→ 自定义字段 → 字段能力绑定 → 版本化履约策略”。标准目录不是全量固定必填字段;当前代码注册且唯一允许的履约策略是 `SHIP_AVAILABLE_ROLLING_V1`。冻结时只检查已启用的 Line `reservation_id:string`、`part_number:string`、`qty:decimal`(严格大于 0)和已人工确认的 Bill-to 客户,其他标准或自定义字段可按版本需要冻结为 `field_id -> value`。`uom` 当前不参与门禁或换算。 + +`inventory_source_hint` 保持可选的 Line 字段,仅供库存路由从冻结 Snapshot 读取;不存在 `header.inventory_source_hint_default`,也不引入 `shipping_method`。库存路由禁止回读可变 `FieldValue`,避免已冻结履约事实随解析修正漂移。 + +`customer_po_number` 对应客户 PO(ERP `xmda033`);内部自动生成且全局唯一的 `erp_order_number` 是系统事实,不属于订单字段目录。`shipping_reservations.reservation_id` 以单列唯一约束全局注册,`po_number_normalized` 保存客户 PO 去首尾空格、转大写后的结果(前导零及中间字符不变)。PO 不属于首次履约最小字段,因此首次注册允许为空;同一快照内重复、不同 PO 重复、已注册 Reservation 的后续记录缺 PO 均阻断。相同 PO 且料号/数量发生变化仅返回 `SHIPPING.RESERVATION_REVISION_REVIEW_REQUIRED`,并提供 previous/proposed 差异供人工确认。已有有效 Artifact 或上传状态时返回 `SHIPPING.RESERVATION_REVISION_LOCKED`,不得直接修订。 + +**57 项目录与重建说明**:Header 为 `customer_po_number`、`order_date`、`source_order_number`、`contract_number`、`order_type`、`sales_channel`、客户/账款/收货信息、交付组织、目的地、币种、贸易与付款条款、唛头、直发、紧急和订单备注;Line 为行号、预约单、料号、`product_revision`、客户料号、客户 PO 行号、产品特征、数量/单位及参考和计价数量、交期、价格税额、站点/地址/库存约束、批号、库存路由线索、部分交货/保税、包装、项目/WBS/活动和行备注。`aws_part_number` 不属于本目录。 + +迁移 `027d8e9f0a1b_expand_shipping_standard_field_catalog` 按“未投产、不保留历史订单配置”执行:清空旧 Schema 版本、履约策略、抽取/快照/Reservation/Artifact、Candidate/Run、Excel 模板、字段 ID 相关 Profile/路由/质量验收,并解除 Task、库存源和运行绑定的相关引用;库存源会被停用,保留库存文件、库存源主体、客户主数据和 Dify 配置。迁移后管理员必须重新发布 Schema 与 `SHIP_AVAILABLE_ROLLING_V1` 策略,并重新建立订单文档 Profile、库存解析 Profile/路由规则和 Excel 模板,再启用库存源。Dify 无需修改画布;只需继续按新 Schema 发布契约返回 Observation。 + +**迁移后管理员重建顺序(阶段 5 Review)**: + +1. 在“订单字段规则”确认 57 项目录,发布目标 Schema;初始化生成的 `SHIP_AVAILABLE_ROLLING_V1` 仅为草稿,未发布前所有订单冻结安全阻断。 +2. 在同一页面核对四项受控能力的字段绑定并显式发布策略;页面只允许选择当前 published Schema 的兼容字段。 +3. 重新发布订单文档 Profile、库存解析 Profile、库存源路由规则和 Excel 模板;这些配置引用的稳定 `field_id` 必须属于当前 Schema,服务端会在发布时复核。 +4. 为库存源绑定已发布的 Profile/模板并完成停用状态下的 RPA 配置测试,测试通过后再启用库存源。 + +库存源测试不依赖履约策略,因其不冻结订单、不匹配订单、不生成 Excel 或上传;因此“库存源可测试”和“订单可履约”是两个独立状态。订单冻结、库存核验、滚动制单与上传仍强制要求已发布策略和冻结 Snapshot,不能以库存源已启用替代。 + +#### Dify 手工配置说明(阶段 1) + +本阶段不由 HXOPS 修改 Dify 画布或 Tool。业务管理员仅需核对现有 Workflow 继续按照 HXOPS 发布契约返回 Observation:`reservation_id`、`part_number`、`qty` 均为 Line 值,必须附当前文档可验证的 quote 与 document ID;不得回传 `inventory_source_hint_default` 或 `shipping_method`,`inventory_source_hint` 缺失时留空。Dify 不判断重复 Reservation、不选择库存源、不冻结订单、不生成 Excel 或上传;这些结果全部由 HXOPS 门禁裁决。 + +#### 字段能力绑定与履约策略(阶段 2) + +字段目录只定义数据身份,`business_purpose` 仅保留为 Schema 抽取配置的历史元数据,禁止作为库存、冻结、Reservation、导出或上传的履约真相。管理端仅允许使用代码注册的能力:`fulfillment.reservation_identity`、`fulfillment.part_number`、`fulfillment.quantity` 和可选 `routing.inventory_source_hint`;禁止自由脚本、SQL、JSONPath 或外部调用。能力按稳定 `field_id` 绑定,字段必须匹配指定的 Header/Line 作用域和数据类型;因此自定义字段可在满足约束后承担能力,不能按名称猜测。 + +当前唯一允许的策略为 `SHIP_AVAILABLE_ROLLING_V1`。发布策略会退役前一版本;冻结时把策略 ID、编码、版本、checksum、完整 definition 与绑定字段 ID 写入 Snapshot,库存、Reservation、滚动制单和上传只能读取这个冻结事实。发布新策略不会重解释已有快照。Dify 无需新增配置:仍只依据 HXOPS 发布的 Schema 契约返回 Observation,不能选择能力绑定、发布策略或裁决履约。 + +#### 策略管理闭环(阶段 3) + +管理员在“订单字段规则”页面只能看到代码注册的四项能力及当前 `published` Schema 中作用域、数据类型均兼容的字段;页面没有自由能力代码、表达式、JSONPath、SQL 或脚本输入。创建策略草稿时记录变更说明,发布使用策略 `lock_version` 防止并发覆盖并原子退役旧版本。后端再次校验:只要当前已有 published Schema,所有策略绑定字段必须纳入该版本;因此 API、批处理或旧页面都不能绕过 UI 过滤创建“目录中存在但冻结时不可用”的策略。历史 Snapshot 仍只消费冻结 definition,不会受新策略影响。 + +反向依赖同样在 Schema 发布时执行:当前 published 履约策略绑定的字段、库存路由规则、库存解析 Profile、订单文档 Profile、Excel 模板和客户识别定义都不能被新的 Schema 版本移除。这样策略、库存与制单的字段问题在配置发布时阻断,而不会延后到冻结或库存核验运行时才暴露。 + +**阶段 3 Dify 手工配置**:无需修改 Dify 画布、变量、Prompt 或 Tool。Dify 继续只按 HXOPS 发布 Schema 的稳定 `field_id` 返回 Observation 与当前文档证据;不配置、选择或发布履约策略。 + +**阶段 6/7 Review(2026-07-23)**:冻结入口在取得当前 published 策略前 fail closed;即使已接受订单、必需字段和已确认 Bill-to 客户齐全,未发布策略也以 `SHIPPING.FULFILLMENT_POLICY_NOT_PUBLISHED` 阻断且不写入 Snapshot。管理员策略 API 同样完成权限和发布顺序回归:普通用户返回 `AUTH.FORBIDDEN`;管理员只能在当前 Schema 已发布且包含绑定字段时发布策略。阶段回归为 33 passed,前端 production build 通过。 + +**完整迁移链 Review(2026-07-23)**:已在隔离 PostgreSQL 空库从初始 revision 完整执行 `flask db upgrade` 至唯一 head `027d8e9f0a1b`。验收确认 57 个 active 标准字段、`customer_po_number` 快照列以及移除 `aws_part_number` 的快照行列均符合设计。验收过程中修复了历史迁移对 sibling 分支列、旧 ERP 映射表、空路由配置和 PostgreSQL 63 字符索引名的错误假设;这些修复保证新环境可完整部署,且有迁移专项回归覆盖。正式原始库同样执行该升级,但 `027d8e9f0a1b` 会按“未投产、不保留历史”决策清空受影响货代配置和履约事实,必须在执行前确认备份,并在升级后遵循本节的管理员重建顺序。 + +**管理员重建演练 Review(阶段 9,2026-07-23)**:同一隔离 PostgreSQL 中,在迁移建立的 57 字段目录上实际创建并发布了只含 `reservation_id`、`part_number`、`qty` 和可选 `inventory_source_hint` 的 Schema Version;随后成功创建并发布 `SHIP_AVAILABLE_ROLLING_V1`。这证明标准目录不等于全量必填,且“先发布 Schema、再显式发布策略”的重建路径可执行。Profile、路由、Excel 模板与库存源 RPA 测试仍必须由管理员按阶段 5 顺序在目标环境完成;Dify 不需要修改。 + +### 6.8 Bill-to / Ship-to 客户主数据匹配(2026-07) 订单 Schema 仍是全局唯一的一组业务字段,不按 EML/PDF 或库存源拆分。当前客户相关头字段为: diff --git a/docs/funclist.md b/docs/funclist.md index 797aabe1..08d37a65 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -17,7 +17,10 @@ - 文档级订单抽取优化阶段 7 已完成工程门禁、但质量验收延期:自动建单默认关闭,影子模式完整落 Candidate/证据但零 Task;只有当前 Schema 的达标质量批次和不同账号双角色批准全部满足后才可开启。人工真值、100 个影子 Run、20 个测试环境 Run 与 Dify 实配尚未验收,因此不得宣称阶段完成或达到 95%。 - MinerU + 订单文档 Profile 运行基础已实现:Intake 持久化 Document 后创建独立版本化布局 Job,MinerU `pipeline` 不再阻塞 Intake;布局保存 parser revision/checksum/大小/质量/lease,失败版本不覆盖当前成功版本。版本化 Profile 绑定不可变 Schema 和稳定字段 ID,Run 冻结完整发布快照。唯一精确模板表且完整具备 `part_number + qty` 时由后端确定性解析并跳过该附件 LLM;模板级 `Part Number -> customer_part_number`、`Vendor Item# -> part_number` 合法,零 Qty 行删除。多表/多 Profile/结构漂移/Provider 失败均安全回退,布局 HTML 和坐标不进入 Dify。 - PDF 模型输入优先使用 MinerU 分页文本块与表格 TSV,保留表头和行列关系;MinerU 不可用时回退原 `extracted_text`。Dify Manifest 仅携带紧凑纯文本,不包含 HTML、bbox、task 原响应或内部证据标识。 -- 订单文档 Profile 可视化治理已实现:管理员从 ready MinerU 样本文档选择表格、表头/数据行和受控列映射,可标记不支持的行结构;结构指纹仅由后端计算。支持草稿更新、发布、删除、新版本复制和退役,重复目标字段在前后端阻断;业务管理员无需编辑 JSON、HTML、正则或脚本。 +- 订单文档 Profile 可视化治理已实现:管理员从 ready MinerU 样本文档选择表格、表头结束行/数据起始行和受控列映射;多行表头按逻辑列合并为虚拟列头后统一映射,并与明细多物理行版式独立配置。切换样本会清理旧坐标状态,避免配置区消失。结构指纹仅由后端计算;支持草稿更新、发布、删除、新版本复制和退役,重复目标字段在前后端阻断;业务管理员无需编辑 JSON、HTML、正则或脚本。 +- 坐标订单模板的逻辑明细重建已实现:数据页表头不完整时使用稳定虚拟表头;管理员确认相对列边界和固定字段映射后,系统按 x/y、字段格式和同行顺序辅助归列,合并多条物理续行,回写 `Item deleted`,在合计/说明区终止,并在模板页显示有效/删除明细及来源物理行。结果继续保持人工审核和盲测门禁,不直接提升为 accepted 履约证据。 +- 多行明细版式支持动态 N 行:模板页可增加或删除第 2..N 行,每行独立设置边界和字段,允许跨行横坐标重叠;第 1 行以 `line_no` 开始明细,后续所有行按相对顺序合并。没有固定为主行/补充行/属性行三种角色。 +- 模板页支持基于 PDF/OCR 冻结字符坐标自动识别动态行版式:既可首次自动识别全部物理行,也可只重新识别当前选中行而不覆盖其他行。工作台左侧纵向选择物理行,右侧横向编辑当前行列配置;边界尺可拖动,每个列卡片可明确在本列后新增或删除列,列卡片同步变化。实时候选全宽显示在编辑区下方。样本上传/删除与样本选择组成同一控件组,基础字段按内容宽度紧凑排列,低频参数收进高级设置。 - L0 人工真值辅助继续保持非生产隔离:新增 PDF 原生字符坐标严格对齐候选,仅接受唯一、同视觉行、连续且非重叠文本;30 份真实 PDF 复评仍不足以自动生成完整 cell 真值,因此未开放 LayoutCell 自动接受、自动建单或 95% 准确率声明。 - L1 文档布局生命周期已实现:Document 使用独立递增布局版本和当前成功引用;布局任务支持幂等调度、parser revision 防漂移、lease 防旧 Worker 回写、超时恢复、尝试耗尽、payload 大小门禁、级联删除、管理员脱敏诊断和显式重解析。人工真值延期不阻塞该生命周期,但继续阻断 cell 自动接受与准确率声明;Dify 无需修改。 - L2 原生 PDF 工程能力已实现:PDFium 提取真实字符 bbox,MinerU HTML cell 通过唯一文本对齐或严格有框表 OpenCV+全文本门禁生成可追溯 token/cell 候选;只保存表格区域 token,失败逐表隔离,revision 升至 v2。候选固定 needs_review;人工真值、准确率和性能验收延期,因此未进入 OCR 自动接受,Dify 无需修改。 @@ -110,9 +113,19 @@ | 多订单 Candidate 判重与自动建批 | 已实现 | Candidate 使用 `shipping-v1` 身份指纹与 `shipping-content-v4` 内容指纹;高置信 `part_number`+Qty 订单可自动建 Task;缺失/非法 Reservation、未解决字段冲突继续阻断下游,库存源线索统一为 `inventory_source_hint` | | 订单解析结果持久只读展示 | 已实现 | Task Detail 顶层投影 `order_header` / `order_header_fields` / `order_line_fields` / `lines` / `parse_validation` / `process_field_gate` / `source_candidate`;右侧工作台按任务锁定 Schema 的显示名称和 `sequence` 展示订单信息与动态明细列,避免前端写死字段顺序;Candidate 审核非编辑态同步展示关键行 | | 动态订单解析真相 | 已实现 | Task 通过 `current_order_extraction_id` 追溯 `ShippingOrderExtraction/Line/Decision/FieldValue`;它们只承载解析结果。订单冻结后由 `order_snapshot_id` 供库存、RPA、匹配和导出读取,旧 `shipping_task_lines`、`lines_json` 和兼容投影不恢复。 | +| 货代字段分层与冻结策略(阶段 1) | 已实现,Review 通过 | 平台系统事实与 57 个订单标准字段目录分离;字段可按版本启用而非全量必填。`customer_po_number` 是客户 PO;固定 `SHIP_AVAILABLE_ROLLING_V1` 仅校验 `reservation_id + part_number + qty>0 + 已确认客户`,自定义字段仍可随 Snapshot 冻结;`inventory_source_hint` 保持可选 Line 路由线索。 | +| 字段能力绑定与版本化履约策略(阶段 2) | 已实现,Review 通过 | 独立策略版本按稳定 `field_id` 绑定受控货代能力;冻结策略定义避免新发布版本重解释历史订单。 | +| 履约策略管理闭环(阶段 3) | 已实现,Review 通过 | 管理端仅列出四项注册能力与当前 published Schema 中 scope/type 相符的字段;创建草稿、乐观锁发布和旧版本退役均由后端裁决,API 不能绕过 Schema 纳入门禁。 | +| Schema-策略反向依赖门禁(阶段 4) | 已实现,Review 通过 | Schema 发布反查当前 published 策略绑定,不能移除仍会被冻结、库存、制单与上传使用的字段;与路由/Profile/模板引用统一阻断。 | +| 迁移后管理员重建顺序(阶段 5) | 已实现,Review 通过 | 明确按 Schema → 策略 → 文档/库存 Profile、路由、模板 → 停用源测试 → 启用源重建;库存测试与订单履约状态独立,不能绕过策略冻结门禁。 | +| 冻结入口策略发布门禁(阶段 6) | 已实现,Review 通过 | 即使 Schema、字段值与订购客户均有效,未发布履约策略仍会以 `SHIPPING.FULFILLMENT_POLICY_NOT_PUBLISHED` 阻断冻结且不写入 Snapshot。 | +| 履约策略管理 API 验收(阶段 7) | 已实现,Review 通过 | 普通用户不能发布策略;管理员只能在当前 Schema 已发布并包含绑定字段时发布策略,前端与服务端门禁一致。 | +| PostgreSQL 完整迁移链(阶段 8) | 已实现,Review 通过 | 隔离 PostgreSQL 空库从初始 revision 升级至 `027d8e9f0a1b`;修复历史迁移的空库分支假设后,57 字段目录与快照物理结构均通过核验。 | +| 管理员重建演练(阶段 9) | 已实现,Review 通过 | 隔离库实际发布最小四字段 Schema 与 `SHIP_AVAILABLE_ROLLING_V1`,验证目录可选与策略显式发布路径;Profile/路由/模板/RPA 仍按上线清单手工重建。 | +| Reservation 全局唯一与修订门禁(阶段 1) | 已实现,待阶段 Review | 单列 Reservation 唯一约束绑定标准化 PO;不同 PO 或同一快照内重复一律阻断,同 PO 内容变更返回人工差异确认,已有有效 Artifact/上传时禁止直接修订。 | | 订单字段对账与冲突复核 | 已实现 | Candidate→Task 字段级自动补空/冲突落库;未解决冲突阻断库存/匹配/导出;workspace 冲突查询与解决 API;改单支持 `expected_order_data_version` 与幂等键;工作台解析卡可解决冲突 | | 库存源/RPA Profile 数据库主数据 | 已实现 | 以 Inventory Source 为业务主键;Source 持久化 DBS 报表路径与查询参数;订单到站点的选择统一由路由规则维护;RPA Profile 仅保存登录、密文凭据与连接级登录配置;YAML 不再作为运行时真相源 | -| 货代配置工作台 | 在建(导航补齐) | 管理端“货代配置”将提供“库存配置”和“客户识别规则”二级入口;订单解析、库存文件解析方案、发货模板、库存站点和路由规则仍集中在库存配置页。两页复用货代配置权限,客户主数据仍位于货代工作台。 | +| 货代管理工作台 | 在建(导航补齐) | 管理端“货代管理”按“订单识别、库存管理”组织业务入口:订单识别依次提供订单字段规则、订单文档模板、客户识别规则和识别任务;库存管理工作台依次维护库存字段与解析、系统连接、库存站点、仓库映射、路由规则和发货模板,并将库存快照、导出记录归入运行与审计。各页面复用货代管理权限,现有深链保持兼容。 | | 发货模板可读配置 | 已实现 | 模板上传后读取工作表与首行表头供选择目标列;映射逐项展示字段说明和来源分组;文件名规则显式展示可用业务变量,默认推荐 `{business_no}.xlsx` | | 通用库存源路由规则 | 已实现 | 可配置、版本化规则从订单事实产生 `source_code` 候选;Reservation ID 仅为首批兜底事实字段 | | 库存文件优先匹配 | 已实现 | 正常货代流程按 `source_code` 匹配最新有效库存文件,不自动触发 RPA;RPA 仅由排程或用户手动刷新执行 | @@ -121,7 +134,7 @@ | 唯一订单 Schema 与动态字段基础 | 已实现 | 管理员以固定高度字段字典维护系统标识、版本显示名称、位置、格式和识别规则;两个名称不受“纳入当前版本”开关限制,未纳入字段配置可保存但不进入发布契约;系统标识可重命名且历史快照保留旧值,位置/类型与已发布版本保持安全门禁;管理端提供分页版本历史、严格只读快照、任意版本间服务端字段级差异、追加式配置审计时间线、版本实际使用统计和单次解析证据链;历史发布/退役版本可复制为新草稿,URL 可按业务版本号恢复;新版本移除下游引用字段时阻断发布 | | 通用上下文字段目录与运行时 | 已实现(阶段 3、5) | 复用订单解析字段目录,按通用上下文字段/订单信息/货品明细分组;迁移自动在当前草稿补齐发件人邮箱/企业域名两个完整字段配置,管理员审核后发布。首批受控来源为 EML From 邮箱/域名。Run 按 Intake 冻结规范值,Extraction 独立写入 Observation→Decision→FieldValue 与审计快照;缺失/非法/多地址不做其他来源兜底,公共域名保留真实值。Dify 契约和 documents 输入隔离确定性上下文;Schema 发布可审计地控制 `never`、受控不可逆 `redacted`、Run 冻结值 `confirmed_readonly`,并通过独立 `readonly_context` 只读输入按 Intake 传递。 | | Schema 驱动 Dify 订单解析 | 已实现 | Worker 向专用 Workflow 传入冻结 published Schema 与 Document;Workflow 按稳定 field_id 返回 Observation,后端完成类型校验、原文核验、跨文档裁决和类型化值持久化 | -| 订单文档解析 Profile | 已实现 | 版本化草稿/发布/退役、Schema/field_id 绑定、服务端结构指纹、固定注册解析器、Run 快照和 Worker 精确匹配已完成;管理端可从 MinerU 样本可视化维护表头、数据起始行、行结构和列映射,并完成新版本治理,无自由 JSON/脚本入口 | +| 订单文档解析 Profile | 已实现 | 版本化草稿/发布/退役、Schema/field_id 绑定、服务端结构指纹、固定注册解析器、Run 快照和 Worker 精确匹配已完成;管理端可从 MinerU 样本维护表头结束行、数据起始行和列映射,多行表头会合并为虚拟列头且与明细多物理行版式独立配置,无自由 JSON/脚本入口 | | 文档布局版本与任务生命周期 | 已实现(L1) | 独立布局版本/Job、当前成功引用、parser revision、checksum/大小门禁、lease/超时恢复、重试耗尽、管理员诊断和显式重解析已完成;人工 cell 真值延期,不开放自动 accepted 或 95% 声明 | | 原生 PDF 结构候选 | 工程已实现(L2 质量待验收) | PDFium 字符 bbox、稳定 token/cell、唯一文本对齐、OpenCV 有框表双门禁、逐表故障隔离和 revision v2 已完成;候选固定 needs_review,人工真值/准确率/P95 未验收 | | 扫描 PDF OCR 与 EML HTML 布局 | 工程已实现(L3 质量待验收) | RapidOCR 坐标/置信度、OCR+网格+全文本门禁、HTML 主动内容清理、DOM rowspan/colspan、hash/摘要隐私和 revision v3 已完成;候选固定 needs_review,真实扫描质量/P95 未验收 | diff --git a/docs/tec.md b/docs/tec.md index dcd25a9d..d2de2638 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -12,7 +12,13 @@ - 原生 PDF 候选使用已有 `pypdfium2` 提取字符 bbox,并只为 MinerU 表格区域生成稳定 token。HTML cell 优先做唯一/连续/非重叠字符对齐;失败时仅允许 OpenCV 多参数有框网格共识,并由原生文本 100% 验证。结果以内嵌 `shipping_document_layout.v1` 保存且固定 `needs_review`;parser revision 已提升为 `v2`,使历史 v1 结果不会静默复用。 - L3 将 parser revision 提升为 `v3`。扫描 PDF 直接适配 RapidOCR 多边形坐标,OCR cell 必须同时通过 OpenCV 网格和全部非空 cell 文本一致性;EML HTML 只保留清洗后的 table DOM,并用逻辑网格表达 rowspan/colspan。OCR/HTML 均固定 needs_review,原始 OCR 响应、页面图、主动 HTML 和临时表格片段不入库或 Dify。 - L4 新增 layout.v1→冻结 Schema 映射层,复用现有 HTML Grid 安全规则并保留真实 cell/token evidence。Run snapshot 升级为 v3并冻结内部 `layout_schema_candidates`;跨页只读显式 continuation。Manifest 强制剥离布局及映射候选,needs_review 不参与当前确定性执行。 +- 订单文档坐标 Profile 使用冻结相对列边界、列字段编码和新行起始列生成稳定虚拟表头,避免数据页残缺/后置表头导致结构指纹漂移。重建器先按字体高度形成 y-band,再把相邻字符组成文本片段,以 x-overlap 为主、字段格式和同行顺序为辅归列;物理 `continuation` 按列合并到最近 `data`,`deleted` 回写最近明细,`summary` 终止数据区。无逻辑明细的纯表头页不算 Profile 命中。 +- 多行明细使用 `subrow_layouts[]` 表达任意连续 N 行版式:`row_offset=0` 固定为含 `line_no` 的 main 行,`row_offset=1..N-1` 为 continuation;offset 必须从 0 连续且唯一。每行独立保存边界和字段编码,重叠横坐标不共享列语义;重建时按当前明细内相对行序选取对应布局,超过最后已配置行时继续使用最后一行布局。 +- 坐标版式建议先按自适应 y-band 分组物理行,再以左侧行号识别逻辑明细起点;相同 `row_offset` 的文本片段按相对 x 中心聚类,以相邻中心中点生成边界。接口只自动绑定确定性的 `line_no`,其他字段仍由管理员根据列示例确认,建议状态固定为 `needs_review`。 - `shipping_order_document_profiles` 保存模板编码、版本、绑定 Schema、精确表头结构指纹、固定列规则、稳定目标 field_id、checksum 和乐观锁。同一模板只允许一个 published 版本;Run `snapshot_version=2` 冻结全部匹配 Schema 的 published Profile 与 Document 布局快照,后续发布/退役不会改变排队中的运行。 +- **货代字段与履约冻结(阶段 1)**:系统事实由代码/数据库固定;订单字段区分 57 个可按版本启用的标准目录与自定义字段,均以稳定 `field_id` 冻结。`SHIP_AVAILABLE_ROLLING_V1` 是当前唯一代码注册策略,只要求 Line `reservation_id:string`、`part_number:string`、`qty:decimal > 0` 和已确认订购客户;不要求全部 57 个字段,不新增 Header `inventory_source_hint_default` 或 `shipping_method`。`inventory_source_hint` 只可作为可选 Line 路由线索,库存路由只读取冻结 Snapshot。 +- **货代字段能力与策略(阶段 2)**:`ShippingFulfillmentPolicy` 独立版本化,字段能力只允许代码注册并按稳定 `field_id` 绑定;scope/value_type 不匹配、缺少最低能力或未发布策略均 fail closed。冻结 Snapshot 保存策略定义与 checksum,履约消费者不读取可变 Schema 的 `business_purpose`;自定义字段只要类型和作用域符合即可被策略受控绑定。 +- **Reservation 注册**:`shipping_reservations` 通过单列唯一 `reservation_id` 强制全局唯一,并持久化标准化 PO;PO 仅 trim + uppercase,保留前导零和中间字符。首次注册可缺 PO,但 Reservation 已注册后的重复记录缺 PO、不同 PO 或同快照重复均阻断;同 PO 内容变化返回可审计前后差异并等待人工确认;有效 Artifact 或上传后禁止直接修订。Dify 不参与这些判断,继续只返回字段 Observation。 - Worker 仅对唯一表/唯一 Profile 精确命中执行确定性模板映射。Profile 可以合法覆盖裸表头的通用语义,如 `Part Number -> customer_part_number`、`Vendor Item# -> part_number`;显式零 Qty 删除。多 Profile 命中、多表命中、冻结 field_id 漂移、MinerU 行关系丢失或缺少 `part_number + qty` 时不自动合并,转 Dify/复核。Dify Manifest 会剥离布局 HTML、bbox 和内部 field_code,只携带稳定 field_id 的紧凑候选,避免 Token 膨胀。 - Profile 管理端从 ready MinerU 布局生成最小网格预览;HTML、bbox、全文和结构指纹不下发浏览器。`from-sample` 创建/更新接口重新读取持久化 HTML 并计算指纹,更新草稿要求 `expected_lock_version`。页面仅允许注册解析器与 Schema line field 下拉,重复目标字段由前端提示、Pydantic 契约再次阻断;发布/复制/退役形成完整不可变版本生命周期。 - Dify 是无状态模型执行层;HXOPS 是计划、并发/重试、Schema、跨文档合并、冲突、审计、成本、业务状态和持久化真相源。Reservation/Allocation 等安全语义由后端硬规则兜底,管理员配置不可覆盖。 diff --git a/docs/test_plan_matrix.md b/docs/test_plan_matrix.md index 2bf310a6..0590c93d 100644 --- a/docs/test_plan_matrix.md +++ b/docs/test_plan_matrix.md @@ -57,7 +57,10 @@ | **发货通知** | **订单文档模板 Profile 纯契约** | 以表头网格精确结构指纹选择固定列规则,允许模板级字段语义覆盖全局 Schema;只运行注册解析器。 | `test_shipping_order_document_profile.py` | `Part Number -> customer_part_number`、`Vendor Item# -> part_number`、复合料号 cell、零 Qty、结构漂移、MinerU 行关系丢失、自由解析器注入 | 精确命中时模板映射原样生效;零 Qty 行删除;结构变化不做相似匹配;行关系丢失显式阻断;未知解析器或非法目标字段拒绝保存。 | | **发货通知** | **订单文档 Profile 发布与运行锁定** | Profile 绑定不可变 Schema/稳定 field_id,版本化发布;Run 冻结完整 Profile 与 MinerU 紧凑布局,Worker 只执行唯一精确匹配。 | `test_shipping_order_document_profile_service.py`、`test_order_document_profile_migration.py`、`test_shipping_document_layout_runtime.py`、`test_agent_runtime_bindings.py`、`test_shipping_order_extraction_runs.py` | 并发草稿覆盖、新版发布、字段退役、Provider 失败、多附件预算、多表/多 Profile、零 Qty、Decimal JSON、布局 HTML 泄漏 Dify、Run 后配置变化 | 乐观锁与单 published 唯一索引生效;字段引用阻断退役;Run 快照不漂移;Provider 失败安全回退;唯一完整表跳过 Dify;多表不自动合并;HTML/bbox/field_code 不进入 Dify;零 Qty 删除。 | | **发货通知** | **订单文档 Profile 可视化治理** | 管理员只从 ready MinerU 样本选择表格、行和受控字段/解析器,完成草稿、新版本、发布与退役;浏览器不持有可伪造运行契约。 | `test_shipping_order_document_profile_service.py`、`orderProfileForm.utils.spec.ts`、`shippingConfigNavigation.spec.ts`、前端生产构建 | 普通用户访问、伪造结构指纹、HTML/bbox 泄漏、越界行、重复目标字段、复合解析器冲突、过期 lock、新版本重配、unsupported 行结构、`ITEM NO 00010` 混入表头 | 普通用户拒绝;预览仅 cell 文本;指纹后端计算;表头污染返回稳定诊断并拒绝建草稿;越界/过期锁/重复字段阻断;只允许注册解析器;复制草稿须用样本重新确认;无需编辑 JSON/HTML/脚本。 | -| **发货通知** | **文档版面坐标重建候选** | 仅在可信 PDF glyph 坐标与人工确认列锚点同时存在时,按 x 列归属、y 视觉行、内容适配度及相邻连续性重建错误 MinerU 网格的复核候选。 | `test_shipping_coordinate_table_reconstruction.py` | `00010/00020` 行号、料号/数量列、跨视觉行续行、`** Item deleted **`、无锚点行、列归属并列 | 候选固定 `needs_review` 并保留 glyph 索引;续行不伪装为新明细;删除标记仅关联前一强行号;无坐标/歧义绝不自动接受、发布 Profile 或进入履约。 | +| **发货通知** | **文档版面坐标重建候选** | 在可信 PDF/OCR 字符坐标存在时自动建议动态行数、列边界和列示例;管理员确认字段后,按 x 列归属、y 视觉行、字段内容适配及同行顺序重建错误 MinerU 网格,再按动态 N 行版式合并为可审核逻辑明细。 | `test_shipping_coordinate_table_reconstruction.py`、`test_shipping_order_document_profile_service.py` | `00010/00020` 行号、料号/数量/单位边界、2/3/4/N 行版式、每行不同列数、单内容块续行、跨行重叠边界、`** Item deleted **`、TOTAL 终止、残缺/后置表头、纯表头页、列归属并列 | 建议与候选固定 `needs_review`;自动建议排除表头/合计、自动标出首行 `line_no` 并只返回相对边界/少量示例;坐标虚拟表头不依赖数据页完整表头;第 2..N 行按独立边界合并;无坐标/歧义绝不自动接受、发布 Profile 或进入履约。 | +| **发货通知** | **坐标修复模板闭环** | 结构污染 PDF 由管理员确认列边界后重建,确认结果随 Profile 与 Run 冻结。 | `test_shipping_coordinate_table_reconstruction.py`、`test_shipping_order_document_profile_service.py`、前端生产构建 | 表头混入首条明细、无文本层 PDF、非法边界、未确认候选、盲测与 Run 证据缺失 | 浏览器只看到候选网格;边界必须从 0 到 1 严格递增;重建固定待审核且须显式确认;Profile/Run/盲测只用冻结坐标证据,任何缺失均阻断,不回退原始错误网格或 Dify。 | +| **发货通知** | **订单模板页样本上传** | 管理员可从订单文档模板页直接上传 PDF/EML,建立隔离样本 Intake 并复用异步预解析和布局 Job。 | `test_shipping_order_document_profile_service.py`、前端生产构建、Alembic upgrade | PDF、EML 正文 HTML、多附件 EML、非 PDF/EML、样本解析中/失败、业务 Intake 混入 | 样本 Intake purpose 固定为 `order_document_profile_sample`,不绑定会话,不创建 Candidate/Task/指纹或 Dify 调用;仅解析完成的单 Document 表格可配置 Profile;文件类型前后端均拒绝;样本状态不泄露正文、HTML 或 bbox。 | +| **发货通知** | **订单模板样本治理与版本识别** | 样本可按文件名搜索并展示时间/状态;当前发布版本可辨识;专用样本受控删除。 | `test_shipping_order_document_profile_service.py`、前端生产构建 | 同名样本、历史业务附件、解析中样本、盲测引用、资产共享、多个版本 | 选择器标明文件名/时间/状态/表格数;同编码 published 版本标记当前生效;仅 `order_document_profile_sample` 的已解析、未盲测引用且未共享资产样本可删除;删除同步回收源文件和布局,历史业务附件及盲测证据不可删除。 | | **发货通知** | **订单文档 Profile 独立盲测资格** | 发布 Profile 与确定性自动建单资格分离;盲测真值、执行摘要和批准状态绑定 checksum。 | `test_shipping_document_profile_quality.py`、`test_shipping_document_profile_quality_migration.py`、`test_agent_runtime_bindings.py` | 少于 3 样本、真值不匹配、批准后编辑、checksum 漂移、未知/多模板、Dify 不可用 | 至少 3 个独立样本全通过且管理员批准才放行;批准样本不可改;checksum 变化立即失效;唯一已批准 Profile 直接生成确定性订单,其他情形回退 Dify/人工。 | | **发货通知** | **Workflow 结果缓存与重试** | Dify 成功后先独立保存结构化 orders;即使无 workflow_run_id,HXOPS 落库失败重试也不得再次调用 Dify。 | `test_agent_runtime_bindings.py::test_worker_caches_provider_output_and_does_not_call_dify_twice` | 首次 Provider 成功、后续 DB 暂时失败 | Dify 调用 1 次、持久化尝试 2 次,Run 最终 completed。 | | **发货通知** | **Provider 变更与密钥轮换** | App ID/Base URL 漂移阻断旧 Run;API Key 轮换允许旧 Run 使用新密钥继续。 | `test_agent_runtime_bindings.py` Provider drift / key rotation 用例 | 排队后修改 App ID、Base URL 或 API Key | 前两者 Run/Job failed 且不调用 Dify;密钥轮换成功完成。 | @@ -66,6 +69,15 @@ | **发货通知** | **一附件多订单与部分成功** | 一个 Document 可形成多个 Candidate;高置信订单自动建 Task,低置信订单保留。 | `test_shipping_notice_order_extraction.py::test_persist_order_extraction_result_supports_multiple_orders_partial_success_and_replay` | 同一附件 2 个订单,其中 1 个低置信 | 2 Candidate、1 Task、1 pending;Intake=`partially_completed`;重放不重复建单。 | | **发货通知** | **订单抽取快照与权限** | Run 冻结用户、会话、Schema、邮件上下文和 Document;排队期间来源变化必须拒绝。 | test_shipping_order_extraction_runs.py、test_agent_runtime_bindings.py、test_shipping_order_schema_runtime.py | 越权读取、App/Base URL 漂移、正文或确定性上下文变化 | 用户态不泄密;执行身份漂移和来源变化返回稳定错误码;不创建 Candidate。 | | **发货通知** | **自动建单与流程字段门禁** | 分类、`part_number`/Qty 置信度与原文证据达标即建 Task;缺 Reservation 仍建单但禁止库存链;`inventory_source_hint` 仅作可选路由线索。 | `test_shipping_notice_order_extraction.py` / `test_shipping_notice_tools.py` | 高置信 `part_number`+Qty,Reservation 为空、库存源线索可选 | Task=`pending_review/rsv_req`;`auto_progress` 返回 needs_human 且禁止库存/匹配/Excel;库存源线索缺失不单独阻断。 | +| **发货通知** | **字段分层、冻结与 Reservation 全局唯一(阶段 1)** | 57 个预置字段为版本化标准目录;固定滚动策略只校验当前最小履约字段与已确认客户,Reservation 按单列全局唯一绑定客户 PO。 | `test_shipping_order_snapshot.py`、`test_shipping_rolling_fulfillment.py`、`test_shipping_reservation_global_unique_migration.py`、`test_shipping_inventory_routing_engine.py` | 仅最小字段、缺任一字段、正/零/负 Decimal、未确认客户、同快照重复、跨 PO、同 PO 变更、有效 Artifact/上传、PO 大小写/空格、缺 PO | 不要求全部 57 字段;`customer_po_number` 用于 PO 判定;Snapshot 冻结策略和 field_id;路由只读 Snapshot;同 PO 变更返回前后差异并要求人工确认;不同 PO、重复 Reservation 和锁定修订阻断。 | +| **发货通知** | **字段能力绑定与策略快照(阶段 2)** | 履约角色由受控策略而非 `business_purpose` 决定,自定义字段可按 scope/type 绑定能力。 | `test_shipping_fulfillment_policy.py`、`test_shipping_order_field_purposes.py`、`test_shipping_order_snapshot.py` | 自定义预约单字段、范围/类型错误、缺最低能力、新旧策略发布、冻结后策略变更 | 仅注册能力可绑定;错误绑定/无发布策略 fail closed;冻结保存完整策略定义,历史 Snapshot 不被新策略重解释。 | +| **发货通知** | **履约策略管理闭环(阶段 3)** | 管理端只显示注册能力及当前 published Schema 的兼容字段;服务端在发布时二次验证字段纳入状态。 | `test_shipping_fulfillment_policy.py`、前端 build | 未发布 Schema、scope/type 不符、目录 active 但未纳入 Schema、并发发布、历史 Snapshot | 不存在自由表达式入口;不兼容或未纳入字段不能发布;旧策略原子退役;冻结订单不被新策略重解释。 | +| **发货通知** | **Schema-策略反向依赖门禁(阶段 4)** | 已发布履约策略所绑定字段成为 Schema 发布依赖,和路由/Profile/模板引用同级处理。 | `test_shipping_fulfillment_policy.py`、`test_shipping_order_schema.py` | 先发布策略再移除绑定字段、替换字段、并存库存 Profile 引用 | 新 Schema 在发布前返回依赖阻断;当前发布 Schema、策略与库存配置保持可冻结、可匹配、可制单的一致状态。 | +| **发货通知** | **迁移后管理员重建顺序(阶段 5)** | Schema/策略决定订单履约就绪;库存源配置测试独立于订单冻结和上传。 | `test_shipping_fulfillment_policy.py`、`test_shipping_excel_template.py`、`test_shipping_order_schema.py` | 初始策略草稿、未发布策略、Schema 后策略发布、Profile/模板重建、停用源测试 | 未发布策略时冻结 fail closed;策略仅绑定当前 Schema 字段;库存测试不生成订单履约副作用,启用源不等于绕过订单策略门禁。 | +| **发货通知** | **冻结策略发布门禁(阶段 6)** | 冻结入口必须取得当前 published 策略,不能由已发布 Schema 或前端状态替代。 | `test_shipping_order_snapshot.py`、`test_shipping_fulfillment_policy.py` | Schema/字段/已确认客户完整但无 published 策略 | 返回 `SHIPPING.FULFILLMENT_POLICY_NOT_PUBLISHED`,不产生 Snapshot 或后续库存履约事实。 | +| **发货通知** | **履约策略管理 API(阶段 7)** | 管理员 API 与页面字段过滤共同形成发布闭环。 | `test_shipping_order_schema.py`、`test_shipping_fulfillment_policy.py`、前端 build | 普通用户发布、Schema 已发布后发布策略、字段纳入校验 | 非管理员返回 `AUTH.FORBIDDEN`;管理员发布的策略只绑定当前 published Schema 的兼容字段。 | +| **发货通知** | **完整 PostgreSQL 迁移链(阶段 8)** | 空库必须从初始 revision 无人工补表地升级到当前货代 head;历史兼容回填不能假设 sibling 分支字段/表存在。 | `test_shipping_inventory_source_gate_migration.py`、字段目录/Reservation 迁移测试、隔离 PostgreSQL `flask db upgrade` | 缺 `step_payload_json`、缺任务状态列、缺旧 ERP 表、无旧路由配置、PostgreSQL 索引名长度 | 升级抵达唯一 head `027d8e9f0a1b`;57 个 active 标准字段、`customer_po_number` 和移除 `aws_part_number` 的快照结构均经数据库核验。 | +| **发货通知** | **管理员重建演练(阶段 9)** | 57 字段目录可发布为满足当前履约最低要求的 Schema,策略必须随后显式发布。 | 隔离 PostgreSQL 重建演练、`test_shipping_order_schema.py`、`test_shipping_fulfillment_policy.py` | 仅四字段发布、策略草稿、策略发布 | Schema 发布 4 项字段成功;`SHIP_AVAILABLE_ROLLING_V1` 成功发布;未发布策略时冻结仍 fail closed。 | | **发货通知** | **库存连接器 API 命名** | 连接器候选使用 `connector_type`,任务 API 使用 `inventory_connector_type`;不得返回旧 `inventory_source_type`。 | `test_shipping_notice_openapi_contract.py` | 获取动态 OpenAPI 与静态 Dify 快照 | 订单行使用动态 `fields[]`,字段项明确 `field_id + observations[]` 且不暴露废弃固定路由字段;状态查询说明仅含 `inventory_connector_type`。 | | **发货通知** | **任务级人工库存发布方案门禁** | 已有任务可人工上传 `.xls/.xlsx/.csv`,但必须按已确认库存站点的 published Profile 确定性解析。 | `test_shipping_notice_inventory_rpa_workflow.py` | 完全一致文件、关键表头漂移文件 | 一致文件直接进入 `ready_to_match` 且快照记录发布方案映射;漂移文件回滚文件、快照、任务链接和库存投影,不进入字段对齐或 LLM 映射。 | | **发货通知** | **重新上传库存状态收敛** | 用户可重新选择正式库存文件,但不能重开任务级猜列或映射确认。 | `test_shipping_notice_tools.py`、前端 shipping decision/menu 单测 | 已有关联库存、已有匹配/导出结果、废弃映射动作 | `reparse_inventory` 停用当前 active link 并清理库存、匹配和导出派生结果,返回“选择库存文件/重新获取库存”;前端不生成 `confirm_inventory_mapping`、`correct_inventory_mapping`、`paste_inventory_json` 或 `edit_inventory_mapping`。 | diff --git a/frontend/src/app/router/routes/admin.routes.ts b/frontend/src/app/router/routes/admin.routes.ts index 80319dd4..541f8ade 100644 --- a/frontend/src/app/router/routes/admin.routes.ts +++ b/frontend/src/app/router/routes/admin.routes.ts @@ -157,7 +157,7 @@ export const adminRoutes: RouteRecordRaw[] = [ path: "shipping-notice", name: "AdminShippingInventory", component: ShippingInventoryPage, - meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'inventory', title: "库存配置" }, + meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'inventory', title: "货代管理" }, }, { path: "shipping-identity-rules", @@ -169,7 +169,7 @@ export const adminRoutes: RouteRecordRaw[] = [ path: "shipping-order-extraction-runs", name: "AdminShippingOrderExtractionRuns", component: ShippingOrderExtractionRunsPage, - meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_extraction_runs', title: "订单识别运行" }, + meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_extraction_runs', title: "识别任务" }, }, { path: "shipping-order-document-profiles", diff --git a/frontend/src/features/admin/api/shipping-order-document-profile.api.ts b/frontend/src/features/admin/api/shipping-order-document-profile.api.ts index 3d1bb057..29739d6a 100644 --- a/frontend/src/features/admin/api/shipping-order-document-profile.api.ts +++ b/frontend/src/features/admin/api/shipping-order-document-profile.api.ts @@ -10,6 +10,9 @@ import { getAuthHeaders } from '@/shared/utils/auth'; import type { CreateOrderProfileFromSampleInput, OrderProfileSampleDocument, + CoordinateReconstructionPreview, + CoordinateReconstructionSuggestion, + CoordinateReconstructionSettings, OrderProfileSampleIntake, OrderProfileSamplePreview, ShippingOrderDocumentProfile, @@ -39,12 +42,50 @@ export const getOrderProfileSampleStatus = (intakeNo: string) => auth(), ); +/** 删除可安全回收的专用模板样本;历史业务附件与盲测样本由服务端保护。 */ +export const deleteOrderProfileSample = (intakeNo: string) => + requestJson( + `/api/admin/shipping-notice/order-document-profile-samples/intakes/${encodeURIComponent(intakeNo)}`, + { method: 'DELETE', ...auth() }, + ); + /** 读取一个样本文档的网格预览,不返回 HTML 或 bbox。 */ export const getOrderProfileSampleTables = (documentId: number) => requestJson( `/api/admin/shipping-notice/order-document-profile-samples/${documentId}/tables`, auth(), ); +/** 以管理员确认的相对列边界生成坐标重建候选;结果始终待人工审核。 */ +export const previewOrderProfileCoordinateReconstruction = ( + documentId: number, tableId: string, coordinateReconstruction: CoordinateReconstructionSettings, +) => requestJson( + '/api/admin/shipping-notice/order-document-profile-samples/coordinate-reconstruction-preview', { + method: 'POST', + body: JSON.stringify({ document_id: documentId, table_id: tableId, coordinate_reconstruction: coordinateReconstruction }), + ...jsonAuth(), + }, +); + +/** 从冻结字符坐标建议全部或指定物理行;rowOffset 省略时保持原有全量识别。 */ +export const suggestOrderProfileCoordinateReconstruction = ( + documentId: number, tableId: string, rowOffset?: number, +) => + requestJson( + '/api/admin/shipping-notice/order-document-profile-samples/coordinate-reconstruction-suggestion', { + method: 'POST', + body: JSON.stringify({ document_id: documentId, table_id: tableId, row_offset: rowOffset }), + ...jsonAuth(), + }, + ); + +/** 为扫描 PDF 生成 OCR 坐标证据;随后仍必须由管理员审核重建网格。 */ +export const generateOrderProfileOcrCoordinateEvidence = (documentId: number, tableId: string) => + requestJson<{ document_id: number; table_id: string; source: 'ocr' }>( + '/api/admin/shipping-notice/order-document-profile-samples/ocr-coordinate-evidence', { + method: 'POST', body: JSON.stringify({ document_id: documentId, table_id: tableId }), ...jsonAuth(), + }, + ); + /** 由真实样本和结构化列选择创建 Profile 草稿。 */ export const createOrderProfileFromSample = (payload: CreateOrderProfileFromSampleInput) => requestJson('/api/admin/shipping-notice/order-document-profiles/from-sample', { diff --git a/frontend/src/features/admin/api/shipping-order-schema.api.ts b/frontend/src/features/admin/api/shipping-order-schema.api.ts index 5595b5f7..23b2fa67 100644 --- a/frontend/src/features/admin/api/shipping-order-schema.api.ts +++ b/frontend/src/features/admin/api/shipping-order-schema.api.ts @@ -16,6 +16,8 @@ import type { ShippingOrderSchemaVersionDiff, ShippingOrderSchemaVersionPage, ShippingOrderSchemaVersionUsage, + ShippingFulfillmentPolicy, + ShippingFulfillmentPolicyState, } from '../types/shipping-order-schema.types'; const auth = () => ({ headers: getAuthHeaders() }); @@ -143,3 +145,21 @@ export const publishShippingOrderSchemaDraft = (versionId: number, expectedLockV `/api/admin/shipping-order-schema/versions/${versionId}/publish`, { method: 'POST', body: JSON.stringify({ expected_lock_version: expectedLockVersion }), ...jsonAuth() }, ); + +/** 读取受控履约能力目录及策略版本,页面不提供任意表达式配置。 */ +export const getShippingFulfillmentPolicyState = () => + requestJson('/api/admin/shipping-fulfillment-policies', auth()); + +/** 创建按稳定字段 ID 绑定的下一履约策略草稿。 */ +export const createShippingFulfillmentPolicyDraft = (payload: { + field_bindings: Array<{ capability_code: string; field_id: string }>; + change_note?: string; +}) => requestJson('/api/admin/shipping-fulfillment-policies', { + method: 'POST', body: JSON.stringify(payload), ...jsonAuth(), +}); + +/** 显式发布策略草稿;服务端原子退役上一发布版本。 */ +export const publishShippingFulfillmentPolicy = (policyId: number, expectedLockVersion: number) => + requestJson(`/api/admin/shipping-fulfillment-policies/${policyId}/publish`, { + method: 'POST', body: JSON.stringify({ expected_lock_version: expectedLockVersion }), ...jsonAuth(), + }); diff --git a/frontend/src/features/admin/components/AdminNav.vue b/frontend/src/features/admin/components/AdminNav.vue index 0706ced6..0a407b8b 100644 --- a/frontend/src/features/admin/components/AdminNav.vue +++ b/frontend/src/features/admin/components/AdminNav.vue @@ -1,6 +1,6 @@ /** * features/admin/components/AdminNav.vue - * 管理后台左侧导航,使用子路由跳转。 + * 管理后台左侧导航,在模块原始顺序中渲染货代手风琴、企微和报表二级菜单。 * 依赖:admin-nav.store、modules 常量、vue-router。 * 逻辑:报表/企微子菜单默认折叠;当前路由落在对应模块时自动展开以便看到激活项。 */ @@ -10,13 +10,15 @@ import { useI18n } from 'vue-i18n'; import { useRoute, useRouter } from 'vue-router'; import { LayoutDashboard, UserPlus, UserCog, Building, Bot, FileText, - Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2, AppWindow, Warehouse + Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2, AppWindow, Warehouse, + ChevronDown, ChevronRight } from 'lucide-vue-next'; import type { Component } from 'vue'; import { config } from '@/config'; import { ADMIN_MODULE_METAS, ADMIN_REPORT_TABLES, SHIPPING_CONFIG_SUB_MODULE_METAS } from '../constants/modules'; import { useAdminNavStore } from '../stores/admin-nav.store'; -import type { AdminModuleId, ShippingConfigSubModuleId } from '../types/admin.types'; +import type { ShippingManagementGroupKey } from '../stores/admin-nav.store'; +import type { AdminModuleId } from '../types/admin.types'; const { t } = useI18n(); const route = useRoute(); @@ -45,18 +47,13 @@ const visibleModules = computed(() => ADMIN_MODULE_METAS.filter((item) => config.admin.modules[item.configKey] !== false), ); -const standardModules = computed(() => - visibleModules.value.filter((item) => item.id !== 'wecom' && item.id !== 'shipping_inventory'), -); - const isModuleActive = (moduleId: AdminModuleId): boolean => route.meta.adminModule === moduleId; const isReportsActive = computed(() => route.meta.adminModule === 'reports'); const isWecomActive = computed(() => route.meta.adminModule === 'wecom'); -const isShippingConfigActive = computed(() => route.meta.adminModule === 'shipping_inventory'); -const isShippingConfigSubModuleActive = (subModule: ShippingConfigSubModuleId): boolean => - route.meta.adminSubModule === subModule; +const isShippingManagementActive = computed(() => route.meta.adminModule === 'shipping_inventory'); +const shippingNavGroups = [...new Set(SHIPPING_CONFIG_SUB_MODULE_METAS.map((item) => item.groupKey))]; const wecomSubRoutes = [ { name: 'AdminWecomSettings', labelKey: 'admin.wecom.nav.settings' }, @@ -68,8 +65,24 @@ const navigateWecom = (routeName: string): void => { router.push({ name: routeName }); }; -const navigateShippingConfig = (routeName: string): void => { - router.push({ name: routeName }); +/** 判断货代二级菜单当前项;综合工作台按 section 深链高亮,库存字段目录归入库存解析。 */ +const isShippingNavActive = (item: typeof SHIPPING_CONFIG_SUB_MODULE_METAS[number]): boolean => { + if (route.name !== item.routeName) return false; + if (!item.query) return true; + const section = typeof route.query.section === 'string' ? route.query.section : 'orderSchema'; + if (item.query.section === 'parsing') return section === 'parsing' || section === 'inventoryFields'; + return section === item.query.section; +}; + +/** 打开货代独立页面或综合工作台区段,保留可收藏的 section 深链。 */ +const navigateShipping = (item: typeof SHIPPING_CONFIG_SUB_MODULE_METAS[number]): void => { + router.push({ name: item.routeName, query: item.query }); +}; + +/** 返回当前货代页面所在分组,用于路由进入时只展开对应手风琴。 */ +const currentShippingGroup = (): ShippingManagementGroupKey | null => { + const currentItem = SHIPPING_CONFIG_SUB_MODULE_METAS.find(isShippingNavActive); + return currentItem?.groupKey ?? null; }; const getReportTableLabel = (table: string): string => { @@ -88,7 +101,7 @@ const navigateReport = (table: string): void => { }; /** - * 进入报表/企微模块时自动展开子菜单,避免当前页在折叠状态下不可见。 + * 进入报表、企微或货代模块时自动展开子菜单,避免当前页在折叠状态下不可见。 */ watch( isReportsActive, @@ -107,12 +120,22 @@ watch( ); watch( - isShippingConfigActive, + isShippingManagementActive, (active) => { - if (active) navStore.shippingConfigExpanded = true; + if (!active) return; + navStore.shippingManagementExpanded = true; + navStore.shippingManagementGroup = currentShippingGroup(); }, { immediate: true }, ); + +watch( + () => [route.name, route.query.section], + () => { + if (isShippingManagementActive.value) navStore.shippingManagementGroup = currentShippingGroup(); + }, +); +