feat(shipping-notice): 添加货代履约策略管理功能,支持策略创建、发布及版本控制,增强订单冻结和预约管理逻辑
This commit is contained in:
1 parent
abd8fc1e16
commit
d62f5107b2
82 files changed
+4914
-514
No files matched your search
@@ -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/<string:intake_no>', 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/<int:document_id>/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():
|
||||
|
||||
@@ -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/<int:policy_id>/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():
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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)
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
|
||||
+410
-17
@@ -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:
|
||||
|
||||
@@ -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 = '<tr data-row-role="header">' + ''.join(
|
||||
f'<th>{html.escape(code)}</th>' for code in field_codes
|
||||
) + '</tr>'
|
||||
body = ''.join(
|
||||
'<tr data-row-role="{}" data-source-rows="{}">{}</tr>'.format(
|
||||
row.role, ','.join(str(index) for index in row.source_row_indices),
|
||||
''.join(f'<td>{html.escape(row.fields.get(code, ""))}</td>' for code in field_codes),
|
||||
)
|
||||
for row in logical_rows
|
||||
)
|
||||
return f'<table>{header}{body}</table>'
|
||||
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 = '<tr data-row-role="header">' + ''.join(
|
||||
f'<th>coordinate_column_{index + 1}</th>' for index in range(len(anchors))
|
||||
) + '</tr>'
|
||||
body = ''.join(
|
||||
'<tr data-row-role="{}" data-source-rows="{}">{}</tr>'.format(
|
||||
row['role'], ','.join(str(index) for index in row['source_rows']),
|
||||
''.join(
|
||||
f'<td>{html.escape(str(row["values"].get(index, "")))}</td>'
|
||||
for index in range(len(anchors))
|
||||
),
|
||||
)
|
||||
for row in logical_rows
|
||||
)
|
||||
return f'<table>{header}{body}</table>'
|
||||
|
||||
|
||||
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:
|
||||
|
||||
@@ -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 {}
|
||||
|
||||
@@ -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']
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
@@ -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({
|
||||
|
||||
@@ -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':
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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, ''):
|
||||
|
||||
@@ -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'
|
||||
}),
|
||||
}
|
||||
@@ -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))
|
||||
|
||||
@@ -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 语义不同,管理员配置不得覆盖安全边界。
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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')
|
||||
@@ -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')
|
||||
@@ -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')
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
+34
-34
@@ -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:
|
||||
|
||||
+12
-4
@@ -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(
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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('<tr ') == 2
|
||||
|
||||
|
||||
def test_reconstructed_profile_html_marks_deleted_and_stops_at_summary():
|
||||
"""删除标记回写最近明细;TOTAL AMOUNT 之后的文本不得进入逻辑明细。"""
|
||||
html = reconstruct_order_profile_html(
|
||||
characters=_glyphs(
|
||||
[('00010', 12), ('PART-A', 62)],
|
||||
[('** Item deleted **', 62)],
|
||||
[('TOTAL AMOUNT', 62), ('100.00', 150)],
|
||||
[('00020', 12), ('PART-B', 62)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
reconstruction=CoordinateReconstructionProfile(column_boundaries=[0, 0.3, 0.7, 1]),
|
||||
)
|
||||
assert 'data-row-role="deleted"' in html
|
||||
assert 'PART-B' not in html
|
||||
|
||||
|
||||
def test_coordinate_reconstruction_uses_fixed_field_content_for_boundary_tie():
|
||||
"""字符恰好跨数量与单位边界时,固定字段类型只能作为几何并列的辅助证据。"""
|
||||
result = reconstruct_table_from_positioned_text(
|
||||
characters=[
|
||||
{'text': 'E', 'bbox': {'x0': 96, 'y0': 20, 'x1': 100, 'y1': 30}},
|
||||
{'text': 'A', 'bbox': {'x0': 100, 'y0': 20, 'x1': 104, 'y1': 30}},
|
||||
],
|
||||
table_bbox=LayoutBBox(x0=0, y0=0, x1=200, y1=100),
|
||||
column_anchors=[
|
||||
{'column_index': 0, 'field_code': 'qty', 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 100}},
|
||||
{'column_index': 1, 'field_code': 'uom', 'bbox': {'x0': 100, 'y0': 0, 'x1': 200, 'y1': 100}},
|
||||
],
|
||||
)
|
||||
assert result.rows[0].cells[0].column_index == 1
|
||||
assert result.rows[0].cells[0].text == 'EA'
|
||||
|
||||
|
||||
def test_coordinate_profile_parses_one_logical_line_from_multiple_visual_rows():
|
||||
"""端到端验证:一条数据行加两条续行只能产出一条可审核订单明细。"""
|
||||
settings = CoordinateReconstructionProfile(
|
||||
column_boundaries=[0, 0.2, 0.7, 1],
|
||||
column_field_codes=['line_no', 'part_number', 'qty'],
|
||||
)
|
||||
html = reconstruct_order_profile_html(
|
||||
characters=_glyphs(
|
||||
[('00020', 12), ('6Y70B2501901', 52), ('30', 160)],
|
||||
[('D4-A08AR1200002', 52)],
|
||||
[('RoHS2', 52)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
reconstruction=settings,
|
||||
)
|
||||
grid = parse_html_grid(html, table_id='inventec')
|
||||
profile = OrderDocumentProfile(
|
||||
profile_code='INVENTEC_PO', version=1,
|
||||
structure_fingerprint=order_profile_structure_fingerprint(grid, header_row_index=0),
|
||||
header_row_index=0, data_start_row_index=1,
|
||||
column_rules=[
|
||||
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['line_no']),
|
||||
OrderProfileColumnRule(column_index=1, extractor_key='direct', target_field_codes=['part_number']),
|
||||
OrderProfileColumnRule(column_index=2, extractor_key='direct', target_field_codes=['qty']),
|
||||
],
|
||||
coordinate_reconstruction=settings,
|
||||
)
|
||||
contract = compile_table_header_contract({'fields': [
|
||||
{'field_code': 'line_no', 'display_name': 'Line', 'enabled': True},
|
||||
{'field_code': 'part_number', 'display_name': 'Part', 'enabled': True},
|
||||
{'field_code': 'qty', 'display_name': 'Qty', 'value_type': 'decimal', 'enabled': True},
|
||||
]})
|
||||
|
||||
parsed = parse_html_table_with_order_profile(html, table_id='inventec', profile=profile, contract=contract)
|
||||
|
||||
assert parsed.matched is True
|
||||
assert len(parsed.rows) == 1
|
||||
assert parsed.rows[0].fields == {
|
||||
'line_no': '00020', 'part_number': '6Y70B2501901 D4-A08AR1200002 RoHS2', 'qty': 30,
|
||||
}
|
||||
|
||||
|
||||
def test_multi_subrow_profile_uses_independent_overlapping_boundaries():
|
||||
"""主行和补充行可在相同横坐标表达不同字段,并合并为一条逻辑明细。"""
|
||||
settings = CoordinateReconstructionProfile(subrow_layouts=[
|
||||
{
|
||||
'role': 'main', 'row_offset': 0,
|
||||
'column_boundaries': [0, 0.12, 0.32, 0.5, 0.68, 0.84, 1],
|
||||
'column_field_codes': ['line_no', 'part_number', 'remark', 'unit_price', 'qty', 'uom'],
|
||||
},
|
||||
{
|
||||
'role': 'continuation', 'row_offset': 1,
|
||||
'column_boundaries': [0, 0.18, 0.48, 0.7, 1],
|
||||
'column_field_codes': [None, 'customer_part_number', 'required_date', 'remark'],
|
||||
},
|
||||
{
|
||||
'role': 'continuation', 'row_offset': 2,
|
||||
'column_boundaries': [0, 0.25, 0.55, 1],
|
||||
'column_field_codes': [None, 'inventory_source_hint', 'remark'],
|
||||
},
|
||||
])
|
||||
html = reconstruct_order_profile_html(
|
||||
characters=_glyphs(
|
||||
[('00020', 12), ('6Y70B2501901', 46), ('SET,RACK', 102), ('941.76', 154), ('30', 208), ('EA', 260)],
|
||||
[('D4-A08AR1200002', 58), ('06/29/2026', 150), ('Ship by land', 220)],
|
||||
[('RoHS2', 82), ('EXW AWS HUB', 180)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 320, 'y1': 100},
|
||||
reconstruction=settings,
|
||||
)
|
||||
|
||||
assert html.count('data-row-role="data"') == 1
|
||||
assert '6Y70B2501901' in html
|
||||
assert 'D4-A08AR1200002' in html
|
||||
assert '06/29/2026' in html
|
||||
assert 'EXW AWS HUB' in html
|
||||
assert 'data-source-rows="0,1,2"' in html
|
||||
|
||||
|
||||
def test_multi_subrow_profile_parses_merged_fields_with_existing_profile_parser():
|
||||
"""多子行输出必须继续由既有固定列 Profile 解析器消费,避免另造运行链路。"""
|
||||
settings = CoordinateReconstructionProfile(subrow_layouts=[
|
||||
{'role': 'main', 'row_offset': 0, 'column_boundaries': [0, 0.2, 0.65, 1],
|
||||
'column_field_codes': ['line_no', 'part_number', 'qty']},
|
||||
{'role': 'continuation', 'row_offset': 1, 'column_boundaries': [0, 0.4, 0.7, 1],
|
||||
'column_field_codes': [None, 'required_date', 'remark']},
|
||||
])
|
||||
html = reconstruct_order_profile_html(
|
||||
characters=_glyphs(
|
||||
[('00020', 12), ('PART-20', 70), ('30', 240)],
|
||||
[('06/29/2026', 135), ('Ship by land', 235)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 320, 'y1': 70},
|
||||
reconstruction=settings,
|
||||
)
|
||||
grid = parse_html_grid(html, table_id='multi-subrow')
|
||||
headers = ['line_no', 'part_number', 'qty', 'required_date', 'remark']
|
||||
profile = OrderDocumentProfile(
|
||||
profile_code='MULTI_SUBROW', version=1,
|
||||
structure_fingerprint=order_profile_structure_fingerprint(grid, header_row_index=0),
|
||||
header_row_index=0, data_start_row_index=1,
|
||||
column_rules=[
|
||||
OrderProfileColumnRule(column_index=index, extractor_key='direct', target_field_codes=[code])
|
||||
for index, code in enumerate(headers)
|
||||
],
|
||||
coordinate_reconstruction=settings,
|
||||
)
|
||||
contract = compile_table_header_contract({'fields': [
|
||||
{'field_code': 'line_no', 'enabled': True},
|
||||
{'field_code': 'part_number', 'enabled': True},
|
||||
{'field_code': 'qty', 'value_type': 'decimal', 'enabled': True},
|
||||
{'field_code': 'required_date', 'value_type': 'date', 'enabled': True},
|
||||
{'field_code': 'remark', 'enabled': True},
|
||||
]})
|
||||
|
||||
parsed = parse_html_table_with_order_profile(html, table_id='multi-subrow', profile=profile, contract=contract)
|
||||
|
||||
assert parsed.matched is True
|
||||
assert len(parsed.rows) == 1
|
||||
assert parsed.rows[0].fields['part_number'] == 'PART-20'
|
||||
assert parsed.rows[0].fields['qty'] == 30
|
||||
assert parsed.rows[0].fields['required_date'] == '2026-06-29'
|
||||
assert parsed.rows[0].fields['remark'] == 'Ship by land'
|
||||
|
||||
|
||||
def test_multi_subrow_profile_supports_four_or_more_physical_rows():
|
||||
"""逻辑明细行数由模板动态定义,四行版式不得被固定三行实现截断。"""
|
||||
settings = CoordinateReconstructionProfile(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, 'remark']},
|
||||
])
|
||||
html = reconstruct_order_profile_html(
|
||||
characters=_glyphs(
|
||||
[('10', 12), ('PART-10', 100), ('3', 270)],
|
||||
[('VENDOR-10', 180)],
|
||||
[('05/05/2026', 180)],
|
||||
[('R2_SA;HF_SA', 180)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 320, 'y1': 100},
|
||||
reconstruction=settings,
|
||||
)
|
||||
|
||||
assert html.count('data-row-role="data"') == 1
|
||||
assert 'data-source-rows="0,1,2,3"' in html
|
||||
assert 'VENDOR-10' in html
|
||||
assert '05/05/2026' in html
|
||||
assert 'R2_SA;HF_SA' in html
|
||||
|
||||
|
||||
def test_layout_suggestion_uses_real_rows_and_dynamic_column_counts():
|
||||
"""自动建议应从真实横坐标生成动态行数,并忽略表头和合计区域。"""
|
||||
suggestions = suggest_multi_subrow_layouts(
|
||||
characters=_glyphs(
|
||||
[('ITEM NO', 12), ('MATERIAL NO', 70), ('ORDER QUANTITY', 240)],
|
||||
[('00020', 12), ('6Y70B2501401', 70), ('36', 250)],
|
||||
[('B3-AR1000270A1', 105), ('06/29/2026', 180), ('Ship by land', 240)],
|
||||
[('RoHS2', 20), ('A', 105), ('EXW AWS HUB', 145)],
|
||||
[('TOTAL AMOUNT', 220), ('1815.48', 280)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 320, 'y1': 130},
|
||||
)
|
||||
|
||||
assert len(suggestions) == 3
|
||||
assert suggestions[0].suggested_field_codes[0] == 'line_no'
|
||||
assert suggestions[0].column_samples[0] == ['00020']
|
||||
assert 'B3-AR1000270A1' in suggestions[1].column_samples[0]
|
||||
assert suggestions[2].column_boundaries[0] == 0
|
||||
assert suggestions[2].column_boundaries[-1] == 1
|
||||
@@ -39,10 +39,19 @@ def _freeze_export_snapshot(
|
||||
*, header: dict[int, object] | None = None, lines: list[tuple[int, int, str, int, str]] | None = None,
|
||||
) -> 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='值不一致'):
|
||||
|
||||
@@ -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'
|
||||
@@ -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)],
|
||||
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
|
||||
@@ -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': '<table><tr><td>broken</td></tr></table>',
|
||||
}],
|
||||
'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': '<table><tr><td>broken</td></tr></table>'}],
|
||||
'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': '<table><tr><td>broken</td></tr></table>'}],
|
||||
'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']]
|
||||
@@ -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'
|
||||
@@ -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'])
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -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'
|
||||
@@ -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')}
|
||||
@@ -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])
|
||||
|
||||
@@ -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()
|
||||
|
||||
+7
-2
@@ -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 时,必须转人工复核并阻断自动冻结。
|
||||
|
||||
@@ -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 前仍建议在解析确认阶段核对单价与金额。
|
||||
|
||||
|
||||
@@ -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 或库存源拆分。当前客户相关头字段为:
|
||||
|
||||
|
||||
+16
-3
@@ -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 未验收 |
|
||||
|
||||
@@ -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 等安全语义由后端硬规则兜底,管理员配置不可覆盖。
|
||||
|
||||
@@ -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`。 |
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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<void>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/intakes/${encodeURIComponent(intakeNo)}`,
|
||||
{ method: 'DELETE', ...auth() },
|
||||
);
|
||||
|
||||
/** 读取一个样本文档的网格预览,不返回 HTML 或 bbox。 */
|
||||
export const getOrderProfileSampleTables = (documentId: number) =>
|
||||
requestJson<OrderProfileSamplePreview>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/tables`, auth(),
|
||||
);
|
||||
|
||||
/** 以管理员确认的相对列边界生成坐标重建候选;结果始终待人工审核。 */
|
||||
export const previewOrderProfileCoordinateReconstruction = (
|
||||
documentId: number, tableId: string, coordinateReconstruction: CoordinateReconstructionSettings,
|
||||
) => requestJson<CoordinateReconstructionPreview>(
|
||||
'/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<CoordinateReconstructionSuggestion>(
|
||||
'/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<ShippingOrderDocumentProfile>('/api/admin/shipping-notice/order-document-profiles/from-sample', {
|
||||
|
||||
@@ -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<ShippingFulfillmentPolicyState>('/api/admin/shipping-fulfillment-policies', auth());
|
||||
|
||||
/** 创建按稳定字段 ID 绑定的下一履约策略草稿。 */
|
||||
export const createShippingFulfillmentPolicyDraft = (payload: {
|
||||
field_bindings: Array<{ capability_code: string; field_id: string }>;
|
||||
change_note?: string;
|
||||
}) => requestJson<ShippingFulfillmentPolicy>('/api/admin/shipping-fulfillment-policies', {
|
||||
method: 'POST', body: JSON.stringify(payload), ...jsonAuth(),
|
||||
});
|
||||
|
||||
/** 显式发布策略草稿;服务端原子退役上一发布版本。 */
|
||||
export const publishShippingFulfillmentPolicy = (policyId: number, expectedLockVersion: number) =>
|
||||
requestJson<ShippingFulfillmentPolicy>(`/api/admin/shipping-fulfillment-policies/${policyId}/publish`, {
|
||||
method: 'POST', body: JSON.stringify({ expected_lock_version: expectedLockVersion }), ...jsonAuth(),
|
||||
});
|
||||
@@ -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();
|
||||
},
|
||||
);
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -121,91 +144,106 @@ watch(
|
||||
:class="navStore.sidebarCollapsed ? 'w-0 md:w-20' : 'w-full md:w-64'"
|
||||
>
|
||||
<nav class="flex md:flex-col p-3 gap-1 overflow-x-auto md:overflow-visible no-scrollbar">
|
||||
<button
|
||||
v-for="item in standardModules"
|
||||
:key="item.id"
|
||||
type="button"
|
||||
class="admin-nav-btn group"
|
||||
:class="{ 'admin-nav-btn--active': isModuleActive(item.id) }"
|
||||
:title="navStore.sidebarCollapsed ? t(item.labelKey) : ''"
|
||||
@click="navigateModule(item.routeName)"
|
||||
>
|
||||
<component
|
||||
:is="iconMap[item.id]"
|
||||
class="w-5 h-5 transition-transform group-hover:scale-110 flex-shrink-0"
|
||||
:class="isModuleActive(item.id) ? 'text-brand-600' : 'text-muted group-hover:text-secondary'"
|
||||
/>
|
||||
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t(item.labelKey) }}</span>
|
||||
<span
|
||||
v-if="navStore.badgeForModule(item.id) && !navStore.sidebarCollapsed"
|
||||
class="ml-auto bg-red-500 text-white text-[10px] font-bold px-2 py-0.5 rounded-full shadow-sm"
|
||||
>
|
||||
{{ navStore.badgeForModule(item.id) }}
|
||||
</span>
|
||||
<div
|
||||
v-if="isModuleActive(item.id)"
|
||||
class="absolute left-0 top-1/2 -translate-y-1/2 w-1 h-6 bg-brand-600 rounded-r-full"
|
||||
/>
|
||||
</button>
|
||||
|
||||
<div v-if="config.admin.modules.wecom !== false" class="flex flex-col flex-shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
class="admin-nav-btn group justify-between"
|
||||
:class="{ 'admin-nav-btn--active': isWecomActive }"
|
||||
@click="navStore.wecomExpanded = !navStore.wecomExpanded"
|
||||
>
|
||||
<div class="flex items-center gap-3">
|
||||
<Link2 class="w-5 h-5 flex-shrink-0" :class="isWecomActive ? 'text-brand-600' : 'text-muted'" />
|
||||
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t('admin.nav.wecom') }}</span>
|
||||
</div>
|
||||
</button>
|
||||
<div
|
||||
v-if="navStore.wecomExpanded && !navStore.sidebarCollapsed"
|
||||
class="pl-4 space-y-1 mt-1 border-l-2 border-subtle ml-6"
|
||||
>
|
||||
<template v-for="item in visibleModules" :key="item.id">
|
||||
<div v-if="item.id === 'shipping_inventory'" class="flex flex-col flex-shrink-0">
|
||||
<button
|
||||
v-for="sub in wecomSubRoutes"
|
||||
:key="sub.name"
|
||||
type="button"
|
||||
class="admin-nav-subitem"
|
||||
:class="{ 'admin-nav-subitem--active': route.name === sub.name }"
|
||||
@click="navigateWecom(sub.name)"
|
||||
class="admin-nav-btn group justify-between"
|
||||
:class="{ 'admin-nav-btn--active': isShippingManagementActive }"
|
||||
:title="navStore.sidebarCollapsed ? t(item.labelKey) : ''"
|
||||
@click="navStore.shippingManagementExpanded = !navStore.shippingManagementExpanded"
|
||||
>
|
||||
{{ t(sub.labelKey) }}
|
||||
<div class="flex items-center gap-3">
|
||||
<Warehouse class="w-5 h-5 flex-shrink-0" :class="isShippingManagementActive ? 'text-brand-600' : 'text-muted'" />
|
||||
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t(item.labelKey) }}</span>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="config.admin.modules.shipping_inventory !== false" class="flex flex-col flex-shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
class="admin-nav-btn group justify-between"
|
||||
:class="{ 'admin-nav-btn--active': isShippingConfigActive }"
|
||||
:title="navStore.sidebarCollapsed ? t('admin.nav.shippingConfig') : ''"
|
||||
@click="navStore.shippingConfigExpanded = !navStore.shippingConfigExpanded"
|
||||
>
|
||||
<div class="flex items-center gap-3">
|
||||
<Warehouse class="w-5 h-5 flex-shrink-0" :class="isShippingConfigActive ? 'text-brand-600' : 'text-muted'" />
|
||||
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t('admin.nav.shippingConfig') }}</span>
|
||||
<div
|
||||
v-if="navStore.shippingManagementExpanded && !navStore.sidebarCollapsed"
|
||||
class="mt-1 ml-6 space-y-1 border-l-2 border-subtle pl-3 pb-1"
|
||||
>
|
||||
<section v-for="groupKey in shippingNavGroups" :key="groupKey" class="shipping-nav-group">
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center justify-between rounded-lg px-3 py-2 text-left text-xs font-semibold text-secondary transition-colors hover:bg-surface-soft"
|
||||
:aria-expanded="navStore.shippingManagementGroup === groupKey"
|
||||
@click="navStore.toggleShippingManagementGroup(groupKey)"
|
||||
>
|
||||
<span>{{ t(groupKey) }}</span>
|
||||
<ChevronDown v-if="navStore.shippingManagementGroup === groupKey" class="h-3.5 w-3.5 text-muted" />
|
||||
<ChevronRight v-else class="h-3.5 w-3.5 text-muted" />
|
||||
</button>
|
||||
<div v-if="navStore.shippingManagementGroup === groupKey" class="ml-2 border-l border-subtle pl-2 py-1 space-y-0.5">
|
||||
<button
|
||||
v-for="sub in SHIPPING_CONFIG_SUB_MODULE_METAS.filter((entry) => entry.groupKey === groupKey)"
|
||||
:key="sub.id"
|
||||
type="button"
|
||||
class="admin-nav-subitem py-1.5 pl-3"
|
||||
:class="{ 'admin-nav-subitem--active': isShippingNavActive(sub) }"
|
||||
@click="navigateShipping(sub)"
|
||||
>
|
||||
{{ t(sub.labelKey) }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</button>
|
||||
<div
|
||||
v-if="navStore.shippingConfigExpanded && !navStore.sidebarCollapsed"
|
||||
class="pl-4 space-y-1 mt-1 border-l-2 border-subtle ml-6"
|
||||
>
|
||||
<button
|
||||
v-for="sub in SHIPPING_CONFIG_SUB_MODULE_METAS"
|
||||
:key="sub.id"
|
||||
type="button"
|
||||
class="admin-nav-subitem"
|
||||
:class="{ 'admin-nav-subitem--active': isShippingConfigSubModuleActive(sub.id) }"
|
||||
@click="navigateShippingConfig(sub.routeName)"
|
||||
>
|
||||
{{ t(sub.labelKey) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="item.id === 'wecom'" class="flex flex-col flex-shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
class="admin-nav-btn group justify-between"
|
||||
:class="{ 'admin-nav-btn--active': isWecomActive }"
|
||||
@click="navStore.wecomExpanded = !navStore.wecomExpanded"
|
||||
>
|
||||
<div class="flex items-center gap-3">
|
||||
<Link2 class="w-5 h-5 flex-shrink-0" :class="isWecomActive ? 'text-brand-600' : 'text-muted'" />
|
||||
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t(item.labelKey) }}</span>
|
||||
</div>
|
||||
</button>
|
||||
<div
|
||||
v-if="navStore.wecomExpanded && !navStore.sidebarCollapsed"
|
||||
class="pl-4 space-y-1 mt-1 border-l-2 border-subtle ml-6"
|
||||
>
|
||||
<button
|
||||
v-for="sub in wecomSubRoutes"
|
||||
:key="sub.name"
|
||||
type="button"
|
||||
class="admin-nav-subitem"
|
||||
:class="{ 'admin-nav-subitem--active': route.name === sub.name }"
|
||||
@click="navigateWecom(sub.name)"
|
||||
>
|
||||
{{ t(sub.labelKey) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="admin-nav-btn group"
|
||||
:class="{ 'admin-nav-btn--active': isModuleActive(item.id) }"
|
||||
:title="navStore.sidebarCollapsed ? t(item.labelKey) : ''"
|
||||
@click="navigateModule(item.routeName)"
|
||||
>
|
||||
<component
|
||||
:is="iconMap[item.id]"
|
||||
class="w-5 h-5 transition-transform group-hover:scale-110 flex-shrink-0"
|
||||
:class="isModuleActive(item.id) ? 'text-brand-600' : 'text-muted group-hover:text-secondary'"
|
||||
/>
|
||||
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t(item.labelKey) }}</span>
|
||||
<span
|
||||
v-if="navStore.badgeForModule(item.id) && !navStore.sidebarCollapsed"
|
||||
class="ml-auto bg-red-500 text-white text-[10px] font-bold px-2 py-0.5 rounded-full shadow-sm"
|
||||
>
|
||||
{{ navStore.badgeForModule(item.id) }}
|
||||
</span>
|
||||
<div
|
||||
v-if="isModuleActive(item.id)"
|
||||
class="absolute left-0 top-1/2 -translate-y-1/2 w-1 h-6 bg-brand-600 rounded-r-full"
|
||||
/>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<div v-if="config.admin.modules.reports !== false" class="flex flex-col flex-shrink-0">
|
||||
<button
|
||||
|
||||
@@ -18,6 +18,8 @@ export interface ShippingConfigSubModuleMeta {
|
||||
routeName: 'AdminShippingInventory' | 'AdminShippingIdentityRules' | 'AdminShippingOrderExtractionRuns' | 'AdminShippingOrderDocumentProfiles';
|
||||
path: 'shipping-notice' | 'shipping-identity-rules' | 'shipping-order-extraction-runs' | 'shipping-order-document-profiles';
|
||||
labelKey: string;
|
||||
groupKey: 'admin.nav.shippingOrderRecognition' | 'admin.nav.shippingInventoryManagement' | 'admin.nav.shippingRunAudit';
|
||||
query?: { section: 'orderSchema' | 'parsing' | 'profiles' | 'sources' | 'mappings' | 'rules' | 'templates' | 'snapshots' | 'exports' };
|
||||
}
|
||||
|
||||
/** 已独立拆分的模块(全部 admin 模块均已拆分) */
|
||||
@@ -33,21 +35,29 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
|
||||
{ id: 'agents', routeName: 'AdminAgents', path: 'agents', labelKey: 'admin.nav.agents', configKey: 'agents' },
|
||||
{ id: 'knowledge_base', routeName: 'AdminKnowledgeBase', path: 'knowledge-base', labelKey: 'admin.nav.knowledgeBase', configKey: 'knowledge_base' },
|
||||
{ id: 'schedules', routeName: 'AdminSchedules', path: 'schedules', labelKey: 'admin.nav.schedules', configKey: 'schedules' },
|
||||
{ id: 'shipping_inventory', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.nav.shippingConfig', configKey: 'shipping_inventory' },
|
||||
{ id: 'announcements', routeName: 'AdminAnnouncements', path: 'announcements', labelKey: 'admin.nav.announcements', configKey: 'announcements' },
|
||||
{ id: 'questions', routeName: 'AdminQuestions', path: 'questions', labelKey: 'admin.nav.questions', configKey: 'questions' },
|
||||
{ id: 'wecom', routeName: 'AdminWecom', path: 'wecom', labelKey: 'admin.nav.wecom', configKey: 'wecom' },
|
||||
{ id: 'permissions', routeName: 'AdminPermissions', path: 'permissions', labelKey: 'admin.nav.permissions', configKey: 'permissions' },
|
||||
{ id: 'platform_apps', routeName: 'AdminPlatformApps', path: 'platform-apps', labelKey: 'admin.nav.platformApps', configKey: 'platform_apps' },
|
||||
{ id: 'shipping_inventory', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.nav.shippingInventory', configKey: 'shipping_inventory' },
|
||||
{ id: 'requests', routeName: 'AdminRequests', path: 'requests', labelKey: 'admin.nav.requests', configKey: 'requests' },
|
||||
];
|
||||
|
||||
/** 货代配置的二级导航唯一真相源;各页面共用父模块权限与可见性开关。 */
|
||||
/** 货代管理的业务导航唯一真相源;按基础定义、适配规则、运行任务的依赖顺序排列。 */
|
||||
export const SHIPPING_CONFIG_SUB_MODULE_METAS: ShippingConfigSubModuleMeta[] = [
|
||||
{ id: 'inventory', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.nav.shippingInventory' },
|
||||
{ id: 'identity_rules', routeName: 'AdminShippingIdentityRules', path: 'shipping-identity-rules', labelKey: 'admin.nav.shippingIdentityRules' },
|
||||
{ id: 'order_extraction_runs', routeName: 'AdminShippingOrderExtractionRuns', path: 'shipping-order-extraction-runs', labelKey: 'admin.nav.shippingOrderExtractionRuns' },
|
||||
{ id: 'order_document_profiles', routeName: 'AdminShippingOrderDocumentProfiles', path: 'shipping-order-document-profiles', labelKey: 'admin.nav.shippingOrderDocumentProfiles' },
|
||||
{ id: 'order_fields', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.nav.shippingOrderFields', groupKey: 'admin.nav.shippingOrderRecognition', query: { section: 'orderSchema' } },
|
||||
{ id: 'order_document_profiles', routeName: 'AdminShippingOrderDocumentProfiles', path: 'shipping-order-document-profiles', labelKey: 'admin.nav.shippingOrderDocumentProfiles', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
{ id: 'identity_rules', routeName: 'AdminShippingIdentityRules', path: 'shipping-identity-rules', labelKey: 'admin.nav.shippingIdentityRules', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
{ id: 'order_extraction_runs', routeName: 'AdminShippingOrderExtractionRuns', path: 'shipping-order-extraction-runs', labelKey: 'admin.nav.shippingOrderExtractionRuns', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
{ id: 'inventory_fields', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.parsingProfiles', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'parsing' } },
|
||||
{ id: 'connections', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.connections', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'profiles' } },
|
||||
{ id: 'inventory_sites', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.sources', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'sources' } },
|
||||
{ id: 'warehouse_mappings', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.externalMappings', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'mappings' } },
|
||||
{ id: 'routing_rules', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.rules', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'rules' } },
|
||||
{ id: 'shipping_templates', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.excelTemplates', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'templates' } },
|
||||
{ id: 'inventory_snapshots', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } },
|
||||
{ id: 'export_records', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } },
|
||||
];
|
||||
|
||||
export const ADMIN_REPORT_TABLES: AdminReportTableId[] = [
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-inventory/ShippingInventoryPage.vue
|
||||
用途:以统一配置工作台维护订单字段、库存接入、Excel 导出和运行审计。
|
||||
依赖:admin.api、ShippingOrderSchemaPage、Vue Composition API、Vue I18n。
|
||||
逻辑:按订单字段到库存路由的业务链路组织配置;订单字段复用同一页面内的 Schema 编辑器,避免形成割裂入口。
|
||||
用途:以统一货代管理工作台维护订单字段、库存接入、Excel 导出和运行审计。
|
||||
依赖:admin.api、ShippingOrderSchemaPage、Vue Router、Vue Composition API、Vue I18n。
|
||||
逻辑:由 AdminLayout 统一业务目录选择工作区;section 深链与当前工作区双向同步。
|
||||
-->
|
||||
<template>
|
||||
<section class="inventory-console">
|
||||
@@ -21,22 +21,6 @@
|
||||
</header>
|
||||
|
||||
<div class="console-layout">
|
||||
<aside class="section-nav" aria-label="Shipping configuration sections">
|
||||
<section v-for="group in tabGroups" :key="group.labelKey" class="nav-group">
|
||||
<p>{{ t(group.labelKey) }}</p>
|
||||
<button
|
||||
v-for="tab in group.tabs"
|
||||
:key="tab.key"
|
||||
type="button"
|
||||
:class="{ active: activeTab === tab.key || (tab.key === 'parsing' && activeTab === 'inventoryFields') }"
|
||||
@click="selectTab(tab.key)"
|
||||
>
|
||||
<span>{{ t(tab.labelKey) }}</span>
|
||||
<small v-if="tab.count !== null">{{ tab.count }}</small>
|
||||
</button>
|
||||
</section>
|
||||
</aside>
|
||||
|
||||
<main class="workbench">
|
||||
<div v-if="activeTab !== 'orderSchema'" class="workbench-heading">
|
||||
<div>
|
||||
@@ -435,8 +419,9 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
/** 加载六个库存管理工作区,并将每个工作区限制在各自的真实配置或运行数据边界内。 */
|
||||
import { computed, nextTick, onMounted, reactive, ref } from 'vue';
|
||||
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import * as XLSX from 'xlsx';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
@@ -504,6 +489,8 @@ type InventoryFieldForm = { display_name: string; description: string; value_typ
|
||||
type SourceActivation = { ready: boolean; checks: ShippingInventoryReadinessCheck[]; missing_requirements: string[] };
|
||||
|
||||
const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const message = useMessage();
|
||||
const activeTab = ref<TabKey>('orderSchema');
|
||||
const selectedId = ref<number | null>(null);
|
||||
@@ -639,13 +626,13 @@ const operators = [
|
||||
];
|
||||
|
||||
const tabs = computed(() => [
|
||||
{ key: 'orderSchema' as const, group: 'foundation', labelKey: 'admin.shippingInventory.orderFields', helpKey: '', count: null },
|
||||
{ key: 'parsing' as const, group: 'foundation', labelKey: 'admin.shippingInventory.parsingProfiles', helpKey: 'admin.shippingInventory.parsingProfilesHelp', count: parsingProfiles.value.length },
|
||||
{ key: 'templates' as const, group: 'foundation', labelKey: 'admin.shippingInventory.excelTemplates', helpKey: 'admin.shippingInventory.excelTemplatesHelp', count: excelTemplates.value.length },
|
||||
{ key: 'orderSchema' as const, group: 'order', labelKey: 'admin.shippingInventory.orderFields', helpKey: '', count: null },
|
||||
{ key: 'parsing' as const, group: 'inventory', labelKey: 'admin.shippingInventory.parsingProfiles', helpKey: 'admin.shippingInventory.parsingProfilesHelp', count: parsingProfiles.value.length },
|
||||
{ key: 'profiles' as const, group: 'inventory', labelKey: 'admin.shippingInventory.connections', helpKey: 'admin.shippingInventory.connectionsHelp', count: profiles.value.length },
|
||||
{ key: 'sources' as const, group: 'inventory', labelKey: 'admin.shippingInventory.sources', helpKey: 'admin.shippingInventory.sourcesHelp', count: sources.value.length },
|
||||
{ key: 'rules' as const, group: 'inventory', labelKey: 'admin.shippingInventory.rules', helpKey: 'admin.shippingInventory.rulesHelp', count: rules.value.length },
|
||||
{ key: 'mappings' as const, group: 'inventory', labelKey: 'admin.shippingInventory.externalMappings', helpKey: 'admin.shippingInventory.mappingsHelp', count: mappings.value.length },
|
||||
{ key: 'rules' as const, group: 'inventory', labelKey: 'admin.shippingInventory.rules', helpKey: 'admin.shippingInventory.rulesHelp', count: rules.value.length },
|
||||
{ key: 'templates' as const, group: 'inventory', labelKey: 'admin.shippingInventory.excelTemplates', helpKey: 'admin.shippingInventory.excelTemplatesHelp', count: excelTemplates.value.length },
|
||||
{ key: 'snapshots' as const, group: 'audit', labelKey: 'admin.shippingInventory.snapshots', helpKey: 'admin.shippingInventory.snapshotsHelp', count: snapshots.value.length },
|
||||
{ key: 'exports' as const, group: 'audit', labelKey: 'admin.shippingInventory.exports', helpKey: 'admin.shippingInventory.exportsHelp', count: exports.value.length },
|
||||
]);
|
||||
@@ -653,11 +640,6 @@ const snapshotColumnLabels = computed(() => [t('admin.shippingInventory.snapshot
|
||||
const exportColumnLabels = computed(() => [t('admin.shippingInventory.runNo'), t('admin.shippingInventory.source'), t('admin.shippingInventory.connection'), t('admin.shippingInventory.triggerMode'), t('admin.shippingInventory.startedAt'), t('admin.shippingInventory.duration'), t('admin.shippingInventory.exportResult'), t('admin.shippingInventory.status'), t('admin.shippingInventory.actions')]);
|
||||
const snapshotTableWidth = computed(() => snapshotColumnWidths.value.reduce((total, width) => total + width, 0));
|
||||
const exportTableWidth = computed(() => exportColumnWidths.value.reduce((total, width) => total + width, 0));
|
||||
const tabGroups = computed(() => [
|
||||
{ labelKey: 'admin.shippingInventory.groupFoundation', tabs: tabs.value.filter((tab) => tab.group === 'foundation') },
|
||||
{ labelKey: 'admin.shippingInventory.groupInventory', tabs: tabs.value.filter((tab) => tab.group === 'inventory') },
|
||||
{ labelKey: 'admin.shippingInventory.groupAudit', tabs: tabs.value.filter((tab) => tab.group === 'audit') },
|
||||
]);
|
||||
const currentTab = computed(() => tabs.value.find((item) => item.key === activeTab.value) ?? tabs.value[0]!);
|
||||
const currentSection = computed(() => activeTab.value === 'inventoryFields'
|
||||
? { labelKey: 'admin.shippingInventory.parsingProfiles', helpKey: 'admin.shippingInventory.parsingProfilesHelp' }
|
||||
@@ -801,14 +783,26 @@ async function load(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** 切换管理对象时清空选择,避免不同对象的数据残留在编辑器中。 */
|
||||
/** 切换管理对象时同步深链并清空选择,避免不同对象的数据残留在编辑器中。 */
|
||||
function selectTab(tab: TabKey): void {
|
||||
activeTab.value = tab;
|
||||
void router.replace({ query: { ...route.query, section: tab } });
|
||||
if (tab === 'snapshots') snapshotPage.value = 1;
|
||||
if (tab === 'exports') exportPage.value = 1;
|
||||
closeDrawer();
|
||||
}
|
||||
|
||||
/** 接收侧栏或书签中的 section 深链,仅允许打开工作台已注册区段。 */
|
||||
watch(
|
||||
() => route.query.section,
|
||||
(section) => {
|
||||
if (typeof section === 'string' && tabs.value.some((tab) => tab.key === section)) {
|
||||
activeTab.value = section as TabKey;
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/** 在库存映射内切换解析方案与字段目录,保持左侧业务入口不分裂。 */
|
||||
function selectInventoryMappingTab(tab: 'parsing' | 'inventoryFields'): void {
|
||||
activeTab.value = tab;
|
||||
@@ -1465,7 +1459,7 @@ function openAuditDetail(item: Item, kind: 'snapshot' | 'export'): void { auditD
|
||||
function paginate(items: Item[], page: number): Item[] { const start = (page - 1) * auditPageSize.value; return items.slice(start, start + auditPageSize.value); }
|
||||
function downloadSnapshot(item: Item): void { void downloadShippingInventorySnapshot(Number(item.id), `${item.inventory_file_no || 'inventory'}.xlsx`).catch((cause) => { showError(cause, 'downloadFailed'); }); }
|
||||
|
||||
/** 将货代配置的操作失败交给平台统一消息弹窗,禁止跨工作区保留页面级错误。 */
|
||||
/** 将货代管理操作失败交给平台统一消息弹窗,禁止跨工作区保留页面级错误。 */
|
||||
function showError(cause: unknown, fallbackKey: 'loadFailed' | 'saveFailed' | 'deleteFailed' | 'downloadFailed' | 'inventoryAnalysisFailed' | 'configurationTestFailed' | 'templateLayoutReadFailed'): void {
|
||||
message.error(cause instanceof Error ? cause.message : t(`admin.shippingInventory.${fallbackKey}`));
|
||||
}
|
||||
@@ -1495,15 +1489,7 @@ onMounted(load);
|
||||
.flow-strip { align-self: center; display: flex; align-items: center; gap: 8px; padding: 7px 10px; border: 1px solid #e0f2fe; border-radius: 6px; background: #f0f9ff; color: #0369a1; font-size: 12px; font-weight: 500; }
|
||||
.flow-strip i { color: #7dd3fc; font-style: normal; }
|
||||
.schema-prerequisite { margin: 0 0 14px; border: 1px solid #fde68a; border-radius: 6px; background: #fffbeb; padding: 10px 12px; color: #92400e; font-size: 13px; }
|
||||
.console-layout { display: grid; grid-template-columns: 220px minmax(0, 1fr); gap: 22px; padding-top: 20px; }
|
||||
.section-nav { display: flex; flex-direction: column; gap: 16px; }
|
||||
.nav-group { display: grid; gap: 3px; }
|
||||
.nav-group > p { margin: 0 10px 3px; color: #94a3b8; font-size: 11px; font-weight: 600; }
|
||||
.section-nav button { display: flex; align-items: center; justify-content: space-between; border: 0; border-left: 2px solid transparent; border-radius: 4px; background: transparent; padding: 9px 10px; color: #64748b; font-size: 13px; text-align: left; cursor: pointer; }
|
||||
.section-nav button:hover { background: #f8fafc; color: #334155; }
|
||||
.section-nav button.active { border-left-color: #0ea5e9; background: #f0f9ff; color: #0369a1; font-weight: 600; }
|
||||
.section-nav small { min-width: 20px; border-radius: 999px; background: #f1f5f9; padding: 2px 5px; color: #94a3b8; font-size: 11px; text-align: center; }
|
||||
.section-nav .active small { background: #e0f2fe; color: #0284c7; }
|
||||
.console-layout { padding-top: 20px; }
|
||||
.workbench-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
||||
.workbench-heading h2 { margin: 0; color: #1e293b; font-size: 16px; font-weight: 600; letter-spacing: 0; }
|
||||
.workbench-heading p { max-width: 660px; margin: 5px 0 0; color: #64748b; font-size: 13px; }
|
||||
@@ -1602,6 +1588,6 @@ onMounted(load);
|
||||
.audit-detail dl { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 0; margin: 0; padding: 18px 20px; }.audit-detail dt, .audit-detail dd { margin: 0; padding: 11px 0; border-bottom: 1px solid #edf2f7; font-size: 13px; }.audit-detail dt { color: #64748b; }.audit-detail dd { overflow-wrap: anywhere; color: #334155; }
|
||||
.object-list .empty-state { grid-column: 1 / -1; display: grid; min-height: 260px; place-items: center; }
|
||||
.empty-state { border: 1px dashed #c9d7e5; border-radius: 10px; background: #f9fbfd; padding: 38px 18px; color: #7b899a; font-size: 13px; text-align: center; }
|
||||
@media (max-width: 980px) { .console-header { display: block; } .flow-strip { display: inline-flex; margin-top: 18px; } .console-layout { grid-template-columns: 1fr; } .section-nav { flex-direction: row; gap: 12px; overflow-x: auto; } .nav-group { display: flex; align-items: center; gap: 4px; } .nav-group > p { display: none; } .section-nav button { min-width: max-content; border-bottom: 3px solid transparent; border-left: 0; } .section-nav button.active { border-bottom-color: #16877f; border-left: 0; } .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card { grid-template-columns: 1fr 1fr; } .mapping-value-row { grid-template-columns: minmax(0, 1.6fr) minmax(180px, 1fr); }.readiness-audit { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@media (max-width: 980px) { .console-header { display: block; } .flow-strip { display: inline-flex; margin-top: 18px; } .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card { grid-template-columns: 1fr 1fr; } .mapping-value-row { grid-template-columns: minmax(0, 1.6fr) minmax(180px, 1fr); }.readiness-audit { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@media (max-width: 640px) { .inventory-console { padding: 18px; } .editor-form, .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card, .mapping-value-row, .parsing-mapping-card, .readonly-mapping-section .parsing-mapping-card, .parsing-summary { grid-template-columns: 1fr; } .mapping-arrow { transform: rotate(90deg); }.workbench-heading { display: block; } .workbench-heading .primary-action { margin-top: 12px; }.batch-source-list { grid-template-columns: 1fr; }.batch-stat-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }.batch-run { grid-template-columns: 9px minmax(0, 1fr); }.batch-run-error { grid-column: 2; }.readiness-heading { display: grid; }.readiness-count { justify-self: start; }.readiness-steps li { grid-template-columns: 24px minmax(0, 1fr); }.readiness-action { grid-column: 2; justify-self: start; }.readiness-footer { justify-content: stretch; }.readiness-footer .primary-action { width: 100%; } }
|
||||
</style>
|
||||
+653
-72
@@ -1,8 +1,8 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/ShippingOrderDocumentProfilesPage.vue
|
||||
用途:通过 MinerU 样本表格可视化创建和发布订单文档 Profile。
|
||||
用途:通过 MinerU/PDF 坐标样本工作台创建、复核和发布订单文档 Profile。
|
||||
依赖:Profile/Schema API、BusinessError、useMessage、Vue I18n。
|
||||
逻辑:管理员选择真实样本、表格、表头行和列目标;浏览器不展示 HTML,也不编辑 JSON/结构指纹。
|
||||
逻辑:管理员选择样本并按物理行编辑列边界和字段;后端提供全量/当前行建议及最终候选,浏览器不展示 HTML 或结构指纹。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue';
|
||||
@@ -14,12 +14,16 @@ import {
|
||||
createOrderProfileSample,
|
||||
createOrderProfileFromSample,
|
||||
deleteOrderDocumentProfile,
|
||||
deleteOrderProfileSample,
|
||||
getOrderProfileSampleTables,
|
||||
getOrderProfileSampleStatus,
|
||||
generateOrderProfileOcrCoordinateEvidence,
|
||||
listOrderDocumentProfiles,
|
||||
listOrderProfileSamples,
|
||||
publishOrderDocumentProfile,
|
||||
retireOrderDocumentProfile,
|
||||
previewOrderProfileCoordinateReconstruction,
|
||||
suggestOrderProfileCoordinateReconstruction,
|
||||
updateOrderProfileFromSample,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
@@ -28,11 +32,16 @@ import type {
|
||||
OrderProfileSampleDocument,
|
||||
OrderProfileSamplePreview,
|
||||
OrderProfileSampleTable,
|
||||
CoordinateReconstructionPreview,
|
||||
CoordinateReconstructionSettings,
|
||||
CoordinateSubrowLayout,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import {
|
||||
buildOrderProfileColumnRules,
|
||||
findDuplicateOrderProfileTargets,
|
||||
mergeOrderProfileHeaderLabels,
|
||||
shouldShowStandardOrderProfilePreview,
|
||||
} from './orderProfileForm.utils';
|
||||
import type {
|
||||
ShippingOrderFieldConfig,
|
||||
@@ -49,7 +58,27 @@ const editingProfileId = ref<number | null>(null);
|
||||
const editingLockVersion = ref<number | null>(null);
|
||||
const profiles = ref<ShippingOrderDocumentProfile[]>([]);
|
||||
const samples = ref<OrderProfileSampleDocument[]>([]);
|
||||
const sampleSearch = ref('');
|
||||
const preview = ref<OrderProfileSamplePreview | null>(null);
|
||||
const reconstructionPreview = ref<CoordinateReconstructionPreview | null>(null);
|
||||
const reconstructing = ref(false);
|
||||
const reconstructionPreviewFailed = ref(false);
|
||||
const suggesting = ref(false);
|
||||
const suggestingSubrowIndex = ref<number | null>(null);
|
||||
const ocrGenerating = ref(false);
|
||||
const reconstructionMethod = ref<CoordinateReconstructionSettings['method']>('native_pdf_coordinates.v1');
|
||||
const reconstructionConfirmed = ref(false);
|
||||
const reconstructionFieldSignature = ref('');
|
||||
const columnBoundaryInput = ref('0, 0.10, 0.25, 0.33, 0.52, 0.65, 0.77, 0.88, 0.94, 1');
|
||||
const multiSubrowEnabled = ref(false);
|
||||
type SubrowEditor = {
|
||||
role: CoordinateSubrowLayout['role']; row_offset: number; boundaries: string;
|
||||
fields: Array<string | null>; samples: string[][];
|
||||
};
|
||||
const subrowEditors = ref<SubrowEditor[]>([
|
||||
{ role: 'main', row_offset: 0, boundaries: '0, 1', fields: [null], samples: [] },
|
||||
]);
|
||||
const selectedSubrowIndex = ref(0);
|
||||
const publishedSchemas = ref<ShippingOrderSchemaVersion[]>([]);
|
||||
const form = reactive({
|
||||
profile_code: '', display_name: '', schema_version_id: 0,
|
||||
@@ -62,6 +91,32 @@ const columnRules = ref<Array<{ extractor_key: 'direct' | 'temp_internal_parts';
|
||||
const selectedTable = computed<OrderProfileSampleTable | null>(() => (
|
||||
preview.value?.tables.find((item) => item.table_id === form.table_id) || null
|
||||
));
|
||||
const showStandardPreview = computed(() => shouldShowStandardOrderProfilePreview(
|
||||
Boolean(selectedTable.value?.profile_creation_allowed),
|
||||
multiSubrowEnabled.value,
|
||||
Boolean(selectedTable.value?.coordinate_reconstruction_available),
|
||||
));
|
||||
const displayedTable = computed<OrderProfileSampleTable | CoordinateReconstructionPreview | null>(() => (
|
||||
reconstructionPreview.value || selectedTable.value
|
||||
));
|
||||
const mergedHeaderLabels = computed(() => mergeOrderProfileHeaderLabels(
|
||||
displayedTable.value?.rows || [],
|
||||
form.header_row_index,
|
||||
displayedTable.value?.column_count || 0,
|
||||
));
|
||||
const displayedRowRole = (rowIndex: number) => (
|
||||
reconstructionPreview.value?.row_roles[rowIndex] || (rowIndex <= form.header_row_index ? 'header' : 'data')
|
||||
);
|
||||
const displayedSourceRows = (rowIndex: number) => reconstructionPreview.value?.source_row_indices[rowIndex] || [];
|
||||
const visibleSamples = computed(() => {
|
||||
const keyword = sampleSearch.value.trim().toLowerCase();
|
||||
return samples.value.filter((sample) => !keyword || String(sample.filename || '').toLowerCase().includes(keyword));
|
||||
});
|
||||
const selectedSample = computed(() => samples.value.find((sample) => sample.document_id === form.document_id) || null);
|
||||
const selectedSubrow = computed(() => subrowEditors.value[selectedSubrowIndex.value] || subrowEditors.value[0]);
|
||||
const currentProfileIds = computed(() => new Set(
|
||||
profiles.value.filter((profile) => profile.status === 'published').map((profile) => profile.id),
|
||||
));
|
||||
const selectedSchema = computed(() => publishedSchemas.value.find((item) => item.id === form.schema_version_id) || null);
|
||||
const lineFields = computed<ShippingOrderFieldConfig[]>(() => (
|
||||
selectedSchema.value?.definition?.fields.filter((item) => item.enabled !== false && item.scope === 'line') || []
|
||||
@@ -77,14 +132,25 @@ const duplicateTargets = computed(() => {
|
||||
if (form.row_structure !== 'preserved') return [];
|
||||
return findDuplicateOrderProfileTargets(normalizedRules());
|
||||
});
|
||||
const reconstructionMatchesFields = computed(() => (
|
||||
!reconstructionPreview.value || reconstructionFieldSignature.value === coordinateFieldSignature()
|
||||
));
|
||||
const livePreviewStatusKey = computed(() => {
|
||||
if (reconstructing.value) return 'livePreviewUpdating';
|
||||
if (!subrowEditors.value[0]?.fields.includes('line_no')) return 'livePreviewWaitingLineNo';
|
||||
if (reconstructionPreviewFailed.value) return 'livePreviewFailed';
|
||||
if (reconstructionPreview.value && reconstructionMatchesFields.value) return 'livePreviewReady';
|
||||
return 'livePreviewEmpty';
|
||||
});
|
||||
const canSave = computed(() => Boolean(
|
||||
form.profile_code.trim() && form.display_name.trim() && form.schema_version_id
|
||||
&& form.document_id && form.table_id && selectedTable.value
|
||||
&& selectedTable.value.profile_creation_allowed
|
||||
&& form.document_id && form.table_id && displayedTable.value
|
||||
&& (selectedTable.value?.profile_creation_allowed || reconstructionConfirmed.value)
|
||||
&& form.data_start_row_index > form.header_row_index
|
||||
&& form.header_row_index >= 0
|
||||
&& form.data_start_row_index < (selectedTable.value?.row_count || 0)
|
||||
&& form.data_start_row_index < (displayedTable.value?.row_count || 0)
|
||||
&& duplicateTargets.value.length === 0
|
||||
&& reconstructionMatchesFields.value
|
||||
&& (form.row_structure === 'unsupported_row_structure' || hasConfiguredColumn.value),
|
||||
));
|
||||
|
||||
@@ -115,6 +181,8 @@ const load = async () => {
|
||||
/** 选择样本文档后读取由后端展开的网格。 */
|
||||
const loadPreview = async () => {
|
||||
preview.value = null;
|
||||
reconstructionPreview.value = null;
|
||||
reconstructionConfirmed.value = false;
|
||||
form.table_id = '';
|
||||
if (!form.document_id) return;
|
||||
try {
|
||||
@@ -145,6 +213,8 @@ const uploadSample = async (event: Event) => {
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 1000));
|
||||
}
|
||||
await load();
|
||||
const uploadedSample = samples.value.find((sample) => sample.intake_no === intake.intake_no);
|
||||
if (uploadedSample) form.document_id = uploadedSample.document_id;
|
||||
message.success(t('admin.shippingOrderProfiles.sampleUploaded'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
@@ -156,10 +226,274 @@ const uploadSample = async (event: Event) => {
|
||||
|
||||
/** 表格变化时按真实列数初始化受控列映射。 */
|
||||
const resetColumns = () => {
|
||||
const count = selectedTable.value?.column_count || 0;
|
||||
const count = displayedTable.value?.column_count || 0;
|
||||
columnRules.value = Array.from({ length: count }, () => ({ extractor_key: 'direct', target: '' }));
|
||||
form.header_row_index = 0;
|
||||
form.data_start_row_index = Math.min(1, Math.max((selectedTable.value?.row_count || 1) - 1, 0));
|
||||
form.data_start_row_index = Math.min(1, Math.max((displayedTable.value?.row_count || 1) - 1, 0));
|
||||
};
|
||||
|
||||
/** 清理上一张表的坐标重建编辑状态,避免切换样本后隐藏或污染当前配置区。 */
|
||||
const resetCoordinateReconstructionState = () => {
|
||||
if (reconstructionPreviewTimer) window.clearTimeout(reconstructionPreviewTimer);
|
||||
reconstructionPreviewTimer = null;
|
||||
reconstructionPreviewRequestId += 1;
|
||||
multiSubrowEnabled.value = false;
|
||||
subrowEditors.value = [
|
||||
{ role: 'main', row_offset: 0, boundaries: '0, 1', fields: [null], samples: [] },
|
||||
];
|
||||
selectedSubrowIndex.value = 0;
|
||||
reconstructionPreview.value = null;
|
||||
reconstructionPreviewFailed.value = false;
|
||||
reconstructionConfirmed.value = false;
|
||||
reconstructionFieldSignature.value = '';
|
||||
};
|
||||
|
||||
/** 按重建列数保留已有字段映射,并只补齐或裁掉实际变化的列。 */
|
||||
const resizeColumns = (count: number) => {
|
||||
columnRules.value = Array.from({ length: count }, (_, index) => (
|
||||
columnRules.value[index] || { extractor_key: 'direct', target: '' }
|
||||
));
|
||||
};
|
||||
|
||||
/** 解析 0..1 严格递增边界;单内容块物理行允许只使用 0,1。 */
|
||||
const parseBoundaryInput = (raw: string): number[] | null => {
|
||||
const values = raw.split(',').map((item) => Number(item.trim()));
|
||||
if (values.length < 2 || values.some((value) => !Number.isFinite(value)) || values[0] !== 0 || values[values.length - 1] !== 1
|
||||
|| values.some((value, index) => index > 0 && value <= values[index - 1]!)) return null;
|
||||
return values;
|
||||
};
|
||||
|
||||
/** 边界数量变化时保留已有子行字段映射,并补齐新的列。 */
|
||||
const syncSubrowFields = (editor: SubrowEditor) => {
|
||||
const count = Math.max((parseBoundaryInput(editor.boundaries)?.length || 1) - 1, 0);
|
||||
editor.fields = Array.from({ length: count }, (_, index) => editor.fields[index] || null);
|
||||
};
|
||||
|
||||
/** 返回边界尺的有效刻度;输入异常时保留最小可编辑区间。 */
|
||||
const subrowBoundaries = (editor: SubrowEditor) => parseBoundaryInput(editor.boundaries) || [0, 1];
|
||||
|
||||
/** 拖动内部刻度时限制其不能越过相邻边界,并同步字段列数。 */
|
||||
const updateSubrowBoundary = (editor: SubrowEditor, boundaryIndex: number, rawValue: string) => {
|
||||
const values = [...subrowBoundaries(editor)];
|
||||
const previous = values[boundaryIndex - 1] ?? 0;
|
||||
const next = values[boundaryIndex + 1] ?? 1;
|
||||
values[boundaryIndex] = Math.min(next - 0.01, Math.max(previous + 0.01, Number(rawValue)));
|
||||
editor.boundaries = values.map((value) => Number(value.toFixed(2))).join(', ');
|
||||
syncSubrowFields(editor);
|
||||
};
|
||||
|
||||
/** 只有区间宽度足够容纳两个最小 1% 列时才允许继续拆分。 */
|
||||
const canSplitSubrowColumn = (editor: SubrowEditor, columnIndex: number) => {
|
||||
const boundaries = subrowBoundaries(editor);
|
||||
return boundaries[columnIndex + 1]! - boundaries[columnIndex]! >= 0.02;
|
||||
};
|
||||
|
||||
/** 在当前逻辑明细末尾增加任意一条物理子行配置。 */
|
||||
const addSubrow = () => {
|
||||
subrowEditors.value.push({
|
||||
role: 'continuation', row_offset: subrowEditors.value.length,
|
||||
boundaries: '0, 1', fields: [null], samples: [],
|
||||
});
|
||||
selectedSubrowIndex.value = subrowEditors.value.length - 1;
|
||||
};
|
||||
|
||||
/** 删除指定续行并重排 row_offset;首行是新明细锚点,禁止删除。 */
|
||||
const removeSubrow = (index: number) => {
|
||||
if (index <= 0) return;
|
||||
subrowEditors.value.splice(index, 1);
|
||||
subrowEditors.value.forEach((item, rowIndex) => {
|
||||
item.row_offset = rowIndex;
|
||||
item.role = rowIndex === 0 ? 'main' : 'continuation';
|
||||
});
|
||||
selectedSubrowIndex.value = Math.min(selectedSubrowIndex.value, subrowEditors.value.length - 1);
|
||||
};
|
||||
|
||||
/** 在指定列区间中点插入新边界;原列配置保留,新列插入其后等待映射。 */
|
||||
const addSubrowColumn = (editor: SubrowEditor, columnIndex: number) => {
|
||||
const boundaries = [...subrowBoundaries(editor)];
|
||||
const midpoint = Number(((boundaries[columnIndex]! + boundaries[columnIndex + 1]!) / 2).toFixed(2));
|
||||
boundaries.splice(columnIndex + 1, 0, midpoint);
|
||||
editor.boundaries = boundaries.join(', ');
|
||||
editor.fields.splice(columnIndex + 1, 0, null);
|
||||
editor.samples.splice(columnIndex + 1, 0, []);
|
||||
};
|
||||
|
||||
/** 删除当前物理行的一列并合并相邻边界;每行至少保留一列。 */
|
||||
const removeSubrowColumn = (editor: SubrowEditor, columnIndex: number) => {
|
||||
if (editor.fields.length <= 1) return;
|
||||
const boundaries = [...subrowBoundaries(editor)];
|
||||
boundaries.splice(columnIndex === 0 ? 1 : columnIndex, 1);
|
||||
editor.boundaries = boundaries.join(', ');
|
||||
editor.fields.splice(columnIndex, 1);
|
||||
editor.samples.splice(columnIndex, 1);
|
||||
};
|
||||
|
||||
/** 将多子行编辑器转换为严格契约;主行必须映射 line_no 才能识别新明细。 */
|
||||
const multiSubrowLayouts = (): CoordinateSubrowLayout[] | null => {
|
||||
const result: CoordinateSubrowLayout[] = [];
|
||||
for (const editor of subrowEditors.value) {
|
||||
const boundaries = parseBoundaryInput(editor.boundaries);
|
||||
if (!boundaries) return null;
|
||||
const columnCount = boundaries.length - 1;
|
||||
result.push({
|
||||
role: editor.role, row_offset: editor.row_offset,
|
||||
column_boundaries: boundaries,
|
||||
column_field_codes: Array.from({ length: columnCount }, (_, index) => editor.fields[index] || null),
|
||||
});
|
||||
}
|
||||
const main = result.find((item) => item.role === 'main');
|
||||
return main?.column_field_codes.includes('line_no') ? result : null;
|
||||
};
|
||||
|
||||
/** 将管理员确认的相对列边界转为受控坐标重建参数。 */
|
||||
const coordinateReconstructionSettings = (includeFieldRules = false): CoordinateReconstructionSettings | null => {
|
||||
if (multiSubrowEnabled.value) {
|
||||
const layouts = multiSubrowLayouts();
|
||||
return layouts ? { method: reconstructionMethod.value, column_boundaries: [], subrow_layouts: layouts } : null;
|
||||
}
|
||||
const values = parseBoundaryInput(columnBoundaryInput.value);
|
||||
if (!values) return null;
|
||||
const fieldCodes = includeFieldRules ? columnRules.value.map((item) => (
|
||||
item.extractor_key === 'direct' ? (item.target || null) : 'customer_part_number'
|
||||
)) : [];
|
||||
const lineStartColumn = fieldCodes.findIndex((code) => code === 'line_no');
|
||||
return {
|
||||
method: reconstructionMethod.value,
|
||||
column_boundaries: values,
|
||||
column_field_codes: fieldCodes.some(Boolean) ? fieldCodes : [],
|
||||
line_start_column_index: lineStartColumn >= 0 ? lineStartColumn : 0,
|
||||
};
|
||||
};
|
||||
|
||||
/** 生成影响内容适配和新行判断的列映射签名,用于阻止未复核配置直接保存。 */
|
||||
const coordinateFieldSignature = () => JSON.stringify({
|
||||
columnRules: columnRules.value.map((item) => ({ extractor_key: item.extractor_key, target: item.target })),
|
||||
multiSubrowEnabled: multiSubrowEnabled.value,
|
||||
subrows: subrowEditors.value,
|
||||
});
|
||||
|
||||
/** 用后端冻结坐标生成行版式和边界建议;仅确定性行号自动绑定,其余字段由管理员确认。 */
|
||||
const suggestLayouts = async () => {
|
||||
if (!form.document_id || !form.table_id) return;
|
||||
suggesting.value = true;
|
||||
reconstructionPreview.value = null;
|
||||
reconstructionConfirmed.value = false;
|
||||
try {
|
||||
const suggestion = await suggestOrderProfileCoordinateReconstruction(form.document_id, form.table_id);
|
||||
multiSubrowEnabled.value = true;
|
||||
subrowEditors.value = suggestion.subrow_layouts.map((item) => ({
|
||||
role: item.role,
|
||||
row_offset: item.row_offset,
|
||||
boundaries: item.column_boundaries.join(', '),
|
||||
fields: [...item.suggested_field_codes],
|
||||
samples: item.column_samples,
|
||||
}));
|
||||
selectedSubrowIndex.value = 0;
|
||||
message.success(t('admin.shippingOrderProfiles.layoutSuggestionReady'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
suggesting.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 仅重新识别当前物理行,按列位置保留已确认字段,不覆盖其他行版式。 */
|
||||
const suggestCurrentSubrow = async () => {
|
||||
const editor = selectedSubrow.value;
|
||||
if (!editor || !form.document_id || !form.table_id) return;
|
||||
suggestingSubrowIndex.value = editor.row_offset;
|
||||
try {
|
||||
const suggestion = await suggestOrderProfileCoordinateReconstruction(
|
||||
form.document_id, form.table_id, editor.row_offset,
|
||||
);
|
||||
const current = suggestion.subrow_layouts[0];
|
||||
if (!current) return;
|
||||
const previousFields = [...editor.fields];
|
||||
editor.boundaries = current.column_boundaries.join(', ');
|
||||
editor.samples = current.column_samples;
|
||||
editor.fields = current.suggested_field_codes.map((code, index) => code || previousFields[index] || null);
|
||||
message.success(t('admin.shippingOrderProfiles.currentRowSuggestionReady'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
suggestingSubrowIndex.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
/** 对扫描 PDF 生成 OCR 字符坐标,随后重新加载表格并继续人工审核。 */
|
||||
const generateOcrEvidence = async () => {
|
||||
if (!form.document_id || !form.table_id) return;
|
||||
const tableId = form.table_id;
|
||||
ocrGenerating.value = true;
|
||||
try {
|
||||
await generateOrderProfileOcrCoordinateEvidence(form.document_id, form.table_id);
|
||||
reconstructionMethod.value = 'ocr_pdf_coordinates.v1';
|
||||
await loadPreview();
|
||||
form.table_id = preview.value?.tables.some((table) => table.table_id === tableId)
|
||||
? tableId : (preview.value?.tables[0]?.table_id || '');
|
||||
message.success(t('admin.shippingOrderProfiles.ocrEvidenceReady'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
ocrGenerating.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
let reconstructionPreviewTimer: ReturnType<typeof window.setTimeout> | null = null;
|
||||
let reconstructionPreviewRequestId = 0;
|
||||
|
||||
/** 请求只读重建候选;自动刷新静默校验,手动刷新继续给出明确错误。 */
|
||||
const runReconstructionPreview = async (silent = false) => {
|
||||
if (multiSubrowEnabled.value && !subrowEditors.value[0]?.fields.includes('line_no')) {
|
||||
if (!silent) message.error(t('admin.shippingOrderProfiles.lineNoRequired'));
|
||||
return;
|
||||
}
|
||||
const settings = coordinateReconstructionSettings(true);
|
||||
if (!settings || !form.document_id || !form.table_id) {
|
||||
if (!silent) message.error(t('admin.shippingOrderProfiles.reconstructionBoundariesInvalid'));
|
||||
return;
|
||||
}
|
||||
const requestId = ++reconstructionPreviewRequestId;
|
||||
reconstructing.value = true;
|
||||
reconstructionPreviewFailed.value = false;
|
||||
reconstructionConfirmed.value = false;
|
||||
try {
|
||||
const result = await previewOrderProfileCoordinateReconstruction(form.document_id, form.table_id, settings);
|
||||
if (requestId !== reconstructionPreviewRequestId) return;
|
||||
reconstructionPreview.value = result;
|
||||
resizeColumns(reconstructionPreview.value.column_count);
|
||||
if (multiSubrowEnabled.value) {
|
||||
const fieldCodes = multiSubrowLayouts()?.flatMap((item) => item.column_field_codes.filter((code): code is string => Boolean(code))) || [];
|
||||
const uniqueCodes = [...new Set(fieldCodes)];
|
||||
columnRules.value = uniqueCodes.map((target) => ({ extractor_key: 'direct', target }));
|
||||
}
|
||||
reconstructionFieldSignature.value = coordinateFieldSignature();
|
||||
form.header_row_index = 0;
|
||||
form.data_start_row_index = Math.min(1, Math.max(reconstructionPreview.value.row_count - 1, 0));
|
||||
} catch (error) {
|
||||
if (requestId !== reconstructionPreviewRequestId) return;
|
||||
reconstructionPreviewFailed.value = true;
|
||||
if (!silent) showError(error);
|
||||
} finally {
|
||||
if (requestId === reconstructionPreviewRequestId) reconstructing.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 手动重建用于显式复核,并保留完整错误反馈。 */
|
||||
const reconstructTable = () => runReconstructionPreview(false);
|
||||
|
||||
/** 映射编辑停止后自动刷新右侧候选,避免每次选择都产生请求。 */
|
||||
const scheduleReconstructionPreview = () => {
|
||||
if (reconstructionPreviewTimer) window.clearTimeout(reconstructionPreviewTimer);
|
||||
reconstructionPreviewFailed.value = false;
|
||||
reconstructionConfirmed.value = false;
|
||||
if (!multiSubrowEnabled.value || !selectedTable.value?.coordinate_reconstruction_available) return;
|
||||
if (!form.document_id || !form.table_id || !subrowEditors.value[0]?.fields.includes('line_no')) return;
|
||||
if (!coordinateReconstructionSettings(true)) return;
|
||||
reconstructionPreviewTimer = window.setTimeout(() => {
|
||||
reconstructionPreviewTimer = null;
|
||||
void runReconstructionPreview(true);
|
||||
}, 500);
|
||||
};
|
||||
|
||||
/** 转换结构化表单为后端白名单列规则,不提交结构指纹或 HTML。 */
|
||||
@@ -185,6 +519,7 @@ const saveDraft = async () => {
|
||||
profile_code: form.profile_code.trim().toUpperCase(),
|
||||
display_name: form.display_name.trim(),
|
||||
column_rules: form.row_structure === 'preserved' ? normalizedRules() : [],
|
||||
coordinate_reconstruction: reconstructionConfirmed.value ? coordinateReconstructionSettings(true) : null,
|
||||
};
|
||||
if (editingProfileId.value && editingLockVersion.value !== null) {
|
||||
await updateOrderProfileFromSample(editingProfileId.value, {
|
||||
@@ -266,6 +601,26 @@ const removeProfile = async (profile: ShippingOrderDocumentProfile) => {
|
||||
}
|
||||
};
|
||||
|
||||
/** 删除前端专用样本;后端再次校验解析状态、所有权与盲测引用。 */
|
||||
const removeSample = async () => {
|
||||
const sample = selectedSample.value;
|
||||
if (!sample?.can_delete || !window.confirm(t('admin.shippingOrderProfiles.deleteSampleConfirm'))) return;
|
||||
try {
|
||||
await deleteOrderProfileSample(sample.intake_no);
|
||||
await load();
|
||||
form.document_id = samples.value[0]?.document_id || 0;
|
||||
if (!form.document_id) preview.value = null;
|
||||
message.success(t('admin.shippingOrderProfiles.sampleDeleted'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
};
|
||||
|
||||
/** 统一显示上传时间,避免同名样本在下拉框中不可区分。 */
|
||||
const formatSampleTime = (value?: string | null) => (
|
||||
value ? new Intl.DateTimeFormat(undefined, { dateStyle: 'short', timeStyle: 'short' }).format(new Date(value)) : '-'
|
||||
);
|
||||
|
||||
/** 退役当前发布版本;历史运行继续使用冻结快照。 */
|
||||
const retireProfile = async (profile: ShippingOrderDocumentProfile) => {
|
||||
if (!window.confirm(t('admin.shippingOrderProfiles.retireConfirm'))) return;
|
||||
@@ -279,7 +634,29 @@ const retireProfile = async (profile: ShippingOrderDocumentProfile) => {
|
||||
};
|
||||
|
||||
watch(() => form.document_id, loadPreview);
|
||||
watch(() => form.table_id, resetColumns);
|
||||
watch(() => form.table_id, () => {
|
||||
resetCoordinateReconstructionState();
|
||||
resetColumns();
|
||||
});
|
||||
watch(() => form.header_row_index, (headerRowIndex) => {
|
||||
if (form.data_start_row_index <= headerRowIndex) form.data_start_row_index = headerRowIndex + 1;
|
||||
});
|
||||
watch(columnRules, () => {
|
||||
if (reconstructionConfirmed.value && reconstructionFieldSignature.value !== coordinateFieldSignature()) {
|
||||
reconstructionConfirmed.value = false;
|
||||
}
|
||||
}, { deep: true });
|
||||
watch(multiSubrowEnabled, (enabled) => {
|
||||
if (enabled) subrowEditors.value.forEach(syncSubrowFields);
|
||||
reconstructionPreview.value = null;
|
||||
reconstructionPreviewFailed.value = false;
|
||||
reconstructionConfirmed.value = false;
|
||||
scheduleReconstructionPreview();
|
||||
});
|
||||
watch(subrowEditors, () => {
|
||||
if (reconstructionPreview.value) reconstructionConfirmed.value = false;
|
||||
scheduleReconstructionPreview();
|
||||
}, { deep: true });
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
@@ -291,83 +668,242 @@ onMounted(load);
|
||||
<p class="mt-1 text-sm text-slate-500">{{ t('admin.shippingOrderProfiles.subtitle') }}</p>
|
||||
</header>
|
||||
|
||||
<div class="grid gap-6 xl:grid-cols-[420px_minmax(0,1fr)]">
|
||||
<form class="space-y-4 rounded-xl border border-slate-200 bg-white p-5 shadow-sm" @submit.prevent="saveDraft">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div class="space-y-6">
|
||||
<form class="space-y-5 rounded-xl border border-slate-200 bg-white p-5 shadow-sm" @submit.prevent="saveDraft">
|
||||
<div class="flex items-center justify-between gap-3 border-b border-slate-100 pb-4">
|
||||
<h2 class="font-semibold">{{ t(editingProfileId ? 'admin.shippingOrderProfiles.editTitle' : 'admin.shippingOrderProfiles.createTitle') }}</h2>
|
||||
<button v-if="editingProfileId" type="button" class="text-sm text-slate-500" @click="cancelEdit">{{ t('common.cancel') }}</button>
|
||||
<div class="flex items-center gap-2">
|
||||
<button v-if="editingProfileId" type="button" class="h-9 rounded-lg px-3 text-sm text-slate-600 hover:bg-slate-100" @click="cancelEdit">{{ t('common.cancel') }}</button>
|
||||
<button type="submit" :disabled="!canSave || saving" class="h-9 rounded-lg bg-blue-600 px-4 text-sm font-medium text-white hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50">
|
||||
{{ saving ? t('admin.shippingOrderProfiles.saving') : t(editingProfileId ? 'admin.shippingOrderProfiles.updateDraft' : 'admin.shippingOrderProfiles.createDraft') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<label class="block text-sm">
|
||||
<span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.sample') }}</span>
|
||||
<select v-model.number="form.document_id" class="w-full rounded-lg border border-slate-300 px-3 py-2">
|
||||
<option :value="0">{{ t('admin.shippingOrderProfiles.selectSample') }}</option>
|
||||
<option v-for="sample in samples" :key="sample.document_id" :value="sample.document_id">
|
||||
{{ sample.filename || `Document ${sample.document_id}` }} ({{ sample.table_count }})
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<div class="rounded-lg border border-dashed border-slate-300 p-3">
|
||||
<p class="text-sm text-slate-600">{{ t('admin.shippingOrderProfiles.uploadSampleHint') }}</p>
|
||||
<input ref="sampleInput" class="sr-only" type="file" accept=".pdf,.eml,application/pdf,message/rfc822" @change="uploadSample" />
|
||||
<button type="button" :disabled="sampleUploading" class="mt-2 rounded border border-blue-300 px-3 py-1.5 text-sm text-blue-700 disabled:opacity-50" @click="sampleInput?.click()">
|
||||
{{ sampleUploading ? t('common.loading') : t('admin.shippingOrderProfiles.uploadSample') }}
|
||||
</button>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div class="max-w-[980px]">
|
||||
<label class="block text-xs font-medium text-slate-600">{{ t('admin.shippingOrderProfiles.sample') }}</label>
|
||||
<div class="mt-1.5 flex flex-wrap items-center gap-2">
|
||||
<input v-model="sampleSearch" class="h-9 w-52 rounded-lg border border-slate-300 px-3 text-sm" :placeholder="t('admin.shippingOrderProfiles.searchSample')" />
|
||||
<select v-model.number="form.document_id" class="h-9 min-w-0 flex-1 rounded-lg border border-slate-300 bg-white px-3 text-sm">
|
||||
<option :value="0">{{ t('admin.shippingOrderProfiles.selectSample') }}</option>
|
||||
<option v-for="sample in visibleSamples" :key="sample.document_id" :value="sample.document_id">
|
||||
{{ sample.filename || `Document ${sample.document_id}` }} · {{ formatSampleTime(sample.created_at) }} · {{ sample.parse_status }} · {{ sample.table_count }} {{ t('admin.shippingOrderProfiles.tablesUnit') }}
|
||||
</option>
|
||||
</select>
|
||||
<input ref="sampleInput" class="sr-only" type="file" accept=".pdf,.eml,application/pdf,message/rfc822" @change="uploadSample" />
|
||||
<button type="button" :disabled="sampleUploading" class="h-9 shrink-0 rounded-lg border border-blue-200 px-3 text-sm font-medium text-blue-700 hover:bg-blue-50 disabled:opacity-50" @click="sampleInput?.click()">
|
||||
{{ sampleUploading ? t('common.loading') : t('admin.shippingOrderProfiles.uploadSample') }}
|
||||
</button>
|
||||
<button type="button" :disabled="!selectedSample?.can_delete" class="h-9 shrink-0 rounded-lg border border-red-200 px-3 text-sm font-medium text-red-600 hover:bg-red-50 disabled:cursor-not-allowed disabled:border-slate-200 disabled:text-slate-400" @click="removeSample">
|
||||
{{ t('admin.shippingOrderProfiles.deleteSample') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="selectedSample" class="mt-1.5 text-xs text-slate-500">
|
||||
{{ t('admin.shippingOrderProfiles.sampleDetails', { time: formatSampleTime(selectedSample.created_at), status: selectedSample.parse_status }) }}
|
||||
· {{ selectedSample.is_template_sample ? t('admin.shippingOrderProfiles.templateSampleOnly') : t('admin.shippingOrderProfiles.businessSampleProtected') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-end gap-x-3 gap-y-3">
|
||||
<label class="w-44 text-xs font-medium text-slate-600">
|
||||
<span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.table') }}</span>
|
||||
<select v-model="form.table_id" class="h-9 w-full rounded-lg border border-slate-300 bg-white px-2.5 text-sm" :disabled="!preview">
|
||||
<option value="">{{ t('admin.shippingOrderProfiles.selectTable') }}</option>
|
||||
<option v-for="table in preview?.tables || []" :key="table.table_id" :value="table.table_id">P{{ table.page_no }} · {{ table.row_count }}×{{ table.column_count }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="w-52 text-xs font-medium text-slate-600">
|
||||
<span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.schema') }}</span>
|
||||
<select v-model.number="form.schema_version_id" :disabled="Boolean(editingProfileId)" class="h-9 w-full rounded-lg border border-slate-300 bg-white px-2.5 text-sm disabled:bg-slate-100">
|
||||
<option v-for="schema in publishedSchemas" :key="schema.id" :value="schema.id">v{{ schema.version }} · {{ schema.status }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="w-44 text-xs font-medium text-slate-600">
|
||||
<span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.code') }}</span>
|
||||
<input v-model="form.profile_code" :disabled="Boolean(editingProfileId)" class="h-9 w-full rounded-lg border border-slate-300 px-2.5 text-sm disabled:bg-slate-100" />
|
||||
</label>
|
||||
<label class="w-72 text-xs font-medium text-slate-600">
|
||||
<span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.name') }}</span>
|
||||
<input v-model="form.display_name" class="h-9 w-full rounded-lg border border-slate-300 px-2.5 text-sm" />
|
||||
</label>
|
||||
<label class="mb-2 flex items-center gap-2 whitespace-nowrap text-sm text-slate-700"><input v-model="form.drop_zero_qty" type="checkbox" />{{ t('admin.shippingOrderProfiles.dropZeroQty') }}</label>
|
||||
</div>
|
||||
|
||||
<details class="max-w-[980px] rounded-lg border border-slate-200 bg-slate-50 px-3 py-2">
|
||||
<summary class="cursor-pointer text-sm font-medium text-slate-700">{{ t('admin.shippingOrderProfiles.advancedSettings') }}</summary>
|
||||
<div class="mt-3 flex flex-wrap items-end gap-3 border-t border-slate-200 pt-3">
|
||||
<label class="w-72 text-xs font-medium text-slate-600"><span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.rowStructure') }}</span><select v-model="form.row_structure" class="h-9 w-full rounded-lg border border-slate-300 bg-white px-2.5 text-sm"><option value="preserved">{{ t('admin.shippingOrderProfiles.rowPreserved') }}</option><option value="unsupported_row_structure">{{ t('admin.shippingOrderProfiles.rowUnsupported') }}</option></select></label>
|
||||
<label class="w-36 text-xs font-medium text-slate-600"><span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.headerRow') }}</span><input v-model.number="form.header_row_index" type="number" min="0" :max="Math.max((displayedTable?.row_count || 1) - 2, 0)" class="h-9 w-full rounded-lg border border-slate-300 px-2.5 text-sm" /></label>
|
||||
<label class="w-32 text-xs font-medium text-slate-600"><span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.dataRow') }}</span><input v-model.number="form.data_start_row_index" type="number" :min="form.header_row_index + 1" :max="Math.max((displayedTable?.row_count || 1) - 1, 0)" class="h-9 w-full rounded-lg border border-slate-300 px-2.5 text-sm" /></label>
|
||||
<label v-if="editingProfileId" class="w-80 text-xs font-medium text-slate-600"><span class="mb-1.5 block">{{ t('admin.shippingOrderProfiles.changeNote') }}</span><input v-model="form.change_note" class="h-9 w-full rounded-lg border border-slate-300 px-2.5 text-sm" /></label>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
<label class="block text-sm">
|
||||
<span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.table') }}</span>
|
||||
<select v-model="form.table_id" class="w-full rounded-lg border border-slate-300 px-3 py-2" :disabled="!preview">
|
||||
<option value="">{{ t('admin.shippingOrderProfiles.selectTable') }}</option>
|
||||
<option v-for="table in preview?.tables || []" :key="table.table_id" :value="table.table_id">
|
||||
P{{ table.page_no }} · {{ table.row_count }}×{{ table.column_count }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<label class="text-sm"><span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.code') }}</span><input v-model="form.profile_code" :disabled="Boolean(editingProfileId)" class="w-full rounded-lg border border-slate-300 px-3 py-2 disabled:bg-slate-100" /></label>
|
||||
<label class="text-sm"><span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.name') }}</span><input v-model="form.display_name" class="w-full rounded-lg border border-slate-300 px-3 py-2" /></label>
|
||||
|
||||
<div v-if="selectedTable && !selectedTable.profile_creation_allowed" class="overflow-hidden rounded-xl border border-slate-200 bg-slate-50">
|
||||
<div class="flex items-start gap-3 border-b border-slate-200 bg-white px-4 py-3">
|
||||
<span class="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-amber-100 text-sm font-bold text-amber-700">!</span>
|
||||
<div>
|
||||
<p class="text-sm font-semibold text-slate-900">{{ t('admin.shippingOrderProfiles.reconstructionRequired') }}</p>
|
||||
<p v-if="selectedTable.coordinate_reconstruction_available" class="mt-1 text-xs leading-5 text-slate-500">{{ t('admin.shippingOrderProfiles.autoSuggestLayoutHint') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<template v-if="selectedTable.coordinate_reconstruction_available">
|
||||
<label class="flex items-center gap-2 border-b border-slate-200 px-4 py-2.5 text-sm font-medium text-slate-700">
|
||||
<input v-model="multiSubrowEnabled" type="checkbox" />
|
||||
{{ t('admin.shippingOrderProfiles.multiSubrowEnabled') }}
|
||||
</label>
|
||||
<label v-if="!multiSubrowEnabled" class="block p-4 text-xs"><span class="mb-1 block">{{ t('admin.shippingOrderProfiles.columnBoundaries') }}</span><input v-model="columnBoundaryInput" class="w-full rounded-lg border border-slate-300 bg-white px-3 py-2" /></label>
|
||||
<div v-else class="p-3">
|
||||
<div class="grid min-w-0 gap-3 lg:grid-cols-[180px_minmax(0,1fr)]">
|
||||
<aside class="overflow-hidden rounded-lg border border-slate-200 bg-white">
|
||||
<div class="border-b border-slate-200 px-3 py-2 text-xs font-semibold text-slate-600">{{ t('admin.shippingOrderProfiles.physicalRows') }}</div>
|
||||
<div class="p-1.5">
|
||||
<button v-for="(editor, editorIndex) in subrowEditors" :key="editor.row_offset" type="button" class="mb-1 flex h-9 w-full items-center justify-between rounded-md px-2.5 text-left text-sm last:mb-0" :class="selectedSubrowIndex === editorIndex ? 'bg-blue-50 font-medium text-blue-700' : 'text-slate-700 hover:bg-slate-50'" @click="selectedSubrowIndex = editorIndex">
|
||||
<span>{{ t(editorIndex === 0 ? 'admin.shippingOrderProfiles.firstSubrow' : 'admin.shippingOrderProfiles.followingSubrow', { index: editorIndex + 1 }) }}</span>
|
||||
<span class="text-xs opacity-60">{{ editor.fields.length }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex border-t border-slate-200 p-1.5">
|
||||
<button type="button" class="h-8 flex-1 rounded-md text-xs font-medium text-blue-700 hover:bg-blue-50" @click="addSubrow">+ {{ t('admin.shippingOrderProfiles.addSubrow') }}</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section v-if="selectedSubrow" class="min-w-0 overflow-hidden rounded-lg border border-slate-200 bg-white">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2 border-b border-slate-200 px-3 py-2">
|
||||
<div><span class="text-sm font-semibold text-slate-900">{{ t(selectedSubrowIndex === 0 ? 'admin.shippingOrderProfiles.firstSubrow' : 'admin.shippingOrderProfiles.followingSubrow', { index: selectedSubrowIndex + 1 }) }}</span><span class="ml-2 text-xs text-slate-400">{{ selectedSubrow.fields.length }} {{ t('admin.shippingOrderProfiles.columnsUnit') }}</span></div>
|
||||
<div class="flex items-center gap-1.5">
|
||||
<button type="button" :disabled="suggestingSubrowIndex !== null" class="h-8 rounded-md border border-blue-200 px-2.5 text-xs font-medium text-blue-700 hover:bg-blue-50 disabled:opacity-50" @click="suggestCurrentSubrow">{{ suggestingSubrowIndex === selectedSubrow.row_offset ? t('common.loading') : t('admin.shippingOrderProfiles.suggestCurrentRow') }}</button>
|
||||
<button v-if="selectedSubrowIndex > 0" type="button" class="h-8 rounded-md px-2.5 text-xs font-medium text-red-600 hover:bg-red-50" @click="removeSubrow(selectedSubrowIndex)">{{ t('common.delete') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-3">
|
||||
<div class="mb-2 flex items-center justify-between text-[11px] font-medium text-slate-500">
|
||||
<span>{{ t('admin.shippingOrderProfiles.visualBoundaries') }}</span>
|
||||
<span>{{ t('admin.shippingOrderProfiles.dragBoundaryHint') }}</span>
|
||||
</div>
|
||||
<div class="relative h-12 rounded-md border border-slate-300 bg-slate-50 px-1 pt-1">
|
||||
<div class="flex h-7 overflow-hidden rounded border border-white bg-white shadow-sm">
|
||||
<div v-for="(_, index) in selectedSubrow.fields" :key="index" class="flex min-w-0 items-center justify-center border-r border-blue-100 bg-blue-50/60 px-1 text-[10px] font-medium text-blue-700 last:border-r-0" :style="{ width: `${(subrowBoundaries(selectedSubrow)[index + 1]! - subrowBoundaries(selectedSubrow)[index]!) * 100}%` }">
|
||||
<span class="truncate">{{ index + 1 }} · {{ Math.round((subrowBoundaries(selectedSubrow)[index + 1]! - subrowBoundaries(selectedSubrow)[index]!) * 100) }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
<template v-for="(boundary, boundaryIndex) in subrowBoundaries(selectedSubrow).slice(1, -1)" :key="boundaryIndex">
|
||||
<span class="pointer-events-none absolute bottom-1 top-1 w-px bg-blue-500" :style="{ left: `${boundary * 100}%` }" />
|
||||
<input :value="boundary" type="range" min="0.01" max="0.99" step="0.01" class="boundary-slider absolute inset-x-0 top-5 h-5 w-full" :aria-label="t('admin.shippingOrderProfiles.boundaryHandle', { index: boundaryIndex + 1 })" @input="updateSubrowBoundary(selectedSubrow, boundaryIndex + 1, ($event.target as HTMLInputElement).value)" />
|
||||
</template>
|
||||
</div>
|
||||
<div class="mt-3 flex gap-2 overflow-x-auto pb-2">
|
||||
<article v-for="(_, index) in selectedSubrow.fields" :key="index" class="w-52 shrink-0 rounded-lg border border-slate-200 bg-slate-50 p-2.5">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="text-xs font-semibold text-slate-700">{{ t('admin.shippingOrderProfiles.subrowColumn', { index: index + 1 }) }}</span>
|
||||
<div class="flex items-center gap-1">
|
||||
<button type="button" :disabled="!canSplitSubrowColumn(selectedSubrow, index)" class="rounded px-1.5 py-0.5 text-[11px] font-medium text-blue-700 hover:bg-blue-50 disabled:cursor-not-allowed disabled:text-slate-300 disabled:hover:bg-transparent" @click="addSubrowColumn(selectedSubrow, index)">+ {{ t('admin.shippingOrderProfiles.insertColumnAfter') }}</button>
|
||||
<button v-if="selectedSubrow.fields.length > 1" type="button" class="rounded px-1.5 py-0.5 text-[11px] text-red-600 hover:bg-red-50" @click="removeSubrowColumn(selectedSubrow, index)">{{ t('common.delete') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-2 truncate rounded-md bg-white px-2 py-1.5 text-xs text-slate-500" :title="selectedSubrow.samples[index]?.join(' / ') || '-'">{{ selectedSubrow.samples[index]?.join(' / ') || '-' }}</div>
|
||||
<select v-model="selectedSubrow.fields[index]" class="mt-2 h-8 w-full rounded-md border border-slate-300 bg-white px-2 text-xs">
|
||||
<option :value="null">{{ t('admin.shippingOrderProfiles.ignoreColumn') }}</option>
|
||||
<option v-for="field in lineFields" :key="field.field_id" :value="field.field_code">{{ field.display_name }} · {{ field.field_code }}</option>
|
||||
</select>
|
||||
<div class="mt-2 font-mono text-[10px] text-slate-400">{{ Math.round(subrowBoundaries(selectedSubrow)[index]! * 100) }}%–{{ Math.round(subrowBoundaries(selectedSubrow)[index + 1]! * 100) }}%</div>
|
||||
</article>
|
||||
</div>
|
||||
<details class="mt-2 text-[11px] text-slate-500">
|
||||
<summary class="cursor-pointer select-none font-medium">{{ t('admin.shippingOrderProfiles.preciseBoundaryValues') }}</summary>
|
||||
<input v-model="selectedSubrow.boundaries" class="mt-1.5 w-full rounded-md border border-slate-300 bg-white px-2 py-1.5 font-mono text-[11px]" @change="syncSubrowFields(selectedSubrow)" />
|
||||
</details>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div class="mt-3 flex flex-wrap items-center gap-2 rounded-lg border border-slate-200 bg-white p-2">
|
||||
<button type="button" :disabled="suggesting" class="h-8 rounded-md border border-blue-200 px-2.5 text-xs font-medium text-blue-700 hover:bg-blue-50 disabled:opacity-50" @click="suggestLayouts">{{ suggesting ? t('common.loading') : t('admin.shippingOrderProfiles.autoSuggestAllRows') }}</button>
|
||||
<button type="button" :disabled="reconstructing" class="h-8 rounded-md bg-blue-600 px-3 text-xs font-medium text-white hover:bg-blue-700 disabled:opacity-50" @click="reconstructTable">{{ t('admin.shippingOrderProfiles.reconstructTable') }}</button>
|
||||
</div>
|
||||
<aside class="mt-3 min-w-0 overflow-hidden rounded-lg border border-slate-200 bg-white">
|
||||
<div class="flex items-center justify-between gap-3 border-b border-slate-200 px-3 py-2">
|
||||
<div>
|
||||
<h3 class="text-sm font-semibold text-slate-900">{{ t('admin.shippingOrderProfiles.livePreview') }}</h3>
|
||||
<p class="mt-0.5 text-[11px]" :class="reconstructionPreviewFailed ? 'text-red-600' : reconstructing ? 'text-blue-600' : 'text-slate-500'">{{ t(`admin.shippingOrderProfiles.${livePreviewStatusKey}`) }}</p>
|
||||
</div>
|
||||
<label v-if="reconstructionPreview" class="flex shrink-0 items-center gap-1.5 text-xs font-medium text-slate-700"><input v-model="reconstructionConfirmed" type="checkbox" />{{ t('admin.shippingOrderProfiles.confirmPreview') }}</label>
|
||||
</div>
|
||||
<div class="max-h-[52vh] min-h-56 overflow-auto">
|
||||
<table v-if="reconstructionPreview" class="min-w-full border-collapse text-xs">
|
||||
<tbody>
|
||||
<tr v-for="(row, rowIndex) in reconstructionPreview.rows" :key="rowIndex" :class="displayedRowRole(rowIndex) === 'deleted' ? 'bg-red-50 text-slate-500' : rowIndex === form.header_row_index ? 'bg-blue-50 font-semibold' : ''">
|
||||
<td class="sticky left-0 min-w-20 border border-slate-200 bg-slate-50 px-2 py-1.5 text-[11px] text-slate-500">
|
||||
<div>{{ t(`admin.shippingOrderProfiles.rowRole.${displayedRowRole(rowIndex)}`) }}</div>
|
||||
<div v-if="displayedSourceRows(rowIndex).length" class="mt-0.5">{{ displayedSourceRows(rowIndex).map((value) => value + 1).join(', ') }}</div>
|
||||
</td>
|
||||
<td v-for="(cell, columnIndex) in row" :key="columnIndex" class="max-w-52 whitespace-nowrap border border-slate-200 px-2 py-1.5" :title="cell">{{ cell }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div v-else class="flex min-h-56 items-center justify-center px-6 text-center text-xs leading-5 text-slate-500">{{ t(`admin.shippingOrderProfiles.${livePreviewStatusKey}`) }}</div>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2 border-t border-slate-200 bg-white px-4 py-2.5">
|
||||
<p class="text-[11px] text-slate-500">{{ t('admin.shippingOrderProfiles.multiSubrowHint') }}</p>
|
||||
<p v-if="reconstructionPreview && !reconstructionMatchesFields" class="text-[11px] font-medium text-amber-700">{{ t('admin.shippingOrderProfiles.rebuildAfterFieldMapping') }}</p>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="flex flex-wrap items-center justify-between gap-3 p-4">
|
||||
<p class="text-xs text-amber-900">{{ t('admin.shippingOrderProfiles.reconstructionUnavailable') }}</p>
|
||||
<button type="button" :disabled="ocrGenerating" class="rounded-lg border border-amber-500 bg-white px-3 py-2 text-sm text-amber-900 disabled:opacity-50" @click="generateOcrEvidence">{{ ocrGenerating ? t('common.loading') : t('admin.shippingOrderProfiles.generateOcrEvidence') }}</button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<label class="block text-sm">
|
||||
<span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.schema') }}</span>
|
||||
<select v-model.number="form.schema_version_id" :disabled="Boolean(editingProfileId)" class="w-full rounded-lg border border-slate-300 px-3 py-2 disabled:bg-slate-100">
|
||||
<option v-for="schema in publishedSchemas" :key="schema.id" :value="schema.id">v{{ schema.version }} · {{ schema.status }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="block text-sm">
|
||||
<span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.rowStructure') }}</span>
|
||||
<select v-model="form.row_structure" class="w-full rounded-lg border border-slate-300 px-3 py-2">
|
||||
<option value="preserved">{{ t('admin.shippingOrderProfiles.rowPreserved') }}</option>
|
||||
<option value="unsupported_row_structure">{{ t('admin.shippingOrderProfiles.rowUnsupported') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<label class="text-sm"><span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.headerRow') }}</span><input v-model.number="form.header_row_index" type="number" min="0" class="w-full rounded-lg border border-slate-300 px-3 py-2" /></label>
|
||||
<label class="text-sm"><span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.dataRow') }}</span><input v-model.number="form.data_start_row_index" type="number" min="1" class="w-full rounded-lg border border-slate-300 px-3 py-2" /></label>
|
||||
</div>
|
||||
<label class="flex items-center gap-2 text-sm"><input v-model="form.drop_zero_qty" type="checkbox" />{{ t('admin.shippingOrderProfiles.dropZeroQty') }}</label>
|
||||
<label class="block text-sm">
|
||||
<span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.changeNote') }}</span>
|
||||
<textarea v-model="form.change_note" rows="2" class="w-full rounded-lg border border-slate-300 px-3 py-2" />
|
||||
</label>
|
||||
<p v-if="duplicateTargets.length" class="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">
|
||||
{{ t('admin.shippingOrderProfiles.duplicateTargets', { fields: duplicateTargets.join(', ') }) }}
|
||||
</p>
|
||||
<p v-if="selectedTable && !selectedTable.profile_creation_allowed" class="rounded-lg bg-amber-50 px-3 py-2 text-sm text-amber-800">
|
||||
<p v-if="selectedTable && !selectedTable.profile_creation_allowed && !reconstructionConfirmed" class="rounded-lg bg-amber-50 px-3 py-2 text-sm text-amber-800">
|
||||
{{ t('admin.shippingOrderProfiles.structureBlocked') }}
|
||||
</p>
|
||||
<button type="submit" :disabled="!canSave || saving" class="w-full rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white disabled:opacity-50">
|
||||
{{ saving ? t('admin.shippingOrderProfiles.saving') : t(editingProfileId ? 'admin.shippingOrderProfiles.updateDraft' : 'admin.shippingOrderProfiles.createDraft') }}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div class="min-w-0 space-y-4">
|
||||
<div class="overflow-auto rounded-xl border border-slate-200 bg-white shadow-sm">
|
||||
<table v-if="selectedTable" class="min-w-full border-collapse text-sm">
|
||||
<div v-if="showStandardPreview" class="min-w-0 space-y-4">
|
||||
<section v-if="displayedTable && form.header_row_index > 0 && form.row_structure === 'preserved'" class="overflow-hidden rounded-xl border border-blue-200 bg-white shadow-sm">
|
||||
<div class="border-b border-blue-100 bg-blue-50 px-4 py-3">
|
||||
<h3 class="text-sm font-semibold text-slate-900">{{ t('admin.shippingOrderProfiles.multiRowHeaderMapping') }}</h3>
|
||||
<p class="mt-1 text-xs text-slate-600">{{ t('admin.shippingOrderProfiles.multiRowHeaderHint', { end: form.header_row_index }) }}</p>
|
||||
</div>
|
||||
<div class="flex gap-2 overflow-x-auto p-3">
|
||||
<article v-for="(label, columnIndex) in mergedHeaderLabels" :key="columnIndex" class="w-52 shrink-0 rounded-lg border border-slate-200 bg-slate-50 p-2.5">
|
||||
<div class="text-[11px] font-semibold text-slate-500">{{ t('admin.shippingOrderProfiles.mergedHeaderColumn', { index: columnIndex + 1 }) }}</div>
|
||||
<div class="mt-1 min-h-10 break-words text-xs font-medium leading-5 text-slate-800">{{ label || '-' }}</div>
|
||||
<select v-model="columnRule(columnIndex).target" class="mt-2 h-8 w-full rounded-md border border-slate-300 bg-white px-2 text-xs">
|
||||
<option value="">{{ t('admin.shippingOrderProfiles.ignoreColumn') }}</option>
|
||||
<option v-for="field in lineFields" :key="field.field_id" :value="field.field_code">{{ field.display_name }} · {{ field.field_code }}</option>
|
||||
</select>
|
||||
<select v-model="columnRule(columnIndex).extractor_key" class="mt-2 h-8 w-full rounded-md border border-slate-300 bg-white px-2 text-xs">
|
||||
<option value="direct">{{ t('admin.shippingOrderProfiles.direct') }}</option>
|
||||
<option value="temp_internal_parts" :disabled="!compositeExtractorAvailable">{{ t('admin.shippingOrderProfiles.compositePart') }}</option>
|
||||
</select>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
<div class="max-h-[70vh] overflow-auto rounded-xl border border-slate-200 bg-white shadow-sm">
|
||||
<div v-if="reconstructionPreview" class="border-b border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900">{{ t('admin.shippingOrderProfiles.reconstructionPreview') }}</div>
|
||||
<table v-if="displayedTable" class="min-w-full border-collapse text-sm">
|
||||
<tbody>
|
||||
<tr v-for="(row, rowIndex) in selectedTable.rows" :key="rowIndex" :class="rowIndex === form.header_row_index ? 'bg-blue-50 font-semibold' : ''">
|
||||
<td class="sticky left-0 border border-slate-200 bg-slate-50 px-2 py-2 text-xs text-slate-500">{{ rowIndex }}</td>
|
||||
<tr v-for="(row, rowIndex) in displayedTable.rows" :key="rowIndex" :class="rowIndex <= form.header_row_index ? 'bg-blue-50 font-semibold' : displayedRowRole(rowIndex) === 'deleted' ? 'bg-red-50 text-slate-500' : ''">
|
||||
<td class="sticky left-0 min-w-24 border border-slate-200 bg-slate-50 px-2 py-2 text-xs text-slate-500">
|
||||
<div>{{ rowIndex }}</div>
|
||||
<div v-if="reconstructionPreview" class="mt-1 font-medium" :class="displayedRowRole(rowIndex) === 'deleted' ? 'text-red-600' : 'text-emerald-700'">
|
||||
{{ t(`admin.shippingOrderProfiles.rowRole.${displayedRowRole(rowIndex)}`) }}
|
||||
</div>
|
||||
<div v-if="displayedSourceRows(rowIndex).length" class="mt-1 text-[11px]">
|
||||
{{ t('admin.shippingOrderProfiles.sourceRows', { rows: displayedSourceRows(rowIndex).map((value) => value + 1).join(', ') }) }}
|
||||
</div>
|
||||
</td>
|
||||
<td v-for="(cell, columnIndex) in row" :key="columnIndex" class="max-w-[260px] border border-slate-200 px-3 py-2 align-top">
|
||||
<div class="break-words">{{ cell }}</div>
|
||||
<div v-if="rowIndex === form.header_row_index && form.row_structure === 'preserved'" class="mt-2 space-y-1">
|
||||
<div v-if="rowIndex === form.header_row_index && form.header_row_index === 0 && form.row_structure === 'preserved' && !multiSubrowEnabled" class="mt-2 space-y-1">
|
||||
<div v-if="columnRule(columnIndex).extractor_key === 'temp_internal_parts'" class="rounded bg-slate-100 px-2 py-1 text-xs text-slate-600">
|
||||
customer_part_number + part_number
|
||||
</div>
|
||||
@@ -380,6 +916,9 @@ onMounted(load);
|
||||
<option value="temp_internal_parts" :disabled="!compositeExtractorAvailable">{{ t('admin.shippingOrderProfiles.compositePart') }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div v-else-if="rowIndex === form.header_row_index && multiSubrowEnabled" class="mt-2 rounded bg-slate-100 px-2 py-1 text-xs text-slate-600">
|
||||
{{ cell }}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
@@ -394,7 +933,7 @@ onMounted(load);
|
||||
<div v-if="loading" class="p-6 text-sm text-slate-500">{{ t('common.loading') }}</div>
|
||||
<div v-else class="divide-y divide-slate-100">
|
||||
<div v-for="profile in profiles" :key="profile.id" class="flex flex-wrap items-center justify-between gap-3 px-5 py-4">
|
||||
<div><div class="font-medium">{{ profile.display_name }} · v{{ profile.version }}</div><div class="text-xs text-slate-500">{{ profile.profile_code }} · Schema v{{ profile.schema_version }} · {{ profile.status }}<span v-if="profile.change_note"> · {{ profile.change_note }}</span></div></div>
|
||||
<div><div class="font-medium">{{ profile.display_name }} · v{{ profile.version }} <span v-if="currentProfileIds.has(profile.id)" class="rounded bg-emerald-100 px-2 py-0.5 text-xs font-medium text-emerald-800">{{ t('admin.shippingOrderProfiles.currentVersion') }}</span></div><div class="text-xs text-slate-500">{{ profile.profile_code }} · Schema v{{ profile.schema_version }} · {{ profile.status }}<span v-if="profile.published_at"> · {{ t('admin.shippingOrderProfiles.publishedAt', { time: formatSampleTime(profile.published_at) }) }}</span><span v-if="profile.change_note"> · {{ profile.change_note }}</span></div></div>
|
||||
<div class="flex gap-2">
|
||||
<button v-if="profile.status === 'draft'" class="rounded border border-slate-300 px-3 py-1.5 text-sm text-slate-700" @click="editDraft(profile)">{{ t('common.edit') }}</button>
|
||||
<button v-if="profile.status === 'draft'" class="rounded border border-blue-300 px-3 py-1.5 text-sm text-blue-700" @click="publishProfile(profile)">{{ t('admin.shippingOrderProfiles.publish') }}</button>
|
||||
@@ -408,3 +947,45 @@ onMounted(load);
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.boundary-slider {
|
||||
appearance: none;
|
||||
background: transparent;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.boundary-slider::-webkit-slider-runnable-track {
|
||||
height: 1px;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.boundary-slider::-webkit-slider-thumb {
|
||||
width: 12px;
|
||||
height: 20px;
|
||||
margin-top: -10px;
|
||||
appearance: none;
|
||||
border: 2px solid white;
|
||||
border-radius: 4px;
|
||||
background: #2563eb;
|
||||
box-shadow: 0 0 0 1px #2563eb;
|
||||
cursor: ew-resize;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.boundary-slider::-moz-range-track {
|
||||
height: 1px;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.boundary-slider::-moz-range-thumb {
|
||||
width: 10px;
|
||||
height: 18px;
|
||||
border: 2px solid white;
|
||||
border-radius: 4px;
|
||||
background: #2563eb;
|
||||
box-shadow: 0 0 0 1px #2563eb;
|
||||
cursor: ew-resize;
|
||||
pointer-events: auto;
|
||||
}
|
||||
</style>
|
||||
+24
-1
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/orderProfileForm.utils.spec.ts
|
||||
* 用途:验证可视化订单模板表单只生成受控规则并阻止目标字段重复映射。
|
||||
* 用途:验证可视化订单模板表单生成受控规则,并确保切换样本时配置入口不会消失。
|
||||
* 依赖:Vitest、orderProfileForm.utils。
|
||||
* 逻辑:覆盖 direct、复合解析器开关及跨列冲突,避免无效配置进入后端。
|
||||
*/
|
||||
@@ -9,6 +9,8 @@ import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
buildOrderProfileColumnRules,
|
||||
findDuplicateOrderProfileTargets,
|
||||
mergeOrderProfileHeaderLabels,
|
||||
shouldShowStandardOrderProfilePreview,
|
||||
} from './orderProfileForm.utils';
|
||||
|
||||
describe('order profile form rules', () => {
|
||||
@@ -45,4 +47,25 @@ describe('order profile form rules', () => {
|
||||
{ extractor_key: 'temp_internal_parts', target: '' },
|
||||
], false)).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps directly configurable tables visible despite stale multi-row state', () => {
|
||||
// 断言上一张表残留的多物理行开关不能隐藏当前可直接配置的表格。
|
||||
expect(shouldShowStandardOrderProfilePreview(true, true, true)).toBe(true);
|
||||
expect(shouldShowStandardOrderProfilePreview(false, true, true)).toBe(false);
|
||||
});
|
||||
|
||||
it('merges every physical header row into stable logical column labels', () => {
|
||||
const labels = mergeOrderProfileHeaderLabels([
|
||||
['Item', 'Material', 'Vendor Part Number'],
|
||||
['Item', 'Description', ''],
|
||||
['IncoTerm', '', 'Manufacturer Part'],
|
||||
], 2, 3);
|
||||
|
||||
// 断言同列跨行文字按顺序合并,并去掉展开 rowspan 产生的重复标签。
|
||||
expect(labels).toEqual([
|
||||
'Item / IncoTerm',
|
||||
'Material / Description',
|
||||
'Vendor Part Number / Manufacturer Part',
|
||||
]);
|
||||
});
|
||||
});
|
||||
+34
-1
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/orderProfileForm.utils.ts
|
||||
* 用途:构造可视化订单模板的白名单列规则,并在提交前发现目标字段冲突。
|
||||
* 用途:构造可视化订单模板的白名单列规则,并控制样本表格配置区的安全显示。
|
||||
* 依赖:订单 Profile DTO。
|
||||
* 逻辑:页面状态只允许 direct 或已注册复合解析器;同一目标字段跨列只能出现一次。
|
||||
*/
|
||||
@@ -12,6 +12,39 @@ export interface OrderProfileColumnSelection {
|
||||
target: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否显示普通表格预览;可直接创建 Profile 的表格不受上一张表多物理行状态影响。
|
||||
* @param profileCreationAllowed - 当前表格是否可直接创建 Profile
|
||||
* @param multiSubrowEnabled - 当前是否启用多物理行坐标重建
|
||||
* @param coordinateReconstructionAvailable - 当前表格是否具备坐标重建证据
|
||||
* @returns 为 true 时显示普通表格及字段配置入口
|
||||
*/
|
||||
export const shouldShowStandardOrderProfilePreview = (
|
||||
profileCreationAllowed: boolean,
|
||||
multiSubrowEnabled: boolean,
|
||||
coordinateReconstructionAvailable: boolean,
|
||||
): boolean => (
|
||||
profileCreationAllowed || !multiSubrowEnabled || !coordinateReconstructionAvailable
|
||||
);
|
||||
|
||||
/**
|
||||
* 将表头区域内同一逻辑列的多行文字合并为虚拟列头,重复的 rowspan/colspan 文本只保留一次。
|
||||
* @param rows - 后端展开后的样本表格行
|
||||
* @param headerRowIndex - 最后一行表头的零基索引
|
||||
* @param columnCount - 表格逻辑列数
|
||||
* @returns 与逻辑列一一对应的合并表头文字
|
||||
*/
|
||||
export const mergeOrderProfileHeaderLabels = (
|
||||
rows: string[][], headerRowIndex: number, columnCount: number,
|
||||
): string[] => Array.from({ length: columnCount }, (_, columnIndex) => {
|
||||
const labels: string[] = [];
|
||||
rows.slice(0, Math.max(headerRowIndex + 1, 0)).forEach((row) => {
|
||||
const label = String(row[columnIndex] || '').replace(/\s+/g, ' ').trim();
|
||||
if (label && !labels.some((item) => item.toLowerCase() === label.toLowerCase())) labels.push(label);
|
||||
});
|
||||
return labels.join(' / ');
|
||||
});
|
||||
|
||||
/** 将逐列选择转换为后端白名单规则;不可用的复合解析器不会进入请求。 */
|
||||
export const buildOrderProfileColumnRules = (
|
||||
selections: OrderProfileColumnSelection[], compositeExtractorAvailable: boolean,
|
||||
|
||||
+104
-1
@@ -15,6 +15,7 @@ import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
createShippingOrderField,
|
||||
createShippingOrderSchemaDraft,
|
||||
createShippingFulfillmentPolicyDraft,
|
||||
deleteShippingOrderField,
|
||||
deleteShippingOrderSchemaDraft,
|
||||
getShippingOrderSchemaVersion,
|
||||
@@ -22,10 +23,12 @@ import {
|
||||
getShippingOrderSchemaVersionUsage,
|
||||
getShippingOrderExtractionAudit,
|
||||
getShippingOrderSchemaState,
|
||||
getShippingFulfillmentPolicyState,
|
||||
initializeShippingOrderSchema,
|
||||
listShippingOrderSchemaVersions,
|
||||
listShippingOrderSchemaAuditEvents,
|
||||
publishShippingOrderSchemaDraft,
|
||||
publishShippingFulfillmentPolicy,
|
||||
reorderShippingOrderFields,
|
||||
saveShippingOrderSchemaDraft,
|
||||
saveShippingOrderAutoCreationPolicy,
|
||||
@@ -48,6 +51,7 @@ import type {
|
||||
ShippingOrderSchemaVersionDiff,
|
||||
ShippingOrderSchemaVersionUsage,
|
||||
ShippingOrderExtractionAudit,
|
||||
ShippingFulfillmentPolicyState,
|
||||
} from '@/features/admin/types/shipping-order-schema.types';
|
||||
|
||||
type DraftFieldEditor = ShippingOrderFieldConfig & { enabled: boolean };
|
||||
@@ -100,6 +104,9 @@ const selectedVersionUsage = ref<ShippingOrderSchemaVersionUsage | null>(null);
|
||||
const extractionAuditOpen = ref(false);
|
||||
const extractionAuditLoading = ref(false);
|
||||
const selectedExtractionAudit = ref<ShippingOrderExtractionAudit | null>(null);
|
||||
const fulfillmentPolicyState = ref<ShippingFulfillmentPolicyState | null>(null);
|
||||
const fulfillmentPolicyNote = ref('');
|
||||
const fulfillmentBindings = reactive<Record<string, string>>({});
|
||||
|
||||
const draft = computed(() => state.value?.versions.find((item) => item.status === 'draft') || null);
|
||||
const published = computed(() => state.value?.versions.find((item) => item.status === 'published') || null);
|
||||
@@ -125,6 +132,14 @@ const selectedContextOption = computed(() => activeContextOptions.value.find(
|
||||
const selectedExposurePolicies = computed(() => (
|
||||
selectedContextOption.value?.allowed_dify_exposure_policies || ['never']
|
||||
));
|
||||
const publishedPolicy = computed(() => fulfillmentPolicyState.value?.policies.find((item) => item.status === 'published') || null);
|
||||
const draftPolicy = computed(() => fulfillmentPolicyState.value?.policies.find((item) => item.status === 'draft') || null);
|
||||
const policyFieldsFor = (capability: { scope: string; value_type: string }) => (state.value?.fields || []).filter((field) => (
|
||||
field.status === 'active'
|
||||
&& published.value?.definition?.fields.some((config) => config.field_id === field.id && config.enabled !== false)
|
||||
&& field.scope === capability.scope
|
||||
&& field.value_type === capability.value_type
|
||||
));
|
||||
|
||||
/** 左侧字段字典按显示名称和字段编号搜索,并保持通用上下文/订单信息/货品明细分组。 */
|
||||
const groupedFields = computed(() => {
|
||||
@@ -482,7 +497,13 @@ const syncDraftFields = (): void => {
|
||||
const load = async (): Promise<void> => {
|
||||
loading.value = true;
|
||||
try {
|
||||
state.value = await getShippingOrderSchemaState();
|
||||
const schemaState = await getShippingOrderSchemaState();
|
||||
state.value = schemaState;
|
||||
fulfillmentPolicyState.value = schemaState.schema ? await getShippingFulfillmentPolicyState() : null;
|
||||
const source = draftPolicy.value || publishedPolicy.value;
|
||||
for (const binding of source?.definition.field_bindings || []) {
|
||||
fulfillmentBindings[binding.capability_code] = binding.field_id;
|
||||
}
|
||||
syncDraftFields();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
@@ -491,6 +512,43 @@ const load = async (): Promise<void> => {
|
||||
}
|
||||
};
|
||||
|
||||
/** 创建策略草稿前只提交受控能力与兼容的已发布字段,服务端继续执行最终校验。 */
|
||||
const createFulfillmentPolicyDraft = async (): Promise<void> => {
|
||||
if (!fulfillmentPolicyState.value || draftPolicy.value) return;
|
||||
saving.value = true;
|
||||
try {
|
||||
await createShippingFulfillmentPolicyDraft({
|
||||
field_bindings: fulfillmentPolicyState.value.capabilities.flatMap((capability) => {
|
||||
const fieldId = fulfillmentBindings[capability.capability_code];
|
||||
return fieldId ? [{ capability_code: capability.capability_code, field_id: fieldId }] : [];
|
||||
}),
|
||||
change_note: fulfillmentPolicyNote.value,
|
||||
});
|
||||
message.success(t('admin.shippingOrderSchema.fulfillmentDraftCreated'));
|
||||
await load();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 发布前使用草稿锁版本,避免两个管理员相互覆盖字段能力定义。 */
|
||||
const publishFulfillmentPolicyDraft = async (): Promise<void> => {
|
||||
if (!draftPolicy.value) return;
|
||||
saving.value = true;
|
||||
try {
|
||||
await publishShippingFulfillmentPolicy(draftPolicy.value.id, draftPolicy.value.lock_version);
|
||||
message.success(t('admin.shippingOrderSchema.fulfillmentPublished'));
|
||||
fulfillmentPolicyNote.value = '';
|
||||
await load();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 初始化唯一订单 Schema。 */
|
||||
const initialize = async (): Promise<void> => {
|
||||
saving.value = true;
|
||||
@@ -793,6 +851,35 @@ onMounted(async () => {
|
||||
<span><strong>{{ t('admin.shippingOrderSchema.autoCreationEnabled') }}</strong><small>{{ t('admin.shippingOrderSchema.autoCreationHint') }}</small></span>
|
||||
</label>
|
||||
|
||||
<section class="fulfillment-policy-card">
|
||||
<header>
|
||||
<div>
|
||||
<p>{{ t('admin.shippingOrderSchema.fulfillmentEyebrow') }}</p>
|
||||
<h2>{{ t('admin.shippingOrderSchema.fulfillmentTitle') }}</h2>
|
||||
<small>{{ t('admin.shippingOrderSchema.fulfillmentHint') }}</small>
|
||||
</div>
|
||||
<span class="read-only-badge">
|
||||
{{ publishedPolicy ? t('admin.shippingOrderSchema.fulfillmentPublishedVersion', { version: publishedPolicy.version }) : t('admin.shippingOrderSchema.fulfillmentNotPublished') }}
|
||||
</span>
|
||||
</header>
|
||||
<p v-if="!published" class="fulfillment-warning">{{ t('admin.shippingOrderSchema.fulfillmentSchemaRequired') }}</p>
|
||||
<div v-else class="fulfillment-bindings">
|
||||
<label v-for="capability in fulfillmentPolicyState?.capabilities || []" :key="capability.capability_code">
|
||||
<span><strong>{{ t(`admin.shippingOrderSchema.fulfillmentCapability.${capability.capability_code}`) }}</strong><small>{{ capability.required ? t('admin.shippingOrderSchema.fulfillmentRequired') : t('admin.shippingOrderSchema.fulfillmentOptional') }}</small></span>
|
||||
<select v-model="fulfillmentBindings[capability.capability_code]" :disabled="saving || Boolean(draftPolicy)">
|
||||
<option value="">{{ t('admin.shippingOrderSchema.fulfillmentSelectField') }}</option>
|
||||
<option v-for="field in policyFieldsFor(capability)" :key="field.id" :value="field.id">{{ displayNameForField(field, 0) }} ({{ field.field_code }})</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<footer v-if="published">
|
||||
<label v-if="!draftPolicy"><span>{{ t('admin.shippingOrderSchema.fulfillmentChangeNote') }}</span><input v-model="fulfillmentPolicyNote" :disabled="saving" :placeholder="t('admin.shippingOrderSchema.fulfillmentChangeNotePlaceholder')"></label>
|
||||
<p v-else>{{ t('admin.shippingOrderSchema.fulfillmentDraftHint', { version: draftPolicy.version }) }}</p>
|
||||
<button v-if="!draftPolicy" type="button" class="secondary-button" :disabled="saving" @click="createFulfillmentPolicyDraft">{{ t('admin.shippingOrderSchema.fulfillmentCreateDraft') }}</button>
|
||||
<button v-else type="button" class="primary-button" :disabled="saving" @click="publishFulfillmentPolicyDraft">{{ t('admin.shippingOrderSchema.fulfillmentPublish') }}</button>
|
||||
</footer>
|
||||
</section>
|
||||
|
||||
<div class="schema-workbench">
|
||||
<aside class="field-panel">
|
||||
<div class="panel-heading">
|
||||
@@ -964,6 +1051,22 @@ onMounted(async () => {
|
||||
.auto-creation-switch span { display: grid; gap: 3px; }
|
||||
.auto-creation-switch strong { color: #334155; font-size: 13px; }
|
||||
.auto-creation-switch small { color: #64748b; font-size: 11px; }
|
||||
.fulfillment-policy-card { display: grid; gap: 14px; margin: 0 0 16px; border: 1px solid #dbe6ef; border-radius: 10px; background: #fff; padding: 16px; }
|
||||
.fulfillment-policy-card > header, .fulfillment-policy-card > footer { display: flex; align-items: center; justify-content: space-between; gap: 14px; }
|
||||
.fulfillment-policy-card h2, .fulfillment-policy-card p { margin: 0; }
|
||||
.fulfillment-policy-card header p { color: #0284c7; font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
|
||||
.fulfillment-policy-card h2 { margin-top: 3px; color: #1e293b; font-size: 14px; }
|
||||
.fulfillment-policy-card header small, .fulfillment-policy-card footer p { color: #64748b; font-size: 12px; }
|
||||
.fulfillment-warning { border-radius: 7px; background: #fff7ed; padding: 9px 11px; color: #9a3412; font-size: 12px; }
|
||||
.fulfillment-bindings { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
|
||||
.fulfillment-bindings label, .fulfillment-policy-card footer label { display: grid; gap: 5px; color: #64748b; font-size: 12px; }
|
||||
.fulfillment-bindings label { grid-template-columns: minmax(0, 1fr) minmax(180px, .8fr); align-items: center; border: 1px solid #edf1f5; border-radius: 7px; padding: 10px; }
|
||||
.fulfillment-bindings span { display: grid; gap: 2px; }
|
||||
.fulfillment-bindings strong { color: #334155; font-weight: 600; }
|
||||
.fulfillment-bindings small { color: #94a3b8; font-size: 10px; }
|
||||
.fulfillment-bindings select, .fulfillment-policy-card footer input { min-width: 0; border: 1px solid #d9e2ec; border-radius: 6px; background: #fff; padding: 8px 9px; color: #334155; font: inherit; font-size: 12px; }
|
||||
.fulfillment-policy-card footer label { flex: 1; }
|
||||
@media (max-width: 900px) { .fulfillment-bindings { grid-template-columns: 1fr; } }
|
||||
.field-panel { display: flex; min-width: 0; min-height: 0; flex-direction: column; border-right: 1px solid #e5ebf1; background: #fbfcfe; }
|
||||
.panel-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 16px 16px 10px; }
|
||||
.panel-heading h2, .rule-heading h2 { margin: 0; color: #1e293b; font-size: 15px; font-weight: 600; }
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
/**
|
||||
* features/admin/shippingConfigNavigation.spec.ts
|
||||
* 用途:锁定货代配置二级导航与后台路由的注册契约。
|
||||
* 依赖:货代配置子模块注册表、后台路由、Vitest。
|
||||
* 用途:锁定货代管理业务分组、深链与后台路由的注册契约。
|
||||
* 依赖:货代管理业务目录注册表、后台路由、Vitest。
|
||||
* 逻辑:防止新增或调整子页面时丢失深链、权限复用或当前子项高亮标识。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { adminRoutes } from '@/app/router/routes/admin.routes';
|
||||
import { SHIPPING_CONFIG_SUB_MODULE_METAS } from './constants/modules';
|
||||
import { ADMIN_MODULE_METAS, SHIPPING_CONFIG_SUB_MODULE_METAS } from './constants/modules';
|
||||
import type { ShippingManagementGroupKey } from './stores/admin-nav.store';
|
||||
|
||||
const shippingRoutes = adminRoutes[0].children?.filter((route) =>
|
||||
route.name === 'AdminShippingInventory'
|
||||
@@ -17,17 +18,45 @@ const shippingRoutes = adminRoutes[0].children?.filter((route) =>
|
||||
) ?? [];
|
||||
|
||||
describe('shipping configuration navigation contract', () => {
|
||||
it('keeps shipping management between schedules and announcements', () => {
|
||||
// 关键断言:货代管理必须保持在排程管理之后、公告管理之前,匹配后台约定的信息架构。
|
||||
const moduleIds = ADMIN_MODULE_METAS.map((item) => item.id);
|
||||
expect(moduleIds.slice(moduleIds.indexOf('schedules'), moduleIds.indexOf('announcements') + 1)).toEqual([
|
||||
'schedules',
|
||||
'shipping_inventory',
|
||||
'announcements',
|
||||
]);
|
||||
});
|
||||
|
||||
it('registers all shipping configuration subpages with discoverable deep links', () => {
|
||||
// 关键断言:导航注册表与深链路由必须一一对应,避免后台入口不可发现。
|
||||
expect(SHIPPING_CONFIG_SUB_MODULE_METAS).toEqual([
|
||||
{ id: 'inventory', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.nav.shippingInventory' },
|
||||
{ id: 'identity_rules', routeName: 'AdminShippingIdentityRules', path: 'shipping-identity-rules', labelKey: 'admin.nav.shippingIdentityRules' },
|
||||
{ id: 'order_extraction_runs', routeName: 'AdminShippingOrderExtractionRuns', path: 'shipping-order-extraction-runs', labelKey: 'admin.nav.shippingOrderExtractionRuns' },
|
||||
{ id: 'order_document_profiles', routeName: 'AdminShippingOrderDocumentProfiles', path: 'shipping-order-document-profiles', labelKey: 'admin.nav.shippingOrderDocumentProfiles' },
|
||||
{ id: 'order_fields', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.nav.shippingOrderFields', groupKey: 'admin.nav.shippingOrderRecognition', query: { section: 'orderSchema' } },
|
||||
{ id: 'order_document_profiles', routeName: 'AdminShippingOrderDocumentProfiles', path: 'shipping-order-document-profiles', labelKey: 'admin.nav.shippingOrderDocumentProfiles', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
{ id: 'identity_rules', routeName: 'AdminShippingIdentityRules', path: 'shipping-identity-rules', labelKey: 'admin.nav.shippingIdentityRules', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
{ id: 'order_extraction_runs', routeName: 'AdminShippingOrderExtractionRuns', path: 'shipping-order-extraction-runs', labelKey: 'admin.nav.shippingOrderExtractionRuns', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
{ id: 'inventory_fields', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.parsingProfiles', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'parsing' } },
|
||||
{ id: 'connections', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.connections', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'profiles' } },
|
||||
{ id: 'inventory_sites', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.sources', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'sources' } },
|
||||
{ id: 'warehouse_mappings', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.externalMappings', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'mappings' } },
|
||||
{ id: 'routing_rules', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.rules', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'rules' } },
|
||||
{ id: 'shipping_templates', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.excelTemplates', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'templates' } },
|
||||
{ id: 'inventory_snapshots', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } },
|
||||
{ id: 'export_records', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } },
|
||||
]);
|
||||
expect(shippingRoutes).toHaveLength(4);
|
||||
});
|
||||
|
||||
it('keeps exactly three ordered accordion groups', () => {
|
||||
// 关键断言:货代功能量较大,侧栏必须保持三组手风琴,避免所有入口同时平铺。
|
||||
const groups = [...new Set(SHIPPING_CONFIG_SUB_MODULE_METAS.map((item) => item.groupKey))] satisfies ShippingManagementGroupKey[];
|
||||
expect(groups).toEqual([
|
||||
'admin.nav.shippingOrderRecognition',
|
||||
'admin.nav.shippingInventoryManagement',
|
||||
'admin.nav.shippingRunAudit',
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps all deep links behind the shared shipping inventory admin boundary', () => {
|
||||
// 关键断言:菜单可见性不是授权;所有页面均须保留 requiresAdmin 和共享模块权限标识。
|
||||
expect(shippingRoutes.map((route) => route.meta)).toEqual([
|
||||
|
||||
@@ -11,6 +11,11 @@ import { ref } from 'vue';
|
||||
import { getAdminDashboardBadges } from '@/features/admin/api/admin.api';
|
||||
import type { AdminModuleId } from '../types/admin.types';
|
||||
|
||||
export type ShippingManagementGroupKey =
|
||||
| 'admin.nav.shippingOrderRecognition'
|
||||
| 'admin.nav.shippingInventoryManagement'
|
||||
| 'admin.nav.shippingRunAudit';
|
||||
|
||||
/** 角标缓存有效期(毫秒):此时间内 ensureBadges 直接复用内存中的计数 */
|
||||
const BADGE_CACHE_TTL_MS = 60_000;
|
||||
|
||||
@@ -20,8 +25,10 @@ export const useAdminNavStore = defineStore('adminNav', () => {
|
||||
const reportsExpanded = ref(false);
|
||||
/** 企业微信子菜单:默认折叠 */
|
||||
const wecomExpanded = ref(false);
|
||||
/** 货代配置子菜单:默认折叠,进入库存或识别规则页时由导航自动展开。 */
|
||||
const shippingConfigExpanded = ref(false);
|
||||
/** 货代管理二级菜单:默认折叠,进入货代页面时自动展开。 */
|
||||
const shippingManagementExpanded = ref(false);
|
||||
/** 货代手风琴当前展开分组;单值约束保证同一时间最多展开一组。 */
|
||||
const shippingManagementGroup = ref<ShippingManagementGroupKey | null>(null);
|
||||
/** 「用户审批」导航角标:pending 注册用户数 */
|
||||
const pendingApprovalsCount = ref(0);
|
||||
/** 「权限申请」导航角标:pending 权限申请数 */
|
||||
@@ -36,6 +43,11 @@ export const useAdminNavStore = defineStore('adminNav', () => {
|
||||
sidebarCollapsed.value = !sidebarCollapsed.value;
|
||||
};
|
||||
|
||||
/** 展开指定货代分组;再次点击当前分组时收起全部功能项。 */
|
||||
const toggleShippingManagementGroup = (groupKey: ShippingManagementGroupKey): void => {
|
||||
shippingManagementGroup.value = shippingManagementGroup.value === groupKey ? null : groupKey;
|
||||
};
|
||||
|
||||
const setBadgeCounts = (approvals: number, requests: number): void => {
|
||||
pendingApprovalsCount.value = approvals;
|
||||
pendingRequestsCount.value = requests;
|
||||
@@ -90,10 +102,12 @@ export const useAdminNavStore = defineStore('adminNav', () => {
|
||||
sidebarCollapsed,
|
||||
reportsExpanded,
|
||||
wecomExpanded,
|
||||
shippingConfigExpanded,
|
||||
shippingManagementExpanded,
|
||||
shippingManagementGroup,
|
||||
pendingApprovalsCount,
|
||||
pendingRequestsCount,
|
||||
toggleSidebar,
|
||||
toggleShippingManagementGroup,
|
||||
setBadgeCounts,
|
||||
badgeForModule,
|
||||
ensureBadges,
|
||||
|
||||
@@ -20,8 +20,20 @@ export type AdminModuleId =
|
||||
| 'shipping_inventory'
|
||||
| 'reports';
|
||||
|
||||
/** 货代配置领域下可由侧栏展示和高亮的稳定子页面。 */
|
||||
export type ShippingConfigSubModuleId = 'inventory' | 'identity_rules' | 'order_extraction_runs' | 'order_document_profiles';
|
||||
/** 货代管理领域下可由侧栏展示和高亮的稳定业务页面。 */
|
||||
export type ShippingConfigSubModuleId =
|
||||
| 'order_fields'
|
||||
| 'order_document_profiles'
|
||||
| 'identity_rules'
|
||||
| 'order_extraction_runs'
|
||||
| 'inventory_fields'
|
||||
| 'connections'
|
||||
| 'inventory_sites'
|
||||
| 'warehouse_mappings'
|
||||
| 'routing_rules'
|
||||
| 'shipping_templates'
|
||||
| 'inventory_snapshots'
|
||||
| 'export_records';
|
||||
|
||||
export type AdminReportTableId =
|
||||
| 'usage_analysis'
|
||||
|
||||
@@ -32,6 +32,7 @@ export interface ShippingOrderDocumentProfile {
|
||||
row_structure: 'preserved' | 'unsupported_row_structure';
|
||||
column_rules: OrderProfileColumnRule[];
|
||||
drop_zero_qty: boolean;
|
||||
coordinate_reconstruction?: CoordinateReconstructionSettings | null;
|
||||
};
|
||||
checksum?: string | null;
|
||||
lock_version: number;
|
||||
@@ -44,12 +45,18 @@ export interface ShippingOrderDocumentProfile {
|
||||
export interface OrderProfileSampleDocument {
|
||||
document_id: number;
|
||||
intake_id: number;
|
||||
intake_no: string;
|
||||
filename?: string | null;
|
||||
content_hash?: string | null;
|
||||
provider?: string | null;
|
||||
provider_version?: string | null;
|
||||
table_count: number;
|
||||
created_at?: string | null;
|
||||
purpose: 'shipping_notice' | 'order_document_profile_sample';
|
||||
parse_status: string;
|
||||
is_template_sample: boolean;
|
||||
can_delete: boolean;
|
||||
delete_block_reason?: 'blind_test_referenced' | null;
|
||||
}
|
||||
|
||||
export interface OrderProfileSampleTable {
|
||||
@@ -60,6 +67,44 @@ export interface OrderProfileSampleTable {
|
||||
rows: string[][];
|
||||
issues: string[];
|
||||
profile_creation_allowed: boolean;
|
||||
coordinate_reconstruction_available?: boolean;
|
||||
ocr_coordinate_reconstruction_available?: boolean;
|
||||
}
|
||||
|
||||
export interface CoordinateReconstructionSettings {
|
||||
method: 'native_pdf_coordinates.v1' | 'ocr_pdf_coordinates.v1';
|
||||
column_boundaries: number[];
|
||||
column_field_codes?: Array<string | null>;
|
||||
line_start_column_index?: number;
|
||||
subrow_layouts?: CoordinateSubrowLayout[];
|
||||
}
|
||||
|
||||
export interface CoordinateSubrowLayout {
|
||||
role: 'main' | 'continuation';
|
||||
row_offset: number;
|
||||
column_boundaries: number[];
|
||||
column_field_codes: Array<string | null>;
|
||||
}
|
||||
|
||||
export interface CoordinateReconstructionPreview {
|
||||
table_id: string;
|
||||
row_count: number;
|
||||
column_count: number;
|
||||
rows: string[][];
|
||||
row_roles: Array<'header' | 'data' | 'deleted'>;
|
||||
source_row_indices: number[][];
|
||||
status: 'needs_review';
|
||||
}
|
||||
|
||||
export interface CoordinateSubrowSuggestion extends CoordinateSubrowLayout {
|
||||
column_samples: string[][];
|
||||
suggested_field_codes: Array<string | null>;
|
||||
}
|
||||
|
||||
export interface CoordinateReconstructionSuggestion {
|
||||
table_id: string;
|
||||
subrow_layouts: CoordinateSubrowSuggestion[];
|
||||
status: 'needs_review';
|
||||
}
|
||||
|
||||
export interface OrderProfileSamplePreview {
|
||||
@@ -85,5 +130,6 @@ export interface CreateOrderProfileFromSampleInput {
|
||||
row_structure: 'preserved' | 'unsupported_row_structure';
|
||||
column_rules: OrderProfileColumnRule[];
|
||||
drop_zero_qty: boolean;
|
||||
coordinate_reconstruction?: CoordinateReconstructionSettings | null;
|
||||
change_note?: string;
|
||||
}
|
||||
@@ -214,3 +214,36 @@ export interface ShippingOrderSchemaState {
|
||||
}>;
|
||||
}>;
|
||||
}
|
||||
|
||||
/** 受控货代履约能力及其版本化字段绑定。 */
|
||||
export interface ShippingFulfillmentCapability {
|
||||
capability_code: string;
|
||||
scope: ShippingOrderField['scope'];
|
||||
value_type: ShippingOrderField['value_type'];
|
||||
required: boolean;
|
||||
}
|
||||
|
||||
export interface ShippingFulfillmentPolicyBinding {
|
||||
capability_code: string;
|
||||
field_id: string;
|
||||
field_code: string;
|
||||
scope: ShippingOrderField['scope'];
|
||||
value_type: ShippingOrderField['value_type'];
|
||||
}
|
||||
|
||||
export interface ShippingFulfillmentPolicy {
|
||||
id: number;
|
||||
policy_code: 'SHIP_AVAILABLE_ROLLING_V1';
|
||||
version: number;
|
||||
status: 'draft' | 'published' | 'retired';
|
||||
definition: { field_bindings: ShippingFulfillmentPolicyBinding[] };
|
||||
checksum: string | null;
|
||||
lock_version: number;
|
||||
change_note: string | null;
|
||||
published_at: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingFulfillmentPolicyState {
|
||||
capabilities: ShippingFulfillmentCapability[];
|
||||
policies: ShippingFulfillmentPolicy[];
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* features/admin/views/AdminLayout.vue
|
||||
* 管理后台壳层:顶栏 + AdminNav + 子路由出口。
|
||||
* 角标仅在 Layout 首次挂载时 ensureBadges(store 内 60s TTL 缓存)。
|
||||
* 管理后台壳层:顶栏 + 左侧导航 + 子路由出口。
|
||||
* 依赖:AdminNav、vue-router、admin-nav.store。
|
||||
* 逻辑:AdminNav 统一承担模块和二级目录导航,内容区保持全宽展示当前页面。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue';
|
||||
@@ -44,7 +45,7 @@ onMounted(() => {
|
||||
|
||||
<main class="flex-1 w-full mx-auto px-4 md:px-8 py-6 md:py-8 flex flex-col md:flex-row gap-8 items-start">
|
||||
<AdminNav />
|
||||
<section class="flex-1 min-w-0 space-y-8 w-full">
|
||||
<section class="flex-1 min-w-0 w-full space-y-8">
|
||||
<router-view />
|
||||
</section>
|
||||
</main>
|
||||
|
||||
@@ -126,6 +126,18 @@ const statusLabel = computed(() => {
|
||||
<div v-if="match.matchedFields?.length" class="mt-1 text-xs text-muted">
|
||||
{{ t('chat.shippingNoticeDuplicateMatchFields', { fields: match.matchedFields.join(', ') }) }}
|
||||
</div>
|
||||
<div v-if="match.reservationDifferences?.length" class="mt-2 space-y-1 border-t border-default pt-2 text-xs">
|
||||
<p class="font-medium text-amber-700">{{ t('chat.shippingNoticeRevisionDifferences') }}</p>
|
||||
<p v-for="difference in match.reservationDifferences" :key="difference.reservationId">
|
||||
{{ t('chat.shippingNoticeRevisionDifference', {
|
||||
reservation: difference.reservationId,
|
||||
previousPart: difference.previous.partNumber,
|
||||
previousQty: difference.previous.qty,
|
||||
proposedPart: difference.proposed.partNumber,
|
||||
proposedQty: difference.proposed.qty,
|
||||
}) }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 space-y-2">
|
||||
|
||||
@@ -151,6 +151,17 @@ export function mapServerCandidate(remote: ShippingNoticeCandidateResponse): Shi
|
||||
matchType: item.match_type,
|
||||
matchedFields: listSafe(item.matched_fields),
|
||||
createdAt: item.created_at,
|
||||
reservationDifferences: (item.reservation_differences || []).map((difference) => ({
|
||||
reservationId: difference.reservation_id,
|
||||
previous: {
|
||||
partNumber: difference.previous.part_number,
|
||||
qty: difference.previous.qty,
|
||||
},
|
||||
proposed: {
|
||||
partNumber: difference.proposed.part_number,
|
||||
qty: difference.proposed.qty,
|
||||
},
|
||||
})),
|
||||
})),
|
||||
allowedActions: (remote.duplicate.allowed_actions || []) as ShippingDuplicateAction[],
|
||||
}
|
||||
|
||||
@@ -716,6 +716,11 @@ export interface ShippingDuplicateMatch {
|
||||
matched_fields: string[];
|
||||
lifecycle?: string;
|
||||
created_at?: string;
|
||||
reservation_differences?: Array<{
|
||||
reservation_id: string;
|
||||
previous: { part_number: string; qty: string };
|
||||
proposed: { part_number: string; qty: string };
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface ShippingDuplicateResult {
|
||||
|
||||
@@ -52,6 +52,11 @@ export interface ShippingDuplicateMatch {
|
||||
matchType: string;
|
||||
matchedFields: string[];
|
||||
createdAt?: string;
|
||||
reservationDifferences?: Array<{
|
||||
reservationId: string;
|
||||
previous: { partNumber: string; qty: string };
|
||||
proposed: { partNumber: string; qty: string };
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface ShippingDuplicateResult {
|
||||
|
||||
@@ -28,16 +28,20 @@
|
||||
"reports": "Data Reports",
|
||||
"schedules": "Schedule Management",
|
||||
"shippingCustomers": "Shipping Customers",
|
||||
"shippingConfig": "Shipping Configuration",
|
||||
"shippingInventory": "Inventory Configuration",
|
||||
"shippingIdentityRules": "Customer Identity Rules",
|
||||
"shippingOrderExtractionRuns": "Order Recognition Runs",
|
||||
"shippingConfig": "Shipping Management",
|
||||
"shippingOrderRecognition": "Order Recognition",
|
||||
"shippingInventoryManagement": "Inventory Management",
|
||||
"shippingRunAudit": "Run Audit",
|
||||
"shippingOrderFields": "Field Rules",
|
||||
"shippingInventory": "Inventory Management",
|
||||
"shippingIdentityRules": "Customer ID",
|
||||
"shippingOrderExtractionRuns": "Recognition Tasks",
|
||||
"platformApps": "Platform Apps",
|
||||
"shippingOrderDocumentProfiles": "Order Document Profiles"
|
||||
"shippingOrderDocumentProfiles": "Doc Templates"
|
||||
},
|
||||
"shippingOrderExtractionRuns": {
|
||||
"eyebrow": "READ-ONLY RUN DIAGNOSTICS",
|
||||
"title": "Order Recognition Runs",
|
||||
"title": "Recognition Tasks",
|
||||
"subtitle": "Inspect asynchronous order-recognition runs, job attempts, and redacted node lifecycles. Order content, prompts, inputs, outputs, and stack traces are never shown.",
|
||||
"refresh": "Refresh",
|
||||
"status": "Status",
|
||||
@@ -53,7 +57,7 @@
|
||||
"next": "Next",
|
||||
"loading": "Loading...",
|
||||
"empty": "No runs found",
|
||||
"loadFailed": "Failed to load order recognition runs",
|
||||
"loadFailed": "Failed to load recognition tasks",
|
||||
"detailFailed": "Failed to load run details",
|
||||
"detailTitle": "Run diagnostics",
|
||||
"workflowRunId": "Workflow Run ID",
|
||||
@@ -75,6 +79,28 @@
|
||||
"eyebrow": "Order field template",
|
||||
"title": "Order Template Configuration",
|
||||
"subtitle": "All EML, PDF, and Word orders share one published field contract. Published versions are immutable.",
|
||||
"fulfillmentEyebrow": "Shipping fulfillment governance",
|
||||
"fulfillmentTitle": "Field capabilities and shipping policy",
|
||||
"fulfillmentHint": "Only compatible fields from the published Schema can bind to controlled capabilities. Frozen orders retain the full policy snapshot.",
|
||||
"fulfillmentPublishedVersion": "Published policy V{version}",
|
||||
"fulfillmentNotPublished": "No fulfillment policy published",
|
||||
"fulfillmentSchemaRequired": "Publish an order Schema before selecting policy binding fields.",
|
||||
"fulfillmentRequired": "Required capability",
|
||||
"fulfillmentOptional": "Optional capability",
|
||||
"fulfillmentSelectField": "Select a compatible field",
|
||||
"fulfillmentChangeNote": "Policy change note (optional)",
|
||||
"fulfillmentChangeNotePlaceholder": "For example: use the customer reservation reference",
|
||||
"fulfillmentCreateDraft": "Create policy draft",
|
||||
"fulfillmentPublish": "Publish policy",
|
||||
"fulfillmentDraftCreated": "Fulfillment policy draft created",
|
||||
"fulfillmentPublished": "Fulfillment policy published; frozen orders are not reinterpreted",
|
||||
"fulfillmentDraftHint": "Policy draft V{version} has locked field bindings. Confirm and publish it.",
|
||||
"fulfillmentCapability": {
|
||||
"fulfillment.reservation_identity": "Reservation identity",
|
||||
"fulfillment.part_number": "Part number",
|
||||
"fulfillment.quantity": "Shipping quantity",
|
||||
"routing.inventory_source_hint": "Inventory source routing hint"
|
||||
},
|
||||
"schemaName": "Template name",
|
||||
"description": "Description",
|
||||
"initialize": "Initialize order template",
|
||||
@@ -369,13 +395,14 @@
|
||||
"orderHeaderIdentityHint": "Order information is a Header field and may provide customer or ship-to candidate evidence. It cannot auto-confirm a customer by itself. Item details do not support this setting."
|
||||
},
|
||||
"shippingInventory": {
|
||||
"title": "Shipping Configuration",
|
||||
"title": "Shipping Management",
|
||||
"subtitle": "Maintain one traceable shipping configuration flow from order fields and inventory parsing to shipping Excel files and inventory routing.",
|
||||
"eyebrow": "Shipping Configuration Workspace",
|
||||
"groupFoundation": "Foundation",
|
||||
"groupOrderRecognition": "Order Recognition",
|
||||
"groupInventory": "Inventory Management",
|
||||
"groupAudit": "Run Audit",
|
||||
"orderFields": "Order Parsing",
|
||||
"orderFields": "Order Field Rules",
|
||||
"orderSchemaRequired": "Publish an Order Fields version first; inventory parsing profiles, shipping Excel templates, and routing rules can then reference order fields.",
|
||||
"connections": "System Connections",
|
||||
"parsingProfiles": "Inventory Parsing",
|
||||
@@ -2469,6 +2496,55 @@
|
||||
"title": "Order Document Profiles",
|
||||
"subtitle": "Configure exact column mappings from MinerU table samples without editing JSON or fingerprints.",
|
||||
"structureBlocked": "This table has a structural error and cannot create a profile. Wait for coordinate-evidence reconstruction and review it; do not repair the raw grid with field mappings.",
|
||||
"reconstructionRequired": "This header contains line data. Confirm column boundaries and rebuild the table first; the result requires manual review.",
|
||||
"columnBoundaries": "Relative column boundaries (0 to 1, comma-separated)",
|
||||
"reconstructTable": "Rebuild table candidate",
|
||||
"confirmReconstruction": "I reviewed the rebuilt grid and allow it to be used for this profile draft",
|
||||
"reconstructionPreview": "Logical line reconstruction (continuations merged; manual review required)",
|
||||
"rowRole": { "header": "Field mapping", "data": "Active line", "deleted": "Deleted" },
|
||||
"sourceRows": "Source visual rows: {rows}",
|
||||
"rebuildAfterFieldMapping": "Field mappings changed. Rebuild the candidate again and review the final logical lines.",
|
||||
"multiSubrowEnabled": "Each line item spans multiple physical rows",
|
||||
"multiSubrowHint": "Row 1 must map its line-number column to line_no. Add rows 2, 3, 4, and beyond as needed; each row has independent boundaries that may overlap other rows.",
|
||||
"subrowColumn": "Column {index}",
|
||||
"firstSubrow": "Row 1 (starts an item)",
|
||||
"followingSubrow": "Row {index}",
|
||||
"addSubrow": "Add row layout",
|
||||
"autoSuggestLayout": "Auto-detect row layout",
|
||||
"autoSuggestLayoutHint": "The system derives row count and column boundaries from PDF/OCR character positions. Confirm fields using the sample text for each column.",
|
||||
"layoutSuggestionReady": "Row layout suggestions are ready. Confirm each field, then rebuild the table candidate.",
|
||||
"columnBoundariesAdvanced": "Column boundaries (advanced calibration; usually unchanged)",
|
||||
"columnSamples": "Samples: {samples}",
|
||||
"lineNoRequired": "Map the order line-number column in row 1 to line_no.",
|
||||
"layoutRow": "Physical row layout",
|
||||
"fieldMapping": "Column samples and field mapping",
|
||||
"rowActions": "Actions",
|
||||
"columnsUnit": "columns",
|
||||
"livePreview": "Live candidate",
|
||||
"livePreviewUpdating": "Updating from the current mapping…",
|
||||
"livePreviewReady": "Updated from the current mapping",
|
||||
"livePreviewWaitingLineNo": "Map the order line-number column in row 1 to line_no first",
|
||||
"livePreviewFailed": "Automatic update failed. Use Rebuild table candidate to view the error",
|
||||
"livePreviewEmpty": "Change a field or boundary to update the candidate here",
|
||||
"confirmPreview": "Confirm candidate",
|
||||
"visualBoundaries": "Visual column boundaries",
|
||||
"dragBoundaryHint": "Drag a blue divider to adjust",
|
||||
"boundaryHandle": "Column boundary {index}",
|
||||
"preciseBoundaryValues": "Exact boundary values",
|
||||
"sourceColumn": "Source",
|
||||
"sampleValue": "Sample value",
|
||||
"targetField": "Mapped field",
|
||||
"advancedSettings": "Advanced settings",
|
||||
"physicalRows": "Physical rows",
|
||||
"addColumn": "Add column",
|
||||
"insertColumnAfter": "Add after",
|
||||
"suggestCurrentRow": "Detect current row",
|
||||
"currentRowSuggestionReady": "The current physical row was detected. Other row settings are unchanged.",
|
||||
"autoSuggestAllRows": "Detect all rows",
|
||||
"reconstructionUnavailable": "This sample has no usable native PDF character coordinates. Upload a PDF with a text layer and try again.",
|
||||
"generateOcrEvidence": "Try OCR reconstruction",
|
||||
"ocrEvidenceReady": "OCR coordinates are ready. Set column boundaries, rebuild, and manually review the candidate grid.",
|
||||
"reconstructionBoundariesInvalid": "Column boundaries must start at 0, end at 1, and be strictly increasing.",
|
||||
"uploadSample": "Upload Template Sample",
|
||||
"uploadSampleHint": "PDF or EML only. It is used only for profile configuration and structural review; no shipping task is created.",
|
||||
"sampleFileTypeInvalid": "Only PDF or EML files are supported as profile samples.",
|
||||
@@ -2476,14 +2552,26 @@
|
||||
"createTitle": "Create Draft from Sample",
|
||||
"editTitle": "Update Draft from Sample",
|
||||
"sample": "Sample document",
|
||||
"searchSample": "Search samples by filename",
|
||||
"selectSample": "Select a parsed document",
|
||||
"tablesUnit": "tables",
|
||||
"sampleDetails": "Uploaded: {time}; parsing status: {status}",
|
||||
"templateSampleOnly": "This sample was uploaded from this page and can be deleted unless a blind test references it.",
|
||||
"businessSampleProtected": "This is a historical business attachment. It is available for review but cannot be deleted here.",
|
||||
"deleteSample": "Delete sample",
|
||||
"deleteSampleConfirm": "Delete this dedicated template sample? Its source file and parsed result will be removed.",
|
||||
"sampleDeleted": "Template sample deleted",
|
||||
"sampleReferencedByBlindTest": "This sample is referenced by a blind test and must be retained for audit.",
|
||||
"table": "Sample table",
|
||||
"selectTable": "Select a table",
|
||||
"code": "Profile code",
|
||||
"name": "Profile name",
|
||||
"schema": "Order schema version",
|
||||
"headerRow": "Header row index",
|
||||
"headerRow": "Last header row",
|
||||
"dataRow": "First data row",
|
||||
"multiRowHeaderMapping": "Multi-row header mapping",
|
||||
"multiRowHeaderHint": "Text in each column is merged from row 0 through row {end}. Map logical columns here; do not configure header rows as line-item layouts.",
|
||||
"mergedHeaderColumn": "Column {index}",
|
||||
"rowStructure": "Line row structure",
|
||||
"rowPreserved": "Table rows and columns are preserved; configure mappings",
|
||||
"rowUnsupported": "Structure is unreliable; register for manual review only",
|
||||
@@ -2497,6 +2585,8 @@
|
||||
"compositePart": "Composite customer/internal part",
|
||||
"previewEmpty": "Select a sample document and table to preview",
|
||||
"versions": "Profile versions",
|
||||
"currentVersion": "Current",
|
||||
"publishedAt": "Published: {time}",
|
||||
"publish": "Publish",
|
||||
"newVersion": "Create new version",
|
||||
"retire": "Retire",
|
||||
|
||||
@@ -72,6 +72,8 @@
|
||||
"shippingNoticeDuplicateMatchTask": "Matched task: {taskNo}",
|
||||
"shippingNoticeDuplicateMatchStatus": "Status: {status}",
|
||||
"shippingNoticeDuplicateMatchFields": "Matched fields: {fields}",
|
||||
"shippingNoticeRevisionDifferences": "This revision changes the following reservations:",
|
||||
"shippingNoticeRevisionDifference": "{reservation}: part number {previousPart} -> {proposedPart}; quantity {previousQty} -> {proposedQty}",
|
||||
"shippingNoticeDuplicateOpenExisting": "Open existing task",
|
||||
"shippingNoticeDuplicateOpenExistingHint": "Do not create a new task; link this file to the existing one.",
|
||||
"shippingNoticeDuplicateCreateRevision": "Create as a revision",
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
{
|
||||
"generic": "Request failed.",
|
||||
"codes": {
|
||||
"SHIPPING.FULFILLMENT_POLICY_INVALID": "The fulfillment policy or field capability binding is invalid.",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "The fulfillment policy was not found.",
|
||||
"SHIPPING.FULFILLMENT_POLICY_CONFLICT": "The fulfillment policy was changed by another administrator. Refresh and try again.",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_PUBLISHED": "No executable fulfillment policy has been published.",
|
||||
"SHIPPING.RESERVATION_PO_REQUIRED": "This reservation already exists. Provide the purchase order before continuing.",
|
||||
"SHIPPING.RESERVATION_PO_CONFLICT": "This reservation is already used by a different purchase order. The duplicate order is blocked.",
|
||||
"SHIPPING.RESERVATION_DUPLICATED_IN_ORDER": "The frozen order contains a duplicate reservation and cannot be frozen.",
|
||||
"SHIPPING.RESERVATION_REVISION_REVIEW_REQUIRED": "The reservation content changed. Show the differences and obtain manual confirmation.",
|
||||
"SHIPPING.RESERVATION_REVISION_LOCKED": "This reservation has an active shipment artifact or has been uploaded, so direct revision is forbidden.",
|
||||
"SHIPPING_NOTICE.BATCH_FILE_LIMIT_EXCEEDED": "The number of uploaded files exceeds the system limit. Split the batch and try again.",
|
||||
"AGENT.EXPOSURE_ROLE_IMMUTABLE": "An application and an internal executor cannot be converted into each other.",
|
||||
"AGENT.ADMIN_SCOPE_INVALID": "The application management tab parameter is invalid.",
|
||||
@@ -25,7 +34,10 @@
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_SCHEMA_INVALID": "The profile must bind to a published or retired order schema version.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_FIELD_INVALID": "The profile references an unavailable order line field.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_HEADER_CONTAMINATED": "The sample header contains order line data. Rebuild the table structure before creating a profile.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE": "This table has no usable native or OCR character coordinates for logical line reconstruction.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID": "The coordinate reconstruction settings or result are invalid. Check the column boundaries and try again.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_SAMPLE_FILE_TYPE_INVALID": "Only PDF or EML files are supported as profile samples.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED": "This template sample is still parsing, referenced by a blind test, or its file is used elsewhere and cannot be deleted.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_IMMUTABLE": "A published order document parsing profile cannot be modified.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_LOCK_VERSION_REQUIRED": "The profile lock version is missing. Refresh and try again.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT": "Another administrator changed the profile. Refresh and try again.",
|
||||
|
||||
@@ -28,15 +28,19 @@
|
||||
"reports": "รายงานข้อมูล",
|
||||
"schedules": "Schedule Management",
|
||||
"shippingCustomers": "ลูกค้าขนส่ง",
|
||||
"shippingConfig": "การตั้งค่าการจัดส่ง",
|
||||
"shippingInventory": "การตั้งค่าคลังสินค้า",
|
||||
"shippingIdentityRules": "กฎการระบุตัวตนลูกค้า",
|
||||
"shippingOrderExtractionRuns": "การทำงานระบุคำสั่งซื้อ",
|
||||
"shippingOrderDocumentProfiles": "โปรไฟล์เอกสารคำสั่งซื้อ"
|
||||
"shippingConfig": "การจัดการการจัดส่ง",
|
||||
"shippingOrderRecognition": "การระบุคำสั่งซื้อ",
|
||||
"shippingInventoryManagement": "การจัดการสต็อก",
|
||||
"shippingRunAudit": "ตรวจสอบงาน",
|
||||
"shippingOrderFields": "กฎฟิลด์",
|
||||
"shippingInventory": "การจัดการสต็อก",
|
||||
"shippingIdentityRules": "ระบุลูกค้า",
|
||||
"shippingOrderExtractionRuns": "งานระบุคำสั่งซื้อ",
|
||||
"shippingOrderDocumentProfiles": "แม่แบบเอกสาร"
|
||||
},
|
||||
"shippingOrderExtractionRuns": {
|
||||
"eyebrow": "การวินิจฉัยการทำงานแบบอ่านอย่างเดียว",
|
||||
"title": "การทำงานระบุคำสั่งซื้อ",
|
||||
"title": "งานระบุคำสั่งซื้อ",
|
||||
"subtitle": "ตรวจสอบการทำงานระบุคำสั่งซื้อแบบอะซิงโครนัส ความพยายามของ Job และวงจรโหนดที่ผ่านการปกปิดข้อมูล โดยไม่แสดงเนื้อหาคำสั่งซื้อ พรอมป์ต์ อินพุต เอาต์พุต หรือสแตกข้อผิดพลาด",
|
||||
"refresh": "รีเฟรช",
|
||||
"status": "สถานะ",
|
||||
@@ -52,7 +56,7 @@
|
||||
"next": "ถัดไป",
|
||||
"loading": "กำลังโหลด...",
|
||||
"empty": "ไม่มีรายการทำงาน",
|
||||
"loadFailed": "โหลดการทำงานระบุคำสั่งซื้อไม่สำเร็จ",
|
||||
"loadFailed": "โหลดงานระบุคำสั่งซื้อไม่สำเร็จ",
|
||||
"detailFailed": "โหลดรายละเอียดการทำงานไม่สำเร็จ",
|
||||
"detailTitle": "รายละเอียดการวินิจฉัย",
|
||||
"workflowRunId": "Workflow Run ID",
|
||||
@@ -74,6 +78,28 @@
|
||||
"eyebrow": "เทมเพลตฟิลด์คำสั่งซื้อ",
|
||||
"title": "การตั้งค่าเทมเพลตคำสั่งซื้อ",
|
||||
"subtitle": "คำสั่งซื้อ EML, PDF และ Word ทั้งหมดใช้สัญญาฟิลด์ที่เผยแพร่ชุดเดียว และแก้ไขเวอร์ชันที่เผยแพร่แล้วไม่ได้",
|
||||
"fulfillmentEyebrow": "การกำกับดูแลการจัดส่งของผู้ให้บริการขนส่ง",
|
||||
"fulfillmentTitle": "ความสามารถของฟิลด์และนโยบายการจัดส่ง",
|
||||
"fulfillmentHint": "เฉพาะฟิลด์ที่เข้ากันได้จาก Schema ที่เผยแพร่แล้วเท่านั้นที่ผูกกับความสามารถที่ควบคุมได้ และคำสั่งซื้อที่แช่แข็งจะเก็บสแนปช็อตนโยบายทั้งหมดไว้",
|
||||
"fulfillmentPublishedVersion": "นโยบายที่เผยแพร่ V{version}",
|
||||
"fulfillmentNotPublished": "ยังไม่มีนโยบายการจัดส่งที่เผยแพร่",
|
||||
"fulfillmentSchemaRequired": "เผยแพร่ Schema คำสั่งซื้อก่อนเลือกฟิลด์สำหรับผูกนโยบาย",
|
||||
"fulfillmentRequired": "ความสามารถที่จำเป็น",
|
||||
"fulfillmentOptional": "ความสามารถที่เลือกได้",
|
||||
"fulfillmentSelectField": "เลือกฟิลด์ที่เข้ากันได้",
|
||||
"fulfillmentChangeNote": "บันทึกการเปลี่ยนนโยบาย (ไม่บังคับ)",
|
||||
"fulfillmentChangeNotePlaceholder": "เช่น ใช้ฟิลด์ reservation ของลูกค้า",
|
||||
"fulfillmentCreateDraft": "สร้างร่างนโยบาย",
|
||||
"fulfillmentPublish": "เผยแพร่นโยบาย",
|
||||
"fulfillmentDraftCreated": "สร้างร่างนโยบายการจัดส่งแล้ว",
|
||||
"fulfillmentPublished": "เผยแพร่นโยบายการจัดส่งแล้ว คำสั่งซื้อที่แช่แข็งจะไม่ถูกตีความใหม่",
|
||||
"fulfillmentDraftHint": "ร่างนโยบาย V{version} ล็อกการผูกฟิลด์แล้ว โปรดยืนยันและเผยแพร่",
|
||||
"fulfillmentCapability": {
|
||||
"fulfillment.reservation_identity": "รหัส Reservation",
|
||||
"fulfillment.part_number": "หมายเลขชิ้นส่วน",
|
||||
"fulfillment.quantity": "จำนวนจัดส่ง",
|
||||
"routing.inventory_source_hint": "คำใบ้การกำหนดเส้นทางแหล่งสต็อก"
|
||||
},
|
||||
"schemaName": "ชื่อเทมเพลต",
|
||||
"description": "คำอธิบาย",
|
||||
"initialize": "เริ่มต้นเทมเพลตคำสั่งซื้อ",
|
||||
@@ -368,13 +394,14 @@
|
||||
"orderHeaderIdentityHint": "ข้อมูลคำสั่งซื้อเป็นฟิลด์ Header และใช้เป็นหลักฐานผู้สมัครสำหรับลูกค้าหรือสถานที่จัดส่งได้ ระบบจะไม่ยืนยันลูกค้าอัตโนมัติจากฟิลด์นี้เพียงอย่างเดียว และรายละเอียดสินค้าไม่รองรับการตั้งค่านี้"
|
||||
},
|
||||
"shippingInventory": {
|
||||
"title": "การตั้งค่าการจัดส่ง",
|
||||
"title": "การจัดการการจัดส่ง",
|
||||
"subtitle": "ดูแลสายการตั้งค่าการจัดส่งที่ตรวจสอบย้อนกลับได้ ตั้งแต่ฟิลด์คำสั่งซื้อ การอ่านสต็อก ไปจนถึง Excel สำหรับจัดส่งและการกำหนดเส้นทางสต็อก",
|
||||
"eyebrow": "พื้นที่ทำงานการตั้งค่าการจัดส่ง",
|
||||
"groupFoundation": "ข้อมูลพื้นฐาน",
|
||||
"groupOrderRecognition": "การระบุคำสั่งซื้อ",
|
||||
"groupInventory": "การจัดการสต็อก",
|
||||
"groupAudit": "บันทึกการทำงาน",
|
||||
"orderFields": "การอ่านคำสั่งซื้อ",
|
||||
"orderFields": "กฎฟิลด์คำสั่งซื้อ",
|
||||
"orderSchemaRequired": "โปรดเผยแพร่เวอร์ชันฟิลด์คำสั่งซื้อก่อน เพื่อให้โปรไฟล์การแยกวิเคราะห์สต็อก เทมเพลต Excel สำหรับจัดส่ง และกฎการกำหนดเส้นทางอ้างอิงฟิลด์คำสั่งซื้อได้",
|
||||
"connections": "การเชื่อมต่อระบบ",
|
||||
"parsingProfiles": "แผนการแยกวิเคราะห์ไฟล์สต็อก",
|
||||
@@ -2337,6 +2364,55 @@
|
||||
"title": "โปรไฟล์เอกสารคำสั่งซื้อ",
|
||||
"subtitle": "ตั้งค่าการแมปคอลัมน์จากตัวอย่างตาราง MinerU โดยไม่ต้องแก้ไข JSON หรือลายนิ้วมือโครงสร้าง",
|
||||
"structureBlocked": "ตารางนี้มีข้อผิดพลาดด้านโครงสร้างและไม่สามารถสร้างโปรไฟล์ได้ โปรดรอการสร้างใหม่จากหลักฐานพิกัดแล้วตรวจทาน ห้ามแก้กริดต้นฉบับด้วยการแมปฟิลด์",
|
||||
"reconstructionRequired": "หัวตารางนี้มีข้อมูลรายการ ต้องยืนยันขอบเขตคอลัมน์และสร้างตารางใหม่ก่อน โดยต้องตรวจทานผลลัพธ์ด้วยคน",
|
||||
"columnBoundaries": "ขอบเขตคอลัมน์สัมพัทธ์ (0 ถึง 1 คั่นด้วยจุลภาค)",
|
||||
"reconstructTable": "สร้างตารางตัวเลือกใหม่",
|
||||
"confirmReconstruction": "ฉันตรวจทานกริดที่สร้างใหม่แล้ว และอนุญาตให้ใช้กับฉบับร่างนี้",
|
||||
"reconstructionPreview": "รายการตรรกะที่สร้างใหม่ (รวมบรรทัดต่อเนื่องแล้ว ต้องตรวจทานด้วยคน)",
|
||||
"rowRole": { "header": "การแมปฟิลด์", "data": "รายการที่ใช้งาน", "deleted": "ลบแล้ว" },
|
||||
"sourceRows": "บรรทัดภาพต้นทาง: {rows}",
|
||||
"rebuildAfterFieldMapping": "การแมปฟิลด์เปลี่ยนแปลงแล้ว โปรดสร้างตัวเลือกใหม่อีกครั้งและตรวจทานรายการตรรกะสุดท้าย",
|
||||
"multiSubrowEnabled": "หนึ่งรายการประกอบด้วยหลายบรรทัด",
|
||||
"multiSubrowHint": "บรรทัดที่ 1 ต้องแมปคอลัมน์เลขรายการเป็น line_no สามารถเพิ่มบรรทัดที่ 2, 3, 4 และต่อไปได้ตามรูปแบบจริง โดยแต่ละบรรทัดมีขอบเขตคอลัมน์อิสระและซ้อนทับกันได้",
|
||||
"subrowColumn": "คอลัมน์ {index}",
|
||||
"firstSubrow": "บรรทัดที่ 1 (เริ่มรายการใหม่)",
|
||||
"followingSubrow": "บรรทัดที่ {index}",
|
||||
"addSubrow": "เพิ่มรูปแบบหนึ่งบรรทัด",
|
||||
"autoSuggestLayout": "ตรวจหารูปแบบบรรทัดอัตโนมัติ",
|
||||
"autoSuggestLayoutHint": "ระบบจะสร้างจำนวนบรรทัดและขอบเขตคอลัมน์จากตำแหน่งอักขระ PDF/OCR โปรดยืนยันฟิลด์จากข้อความตัวอย่างของแต่ละคอลัมน์",
|
||||
"layoutSuggestionReady": "สร้างคำแนะนำรูปแบบบรรทัดแล้ว โปรดยืนยันแต่ละฟิลด์แล้วสร้างตารางตัวอย่างใหม่",
|
||||
"columnBoundariesAdvanced": "ขอบเขตคอลัมน์ (การปรับขั้นสูง โดยปกติไม่ต้องแก้ไข)",
|
||||
"columnSamples": "ตัวอย่าง: {samples}",
|
||||
"lineNoRequired": "ต้องแมปคอลัมน์เลขรายการสั่งซื้อในบรรทัดที่ 1 เป็น line_no",
|
||||
"layoutRow": "รูปแบบบรรทัดจริง",
|
||||
"fieldMapping": "ตัวอย่างคอลัมน์และการแมปฟิลด์",
|
||||
"rowActions": "การดำเนินการ",
|
||||
"columnsUnit": "คอลัมน์",
|
||||
"livePreview": "ตัวเลือกแบบเรียลไทม์",
|
||||
"livePreviewUpdating": "กำลังอัปเดตตามการแมปปัจจุบัน…",
|
||||
"livePreviewReady": "อัปเดตตามการแมปปัจจุบันแล้ว",
|
||||
"livePreviewWaitingLineNo": "โปรดแมปคอลัมน์เลขรายการในบรรทัดที่ 1 เป็น line_no ก่อน",
|
||||
"livePreviewFailed": "อัปเดตอัตโนมัติไม่สำเร็จ โปรดใช้ปุ่มสร้างตารางตัวเลือกใหม่เพื่อดูข้อผิดพลาด",
|
||||
"livePreviewEmpty": "แก้ไขฟิลด์หรือขอบเขตคอลัมน์เพื่ออัปเดตตัวเลือกที่นี่",
|
||||
"confirmPreview": "ยืนยันตัวเลือก",
|
||||
"visualBoundaries": "ขอบเขตคอลัมน์แบบภาพ",
|
||||
"dragBoundaryHint": "ลากตัวแบ่งสีน้ำเงินเพื่อปรับ",
|
||||
"boundaryHandle": "ขอบเขตคอลัมน์ที่ {index}",
|
||||
"preciseBoundaryValues": "ค่าขอบเขตแบบละเอียด",
|
||||
"sourceColumn": "คอลัมน์เดิม",
|
||||
"sampleValue": "ค่าตัวอย่าง",
|
||||
"targetField": "ฟิลด์ที่แมป",
|
||||
"advancedSettings": "การตั้งค่าขั้นสูง",
|
||||
"physicalRows": "บรรทัดจริง",
|
||||
"addColumn": "เพิ่มคอลัมน์",
|
||||
"insertColumnAfter": "เพิ่มด้านหลัง",
|
||||
"suggestCurrentRow": "ตรวจหาบรรทัดปัจจุบัน",
|
||||
"currentRowSuggestionReady": "ตรวจพบบรรทัดจริงปัจจุบันแล้ว การตั้งค่าบรรทัดอื่นไม่เปลี่ยนแปลง",
|
||||
"autoSuggestAllRows": "ตรวจหาทุกบรรทัดอัตโนมัติ",
|
||||
"reconstructionUnavailable": "ตัวอย่างนี้ไม่มีพิกัดอักขระ PDF ที่ใช้งานได้ โปรดอัปโหลด PDF ที่มีชั้นข้อความแล้วลองอีกครั้ง",
|
||||
"generateOcrEvidence": "ลองสร้างใหม่ด้วย OCR",
|
||||
"ocrEvidenceReady": "สร้างพิกัด OCR แล้ว โปรดกำหนดขอบเขตคอลัมน์ สร้างใหม่ และตรวจทานกริดด้วยคน",
|
||||
"reconstructionBoundariesInvalid": "ขอบเขตคอลัมน์ต้องเริ่มที่ 0 สิ้นสุดที่ 1 และเพิ่มขึ้นอย่างเคร่งครัด",
|
||||
"uploadSample": "อัปโหลดตัวอย่างเทมเพลต",
|
||||
"uploadSampleHint": "รองรับเฉพาะ PDF หรือ EML ใช้สำหรับตั้งค่าโปรไฟล์และตรวจทานโครงสร้างเท่านั้น และไม่สร้างงานจัดส่ง",
|
||||
"sampleFileTypeInvalid": "ตัวอย่างโปรไฟล์รองรับเฉพาะไฟล์ PDF หรือ EML",
|
||||
@@ -2344,14 +2420,26 @@
|
||||
"createTitle": "สร้างฉบับร่างจากตัวอย่าง",
|
||||
"editTitle": "อัปเดตฉบับร่างจากตัวอย่าง",
|
||||
"sample": "เอกสารตัวอย่าง",
|
||||
"searchSample": "ค้นหาตัวอย่างตามชื่อไฟล์",
|
||||
"selectSample": "เลือกเอกสารที่แยกข้อมูลแล้ว",
|
||||
"tablesUnit": "ตาราง",
|
||||
"sampleDetails": "อัปโหลด: {time}; สถานะการแยกข้อมูล: {status}",
|
||||
"templateSampleOnly": "ตัวอย่างนี้อัปโหลดจากหน้านี้และลบได้หากไม่มี Blind Test อ้างอิง",
|
||||
"businessSampleProtected": "นี่คือไฟล์แนบทางธุรกิจเดิม ใช้ตรวจทานได้ แต่ลบจากหน้านี้ไม่ได้",
|
||||
"deleteSample": "ลบตัวอย่าง",
|
||||
"deleteSampleConfirm": "ลบตัวอย่างเทมเพลตนี้หรือไม่ ไฟล์ต้นทางและผลการแยกข้อมูลจะถูกลบ",
|
||||
"sampleDeleted": "ลบตัวอย่างเทมเพลตแล้ว",
|
||||
"sampleReferencedByBlindTest": "ตัวอย่างนี้ถูกอ้างอิงโดย Blind Test และต้องเก็บไว้เพื่อการตรวจสอบ",
|
||||
"table": "ตารางตัวอย่าง",
|
||||
"selectTable": "เลือกตาราง",
|
||||
"code": "รหัสโปรไฟล์",
|
||||
"name": "ชื่อโปรไฟล์",
|
||||
"schema": "เวอร์ชันสคีมาคำสั่งซื้อ",
|
||||
"headerRow": "ดัชนีแถวหัวตาราง",
|
||||
"headerRow": "แถวหัวตารางสุดท้าย",
|
||||
"dataRow": "แถวข้อมูลแรก",
|
||||
"multiRowHeaderMapping": "การแมปหัวตารางหลายแถว",
|
||||
"multiRowHeaderHint": "ระบบรวมข้อความในคอลัมน์เดียวกันตั้งแต่แถว 0 ถึงแถว {end} ให้แมปคอลัมน์เชิงตรรกะที่นี่ และอย่ากำหนดแถวหัวตารางเป็นรูปแบบรายการ",
|
||||
"mergedHeaderColumn": "คอลัมน์ {index}",
|
||||
"rowStructure": "โครงสร้างแถวรายการ",
|
||||
"rowPreserved": "โครงสร้างแถวและคอลัมน์ครบถ้วน สามารถตั้งค่าการแมปได้",
|
||||
"rowUnsupported": "โครงสร้างไม่น่าเชื่อถือ ลงทะเบียนเพื่อให้ตรวจสอบด้วยคนเท่านั้น",
|
||||
@@ -2365,6 +2453,8 @@
|
||||
"compositePart": "รหัสลูกค้า/ภายในแบบผสม",
|
||||
"previewEmpty": "เลือกเอกสารและตารางตัวอย่างเพื่อดูตัวอย่าง",
|
||||
"versions": "เวอร์ชันโปรไฟล์",
|
||||
"currentVersion": "ใช้งานอยู่",
|
||||
"publishedAt": "เผยแพร่: {time}",
|
||||
"publish": "เผยแพร่",
|
||||
"newVersion": "สร้างเวอร์ชันใหม่",
|
||||
"retire": "ยกเลิกใช้งาน",
|
||||
|
||||
@@ -72,6 +72,8 @@
|
||||
"shippingNoticeDuplicateMatchTask": "งานที่ตรงกัน: {taskNo}",
|
||||
"shippingNoticeDuplicateMatchStatus": "สถานะ: {status}",
|
||||
"shippingNoticeDuplicateMatchFields": "ฟิลด์ที่ตรงกัน: {fields}",
|
||||
"shippingNoticeRevisionDifferences": "การแก้ไขนี้จะเปลี่ยน Reservation ต่อไปนี้:",
|
||||
"shippingNoticeRevisionDifference": "{reservation}: หมายเลขชิ้นส่วน {previousPart} -> {proposedPart}; จำนวน {previousQty} -> {proposedQty}",
|
||||
"shippingNoticeDuplicateOpenExisting": "เปิดงานที่มีอยู่",
|
||||
"shippingNoticeDuplicateOpenExistingHint": "ไม่สร้างงานใหม่ แต่ผูกไฟล์นี้กับงานเดิม",
|
||||
"shippingNoticeDuplicateCreateRevision": "สร้างเป็นเวอร์ชันแก้ไข",
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
{
|
||||
"generic": "คำขอล้มเหลว",
|
||||
"codes": {
|
||||
"SHIPPING.FULFILLMENT_POLICY_INVALID": "นโยบายการปฏิบัติตามหรือการผูกความสามารถของฟิลด์ไม่ถูกต้อง",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "ไม่พบนโยบายการปฏิบัติตาม",
|
||||
"SHIPPING.FULFILLMENT_POLICY_CONFLICT": "นโยบายการปฏิบัติตามถูกแก้ไขโดยผู้ดูแลรายอื่น โปรดรีเฟรชแล้วลองใหม่",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_PUBLISHED": "ยังไม่มีการเผยแพร่นโยบายการปฏิบัติตามที่ใช้งานได้",
|
||||
"SHIPPING.RESERVATION_PO_REQUIRED": "Reservation นี้มีอยู่แล้ว ต้องระบุใบสั่งซื้อก่อนดำเนินการต่อ",
|
||||
"SHIPPING.RESERVATION_PO_CONFLICT": "Reservation นี้ถูกใช้กับใบสั่งซื้ออื่นแล้ว ระบบบล็อกคำสั่งซื้อซ้ำ",
|
||||
"SHIPPING.RESERVATION_DUPLICATED_IN_ORDER": "พบ Reservation ซ้ำในคำสั่งซื้อเดียวกัน จึงไม่สามารถตรึงคำสั่งซื้อได้",
|
||||
"SHIPPING.RESERVATION_REVISION_REVIEW_REQUIRED": "ข้อมูล Reservation เปลี่ยนแปลง ต้องแสดงความแตกต่างและให้มนุษย์ยืนยัน",
|
||||
"SHIPPING.RESERVATION_REVISION_LOCKED": "Reservation นี้มีไฟล์จัดส่งที่ยังใช้ได้หรืออัปโหลดแล้ว จึงห้ามแก้ไขโดยตรง",
|
||||
"SHIPPING_NOTICE.BATCH_FILE_LIMIT_EXCEEDED": "จำนวนไฟล์ที่อัปโหลดเกินขีดจำกัดของระบบ โปรดแบ่งชุดแล้วลองใหม่",
|
||||
"AGENT.EXPOSURE_ROLE_IMMUTABLE": "ไม่สามารถแปลงแอปพลิเคชันเป็นตัวดำเนินการภายในหรือกลับกันได้",
|
||||
"AGENT.ADMIN_SCOPE_INVALID": "พารามิเตอร์แท็บการจัดการแอปพลิเคชันไม่ถูกต้อง",
|
||||
@@ -25,7 +34,10 @@
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_SCHEMA_INVALID": "โปรไฟล์ต้องผูกกับเวอร์ชันสคีมาคำสั่งซื้อที่เผยแพร่หรือเลิกใช้งานแล้ว",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_FIELD_INVALID": "โปรไฟล์อ้างอิงฟิลด์รายการคำสั่งซื้อที่ไม่พร้อมใช้งาน",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_HEADER_CONTAMINATED": "ส่วนหัวของตัวอย่างมีข้อมูลรายการคำสั่งซื้อ ต้องสร้างโครงสร้างตารางใหม่ก่อนจึงจะสร้างโปรไฟล์ได้",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE": "ตารางนี้ไม่มีพิกัดอักขระแบบต้นฉบับหรือ OCR ที่ใช้งานได้สำหรับสร้างรายการตรรกะใหม่",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID": "การตั้งค่าหรือผลลัพธ์การสร้างใหม่ด้วยพิกัดไม่ถูกต้อง โปรดตรวจสอบขอบเขตคอลัมน์แล้วลองอีกครั้ง",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_SAMPLE_FILE_TYPE_INVALID": "ตัวอย่างโปรไฟล์รองรับเฉพาะไฟล์ PDF หรือ EML",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED": "ตัวอย่างเทมเพลตนี้ยังอยู่ระหว่างแยกข้อมูล ถูกอ้างอิงโดย Blind Test หรือไฟล์ถูกใช้โดยงานอื่น จึงลบไม่ได้",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_IMMUTABLE": "ไม่สามารถแก้ไขโปรไฟล์เอกสารคำสั่งซื้อที่เผยแพร่แล้ว",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_LOCK_VERSION_REQUIRED": "ไม่มีเวอร์ชันล็อกของโปรไฟล์ โปรดรีเฟรชแล้วลองใหม่",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT": "ผู้ดูแลระบบรายอื่นแก้ไขโปรไฟล์แล้ว โปรดรีเฟรชแล้วลองใหม่",
|
||||
|
||||
@@ -29,15 +29,19 @@
|
||||
"reports": "数据报表",
|
||||
"schedules": "排程管理",
|
||||
"shippingCustomers": "货代客户",
|
||||
"shippingConfig": "货代配置",
|
||||
"shippingInventory": "库存配置",
|
||||
"shippingIdentityRules": "客户识别规则",
|
||||
"shippingOrderExtractionRuns": "订单识别运行",
|
||||
"shippingOrderDocumentProfiles": "订单文档模板"
|
||||
"shippingConfig": "货代管理",
|
||||
"shippingOrderRecognition": "订单识别",
|
||||
"shippingInventoryManagement": "库存管理",
|
||||
"shippingRunAudit": "运行审计",
|
||||
"shippingOrderFields": "字段规则",
|
||||
"shippingInventory": "库存管理",
|
||||
"shippingIdentityRules": "客户识别",
|
||||
"shippingOrderExtractionRuns": "识别任务",
|
||||
"shippingOrderDocumentProfiles": "文档模板"
|
||||
},
|
||||
"shippingOrderExtractionRuns": {
|
||||
"eyebrow": "只读运行诊断",
|
||||
"title": "订单识别运行",
|
||||
"title": "识别任务",
|
||||
"subtitle": "用于排查异步订单识别的运行、重试尝试与脱敏节点生命周期;不展示订单正文、提示词、输入输出或错误堆栈。",
|
||||
"refresh": "刷新",
|
||||
"status": "状态",
|
||||
@@ -53,7 +57,7 @@
|
||||
"next": "下一页",
|
||||
"loading": "正在加载...",
|
||||
"empty": "暂无运行记录",
|
||||
"loadFailed": "加载订单识别运行失败",
|
||||
"loadFailed": "加载识别任务失败",
|
||||
"detailFailed": "加载运行详情失败",
|
||||
"detailTitle": "运行诊断详情",
|
||||
"workflowRunId": "Workflow Run ID",
|
||||
@@ -75,6 +79,28 @@
|
||||
"eyebrow": "订单字段模板",
|
||||
"title": "订单模板配置",
|
||||
"subtitle": "所有 EML、PDF 和 Word 订单共享同一份已发布字段契约;发布后版本不可原地修改。",
|
||||
"fulfillmentEyebrow": "货代履约治理",
|
||||
"fulfillmentTitle": "字段能力与发货策略",
|
||||
"fulfillmentHint": "仅可把已发布 Schema 中作用域和格式兼容的字段绑定到受控能力;冻结订单会保留完整策略快照。",
|
||||
"fulfillmentPublishedVersion": "已发布策略 V{version}",
|
||||
"fulfillmentNotPublished": "尚未发布履约策略",
|
||||
"fulfillmentSchemaRequired": "请先发布订单 Schema,才能选择策略绑定字段。",
|
||||
"fulfillmentRequired": "必需能力",
|
||||
"fulfillmentOptional": "可选能力",
|
||||
"fulfillmentSelectField": "请选择兼容字段",
|
||||
"fulfillmentChangeNote": "策略变更说明(可选)",
|
||||
"fulfillmentChangeNotePlaceholder": "例如:改用客户预约单字段",
|
||||
"fulfillmentCreateDraft": "创建策略草稿",
|
||||
"fulfillmentPublish": "发布策略",
|
||||
"fulfillmentDraftCreated": "履约策略草稿已创建",
|
||||
"fulfillmentPublished": "履约策略已发布,历史冻结订单不会被重解释",
|
||||
"fulfillmentDraftHint": "策略草稿 V{version} 已锁定字段绑定,请确认后发布。",
|
||||
"fulfillmentCapability": {
|
||||
"fulfillment.reservation_identity": "Reservation 标识",
|
||||
"fulfillment.part_number": "内部料号",
|
||||
"fulfillment.quantity": "发货数量",
|
||||
"routing.inventory_source_hint": "库存源路由线索"
|
||||
},
|
||||
"schemaName": "模板名称",
|
||||
"description": "说明",
|
||||
"initialize": "初始化订单模板",
|
||||
@@ -369,14 +395,15 @@
|
||||
"operationFailed": "订单模板操作失败"
|
||||
},
|
||||
"shippingInventory": {
|
||||
"title": "货代配置",
|
||||
"title": "货代管理",
|
||||
"subtitle": "从订单字段、库存解析到发货 Excel 和库存路由,维护一条可追溯的发货配置链路。",
|
||||
"eyebrow": "货代发货配置工作台",
|
||||
"groupFoundation": "基础定义",
|
||||
"groupOrderRecognition": "订单识别",
|
||||
"groupInventory": "库存管理",
|
||||
"groupAudit": "运行审计",
|
||||
"orderFields": "订单解析",
|
||||
"orderSchemaRequired": "请先在“订单解析”发布一个版本;库存解析、发货模板和路由规则才能引用订单字段。",
|
||||
"orderFields": "订单字段规则",
|
||||
"orderSchemaRequired": "请先在“订单字段规则”发布一个版本;库存解析、发货模板和路由规则才能引用订单字段。",
|
||||
"connections": "系统连接",
|
||||
"parsingProfiles": "库存解析",
|
||||
"parsingProfilesHelp": "维护可由多个库存站点共享的库存文件结构、字段对应关系和订单字段匹配键。",
|
||||
@@ -576,7 +603,7 @@
|
||||
"saving": "保存中...",
|
||||
"publish": "发布规则",
|
||||
"retire": "归档规则",
|
||||
"flowOrder": "订单解析",
|
||||
"flowOrder": "订单字段规则",
|
||||
"flowInventory": "库存解析",
|
||||
"flowTemplate": "发货模板",
|
||||
"flowRoute": "路由规则",
|
||||
@@ -2447,6 +2474,55 @@
|
||||
"title": "订单文档模板",
|
||||
"subtitle": "从 MinerU 表格样本可视化配置精确列映射;无需编辑 JSON 或结构指纹。",
|
||||
"structureBlocked": "该表格结构异常,不能创建模板。请等待坐标证据重建后再复核,勿通过字段映射修复原始网格。",
|
||||
"reconstructionRequired": "此表头混入明细,需先确认列边界并重建表格;重建结果必须人工审核。",
|
||||
"columnBoundaries": "相对列边界(0 到 1,逗号分隔)",
|
||||
"reconstructTable": "重建表格候选",
|
||||
"confirmReconstruction": "我已审核重建网格,允许将其用于此模板草稿",
|
||||
"reconstructionPreview": "逻辑明细重建候选(续行已合并,待人工审核)",
|
||||
"rowRole": { "header": "字段映射", "data": "有效明细", "deleted": "已删除" },
|
||||
"sourceRows": "来源物理行:{rows}",
|
||||
"rebuildAfterFieldMapping": "字段映射已变化,请再次点击“重建表格候选”并审核最终逻辑明细。",
|
||||
"multiSubrowEnabled": "此模板的一条明细由多行组成",
|
||||
"multiSubrowHint": "第 1 行必须将行号列映射为 line_no;可按实际版式继续增加第 2、3、4…行,每行均可使用独立且相互重叠的列边界。",
|
||||
"subrowColumn": "第 {index} 列",
|
||||
"firstSubrow": "第 1 行(新明细起始)",
|
||||
"followingSubrow": "第 {index} 行",
|
||||
"addSubrow": "增加一行版式",
|
||||
"autoSuggestLayout": "自动识别行版式",
|
||||
"autoSuggestLayoutHint": "系统将根据 PDF/OCR 字符位置自动生成行数和列边界;请根据每列示例文字确认字段。",
|
||||
"layoutSuggestionReady": "已生成行版式建议,请确认各列字段后重建表格候选。",
|
||||
"columnBoundariesAdvanced": "列边界(高级校准,通常无需修改)",
|
||||
"columnSamples": "示例:{samples}",
|
||||
"lineNoRequired": "第 1 行必须将订单行号所在列映射为 line_no。",
|
||||
"layoutRow": "物理行版式",
|
||||
"fieldMapping": "列示例与字段映射",
|
||||
"rowActions": "操作",
|
||||
"columnsUnit": "列",
|
||||
"livePreview": "实时候选",
|
||||
"livePreviewUpdating": "正在按当前映射更新…",
|
||||
"livePreviewReady": "已按当前映射更新",
|
||||
"livePreviewWaitingLineNo": "请先将第 1 行的订单行号列映射为 line_no",
|
||||
"livePreviewFailed": "自动更新失败,可点击“重建表格候选”查看错误",
|
||||
"livePreviewEmpty": "修改字段或列边界后,候选结果将在此自动更新",
|
||||
"confirmPreview": "确认候选",
|
||||
"visualBoundaries": "可视化列边界",
|
||||
"dragBoundaryHint": "拖动蓝色分隔点调整",
|
||||
"boundaryHandle": "第 {index} 个列边界",
|
||||
"preciseBoundaryValues": "精确边界值",
|
||||
"sourceColumn": "原列",
|
||||
"sampleValue": "样例内容",
|
||||
"targetField": "映射字段",
|
||||
"advancedSettings": "高级设置",
|
||||
"physicalRows": "物理行",
|
||||
"addColumn": "添加列",
|
||||
"insertColumnAfter": "后新增",
|
||||
"suggestCurrentRow": "识别当前行",
|
||||
"currentRowSuggestionReady": "当前物理行已识别,其他行配置保持不变。",
|
||||
"autoSuggestAllRows": "自动识别全部行",
|
||||
"reconstructionUnavailable": "此样本没有可用的 PDF 原生字符坐标;请上传带文本层的 PDF 样本后重试。",
|
||||
"generateOcrEvidence": "尝试 OCR 重建",
|
||||
"ocrEvidenceReady": "OCR 坐标已生成。请继续填写列边界、重建并人工审核候选网格。",
|
||||
"reconstructionBoundariesInvalid": "列边界必须从 0 开始、以 1 结束,并按从小到大排列。",
|
||||
"uploadSample": "上传模板样本",
|
||||
"uploadSampleHint": "仅支持 PDF 或 EML,仅用于模板配置和结构复核,不创建发货任务。",
|
||||
"sampleFileTypeInvalid": "模板样本仅支持 PDF 或 EML 文件。",
|
||||
@@ -2454,14 +2530,26 @@
|
||||
"createTitle": "从样本创建草稿",
|
||||
"editTitle": "用样本更新草稿",
|
||||
"sample": "样本文档",
|
||||
"searchSample": "按文件名搜索样本",
|
||||
"selectSample": "选择已解析文档",
|
||||
"tablesUnit": "张表",
|
||||
"sampleDetails": "上传时间:{time};解析状态:{status}",
|
||||
"templateSampleOnly": "这是模板页上传的专用样本;未被盲测引用时可以删除。",
|
||||
"businessSampleProtected": "这是历史业务附件,仅用于复核,不能在模板页删除。",
|
||||
"deleteSample": "删除样本",
|
||||
"deleteSampleConfirm": "确认删除这个模板专用样本?此操作会删除源文件和解析结果。",
|
||||
"sampleDeleted": "模板样本已删除",
|
||||
"sampleReferencedByBlindTest": "此样本已被盲测引用,必须保留审计记录,不能删除。",
|
||||
"table": "样本表格",
|
||||
"selectTable": "选择表格",
|
||||
"code": "模板编码",
|
||||
"name": "模板名称",
|
||||
"schema": "订单字段版本",
|
||||
"headerRow": "表头行索引",
|
||||
"headerRow": "表头结束行",
|
||||
"dataRow": "数据起始行",
|
||||
"multiRowHeaderMapping": "多行表头字段映射",
|
||||
"multiRowHeaderHint": "系统合并第 0 行至第 {end} 行的同列文字;这里只配置逻辑列字段,不要把表头行配置成明细行版式。",
|
||||
"mergedHeaderColumn": "第 {index} 列",
|
||||
"rowStructure": "明细行结构",
|
||||
"rowPreserved": "表格行列结构完整,可配置列映射",
|
||||
"rowUnsupported": "结构不可靠,仅登记模板并转人工复核",
|
||||
@@ -2475,6 +2563,8 @@
|
||||
"compositePart": "复合客户/内部料号",
|
||||
"previewEmpty": "请选择样本文档和表格查看预览",
|
||||
"versions": "模板版本",
|
||||
"currentVersion": "当前生效",
|
||||
"publishedAt": "发布时间:{time}",
|
||||
"publish": "发布",
|
||||
"newVersion": "创建新版本",
|
||||
"retire": "退役",
|
||||
|
||||
@@ -72,6 +72,8 @@
|
||||
"shippingNoticeDuplicateMatchTask": "命中任务:{taskNo}",
|
||||
"shippingNoticeDuplicateMatchStatus": "状态:{status}",
|
||||
"shippingNoticeDuplicateMatchFields": "匹配依据:{fields}",
|
||||
"shippingNoticeRevisionDifferences": "本次修订将变更以下 Reservation:",
|
||||
"shippingNoticeRevisionDifference": "{reservation}:料号 {previousPart} → {proposedPart};数量 {previousQty} → {proposedQty}",
|
||||
"shippingNoticeDuplicateOpenExisting": "打开已有任务",
|
||||
"shippingNoticeDuplicateOpenExistingHint": "不创建新任务,将当前附件关联到已有任务。",
|
||||
"shippingNoticeDuplicateCreateRevision": "作为修订版本创建",
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
{
|
||||
"generic": "请求失败。",
|
||||
"codes": {
|
||||
"SHIPPING.FULFILLMENT_POLICY_INVALID": "货代履约策略或字段能力绑定无效。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "未找到货代履约策略。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_CONFLICT": "货代履约策略已被其他管理员修改,请刷新后重试。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_PUBLISHED": "尚未发布可执行的货代履约策略。",
|
||||
"SHIPPING.RESERVATION_PO_REQUIRED": "该预定单号已存在,必须补齐采购订单后才能继续。",
|
||||
"SHIPPING.RESERVATION_PO_CONFLICT": "该预定单号已被其他采购订单使用,已阻断重复订单。",
|
||||
"SHIPPING.RESERVATION_DUPLICATED_IN_ORDER": "同一订单中存在重复的预定单号,无法冻结。",
|
||||
"SHIPPING.RESERVATION_REVISION_REVIEW_REQUIRED": "该预定单号内容已变更,必须展示差异并经人工确认。",
|
||||
"SHIPPING.RESERVATION_REVISION_LOCKED": "该预定单号已生成有效发货文件或已上传,禁止直接修订。",
|
||||
"SHIPPING_NOTICE.BATCH_FILE_LIMIT_EXCEEDED": "本次上传文件数超过系统限制,请拆分后重试。",
|
||||
"AGENT.EXPOSURE_ROLE_IMMUTABLE": "应用与内部执行器不可互相转换。",
|
||||
"AGENT.ADMIN_SCOPE_INVALID": "应用管理页签参数无效。",
|
||||
@@ -25,7 +34,10 @@
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_SCHEMA_INVALID": "订单文档解析模板必须绑定已发布或已退役的订单字段版本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_FIELD_INVALID": "订单文档解析模板引用了不可用的订单明细字段。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_HEADER_CONTAMINATED": "样本表头混入订单明细,必须先重建表格结构,不能创建模板。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE": "当前表格缺少可用的原生或 OCR 字符坐标,无法重建逻辑明细。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID": "坐标重建配置或结果无效,请检查列边界后重试。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_SAMPLE_FILE_TYPE_INVALID": "模板样本仅支持 PDF 或 EML 文件。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED": "该模板样本仍在解析、被盲测引用或其文件被其他业务使用,不能删除。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_IMMUTABLE": "已发布的订单文档解析模板不可修改。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_LOCK_VERSION_REQUIRED": "订单文档解析模板缺少版本锁,请刷新后重试。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT": "订单文档解析模板已被其他管理员修改,请刷新后重试。",
|
||||
|
||||
@@ -28,15 +28,19 @@
|
||||
"reports": "數據報表",
|
||||
"schedules": "排程管理",
|
||||
"shippingCustomers": "貨代客戶",
|
||||
"shippingConfig": "貨代設定",
|
||||
"shippingInventory": "庫存設定",
|
||||
"shippingIdentityRules": "客戶識別規則",
|
||||
"shippingOrderExtractionRuns": "訂單識別運行",
|
||||
"shippingOrderDocumentProfiles": "訂單文件範本"
|
||||
"shippingConfig": "貨代管理",
|
||||
"shippingOrderRecognition": "訂單識別",
|
||||
"shippingInventoryManagement": "庫存管理",
|
||||
"shippingRunAudit": "執行稽核",
|
||||
"shippingOrderFields": "欄位規則",
|
||||
"shippingInventory": "庫存管理",
|
||||
"shippingIdentityRules": "客戶識別",
|
||||
"shippingOrderExtractionRuns": "識別任務",
|
||||
"shippingOrderDocumentProfiles": "文件範本"
|
||||
},
|
||||
"shippingOrderExtractionRuns": {
|
||||
"eyebrow": "唯讀執行診斷",
|
||||
"title": "訂單識別運行",
|
||||
"title": "識別任務",
|
||||
"subtitle": "用於排查非同步訂單識別的運行、重試嘗試與脫敏節點生命週期;不顯示訂單正文、提示詞、輸入輸出或錯誤堆疊。",
|
||||
"refresh": "重新整理",
|
||||
"status": "狀態",
|
||||
@@ -52,7 +56,7 @@
|
||||
"next": "下一頁",
|
||||
"loading": "正在載入...",
|
||||
"empty": "暫無運行記錄",
|
||||
"loadFailed": "載入訂單識別運行失敗",
|
||||
"loadFailed": "載入識別任務失敗",
|
||||
"detailFailed": "載入運行詳情失敗",
|
||||
"detailTitle": "運行診斷詳情",
|
||||
"workflowRunId": "Workflow Run ID",
|
||||
@@ -74,6 +78,28 @@
|
||||
"eyebrow": "訂單欄位範本",
|
||||
"title": "訂單範本設定",
|
||||
"subtitle": "所有 EML、PDF 和 Word 訂單共享同一份已發布欄位契約;發布後版本不可原地修改。",
|
||||
"fulfillmentEyebrow": "貨代履約治理",
|
||||
"fulfillmentTitle": "欄位能力與出貨策略",
|
||||
"fulfillmentHint": "只能把已發布 Schema 中範圍和格式相容的欄位綁定到受控能力;凍結訂單會保留完整策略快照。",
|
||||
"fulfillmentPublishedVersion": "已發布策略 V{version}",
|
||||
"fulfillmentNotPublished": "尚未發布履約策略",
|
||||
"fulfillmentSchemaRequired": "請先發布訂單 Schema,才能選擇策略綁定欄位。",
|
||||
"fulfillmentRequired": "必要能力",
|
||||
"fulfillmentOptional": "選用能力",
|
||||
"fulfillmentSelectField": "請選擇相容欄位",
|
||||
"fulfillmentChangeNote": "策略變更說明(選填)",
|
||||
"fulfillmentChangeNotePlaceholder": "例如:改用客戶預約單欄位",
|
||||
"fulfillmentCreateDraft": "建立策略草稿",
|
||||
"fulfillmentPublish": "發布策略",
|
||||
"fulfillmentDraftCreated": "履約策略草稿已建立",
|
||||
"fulfillmentPublished": "履約策略已發布,歷史凍結訂單不會被重新解讀",
|
||||
"fulfillmentDraftHint": "策略草稿 V{version} 已鎖定欄位綁定,請確認後發布。",
|
||||
"fulfillmentCapability": {
|
||||
"fulfillment.reservation_identity": "Reservation 識別",
|
||||
"fulfillment.part_number": "內部料號",
|
||||
"fulfillment.quantity": "出貨數量",
|
||||
"routing.inventory_source_hint": "庫存來源路由線索"
|
||||
},
|
||||
"schemaName": "範本名稱",
|
||||
"description": "說明",
|
||||
"initialize": "初始化訂單範本",
|
||||
@@ -368,14 +394,15 @@
|
||||
"orderHeaderIdentityHint": "訂單資訊屬於 Header 欄位,可作為客戶或送貨站點候選證據;系統不會只憑此欄位自動確認客戶。貨品明細不支援此設定。"
|
||||
},
|
||||
"shippingInventory": {
|
||||
"title": "貨代設定",
|
||||
"title": "貨代管理",
|
||||
"subtitle": "從訂單欄位、庫存解析到發貨 Excel 與庫存路由,維護一條可追溯的發貨設定鏈路。",
|
||||
"eyebrow": "貨代發貨設定工作台",
|
||||
"groupFoundation": "基礎定義",
|
||||
"groupOrderRecognition": "訂單識別",
|
||||
"groupInventory": "庫存管理",
|
||||
"groupAudit": "執行稽核",
|
||||
"orderFields": "訂單解析",
|
||||
"orderSchemaRequired": "請先在「訂單解析」發佈一個版本;庫存解析、出貨範本和路由規則才能引用訂單欄位。",
|
||||
"orderFields": "訂單欄位規則",
|
||||
"orderSchemaRequired": "請先在「訂單欄位規則」發佈一個版本;庫存解析、出貨範本和路由規則才能引用訂單欄位。",
|
||||
"connections": "系統連線",
|
||||
"parsingProfiles": "庫存解析",
|
||||
"parsingProfilesHelp": "維護可由多個庫存站點共用的庫存檔案結構、欄位對應與訂單欄位匹配鍵。",
|
||||
@@ -575,7 +602,7 @@
|
||||
"saving": "儲存中...",
|
||||
"publish": "發布規則",
|
||||
"retire": "歸檔規則",
|
||||
"flowOrder": "訂單解析",
|
||||
"flowOrder": "訂單欄位規則",
|
||||
"flowInventory": "庫存解析",
|
||||
"flowTemplate": "發貨模板",
|
||||
"flowRoute": "路由規則",
|
||||
@@ -2337,6 +2364,55 @@
|
||||
"title": "訂單文件範本",
|
||||
"subtitle": "從 MinerU 表格樣本視覺化設定精確欄位對應;無需編輯 JSON 或結構指紋。",
|
||||
"structureBlocked": "此表格結構異常,不能建立範本。請等待座標證據重建後再複核,勿以欄位對應修復原始網格。",
|
||||
"reconstructionRequired": "此表頭混入明細,需先確認欄位邊界並重建表格;重建結果必須人工複核。",
|
||||
"columnBoundaries": "相對欄位邊界(0 到 1,以逗號分隔)",
|
||||
"reconstructTable": "重建表格候選",
|
||||
"confirmReconstruction": "我已複核重建網格,允許將其用於此範本草稿",
|
||||
"reconstructionPreview": "邏輯明細重建候選(續行已合併,需人工複核)",
|
||||
"rowRole": { "header": "欄位映射", "data": "有效明細", "deleted": "已刪除" },
|
||||
"sourceRows": "來源實體行:{rows}",
|
||||
"rebuildAfterFieldMapping": "欄位映射已變更,請再次點擊「重建表格候選」並複核最終邏輯明細。",
|
||||
"multiSubrowEnabled": "此範本的一筆明細由多行組成",
|
||||
"multiSubrowHint": "第 1 行必須將行號欄映射為 line_no;可依實際版式繼續增加第 2、3、4…行,每行均可使用獨立且互相重疊的欄位邊界。",
|
||||
"subrowColumn": "第 {index} 欄",
|
||||
"firstSubrow": "第 1 行(新明細起始)",
|
||||
"followingSubrow": "第 {index} 行",
|
||||
"addSubrow": "增加一行版式",
|
||||
"autoSuggestLayout": "自動識別行版式",
|
||||
"autoSuggestLayoutHint": "系統將依 PDF/OCR 字元位置自動產生行數與欄位邊界;請依每欄範例文字確認欄位。",
|
||||
"layoutSuggestionReady": "已產生行版式建議,請確認各欄欄位後重建表格候選。",
|
||||
"columnBoundariesAdvanced": "欄位邊界(進階校準,通常無須修改)",
|
||||
"columnSamples": "範例:{samples}",
|
||||
"lineNoRequired": "第 1 行必須將訂單行號所在欄映射為 line_no。",
|
||||
"layoutRow": "物理行版式",
|
||||
"fieldMapping": "欄位範例與欄位映射",
|
||||
"rowActions": "操作",
|
||||
"columnsUnit": "欄",
|
||||
"livePreview": "即時候選",
|
||||
"livePreviewUpdating": "正在依目前映射更新…",
|
||||
"livePreviewReady": "已依目前映射更新",
|
||||
"livePreviewWaitingLineNo": "請先將第 1 行的訂單行號欄映射為 line_no",
|
||||
"livePreviewFailed": "自動更新失敗,可點擊「重建表格候選」查看錯誤",
|
||||
"livePreviewEmpty": "修改欄位或欄位邊界後,候選結果將在此自動更新",
|
||||
"confirmPreview": "確認候選",
|
||||
"visualBoundaries": "視覺化欄位邊界",
|
||||
"dragBoundaryHint": "拖動藍色分隔點調整",
|
||||
"boundaryHandle": "第 {index} 個欄位邊界",
|
||||
"preciseBoundaryValues": "精確邊界值",
|
||||
"sourceColumn": "原欄",
|
||||
"sampleValue": "範例內容",
|
||||
"targetField": "映射欄位",
|
||||
"advancedSettings": "進階設定",
|
||||
"physicalRows": "物理行",
|
||||
"addColumn": "新增欄",
|
||||
"insertColumnAfter": "後新增",
|
||||
"suggestCurrentRow": "識別目前行",
|
||||
"currentRowSuggestionReady": "目前物理行已識別,其他行設定保持不變。",
|
||||
"autoSuggestAllRows": "自動識別全部行",
|
||||
"reconstructionUnavailable": "此樣本沒有可用的 PDF 原生字元座標;請上傳具有文字層的 PDF 樣本後重試。",
|
||||
"generateOcrEvidence": "嘗試 OCR 重建",
|
||||
"ocrEvidenceReady": "OCR 座標已產生。請繼續填寫欄位邊界、重建並人工複核候選網格。",
|
||||
"reconstructionBoundariesInvalid": "欄位邊界必須從 0 開始、以 1 結束,並嚴格遞增。",
|
||||
"uploadSample": "上傳範本樣本",
|
||||
"uploadSampleHint": "僅支援 PDF 或 EML,僅用於範本設定與結構複核,不會建立發貨任務。",
|
||||
"sampleFileTypeInvalid": "範本樣本僅支援 PDF 或 EML 檔案。",
|
||||
@@ -2344,14 +2420,26 @@
|
||||
"createTitle": "從樣本建立草稿",
|
||||
"editTitle": "使用樣本更新草稿",
|
||||
"sample": "樣本文件",
|
||||
"searchSample": "依檔名搜尋樣本",
|
||||
"selectSample": "選擇已解析文件",
|
||||
"tablesUnit": "張表",
|
||||
"sampleDetails": "上傳時間:{time};解析狀態:{status}",
|
||||
"templateSampleOnly": "這是範本頁上傳的專用樣本;未被盲測引用時可以刪除。",
|
||||
"businessSampleProtected": "這是歷史業務附件,僅供複核,不能在範本頁刪除。",
|
||||
"deleteSample": "刪除樣本",
|
||||
"deleteSampleConfirm": "確認刪除這個範本專用樣本?此操作會刪除來源檔案與解析結果。",
|
||||
"sampleDeleted": "範本樣本已刪除",
|
||||
"sampleReferencedByBlindTest": "此樣本已被盲測引用,必須保留稽核記錄,不能刪除。",
|
||||
"table": "樣本表格",
|
||||
"selectTable": "選擇表格",
|
||||
"code": "範本編碼",
|
||||
"name": "範本名稱",
|
||||
"schema": "訂單欄位版本",
|
||||
"headerRow": "表頭列索引",
|
||||
"headerRow": "表頭結束列",
|
||||
"dataRow": "資料起始列",
|
||||
"multiRowHeaderMapping": "多列表頭欄位對應",
|
||||
"multiRowHeaderHint": "系統合併第 0 列至第 {end} 列的同欄文字;此處只設定邏輯欄位,不要把表頭列設定成明細列版式。",
|
||||
"mergedHeaderColumn": "第 {index} 欄",
|
||||
"rowStructure": "明細列結構",
|
||||
"rowPreserved": "表格行列結構完整,可設定欄位對應",
|
||||
"rowUnsupported": "結構不可靠,僅登記範本並轉人工複核",
|
||||
@@ -2365,6 +2453,8 @@
|
||||
"compositePart": "複合客戶/內部料號",
|
||||
"previewEmpty": "請選擇樣本文件和表格查看預覽",
|
||||
"versions": "範本版本",
|
||||
"currentVersion": "目前生效",
|
||||
"publishedAt": "發布時間:{time}",
|
||||
"publish": "發布",
|
||||
"newVersion": "建立新版本",
|
||||
"retire": "退役",
|
||||
|
||||
@@ -72,6 +72,8 @@
|
||||
"shippingNoticeDuplicateMatchTask": "命中任務:{taskNo}",
|
||||
"shippingNoticeDuplicateMatchStatus": "狀態:{status}",
|
||||
"shippingNoticeDuplicateMatchFields": "匹配依據:{fields}",
|
||||
"shippingNoticeRevisionDifferences": "此次修訂將變更以下 Reservation:",
|
||||
"shippingNoticeRevisionDifference": "{reservation}:料號 {previousPart} → {proposedPart};數量 {previousQty} → {proposedQty}",
|
||||
"shippingNoticeDuplicateOpenExisting": "開啟已有任務",
|
||||
"shippingNoticeDuplicateOpenExistingHint": "不建立新任務,將目前附件關聯到已有任務。",
|
||||
"shippingNoticeDuplicateCreateRevision": "作為修訂版本建立",
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
{
|
||||
"generic": "請求失敗。",
|
||||
"codes": {
|
||||
"SHIPPING.FULFILLMENT_POLICY_INVALID": "貨代履約策略或欄位能力綁定無效。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "找不到貨代履約策略。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_CONFLICT": "貨代履約策略已被其他管理員修改,請重新整理後再試。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_PUBLISHED": "尚未發佈可執行的貨代履約策略。",
|
||||
"SHIPPING.RESERVATION_PO_REQUIRED": "此預定單號已存在,必須補齊採購訂單後才能繼續。",
|
||||
"SHIPPING.RESERVATION_PO_CONFLICT": "此預定單號已被其他採購訂單使用,已阻擋重複訂單。",
|
||||
"SHIPPING.RESERVATION_DUPLICATED_IN_ORDER": "同一訂單中存在重複的預定單號,無法凍結。",
|
||||
"SHIPPING.RESERVATION_REVISION_REVIEW_REQUIRED": "此預定單號內容已變更,必須顯示差異並經人工確認。",
|
||||
"SHIPPING.RESERVATION_REVISION_LOCKED": "此預定單號已產生有效發貨檔案或已上傳,禁止直接修訂。",
|
||||
"SHIPPING_NOTICE.BATCH_FILE_LIMIT_EXCEEDED": "本次上傳檔案數超過系統限制,請拆分後重試。",
|
||||
"AGENT.EXPOSURE_ROLE_IMMUTABLE": "應用與內部執行器不可互相轉換。",
|
||||
"AGENT.ADMIN_SCOPE_INVALID": "應用管理頁籤參數無效。",
|
||||
@@ -25,7 +34,10 @@
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_SCHEMA_INVALID": "訂單文件解析範本必須綁定已發布或已退役的訂單欄位版本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_FIELD_INVALID": "訂單文件解析範本引用了不可用的訂單明細欄位。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_HEADER_CONTAMINATED": "樣本表頭混入訂單明細,必須先重建表格結構,不能建立範本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE": "目前表格缺少可用的原生或 OCR 字元座標,無法重建邏輯明細。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID": "座標重建設定或結果無效,請檢查欄位邊界後重試。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_SAMPLE_FILE_TYPE_INVALID": "範本樣本僅支援 PDF 或 EML 檔案。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED": "此範本樣本仍在解析、被盲測引用,或其檔案被其他業務使用,不能刪除。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_IMMUTABLE": "已發布的訂單文件解析範本不可修改。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_LOCK_VERSION_REQUIRED": "訂單文件解析範本缺少版本鎖,請重新整理後再試。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT": "訂單文件解析範本已被其他管理員修改,請重新整理後再試。",
|
||||
|
||||
Reference in new issue
Block a user