feat(shipping-notice): 新增订单行与字段冲突管理功能,支持字段冲突查询与解决

This commit is contained in:
hugo committed 2026-07-16 13:03:11 +08:00
1 parent 4fbaed2b4c
commit 9da0481fc3
74 files changed
+4861 -375

No files matched your search

+1 -1
View File
@@ -81,7 +81,7 @@ FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_triggers
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
+4
View File
@@ -164,3 +164,7 @@ FREIGHT_RPA_MOCK=false
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED=false
# 点击发送后的完整订单识别超时;超时 Intake 在状态读取时收口为 failed。
SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS=300
# 订单行双写/切读:dual 写 + shadow 观察;全量 verify 零差异且观察窗口通过后切 table。
# 回滚:将 READ_MODE 改回 json(或 shadow)即可,本期不删 lines_json。
SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE=dual
SHIPPING_NOTICE_ORDER_LINES_READ_MODE=shadow
+1 -1
View File
@@ -110,7 +110,7 @@ SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
# 两者皆无则告警只写日志、不会发企微
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
# 企微发送中短锁秒数(发送失败过期后可重试,默认 120)
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
@@ -464,6 +464,11 @@ def workspace_update_shipping_notice_fields(task_no: str):
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
if data.get('expected_order_data_version') is not None:
payload['expected_order_data_version'] = data.get('expected_order_data_version')
idem = str(data.get('idempotency_key') or '').strip()
if idem:
payload['idempotency_key'] = idem
return jsonify(shipping_tools.update_notice_fields(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-line', methods=['POST'])
@@ -486,8 +491,71 @@ def workspace_update_shipping_notice_line(task_no: str):
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
if data.get('expected_order_data_version') is not None:
payload['expected_order_data_version'] = data.get('expected_order_data_version')
idem = str(data.get('idempotency_key') or '').strip()
if idem:
payload['idempotency_key'] = idem
return jsonify(shipping_tools.update_notice_line(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/field-conflicts', methods=['GET'])
def workspace_list_shipping_field_conflicts(task_no: str):
"""列出任务未解决字段冲突。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
from app.services.shipping_notice.task_field_conflict_service import (
list_open_field_conflicts,
serialize_field_conflict,
)
rows = list_open_field_conflicts(task)
return _ok({
'task_no': task.task_no,
'order_data_version': int(task.order_data_version or 1),
'items': [serialize_field_conflict(row) for row in rows],
'open_count': len(rows),
})
@workspace_shipping_notice_bp.route(
'/shipping-tasks/<task_no>/field-conflicts/<int:conflict_id>/resolve',
methods=['POST'],
)
def workspace_resolve_shipping_field_conflict(task_no: str, conflict_id: int):
"""人工解决字段冲突并回写订单行。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
resolution = str(data.get('resolution') or '').strip()
if not resolution:
raise ValidationError('resolution is required')
def _optional_int(name: str) -> int | None:
raw = data.get(name)
if raw is None or raw == '':
return None
try:
return int(raw)
except (TypeError, ValueError) as exc:
raise ValidationError(f'{name} is invalid') from exc
from app.services.shipping_notice.task_field_conflict_service import resolve_field_conflict
result = resolve_field_conflict(
task=task,
conflict_id=int(conflict_id),
resolution=resolution,
resolved_value=data.get('resolved_value'),
expected_conflict_version=_optional_int('expected_conflict_version'),
expected_order_data_version=_optional_int('expected_order_data_version'),
resolved_by_id=int(user.id),
reason=str(data.get('reason') or '').strip() or None,
idempotency_key=str(data.get('idempotency_key') or '').strip() or None,
)
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/add-notice-line', methods=['POST'])
def workspace_add_shipping_notice_line(task_no: str):
"""为发货通知新增订单行。"""
+7
View File
@@ -233,6 +233,13 @@ class Config:
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE = float(
os.getenv('SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE') or '0.8'
)
# 订单行双写/切读:默认 dual+shadow;切 table 读前须 verify 零差异并完成观察窗口。
SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE = (
os.getenv('SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE') or 'dual'
).strip().lower()
SHIPPING_NOTICE_ORDER_LINES_READ_MODE = (
os.getenv('SHIPPING_NOTICE_ORDER_LINES_READ_MODE') or 'shadow'
).strip().lower()
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
FREIGHT_INVENTORY_DROP_DIR = _data_path(
+3
View File
@@ -28,6 +28,7 @@ from app.models.shipping import (
ShippingTaskEvent,
ShippingTaskInventoryLink,
)
from app.models.shipping_task_line import ShippingTaskFieldConflict, ShippingTaskLine
from app.models.shipping_customer import (
ShippingBusinessSequence,
ShippingCase,
@@ -75,6 +76,8 @@ __all__ = [
'ScheduleRun',
'ShippingBatch',
'ShippingTask',
'ShippingTaskLine',
'ShippingTaskFieldConflict',
'ShippingCustomer',
'ShippingCustomerIdentifier',
'ShippingCustomerExternalRef',
+27 -2
View File
@@ -2,12 +2,13 @@
backend/app/models/shipping.py
用途:货代发货通知批次、任务、事件、库存文件、接入记录、文档/候选与库存映射模型。
依赖:models.base.Base。
依赖:models.base.Base;规范订单行见 shipping_task_line。
逻辑:ShippingBatch.create_idempotency_key 为建单幂等;ShippingTask.idempotency_key 为货代上传幂等;
Intake.create_idempotency_key 承载混合/open_existing 确认请求重放;
Intake/Task/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离;
Document/Candidate 承载「一邮件多订单」识别;ShippingTask.source_candidate_id 记录正式建单来源;
ShippingTask.supersedes_task_id 唯一约束保证修订链线性。
ShippingTask.supersedes_task_id 唯一约束保证修订链线性;
order_data_version / order_lines_migration_status 为规范表双写与切读准备,lines_json 暂保留。
"""
from __future__ import annotations
@@ -172,6 +173,19 @@ class ShippingTask(Base):
required_date: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
lines_json: Mapped[Optional[list]] = mapped_column(JSON, default=list)
parse_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
# 规范订单行乐观版本与迁移状态;业务读路径经 task_line_store(json/shadow/table)。
order_data_version: Mapped[int] = mapped_column(
Integer,
default=1,
server_default=text('1'),
nullable=False,
)
order_lines_migration_status: Mapped[str] = mapped_column(
String(32),
default='pending',
server_default=text("'pending'"),
nullable=False,
)
process_status: Mapped[str] = mapped_column(String(32), default='created', index=True)
current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
@@ -217,6 +231,17 @@ class ShippingTask(Base):
back_populates='task',
cascade='all, delete-orphan',
)
order_lines: Mapped[List['ShippingTaskLine']] = relationship(
'ShippingTaskLine',
back_populates='task',
cascade='all, delete-orphan',
order_by='ShippingTaskLine.position',
)
field_conflicts: Mapped[List['ShippingTaskFieldConflict']] = relationship(
'ShippingTaskFieldConflict',
back_populates='task',
cascade='all, delete-orphan',
)
class ShippingTaskEvent(Base):
+186
View File
@@ -0,0 +1,186 @@
"""
backend/app/models/shipping_task_line.py
用途:规范订单行(ShippingTaskLine)与字段冲突审计(ShippingTaskFieldConflict)模型。
依赖:models.base.Base、shipping_tasks、users。
逻辑:Task.lines_json 在迁移窗口内仍为兼容快照;规范表由阶段四双写填充,阶段六再切读。
"""
from __future__ import annotations
from datetime import datetime
from decimal import Decimal
from typing import TYPE_CHECKING, List, Optional
from sqlalchemy import (
CheckConstraint,
ForeignKey,
Index,
Integer,
JSON,
Numeric,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
if TYPE_CHECKING:
from app.models.shipping import ShippingTask
class ShippingTaskLine(Base):
"""
任务当前订单行投影;稳定主键 + (task_id, position) 唯一。
核心逻辑:Candidate 是不可变抽取审计,本表是任务可变真相源;未知历史字段进 extra_json。
"""
__tablename__ = 'shipping_task_lines'
__table_args__ = (
UniqueConstraint('task_id', 'position', name='uq_shipping_task_lines_task_position'),
CheckConstraint('qty > 0', name='ck_shipping_task_lines_qty_positive'),
Index('ix_shipping_task_lines_task_id', 'task_id'),
Index('ix_shipping_task_lines_reservation_id', 'reservation_id'),
Index('ix_shipping_task_lines_sku', 'sku'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_tasks.id', ondelete='CASCADE'),
nullable=False,
)
position: Mapped[int] = mapped_column(Integer, nullable=False)
sku: Mapped[str] = mapped_column(String(128), nullable=False)
qty: Mapped[Decimal] = mapped_column(Numeric(18, 6), nullable=False)
uom: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
source_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
hub_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
required_date: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
vendor_part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
customer_sku: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
allocation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
unit_price: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 6), nullable=True)
amount: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 6), nullable=True)
currency: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
extra_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
field_sources_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
evidence_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
schema_version: Mapped[str] = mapped_column(
String(64),
nullable=False,
default='shipping-task-line-v1',
server_default=text("'shipping-task-line-v1'"),
)
line_version: Mapped[int] = mapped_column(
Integer,
nullable=False,
default=1,
server_default=text('1'),
)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
task: Mapped[ShippingTask] = relationship('ShippingTask', back_populates='order_lines')
field_conflicts: Mapped[List[ShippingTaskFieldConflict]] = relationship(
'ShippingTaskFieldConflict',
back_populates='line',
cascade='save-update, merge',
)
class ShippingTaskFieldConflict(Base):
"""
订单字段级冲突审计;未解决冲突将在后续阶段阻断下游流程。
核心逻辑:独立于 Candidate/TaskLine,记录双方值、来源、证据与解决结果。
"""
__tablename__ = 'shipping_task_field_conflicts'
__table_args__ = (
CheckConstraint(
"status IN ('open', 'resolved', 'dismissed')",
name='ck_shipping_task_field_conflicts_status',
),
Index('ix_shipping_task_field_conflicts_task_status', 'task_id', 'status'),
Index('ix_shipping_task_field_conflicts_line_id', 'line_id'),
# NULL 在唯一索引中互不冲突,因此拆成「有行」与「无行」两条部分唯一索引。
Index(
'uq_shipping_task_field_conflicts_open_line_field',
'task_id',
'line_id',
'field_name',
unique=True,
postgresql_where=text("status = 'open' AND line_id IS NOT NULL"),
sqlite_where=text("status = 'open' AND line_id IS NOT NULL"),
),
Index(
'uq_shipping_task_field_conflicts_open_task_field',
'task_id',
'field_name',
unique=True,
# 仅任务级冲突(无行/无 position);行级冲突走 position 唯一索引。
postgresql_where=text("status = 'open' AND line_id IS NULL AND position IS NULL"),
sqlite_where=text("status = 'open' AND line_id IS NULL AND position IS NULL"),
),
Index(
'uq_shipping_task_field_conflicts_open_position_field',
'task_id',
'position',
'field_name',
unique=True,
postgresql_where=text("status = 'open' AND position IS NOT NULL"),
sqlite_where=text("status = 'open' AND position IS NOT NULL"),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_tasks.id', ondelete='CASCADE'),
nullable=False,
index=True,
)
line_id: Mapped[Optional[int]] = mapped_column(
# SET NULL:订单行双写重建主键时不得 CASCADE 抹掉冲突审计。
ForeignKey('shipping_task_lines.id', ondelete='SET NULL'),
nullable=True,
)
position: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
field_name: Mapped[str] = mapped_column(String(64), nullable=False)
existing_value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
incoming_value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
existing_source: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
incoming_source: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
existing_evidence_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
incoming_evidence_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
status: Mapped[str] = mapped_column(
String(32),
nullable=False,
default='open',
server_default=text("'open'"),
)
resolved_value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
resolved_at: Mapped[Optional[datetime]] = mapped_column(nullable=True)
resolution_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
conflict_version: Mapped[int] = mapped_column(
Integer,
nullable=False,
default=1,
server_default=text('1'),
)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
task: Mapped[ShippingTask] = relationship('ShippingTask', back_populates='field_conflicts')
line: Mapped[Optional[ShippingTaskLine]] = relationship(
'ShippingTaskLine',
back_populates='field_conflicts',
)
@@ -591,6 +591,7 @@ def create_shipping_batch_from_candidates(
)
intake_by_id = {int(item.id): item for item in intakes}
opened: list[dict[str, Any]] = []
reconciliation_pending: list[dict[str, Any]] = []
create_items: list[dict[str, Any]] = []
create_candidates: list[ShippingNoticeCandidate] = []
now = datetime.utcnow()
@@ -679,16 +680,45 @@ def create_shipping_batch_from_candidates(
)
if target is None:
raise ConflictError(code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND', message='重复目标任务不存在')
backfill_exact_file_open_existing_reservations(
extraction = (
structured.get('extraction')
if isinstance(structured.get('extraction'), dict)
else {}
)
reconciliation = backfill_exact_file_open_existing_reservations(
task=target,
candidate=candidate,
candidate_summary=summary,
duplicate_status=str(fresh.get('status') or ''),
duplicate_matches=matches,
verified_reservation_evidence=list(
extraction.get('verified_reservation_evidence') or []
),
)
candidate.consumed_task_id = int(target.id)
# [STEP] 回填成功或「无需/不可回填但仍应打开旧任务」才算打开成功;
# 冲突、证据不足、行歧义等必须进入对账待审,不得伪装成已打开。
opened_successfully = reconciliation.get('status') == 'applied' or reconciliation.get('reason') in {
'duplicate_status_not_exact_file',
'target_already_complete',
'target_task_not_safe',
}
if opened_successfully:
candidate.consumed_task_id = int(target.id)
opened.append({
'candidate_no': candidate.candidate_no,
'task_no': target.task_no,
'batch_no': None,
'reconciliation': reconciliation,
})
else:
candidate.selected = False
candidate.validation_status = 'needs_review'
reconciliation_pending.append({
'candidate_no': candidate.candidate_no,
'task_no': target.task_no,
'reconciliation': reconciliation,
})
candidate.updated_at = now
opened.append({'candidate_no': candidate.candidate_no, 'task_no': target.task_no, 'batch_no': None})
continue
create_items.append(candidate_to_notice_item(candidate, intake, document))
create_candidates.append(candidate)
@@ -732,11 +762,19 @@ def create_shipping_batch_from_candidates(
batch_obj.process_summary_json = batch_summary
flag_modified(batch_obj, 'process_summary_json')
else:
if opened and reconciliation_pending:
open_message = '部分已打开已有任务;其余订单需人工对账,未创建新批次'
elif opened:
open_message = '已打开已有任务,未创建新批次'
elif reconciliation_pending:
open_message = '打开已有任务需要对账确认,未创建新批次'
else:
open_message = '未创建新批次'
result = {
'status': 'ok',
'batch_no': None,
'idempotent_replay': False,
'message': '已打开已有任务,未创建新批次',
'message': open_message,
'data': {'opened_existing': opened},
}
@@ -772,6 +810,8 @@ def create_shipping_batch_from_candidates(
result['data'] = data
if opened:
result['opened_existing'] = opened
if reconciliation_pending:
result['reconciliation_pending'] = reconciliation_pending
return result
@@ -60,10 +60,14 @@ def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[st
missing_required: list[str] = []
if not normalized_lines:
missing_required.extend(BUILD_REQUIRED_FIELDS)
# Reservation 是逐行匹配键;任一有效订单行缺失都必须保留流程字段门禁。
missing_process = [
field
for field in PROCESS_FIELDS
if not any(str(line.get(field) or '').strip() for line in normalized_lines)
if any(
not validated_reservation_id(line.get(field))
for line in normalized_lines
)
]
blocking = [
{'code': 'invalid_order_line', **item}
@@ -2,7 +2,7 @@
services/shipping_notice/decision_workflow.py
用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配、重解析和映射修正。
依赖:state_machine、tool_response、query_service、inventory_mapping_workflow、inventory_upload、fulfillment_workflow。
依赖:state_machine、tool_response、query_service、inventory_mapping_workflow、inventory_upload、fulfillment_workflow、task_line_store。
逻辑:由 task_workflow 对外转调本文件;本文件在当前任务上下文内执行决策分支,并在必要时回调后端 orchestrator。
"""
@@ -24,6 +24,7 @@ from app.services.shipping_notice.constants import (
)
from app.services.shipping_notice.fulfillment_workflow import match_completed, match_inventory
from app.services.shipping_notice.inventory_mapping import mapping_is_complete
from app.services.shipping_notice.task_line_store import clear_task_order_lines
from app.services.shipping_notice.inventory_mapping_store import upsert_inventory_mapping
from app.services.shipping_notice.inventory_mapping_workflow import (
awaiting_inventory_mapping_confirm,
@@ -535,7 +536,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
task.process_status = "created"
task.review_status = None
task.pending_human_reason = None
task.lines_json = []
clear_task_order_lines(task)
task.parse_confidence = None
task.match_status = None
task.shortage_json = None
@@ -7,7 +7,8 @@ backend/app/services/shipping_notice/document_candidate_persist.py
(parent, content_hash)、(intake, attachment_key)、(intake, primary_document_id) 复用,不重复创建。
Document↔派生资产的引用计数仅在 asset_id 变更时 +1/-1;
Candidate 重复检测可由调用方延后到 SAVEPOINT(run_duplicate_detection=False);
cancel / 阶段二失败可整单释放并清理 structured 投影字段。
cancel / 阶段二失败可整单释放并清理 structured 投影字段;
Candidate brief 另暴露 evidence / missing_fields / field_confidence 供审核与 Task Detail 投影。
"""
from __future__ import annotations
@@ -334,6 +335,13 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
'content_fingerprint': cand.content_fingerprint,
'content_fingerprint_version': cand.content_fingerprint_version,
'conflicts': list(cand.conflicts_json or []),
'missing_fields': list(cand.missing_fields_json or []),
'field_confidence': (
dict(cand.field_confidence_json)
if isinstance(cand.field_confidence_json, dict)
else {}
),
'evidence': list(cand.evidence_json or []),
'duplicate': {
'status': status,
'blocking': blocking,
@@ -2,8 +2,8 @@
services/shipping_notice/export.py
用途:生成发货通知对应的货代出货 Excel,并管理模板与导出文件存储路径。
依赖:openpyxl、app.models.ShippingTask、path_utils、Flask current_app 配置。
逻辑:由 fulfillment_workflow.generate_excel 调用本文件,根据任务数据填充模板后返回导出文件路径。
依赖:openpyxl、app.models.ShippingTask、path_utils、task_line_store、Flask current_app 配置。
逻辑:由 fulfillment_workflow.generate_excel 调用本文件;订单行经 read_task_order_lines 读取。
"""
from __future__ import annotations
@@ -18,6 +18,7 @@ from openpyxl import Workbook, load_workbook
from app.models import ShippingTask
from app.path_utils import backend_dir, resolve_backend_relative_path
from app.services.shipping_notice.task_line_store import read_task_order_lines
DEFAULT_HEADERS = [
"客户名称",
@@ -81,9 +82,7 @@ def _delivery_date_for_task(task: ShippingTask) -> str:
formatted = _format_delivery_date(task.required_date)
if formatted:
return formatted
for line in task.lines_json or []:
if not isinstance(line, dict):
continue
for line in read_task_order_lines(task):
formatted = _format_delivery_date(line.get("required_date"))
if formatted:
return formatted
@@ -91,7 +90,7 @@ def _delivery_date_for_task(task: ShippingTask) -> str:
def _resolve_odm_id(task: ShippingTask) -> str:
notice_lines = [line for line in (task.lines_json or []) if isinstance(line, dict)]
notice_lines = read_task_order_lines(task)
inventory_lines = [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
if not inventory_lines:
return ""
@@ -190,7 +189,7 @@ def _fill_pvmi_template(task: ShippingTask, path: Path) -> None:
business_ref = task.shipping_case.business_no if task.shipping_case and task.shipping_case.business_no else task.task_no
header_ws.cell(DATA_START_ROW, 7).value = business_ref
notice_lines = [line for line in (task.lines_json or []) if isinstance(line, dict)]
notice_lines = read_task_order_lines(task)
if not notice_lines:
notice_lines = [{}]
@@ -229,7 +228,7 @@ def _fill_legacy_template(task: ShippingTask, path: Path) -> None:
"""填充 legacy 模板;技术任务号继续保留在导出文件名与系统记录中。"""
wb = load_workbook(filename=str(path))
ws = wb.active
lines = task.lines_json or [None]
lines = read_task_order_lines(task) or [None]
if ws.max_row == 1 and not any(ws.cell(1, c).value for c in range(1, 9)):
ws.append(DEFAULT_HEADERS)
for line in lines:
@@ -243,7 +242,7 @@ def _fill_blank_workbook(task: ShippingTask, path: Path) -> None:
ws = wb.active
ws.title = "Shipment"
ws.append(DEFAULT_HEADERS)
lines = task.lines_json or [None]
lines = read_task_order_lines(task) or [None]
for line in lines:
ws.append(_row_values(task, line))
wb.save(path)
@@ -2,8 +2,9 @@
services/shipping_notice/fulfillment_workflow.py
用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传/RPA 与自动串联编排。
依赖:customer_identity_gate、match、export、rpa、query_service、inventory_workflow、inventory_mapping_workflow、tool_common、tool_response。
逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match。
依赖:customer_identity_gate、reservation_gate、match、export、rpa、query_service、inventory_workflow、inventory_mapping_workflow、task_line_store、tool_common、tool_response。
逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match;
订单行读取统一经 read_task_order_lines。
"""
from __future__ import annotations
@@ -34,6 +35,9 @@ from app.services.shipping_notice.query_service import (
)
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.reservation_id import is_valid_reservation_id
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
from app.services.shipping_notice.task_line_store import read_task_order_lines
from app.services.shipping_notice.rpa import write_upload_trigger
from app.services.shipping_notice.rpa_attempts import (
max_rpa_upload_attempts,
@@ -55,6 +59,45 @@ def _cfg_bool(key: str, default: bool = False) -> bool:
return str(val).strip().lower() in {"1", "true", "yes", "on"}
def _reservation_gate_response(
task: ShippingTask,
*,
lang: str,
forbidden_next_tools: list[str],
) -> dict[str, Any] | None:
"""
在履约副作用前返回统一 Reservation 门禁响应。
Args:
task: 当前发货任务。
lang: 已解析的响应语言。
forbidden_next_tools: 本入口失败后必须禁止的后续 Tool。
Returns:
存在缺失/非法订单行时返回 needs_human,否则返回 None。
"""
issues = reservation_gate_issues(read_task_order_lines(task))
if not issues:
return None
detail = {
"order_missing_count": len(issues),
"order_missing_preview": issues[:5],
}
return tool_response(
status="needs_human",
task=task,
message=t("workflow.fulfillment.reservation_required", lang=lang).format(
count=len(issues)
),
data={
**serialize_task_for_tool(task),
"reservation_id_required": detail,
},
checkpoint="rsv_req",
stop_agent_turn=True,
forbidden_next_tools=forbidden_next_tools,
)
def _cfg_int(key: str, default: int = 0, *, min_value: int | None = None) -> int:
val = current_app.config.get(key)
if val is None:
@@ -212,6 +255,23 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if customer_gate is not None:
return customer_gate
conflict_gate = field_conflict_gate_response(task, lang=lang)
if conflict_gate is not None:
return conflict_gate
reservation_gate = _reservation_gate_response(
task,
lang=lang,
forbidden_next_tools=[
"ensure_inventory",
"match_inventory",
"generate_shipment_excel",
"upload_to_freight",
],
)
if reservation_gate is not None:
return reservation_gate
# [STEP 1] 先确认字段对齐与库存快照是否已经就绪。
# 若还停在映射确认阶段或完全没有库存,就不能直接进入匹配计算。
if awaiting_inventory_mapping_confirm(task):
@@ -229,8 +289,8 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if lang:
inv_payload["lang"] = lang
return ensure_inventory(inv_payload)
notice_lines = task.lines_json or []
total_notice_lines = len(notice_lines) if isinstance(notice_lines, list) else 0
notice_lines = read_task_order_lines(task)
total_notice_lines = len(notice_lines)
set_task_step_progress(
task,
step_key="step5_match_inventory",
@@ -244,37 +304,12 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
)
db.session.flush()
# [STEP 2] 校验 Reservation ID 前置条件。
# 当前匹配规则要求订单侧必须具备 Reservation ID,缺失时要先打回上游解析而不是继续匹配。
order_missing = [
{"sku": str(line.get("sku") or "").strip(), "reservation_id": str(line.get("reservation_id") or "").strip()}
for line in (notice_lines if isinstance(notice_lines, list) else [])
if not is_valid_reservation_id(line.get("reservation_id"))
]
# [STEP 2] 订单侧 Reservation 已在任何库存副作用前校验;此处只统计库存侧缺失。
inv_missing_count = sum(
1
for row in (inventory_lines or [])
if not is_valid_reservation_id((row or {}).get("reservation_id"))
)
if order_missing:
apply_task_transition(task, TaskTransition.RSV_REQUIRED)
task.match_status = None
task.shortage_json = None
task.line_results_json = None
detail = {
"order_missing_count": len(order_missing),
"order_missing_preview": order_missing[:5],
}
log_task_event(task, "reservation_id_required", detail)
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=t("workflow.fulfillment.reservation_required", lang=lang).format(count=len(order_missing)),
data={**serialize_task_for_tool(task), "reservation_id_required": detail},
stop_agent_turn=True,
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
if not is_inventory_source_stable(task):
return tool_response(
@@ -383,6 +418,18 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
if customer_gate is not None:
return customer_gate
conflict_gate = field_conflict_gate_response(task, lang=lang)
if conflict_gate is not None:
return conflict_gate
reservation_gate = _reservation_gate_response(
task,
lang=lang,
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
if reservation_gate is not None:
return reservation_gate
if not is_inventory_source_stable(task):
return tool_response(
status="failed",
@@ -473,6 +520,18 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
if customer_gate is not None:
return customer_gate
conflict_gate = field_conflict_gate_response(task, lang=lang)
if conflict_gate is not None:
return conflict_gate
reservation_gate = _reservation_gate_response(
task,
lang=lang,
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
if reservation_gate is not None:
return reservation_gate
if not is_inventory_source_stable(task):
return tool_response(
status="failed",
@@ -124,6 +124,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.match_completed_ok_detail": "已匹配 {count}/{count} 行,全部订单行库存满足",
"workflow.fulfillment.match_completed_shortage_detail": "已匹配 {count}/{count} 行,存在缺口,需人工处理",
"workflow.fulfillment.reservation_required": "当前匹配规则要求发货需求(订单)必须提供 Reservation ID。订单缺少 Reservation ID:{count} 行。请重新解析发货通知后再匹配。",
"workflow.gate.field_conflict_blocked": "存在 {count} 条未解决的订单字段冲突,请先复核并解决后再继续库存/匹配/导出。",
"workflow.fulfillment.excel_gate_unmatched": "尚未完成库存匹配。请先上传库存、确认字段对齐并调用 match_inventory。",
"workflow.fulfillment.excel_exists": "发货 Excel 已生成:{file}",
"workflow.fulfillment.match_first": "match_inventory(须先完成库存上传与字段对齐确认)",
@@ -259,6 +260,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.match_completed_ok_detail": "Matched {count}/{count} lines. All order lines are fulfillable.",
"workflow.fulfillment.match_completed_shortage_detail": "Matched {count}/{count} lines. Shortage exists and manual handling is required.",
"workflow.fulfillment.reservation_required": "The current matching rule requires Reservation ID on the order side. {count} order lines are missing Reservation ID. Please re-parse the shipping notice before matching again.",
"workflow.gate.field_conflict_blocked": "There are {count} unresolved order field conflicts. Resolve them before inventory, matching, or export.",
"workflow.fulfillment.excel_gate_unmatched": "Inventory matching is not complete yet. Please upload inventory, confirm field alignment, and call match_inventory first.",
"workflow.fulfillment.excel_exists": "Shipment Excel already exists: {file}",
"workflow.fulfillment.match_first": "match_inventory (inventory upload and field alignment confirmation are required first)",
@@ -394,6 +396,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.match_completed_ok_detail": "จับคู่แล้ว {count}/{count} รายการ และทุกรายการมีสต็อกเพียงพอ",
"workflow.fulfillment.match_completed_shortage_detail": "จับคู่แล้ว {count}/{count} รายการ แต่ยังมีของขาดและต้องให้คนจัดการต่อ",
"workflow.fulfillment.reservation_required": "กฎการจับคู่ปัจจุบันกำหนดให้ฝั่งคำสั่งซื้อมี Reservation ID ขณะนี้มี {count} รายการที่ขาด Reservation ID โปรดแยกใบแจ้งส่งสินค้าใหม่ก่อนแล้วค่อยจับคู่",
"workflow.gate.field_conflict_blocked": "มีข้อขัดแย้งของฟิลด์คำสั่งซื้อที่ยังไม่แก้ {count} รายการ กรุณาตรวจสอบก่อนดำเนินการสต็อก/จับคู่/ส่งออก",
"workflow.fulfillment.excel_gate_unmatched": "ยังจับคู่สต็อกไม่เสร็จ โปรดอัปโหลดสต็อก ยืนยันการจับคู่คอลัมน์ แล้วเรียก match_inventory ก่อน",
"workflow.fulfillment.excel_exists": "สร้างไฟล์ Shipment Excel แล้ว: {file}",
"workflow.fulfillment.match_first": "match_inventory (ต้องอัปโหลดสต็อกและยืนยันการจับคู่คอลัมน์ก่อน)",
@@ -69,6 +69,7 @@ def parse_intake_business_summary(
'po_number': str(line.get('po_number') or '').strip() or None,
'allocation_id': str(line.get('allocation_id') or '').strip() or None,
'source_type': str(line.get('source_type') or '').strip() or None,
'hub_code': str(line.get('hub_code') or '').strip() or None,
'customer_sku': str(line.get('customer_sku') or '').strip() or None,
'vendor_part_number': str(line.get('vendor_part_number') or '').strip() or None,
}
@@ -2,9 +2,10 @@
services/shipping_notice/inventory_mapping_workflow.py
用途:库存字段对齐确认、自动映射推进与库存载入后的 auto-chain 编排。
依赖:inventory_snapshot、inventory_mapping_store、query_service、tool_common、state_machine。
依赖:inventory_snapshot、inventory_mapping_store、query_service、task_line_store、tool_common、state_machine。
逻辑:inventory_workflow / inventory_rpa_workflow 在解析/上传后委托本模块;
task_workflow / fulfillment_workflow 在决策与 auto_progress 中调用映射门禁。
task_workflow / fulfillment_workflow 在决策与 auto_progress 中调用映射门禁;
订单行对齐预览经 read_task_order_lines 读取。
"""
from __future__ import annotations
@@ -26,6 +27,7 @@ from app.services.shipping_notice.inventory_mapping_store import upsert_inventor
from app.services.shipping_notice.inventory_snapshot import build_field_alignment_preview
from app.services.shipping_notice.query_service import serialize_task_for_tool
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.task_line_store import read_task_order_lines
from app.services.shipping_notice.tool_common import (
auto_mapping_allow_llm,
auto_match_enabled,
@@ -74,7 +76,7 @@ def field_alignment_for_task(task: ShippingTask, column_meta: dict[str, Any] | N
meta = column_meta or latest_inventory_column_meta(task)
return build_field_alignment_preview(
task.inventory_lines_json or [],
task.lines_json or [],
read_task_order_lines(task),
column_meta=meta,
)
@@ -2,8 +2,9 @@
services/shipping_notice/inventory_rpa_workflow.py
用途:发货通知库存 RPA 编排(触发导出、等待/超时、回调落盘)。
依赖:customer_identity_gate、rpa、rpa_attempts、inventory_snapshot、inventory_mapping_workflow、query_service、tool_common、state_machine、tool_response。
逻辑:inventory_workflow.ensure_inventory 在 mode=auto/retry_rpa 时委托本模块;tools 门面 re-export rpa_report_inventory。
依赖:customer_identity_gate、reservation_gate、rpa、rpa_attempts、inventory_snapshot、inventory_mapping_workflow、query_service、task_line_store、tool_common、state_machine、tool_response。
逻辑:inventory_workflow.ensure_inventory 在 mode=auto/retry_rpa 时委托本模块;tools 门面 re-export rpa_report_inventory;
Reservation 门禁订单行经 read_task_order_lines 读取。
"""
from __future__ import annotations
@@ -64,6 +65,9 @@ from app.services.shipping_notice.query_service import (
resolve_task_from_payload,
serialize_task_for_tool,
)
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
from app.services.shipping_notice.task_line_store import read_task_order_lines
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
from app.services.shipping_notice.rpa import (
inventory_processed_dir,
write_inventory_export_trigger_for_task,
@@ -998,6 +1002,30 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
if customer_gate is not None:
return customer_gate
conflict_gate = field_conflict_gate_response(task, lang='zh')
if conflict_gate is not None:
return conflict_gate
reservation_issues = reservation_gate_issues(read_task_order_lines(task))
if reservation_issues:
return tool_response(
status="needs_human",
task=task,
message=(
f"当前订单有 {len(reservation_issues)} 行缺少有效 Reservation ID,"
"补齐前不能启动库存 RPA。"
),
data={
**serialize_task_for_tool(task),
"reservation_id_required": {
"order_missing_count": len(reservation_issues),
"order_missing_preview": reservation_issues[:5],
},
},
checkpoint="rsv_req",
stop_agent_turn=True,
)
# [STEP 0] 库存源须在订单解析阶段已确定;RPA 只读取独立字段。
try:
assert_inventory_source_gate(task, operation="ensure_inventory_via_rpa")
@@ -2,8 +2,9 @@
services/shipping_notice/inventory_source_rules.py
用途:根据发货通知路由线索对库存源做确定性裁决。
依赖:inventory_sources、ShippingTask 目的地字段、订单行 source_type 与 step_payload_json。
逻辑:Dify/LLM 只提供行级可选路由线索;本模块负责唯一性判断、冲突检测与人工确认复核。
依赖:inventory_sources、ShippingTask 目的地字段、task_line_store、step_payload_json。
逻辑:Dify/LLM 只提供行级可选路由线索;本模块负责唯一性判断、冲突检测与人工确认复核;
订单行路由线索经 read_task_order_lines 读取。
"""
from __future__ import annotations
@@ -24,6 +25,7 @@ from app.services.shipping_notice.inventory_sources import (
get_inventory_sources_config_version,
list_inventory_sources,
)
from app.services.shipping_notice.task_line_store import read_task_order_lines
@dataclass(frozen=True)
@@ -122,13 +124,12 @@ def extract_destination_candidates(task: ShippingTask) -> list[str]:
_append_candidate(candidates, task.destination_city)
_append_candidate(candidates, task.destination_country)
_append_candidate(candidates, task.warehouse_hint)
for line in task.lines_json or []:
if not isinstance(line, dict):
continue
for line in read_task_order_lines(task):
_extract_destination_object(candidates, line.get("destination"))
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to", "raw_text"):
_append_candidate(candidates, line.get(key))
_append_candidate(candidates, line.get("source_type"))
_append_candidate(candidates, line.get("hub_code"))
return candidates
@@ -2,8 +2,9 @@
services/shipping_notice/inventory_workflow.py
用途:发货通知库存阶段编排(解析、上传、ensure_inventory);RPA 见 inventory_rpa_workflow。
依赖:customer_identity_gate、inventory_*、inventory_mapping_workflow、inventory_rpa_workflow、query_service、state_machine。
逻辑:tools.py 门面 re-export;解析/上传完成后委托 inventory_mapping_workflow 做对齐与 auto-chain。
依赖:customer_identity_gate、reservation_gate、inventory_*、inventory_mapping_workflow、inventory_rpa_workflow、query_service、state_machine、task_line_store。
逻辑:tools.py 门面 re-export;解析/上传完成后委托 inventory_mapping_workflow 做对齐与 auto-chain;
Reservation 门禁订单行经 read_task_order_lines 读取。
"""
from __future__ import annotations
@@ -58,6 +59,9 @@ from app.services.shipping_notice.query_service import (
serialize_batch_for_tool,
serialize_task_for_tool,
)
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
from app.services.shipping_notice.task_line_store import read_task_order_lines
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
@@ -122,14 +126,54 @@ def _extract_partial_inventory_field_mapping(raw: Any) -> dict[str, str]:
return result
def _reservation_gate_response(task: ShippingTask, *, lang: str) -> dict[str, Any] | None:
"""
库存入口统一检查订单侧 Reservation ID。
核心逻辑:任一订单行缺失/非法时阻断,并禁止同轮继续库存副作用。
"""
reservation_issues = reservation_gate_issues(read_task_order_lines(task))
if not reservation_issues:
return None
return tool_response(
status="needs_human",
task=task,
message=t("workflow.fulfillment.reservation_required", lang=lang).format(
count=len(reservation_issues)
),
data={
**serialize_task_for_tool(task),
"reservation_id_required": {
"order_missing_count": len(reservation_issues),
"order_missing_preview": reservation_issues[:5],
},
},
checkpoint="rsv_req",
stop_agent_turn=True,
forbidden_next_tools=[
"ensure_inventory",
"parse_inventory",
"match_inventory",
"generate_shipment_excel",
"upload_to_freight",
],
)
def _inventory_source_gate_response(task: ShippingTask, *, operation: str, lang: str) -> dict[str, Any] | None:
"""
库存相关 Tool 入口统一门禁;未稳定时返回 needs_human 响应。
核心逻辑:仅捕获预期 AppError,其它异常继续向上抛出。
核心逻辑:先拦客户与 Reservation,再检查库存源稳定性;仅捕获预期 AppError。
"""
customer_gate = customer_gate_tool_response(task, operation=operation)
if customer_gate is not None:
return customer_gate
conflict_gate = field_conflict_gate_response(task, lang=lang)
if conflict_gate is not None:
return conflict_gate
reservation_gate = _reservation_gate_response(task, lang=lang)
if reservation_gate is not None:
return reservation_gate
if is_inventory_source_stable(task):
return None
try:
@@ -594,23 +638,10 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
customer_gate = customer_gate_tool_response(task, operation='ensure_inventory')
if customer_gate is not None:
return customer_gate
if not is_inventory_source_stable(task):
try:
assert_inventory_source_gate(task, operation="ensure_inventory")
except AppError:
pass
return tool_response(
status="needs_human",
task=task,
message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
data=serialize_task_for_tool(task),
checkpoint="inventory_source_review",
stop_agent_turn=True,
)
# [STEP 0] 与 parse/upload 共用客户、Reservation、库存源门禁,避免旁路入口绕过订单侧闸门。
gate_resp = _inventory_source_gate_response(task, operation="ensure_inventory", lang=lang)
if gate_resp is not None:
return gate_resp
# [STEP 1] 优先接受当前请求直接携带的库存明细。
# 这条路径用于小表/结构化库存输入,能直接跳过上传与 RPA 等外围链路。
@@ -23,6 +23,7 @@ NOTICE_LINE_FIELDS = (
"po_number",
"allocation_id",
"source_type",
"hub_code",
"customer_sku",
)
@@ -125,11 +126,12 @@ NOTICE_COLUMN_MAP: dict[str, str] = {
"Allocation ID": "allocation_id",
"source type": "source_type",
"Source Type": "source_type",
# Hub Code 与 Source Type 在当前业务中是同一库存路由线索,统一归入 source_type。
"Hub Code": "source_type",
"Hub": "source_type",
"HUB": "source_type",
"hub_code": "source_type",
# Hub Code 与 Source Type 分列落库:前者是站点/Hub 线索,后者是库存来源提示。
"Hub Code": "hub_code",
"Hub": "hub_code",
"HUB": "hub_code",
"hub_code": "hub_code",
"hubCode": "hub_code",
# 单位
"单位": "uom",
"UOM": "uom",
@@ -161,6 +163,7 @@ NOTICE_FIELD_LABELS = {
"po_number": "PO Number",
"allocation_id": "Allocation ID",
"source_type": "库存来源提示",
"hub_code": "Hub Code / 站点线索",
"customer_sku": "客户料号 / HHPN",
}
@@ -129,7 +129,7 @@ def parse_notice_row(
if vendor_part_number:
parsed["vendor_part_number"] = vendor_part_number
for field in ("po_number", "allocation_id", "source_type", "customer_sku"):
for field in ("po_number", "allocation_id", "source_type", "hub_code", "customer_sku"):
idx = columns.get(field)
if idx is None:
continue
@@ -149,6 +149,8 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
"source_type",
"sourceType",
"Source Type",
),
"hub_code": (
"hub_code",
"hubCode",
"Hub Code",
@@ -1,108 +1,54 @@
"""
backend/app/services/shipping_notice/open_existing_reservation_backfill.py
用途:在 exact_file/open_existing 场景下,将最新订单 Candidate 的合法 Reservation ID 安全回填旧任务。
依赖:ShippingNoticeCandidate/ShippingTask、po_number、reservation_id、state_machine、tool_common。
逻辑:batch_from_intakes 在消费 open_existing Candidate 前调用;本模块只处理尚未进入库存链的 rsv_req 任务,
按 PO + SKU + Qty 唯一匹配空值订单行,重算 Reservation 门禁并写入任务审计。
用途:exact_file/open_existing 场景下将 Candidate 字段安全对账到旧任务(兼容入口)。
依赖:task_candidate_reconciliation、tool_common。
逻辑:batch_from_intakes 仍调用本模块;内部委托通用字段对账,并保留 applied/skipped/conflicted 审计语义。
"""
from __future__ import annotations
from collections import Counter
from decimal import Decimal, InvalidOperation
from typing import Any
from app.models import ShippingNoticeCandidate, ShippingTask
from app.services.shipping_notice.constants import PH_RSV_REQ
from app.services.shipping_notice.po_number import normalize_po_number
from app.services.shipping_notice.reservation_id import (
is_valid_reservation_id,
validated_reservation_id,
from app.services.shipping_notice.task_candidate_reconciliation import (
reconcile_exact_file_open_existing,
)
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.tool_common import log_task_event
def _normalized_qty(value: Any) -> str:
def _record_outcome(
*,
task: ShippingTask,
candidate: ShippingNoticeCandidate,
status: str,
reason: str,
updated_line_indexes: list[int] | None = None,
details: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
将订单数量转换为稳定比较值。
记录 open_existing 对账结果(兼容历史事件名)。
Args:
value: Candidate 或 Task 订单行中的数量。
Returns:
去除无意义小数尾零后的十进制字符串;非法值返回空字符串。
可直接放入 Tool opened_existing 响应的结构化结果。
"""
try:
quantity = Decimal(str(value).strip())
except (InvalidOperation, ValueError):
return ""
if quantity <= 0:
return ""
return format(quantity.normalize(), "f")
def _line_match_key(line: dict[str, Any]) -> tuple[str, str] | None:
"""
生成 SKU + Qty 唯一匹配键。
Args:
line: 已标准化或历史任务订单行。
Returns:
大写 SKU 与规范数量组成的键;缺少任一字段时返回 None。
"""
sku = str(line.get("sku") or "").strip().upper()
quantity = _normalized_qty(line.get("qty") if line.get("qty") is not None else line.get("quantity"))
return (sku, quantity) if sku and quantity else None
def _target_is_safe(task: ShippingTask) -> bool:
"""
判断旧任务是否仍允许补充 Reservation。
核心逻辑:只允许 pending_review + rsv_req,且库存、匹配、导出任一真相均未产生。
Args:
task: exact_file 命中的旧任务。
Returns:
是否允许执行只补空值的回填。
"""
return (
str(task.process_status or "").strip() == "pending_review"
and str(task.pending_human_reason or "").strip() == PH_RSV_REQ
and not task.inventory_lines_json
and not task.inventory_snapshot_id
and not str(task.match_status or "").strip()
and not task.line_results_json
and not str(task.export_file_path or "").strip()
and not str(task.export_file_name or "").strip()
result = {
'status': status,
'reason': reason,
'candidate_no': candidate.candidate_no,
'updated_line_indexes': list(updated_line_indexes or []),
**(details or {}),
}
log_task_event(
task,
(
'reservation_backfilled_from_exact_file_candidate'
if status == 'applied'
else 'reservation_backfill_not_applied'
),
result,
)
def _reservation_gate_issues(lines: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""
重算订单行 Reservation ID 门禁。
Args:
lines: 回填后的旧任务订单行。
Returns:
缺失或格式非法的 Reservation 行级问题。
"""
issues: list[dict[str, Any]] = []
for index, line in enumerate(lines):
raw_value = str(line.get("reservation_id") or "").strip()
if is_valid_reservation_id(raw_value):
continue
issues.append(
{
"line_index": index,
"sku": str(line.get("sku") or "").strip(),
"field": "reservation_id",
"reason": "invalid_format" if raw_value else "missing",
"severity": "blocking",
"raw_value": raw_value,
}
)
return issues
return result
def backfill_exact_file_open_existing_reservations(
@@ -112,105 +58,34 @@ def backfill_exact_file_open_existing_reservations(
candidate_summary: dict[str, Any],
duplicate_status: str,
duplicate_matches: list[dict[str, Any]],
) -> bool:
verified_reservation_evidence: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""
从 exact_file Candidate 安全补齐 open_existing 旧任务的 Reservation ID。
从 exact_file Candidate 安全对账 open_existing 旧任务字段。
核心逻辑:要求重复目标唯一、旧任务尚处 rsv_req 且未进入下游;PO 必须一致,
SKU + Qty 在新旧两侧都唯一且旧值为空时才回填。成功后仅重算 Reservation 门禁,
即使门禁清除也继续停留在 parse_review,等待人工确认。
Args:
task: open_existing 指向的旧任务。
candidate: 当前最新订单 Candidate,用于审计定位。
candidate_summary: 已通过 Candidate 校验的业务摘要。
duplicate_status: 本次实时重复检测状态,必须为 exact_file。
duplicate_matches: 本次实时重复目标列表,必须唯一命中当前 task。
Returns:
是否至少安全回填一条订单行。
核心逻辑:委托 task_candidate_reconciliation;冲突写入 ShippingTaskFieldConflict;
自动补齐仅作用于空字段,双方非空且不同绝不覆盖。
"""
matched_task_nos = {
str(item.get("task_no") or "").strip().upper()
for item in duplicate_matches
if str(item.get("task_no") or "").strip()
raw = reconcile_exact_file_open_existing(
task=task,
candidate=candidate,
candidate_summary=candidate_summary,
duplicate_status=duplicate_status,
duplicate_matches=duplicate_matches,
verified_reservation_evidence=verified_reservation_evidence,
)
status = str(raw.get('status') or 'skipped')
reason = str(raw.get('reason') or 'unknown')
details = {
key: value
for key, value in raw.items()
if key not in {'status', 'reason', 'updated_line_indexes'}
}
if (
str(duplicate_status or "").strip() != "exact_file"
or matched_task_nos != {str(task.task_no or "").strip().upper()}
or not _target_is_safe(task)
):
return False
candidate_po = normalize_po_number(candidate_summary.get("po_number"))
task_po = normalize_po_number(task.po_number)
if not candidate_po or not task_po or candidate_po != task_po:
return False
target_lines = [dict(item) for item in (task.lines_json or []) if isinstance(item, dict)]
candidate_lines = [
dict(item)
for item in (candidate_summary.get("lines") or [])
if isinstance(item, dict)
]
target_keys = [_line_match_key(line) for line in target_lines]
candidate_keys = [_line_match_key(line) for line in candidate_lines]
target_counts = Counter(key for key in target_keys if key is not None)
candidate_counts = Counter(key for key in candidate_keys if key is not None)
updated_indexes: list[int] = []
reservation_by_key: dict[tuple[str, str], str] = {}
for line, key in zip(candidate_lines, candidate_keys, strict=True):
reservation_id = validated_reservation_id(line.get("reservation_id"))
if (
key is not None
and reservation_id
and candidate_counts[key] == 1
and target_counts[key] == 1
):
reservation_by_key[key] = reservation_id
for index, (line, key) in enumerate(zip(target_lines, target_keys, strict=True)):
if key not in reservation_by_key or str(line.get("reservation_id") or "").strip():
continue
line["reservation_id"] = reservation_by_key[key]
updated_indexes.append(index)
if not updated_indexes:
return False
# [STEP 1] 回填只写空 Reservation,不改变 PO/SKU/Qty 或库存源路由线索。
task.lines_json = target_lines
issues = _reservation_gate_issues(target_lines)
step_payload = dict(task.step_payload_json or {})
step_payload["parse_validation"] = {
"status": "needs_review" if issues else "ready",
"issues": issues,
"contract_version": "shipping-line-v1",
"resolution_source": "exact_file_candidate_backfill",
}
if issues:
step_payload["process_field_gate"] = {
"status": "needs_enrichment",
"missing_fields": ["reservation_id"],
"issues": issues,
"contract_version": "shipping-order-extraction-v1",
}
apply_task_transition(task, TaskTransition.RSV_REQUIRED)
else:
step_payload.pop("process_field_gate", None)
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
task.error_message = None
task.step_payload_json = step_payload
# [STEP 2] 保留人工复核,并记录可追溯的 Candidate 与订单行索引。
log_task_event(
task,
"reservation_backfilled_from_exact_file_candidate",
{
"candidate_no": candidate.candidate_no,
"duplicate_status": duplicate_status,
"updated_line_indexes": updated_indexes,
"remaining_issue_count": len(issues),
"review_preserved": True,
},
return _record_outcome(
task=task,
candidate=candidate,
status=status,
reason=reason,
updated_line_indexes=list(raw.get('updated_line_indexes') or []),
details=details or None,
)
return True
@@ -160,9 +160,12 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"qty": {"type": "number", "exclusiveMinimum": 0},
"reservation_id": _str_prop("可为空,缺失时 Task 停在补字段门禁"),
"source_type": _str_prop(
"可选订单路由线索;仅在原文有可靠证据时填写,"
"可选订单路由线索(库存来源提示);仅在原文有可靠证据时填写,"
"不代表任务通知来源或已确认的库存连接器类型"
),
"hub_code": _str_prop(
"可选 Hub/站点线索;与 source_type 独立落库,禁止折叠进 source_type"
),
},
"additionalProperties": True,
},
@@ -193,7 +196,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
description=(
"只接受 get_order_extraction_context 的同一快照。HXOPS 仅在分类、SKU/Qty 置信度及原文证据均达标,"
"且无阻断冲突/修订决策时自动建单;Reservation ID 允许缺失,"
"订单行 Source Type 是可选路由线索。"
"订单行 Source Type / Hub Code 是可选路由线索并独立持久化。"
"响应以持久化结果分别返回 created_count、opened_existing_count、pending_count、"
"non_shipping_count;auto_created_count 仅为兼容字段且等于 created_count。"
),
@@ -236,8 +239,8 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"patch": {
"type": "object",
"description": (
"可更新字段:sku/reservation_id/quantity/qty/required_date/uom/source_type;"
"source_type 仅作为可选订单路由线索"
"可更新字段:sku/reservation_id/quantity/qty/required_date/uom/source_type/hub_code;"
"source_type 与 hub_code 均为可选订单路由线索并独立落库"
),
"additionalProperties": True,
},
@@ -42,6 +42,11 @@ from app.services.shipping_notice.duplicate_detection import (
detect_duplicates_for_candidate,
)
from app.services.shipping_notice.document_candidate_persist import generate_candidate_no
from app.services.shipping_notice.order_extraction_evidence import (
adjudicate_order_reservations,
verify_reservation_evidence,
)
from app.services.shipping_notice.reservation_id import validated_reservation_id
EXTRACTION_CONTRACT_VERSION = 'shipping-order-extraction-v1'
_CONTEXT_PATHS = [
@@ -691,7 +696,7 @@ def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]:
'required_order_fields': ['source_intake_no', 'primary_document_id', 'classification', 'lines'],
'auto_create_required_line_fields': ['sku', 'qty'],
'required_process_line_fields': ['reservation_id'],
'optional_routing_line_fields': ['source_type'],
'optional_routing_line_fields': ['source_type', 'hub_code'],
'allowed_missing_process_fields': ['reservation_id'],
},
}
@@ -911,7 +916,34 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
summary.pop('source_intake_no', None)
summary.pop('primary_document_id', None)
assessment = assess_candidate_business_summary(summary)
normalized, backend_conflicts = adjudicate_order_reservations(
assessment['normalized_summary'],
documents=owned_docs,
)
assessment = assess_candidate_business_summary(normalized)
normalized = assessment['normalized_summary']
blocking_conflicts.extend(backend_conflicts)
# [STEP] 证据核验对齐裁决后的行值,门禁比较 (line_index, reservation_id) pair,
# 避免仅比 index 时把被裁决改写过的 Reservation 误判为已核验。
order_for_evidence = dict(raw_order)
order_for_evidence['lines'] = list(normalized.get('lines') or [])
verified_reservation_evidence = verify_reservation_evidence(
order_for_evidence,
documents=owned_docs,
)
reservation_pairs = {
(line_index, reservation_id)
for line_index, line in enumerate(normalized.get('lines') or [])
if isinstance(line, dict)
for reservation_id in [validated_reservation_id(line.get('reservation_id'))]
if reservation_id
}
verified_reservation_pairs = {
(int(item['line_index']), validated_reservation_id(item.get('reservation_id')))
for item in verified_reservation_evidence
if str(item.get('line_index', '')).isdigit()
and validated_reservation_id(item.get('reservation_id'))
}
field_confidence = raw_order.get('field_confidence') if isinstance(raw_order.get('field_confidence'), dict) else {}
sku_conf = _float(field_confidence.get('sku'))
qty_conf = _float(field_confidence.get('qty'))
@@ -926,6 +958,8 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
reasons.append('low_sku_qty_confidence')
if not _evidence_has_sku_qty(raw_order):
reasons.append('missing_sku_qty_evidence')
if reservation_pairs - verified_reservation_pairs:
reasons.append('unverified_reservation_evidence')
if blocking_conflicts:
reasons.append('blocking_conflict')
@@ -980,6 +1014,7 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
'missing_process_fields': assessment['missing_process_fields'],
'process_issues': assessment['process_issues'],
'auto_create_reasons': reasons,
'verified_reservation_evidence': verified_reservation_evidence,
},
}
duplicate = detect_duplicates_for_candidate(
@@ -997,7 +1032,9 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
if matches:
candidate.duplicate_resolution = 'open_existing'
candidate.duplicate_target_task_no = str(matches[0].get('task_no') or '').strip().upper() or None
candidate.selected = True
# [STEP] 仅无审核阻断原因时才选中自动打开;证据/冲突失败必须保持未选中,
# 否则同 Intake 其它 ready Candidate 会被 selection 门禁整批挡住。
candidate.selected = not reasons
candidate.validation_status = 'ready' if not reasons else 'needs_review'
elif duplicate.get('blocking'):
reasons.append('duplicate_decision_required')
@@ -1097,6 +1134,22 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
or create_data.get('opened_existing')
or []
)
for item in (create_result or {}).get('reconciliation_pending') or []:
if not isinstance(item, dict):
continue
reconciliation = (
item.get('reconciliation')
if isinstance(item.get('reconciliation'), dict)
else {}
)
pending.append({
'candidate_no': item.get('candidate_no'),
'task_no': item.get('task_no'),
'reasons': [
str(reconciliation.get('reason') or 'open_existing_reconciliation_required')
],
'reconciliation': reconciliation,
})
created_count = len(created)
opened_existing_count = len(opened_existing)
created_with_missing_fields_count = sum(
@@ -0,0 +1,115 @@
"""
backend/app/services/shipping_notice/order_extraction_evidence.py
用途:校验订单抽取字段证据,并用后端表格解析结果裁决 Reservation ID 来源冲突。
依赖:ShippingNoticeDocument、notice_lines.adjudicate_notice_lines、reservation_id。
逻辑:order_extraction 在 Candidate 落库前调用;可信证据随抽取审计保存,供 open_existing 回填门禁复用。
"""
from __future__ import annotations
from typing import Any
from app.models import ShippingNoticeDocument
from app.services.shipping_notice.notice_lines import adjudicate_notice_lines
from app.services.shipping_notice.reservation_id import validated_reservation_id
def verify_reservation_evidence(
order: dict[str, Any],
*,
documents: list[ShippingNoticeDocument],
) -> list[dict[str, Any]]:
"""
验证每条非空 Reservation ID 的字段级原文证据。
核心逻辑:证据字段必须精确指向同一行,Document 必须属于当前 Intake,
quote 必须原样存在于该 Document 文本,且 quote 中包含标准化后的 Reservation ID。
Args:
order: LLM 提交的单个订单对象。
documents: 当前订单所属 Intake 的全部已锁定 Document。
Returns:
通过验证的证据列表;未通过的证据不会进入可信审计投影。
"""
document_by_id = {int(item.id): item for item in documents}
evidence_items = [
item
for item in (order.get("evidence") or [])
if isinstance(item, dict)
]
verified: list[dict[str, Any]] = []
lines = order.get("lines") if isinstance(order.get("lines"), list) else []
for line_index, raw_line in enumerate(lines):
line = raw_line if isinstance(raw_line, dict) else {}
reservation_id = validated_reservation_id(line.get("reservation_id"))
if not reservation_id:
continue
expected_field = f"lines[{line_index}].reservation_id"
for evidence in evidence_items:
if str(evidence.get("field") or "").strip().lower() != expected_field.lower():
continue
document_id = evidence.get("document_id")
document = (
document_by_id.get(int(document_id))
if str(document_id or "").isdigit()
else None
)
quote = str(evidence.get("quote") or "").strip()
source_text = str(document.extracted_text or "") if document is not None else ""
if not quote or quote not in source_text or reservation_id not in quote:
continue
verified.append(
{
"line_index": line_index,
"field": expected_field,
"reservation_id": reservation_id,
"quote": quote,
"document_id": int(document.id),
}
)
break
return verified
def adjudicate_order_reservations(
summary: dict[str, Any],
*,
documents: list[ShippingNoticeDocument],
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
"""
用当前 Intake 的保留列边界文本裁决 Candidate Reservation ID。
核心逻辑:复用普通通知解析链的 adjudicate_notice_lines;仅明确表格来源冲突作为
本阶段的阻断问题,缺失 Reservation 继续交由流程字段 Gate 处理。
Args:
summary: 已完成基础字段标准化的 Candidate 摘要。
documents: 当前订单所属 Intake 的全部 Document。
Returns:
裁决后的摘要副本,以及需写入 Candidate conflicts 的来源冲突列表。
"""
result = dict(summary)
lines = [
dict(item)
for item in (summary.get("lines") or [])
if isinstance(item, dict)
]
raw_text = "\n".join(str(item.extracted_text or "") for item in documents)
adjudicated, issues, _status = adjudicate_notice_lines(lines, raw_text=raw_text)
result["lines"] = adjudicated
result["reservation_ids"] = sorted(
{
reservation_id
for line in adjudicated
if (reservation_id := validated_reservation_id(line.get("reservation_id")))
}
)
conflicts = [
{**item, "severity": "blocking", "source": "backend_document_adjudication"}
for item in issues
if str(item.get("reason") or "") == "source_conflict"
]
return result, conflicts
@@ -2,10 +2,12 @@
services/shipping_notice/query_service.py
用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链与重复决策字段)。
依赖:models.ShippingBatch、ShippingCase、ShippingTask、ShippingTaskEvent。
依赖:models.ShippingBatch、ShippingCase、ShippingNoticeCandidate、ShippingTask、ShippingTaskEvent、task_line_store。
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉;
SUMMARY/DETAIL 经 _task_version_chain_fields 暴露 document_version / supersedes / duplicate_*。
SUMMARY/DETAIL 经 _task_version_chain_fields 暴露 document_version / supersedes / duplicate_*;
DETAIL 另投影 parse_validation / process_field_gate / source_candidate 供持久只读展示;
订单行经 task_line_store.read_task_order_lines,支持 shadow 差异观测。
"""
from __future__ import annotations
@@ -25,6 +27,7 @@ from app.models import (
ShippingNoticeIntake,
ShippingTask,
)
from app.services.shipping_notice.task_line_store import read_task_order_lines
EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
@@ -364,7 +367,7 @@ def _task_tool_payload(task: ShippingTask) -> dict[str, Any]:
"ship_to": task.ship_to,
"po_number": task.po_number,
"required_date": task.required_date,
"lines": task.lines_json or [],
"lines": read_task_order_lines(task),
"shortage": task.shortage_json,
"line_results": task.line_results_json,
"export_file_name": task.export_file_name,
@@ -375,7 +378,7 @@ def _task_tool_payload(task: ShippingTask) -> dict[str, Any]:
"rpa_runtime": rpa_runtime_mode(step_payload.get("last_inventory_rpa_runtime") if isinstance(step_payload, dict) else None),
}
raw_content = str(task.raw_content or "").strip()
lines = task.lines_json or []
lines = payload["lines"]
from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link
payload["inventory_snapshot"] = serialize_inventory_snapshot_link(task)
@@ -429,6 +432,43 @@ def _task_version_chain_fields(task: ShippingTask) -> dict[str, Any]:
}
def _dict_or_none(value: Any) -> dict[str, Any] | None:
"""将 step_payload 内对象投影为 dict;非 dict 时返回 None。"""
return dict(value) if isinstance(value, dict) else None
def _serialize_open_field_conflicts(task: ShippingTask) -> list[dict[str, Any]]:
"""投影未解决字段冲突,供工作台冲突复核 UI。"""
from app.services.shipping_notice.task_field_conflict_service import (
list_open_field_conflicts,
serialize_field_conflict,
)
return [serialize_field_conflict(row) for row in list_open_field_conflicts(task)]
def _serialize_source_candidate_projection(task: ShippingTask) -> dict[str, Any] | None:
"""
投影建单来源 Candidate 的只读审计字段。
核心逻辑:按 source_candidate_id 取落库 evidence / missing_fields / field_confidence;
Candidate 已清理或不存在时返回 None,不阻断 Task Detail。
"""
if not task.source_candidate_id:
return None
candidate = db.session.get(ShippingNoticeCandidate, int(task.source_candidate_id))
if candidate is None:
return None
field_confidence = candidate.field_confidence_json
return {
"candidate_no": candidate.candidate_no,
"missing_fields": list(candidate.missing_fields_json or []),
"field_confidence": dict(field_confidence) if isinstance(field_confidence, dict) else {},
"evidence": list(candidate.evidence_json or []),
"conflicts": list(candidate.conflicts_json or []),
}
def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str, Any]:
"""按投影类型序列化任务;TOOL 会剔除 Agent 不应复述的内部状态码。"""
from app.services.shipping_notice.rpa import rpa_runtime_mode
@@ -498,21 +538,28 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
data.update(_task_version_chain_fields(task))
return data
if projection == TaskProjection.DETAIL:
step_payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
data = serialize_task(task, TaskProjection.SUMMARY)
data.update({
"customer_code": task.customer_code,
"ship_to": task.ship_to,
"po_number": task.po_number,
"required_date": task.required_date,
"step_payload": task.step_payload_json or {},
"step_payload": step_payload,
"upload_receipt": task.upload_receipt_json or {},
"export_version": task.export_version,
"idempotency_key": task.idempotency_key,
"lines": task.lines_json or [],
"lines": read_task_order_lines(task),
"shortage": task.shortage_json,
"line_results": task.line_results_json or [],
"parse_confidence": task.parse_confidence,
"error_message": task.error_message,
# [STEP] 稳定顶层投影解析门禁与来源 Candidate 审计,供工作台持久只读展示。
"parse_validation": _dict_or_none(step_payload.get("parse_validation")),
"process_field_gate": _dict_or_none(step_payload.get("process_field_gate")),
"source_candidate": _serialize_source_candidate_projection(task),
"order_data_version": int(task.order_data_version or 1),
"field_conflicts": _serialize_open_field_conflicts(task),
"events": [
{
"event_type": e.event_type,
@@ -0,0 +1,43 @@
"""
backend/app/services/shipping_notice/reservation_gate.py
用途:为库存、RPA、匹配、导出和上传入口提供统一的订单侧 Reservation ID 门禁判断。
依赖:reservation_id.is_valid_reservation_id。
逻辑:各推进服务在产生外部或下游副作用前调用本模块,确保任何直接入口都不能绕过订单字段门禁。
"""
from __future__ import annotations
from typing import Any
from app.services.shipping_notice.reservation_id import is_valid_reservation_id
def reservation_gate_issues(lines: list[Any] | None) -> list[dict[str, Any]]:
"""
返回缺失或格式非法的订单行 Reservation ID 问题。
Args:
lines: ShippingTask 订单行数组。
Returns:
含行号、SKU、原值和原因的 blocking issue;全部合法时返回空列表。
"""
issues: list[dict[str, Any]] = []
for index, raw_line in enumerate(lines or []):
if not isinstance(raw_line, dict):
continue
raw_value = str(raw_line.get("reservation_id") or "").strip()
if is_valid_reservation_id(raw_value):
continue
issues.append(
{
"line_index": index,
"sku": str(raw_line.get("sku") or "").strip(),
"field": "reservation_id",
"reason": "invalid_format" if raw_value else "missing",
"severity": "blocking",
"raw_value": raw_value,
}
)
return issues
@@ -2,8 +2,9 @@
services/shipping_notice/state_machine.py
用途:发货通知人工节点(checkpoint)与动作按钮的单一注册表,负责任务 DB 字段与 UI 状态的映射。
依赖:models.ShippingTask、constants(CP_*/PH_*/RS_*)、rpa_attempts。
逻辑:tools.py 通过 apply_task_transition 写库并返回 checkpoint;ui_state.py 与历史兼容模块都从本文件读取按钮/状态;新增人工节点时仅改本文件与测试。
依赖:models.ShippingTask、constants(CP_*/PH_*/RS_*)、rpa_attempts、task_line_store。
逻辑:tools.py 通过 apply_task_transition 写库并返回 checkpoint;ui_state.py 与历史兼容模块都从本文件读取按钮/状态;新增人工节点时仅改本文件与测试;
是否具备可匹配订单行经 read_task_order_lines 判断。
扩展说明(开发者):
- checkpoint id 即 API `checkpoint` / Dify `flow_ckpt`
@@ -18,6 +19,7 @@ from enum import StrEnum
from typing import Any
from app.models import ShippingTask
from app.services.shipping_notice.task_line_store import read_task_order_lines
from app.services.shipping_notice.constants import (
CP_ALIGN_REVIEW,
CP_EXPORT_READY,
@@ -325,8 +327,7 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
and not task.review_status
and not task.pending_human_reason
and not task.match_status
and isinstance(task.lines_json, list)
and len(task.lines_json) > 0
and len(read_task_order_lines(task)) > 0
):
return TaskUiState(
checkpoint=CP_READY_MATCH,
@@ -0,0 +1,443 @@
"""
backend/app/services/shipping_notice/task_candidate_reconciliation.py
用途:将 Candidate 订单行对账到既有 Task(字段级自动补齐 / 冲突落库)。
依赖:po_number、reservation_id、task_line_store、task_field_conflict_service、state_machine。
逻辑:batch_from_intakes / open_existing 路径调用;仅安全态任务可自动补齐。
"""
from __future__ import annotations
from collections import Counter
from decimal import Decimal, InvalidOperation
from typing import Any
from app.models import ShippingNoticeCandidate, ShippingTask
from app.services.shipping_notice.constants import PH_RSV_REQ
from app.services.shipping_notice.po_number import normalize_po_number
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
from app.services.shipping_notice.reservation_id import (
is_valid_reservation_id,
validated_reservation_id,
)
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.task_field_conflict_service import (
line_id_for_conflict_position,
list_open_field_conflicts,
upsert_open_field_conflict,
)
from app.services.shipping_notice.task_line_store import read_task_order_lines, replace_task_order_lines
# 可自动对账字段;SKU/Qty 仅作行对齐键,禁止被 Candidate 覆盖。
RECONCILE_FIELDS: tuple[str, ...] = (
'reservation_id',
'source_type',
'hub_code',
'uom',
'required_date',
'vendor_part_number',
'customer_sku',
'allocation_id',
)
def _normalized_qty(value: Any) -> str:
"""数量稳定比较值。"""
try:
quantity = Decimal(str(value).strip())
except (InvalidOperation, ValueError, AttributeError):
return ''
if quantity <= 0:
return ''
text = format(quantity.normalize(), 'f')
if '.' in text:
text = text.rstrip('0').rstrip('.')
return text
def _line_match_key(line: dict[str, Any]) -> tuple[str, str] | None:
"""唯一业务键:(sku, qty)。"""
sku = str(line.get('sku') or '').strip().upper()
qty = _normalized_qty(line.get('qty'))
if not sku or not qty:
return None
return sku, qty
def _normalize_field_value(field_name: str, value: Any) -> str:
"""字段值规范化后再比较/写入。"""
text = str(value or '').strip()
if not text:
return ''
if field_name == 'reservation_id':
return validated_reservation_id(text) or ''
if field_name in {'sku', 'source_type', 'hub_code', 'uom'}:
return text.upper() if field_name == 'sku' else text
return text
def _target_is_safe(task: ShippingTask) -> bool:
"""
仅尚未进入库存链、仍停在 rsv_req 的任务允许自动对账。
核心逻辑:与历史 open_existing Reservation 回填安全边界保持一致,避免已推进任务被静默改写。
"""
if str(task.process_status or '').strip().lower() != 'pending_review':
return False
if str(task.pending_human_reason or '').strip().lower() != PH_RSV_REQ:
return False
if task.inventory_lines_json or task.line_results_json or task.export_file_path or task.freight_ref_no:
return False
if task.match_status or task.upload_status:
return False
return True
def build_candidate_reconciliation_plan(
*,
task: ShippingTask,
candidate_summary: dict[str, Any],
verified_reservation_evidence: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""
生成字段级对账计划(不落库)。
Returns:
{status, reason?, fills[], conflicts[], ambiguous_keys[], unverified_indexes[]}
"""
target_lines = read_task_order_lines(task)
candidate_lines = [
dict(item) for item in (candidate_summary.get('lines') or []) if isinstance(item, dict)
]
target_keys = [_line_match_key(line) for line in target_lines]
candidate_keys = [_line_match_key(line) for line in candidate_lines]
target_counts = Counter(key for key in target_keys if key is not None)
candidate_counts = Counter(key for key in candidate_keys if key is not None)
trusted_pairs = {
(int(item.get('line_index')), validated_reservation_id(item.get('reservation_id')))
for item in (verified_reservation_evidence or [])
if str(item.get('line_index', '')).isdigit()
and validated_reservation_id(item.get('reservation_id'))
}
fills: list[dict[str, Any]] = []
conflicts: list[dict[str, Any]] = []
ambiguous_keys: list[tuple[str, str]] = []
unverified_indexes: list[int] = []
# [STEP 1] Candidate 侧按唯一键建立可信任字段投影。
incoming_by_key: dict[tuple[str, str], dict[str, Any]] = {}
for candidate_index, (line, key) in enumerate(zip(candidate_lines, candidate_keys, strict=True)):
if key is None:
continue
if candidate_counts[key] != 1:
ambiguous_keys.append(key)
continue
field_payload: dict[str, Any] = {}
for field_name in RECONCILE_FIELDS:
raw = line.get(field_name)
normalized = _normalize_field_value(field_name, raw)
if not normalized:
continue
if field_name == 'reservation_id':
if (candidate_index, normalized) not in trusted_pairs:
unverified_indexes.append(candidate_index)
continue
field_payload[field_name] = {
'value': normalized,
'candidate_line_index': candidate_index,
}
if field_payload:
incoming_by_key[key] = field_payload
if unverified_indexes:
return {
'status': 'skipped',
'reason': 'unverified_reservation_evidence',
'fills': [],
'conflicts': [],
'details': {'candidate_line_indexes': unverified_indexes},
}
if ambiguous_keys:
return {
'status': 'skipped',
'reason': 'ambiguous_line_match',
'fills': [],
'conflicts': [],
'details': {'keys': [list(item) for item in sorted(set(ambiguous_keys))]},
}
# [STEP 2] 对目标唯一行套用规则。
for position, (line, key) in enumerate(zip(target_lines, target_keys, strict=True)):
if key is None or target_counts[key] != 1:
if key is not None and target_counts[key] > 1:
ambiguous_keys.append(key)
continue
incoming_fields = incoming_by_key.get(key) or {}
for field_name, payload in incoming_fields.items():
incoming = str(payload['value'])
existing_raw = str(line.get(field_name) or '').strip()
existing = _normalize_field_value(field_name, existing_raw)
# 非法但非空旧值仍视为“已有值”,禁止静默覆盖(与历史 Reservation 回填一致)。
if not existing and existing_raw:
existing = existing_raw
if not existing:
fills.append(
{
'position': position,
'field_name': field_name,
'value': incoming,
'candidate_line_index': payload['candidate_line_index'],
}
)
continue
if existing == incoming:
continue
conflicts.append(
{
'position': position,
'field_name': field_name,
'existing_value': existing,
'incoming_value': incoming,
'candidate_line_index': payload['candidate_line_index'],
}
)
if ambiguous_keys:
return {
'status': 'skipped',
'reason': 'ambiguous_line_match',
'fills': [],
'conflicts': [],
'details': {'keys': [list(item) for item in sorted(set(ambiguous_keys))]},
}
if conflicts:
return {
'status': 'conflicted',
'reason': 'field_value_conflict',
'fills': fills,
'conflicts': conflicts,
}
if not fills:
return {
'status': 'skipped',
'reason': 'no_fillable_fields',
'fills': [],
'conflicts': [],
}
return {
'status': 'ready',
'reason': 'auto_fill',
'fills': fills,
'conflicts': [],
}
def _apply_fills_to_lines(
target_lines: list[dict[str, Any]],
fills: list[dict[str, Any]],
) -> set[int]:
"""仅对空字段执行 fills,返回变更过的行下标。"""
updated: set[int] = set()
for item in fills:
position = int(item['position'])
if position < 0 or position >= len(target_lines):
continue
field_name = str(item['field_name'])
if str(target_lines[position].get(field_name) or '').strip():
continue
target_lines[position][field_name] = item['value']
updated.add(position)
return updated
def apply_candidate_reconciliation_plan(
*,
task: ShippingTask,
candidate: ShippingNoticeCandidate,
plan: dict[str, Any],
source: str = 'candidate_reconciliation',
) -> dict[str, Any]:
"""
应用对账计划:自动补齐或落库冲突。
核心逻辑:ready/conflicted 均先安全应用空字段 fills(双写);
conflicted 额外落库字段冲突,不覆盖双方已有且不同的业务值。
"""
status = str(plan.get('status') or '')
if status not in {'ready', 'conflicted'}:
return {
'status': 'skipped',
'reason': str(plan.get('reason') or 'not_ready'),
'updated_line_indexes': [],
'details': plan.get('details') or {},
}
# [STEP 1] 无论 ready/conflicted,都先安全应用空字段 fills,并确保规范行存在以便绑定 line_id。
target_lines = [dict(item) for item in read_task_order_lines(task)]
updated_indexes = _apply_fills_to_lines(target_lines, list(plan.get('fills') or []))
target_lines = replace_task_order_lines(
task,
target_lines,
normalize=False,
bump_version=bool(updated_indexes) or status == 'conflicted',
)
if status == 'conflicted':
for item in plan.get('conflicts') or []:
position = int(item['position'])
upsert_open_field_conflict(
task=task,
field_name=str(item['field_name']),
existing_value=item.get('existing_value'),
incoming_value=item.get('incoming_value'),
existing_source='task_lines',
incoming_source=source,
position=position,
line_id=line_id_for_conflict_position(task, position),
incoming_evidence=[
{
'candidate_no': candidate.candidate_no,
'candidate_line_index': item.get('candidate_line_index'),
}
],
)
open_rows = list_open_field_conflicts(task)
issues = reservation_gate_issues(target_lines)
step_payload = dict(task.step_payload_json or {})
step_payload['parse_validation'] = {
'status': 'needs_review',
'issues': issues,
'contract_version': 'shipping-line-v1',
'resolution_source': source,
}
step_payload['process_field_gate'] = {
'status': 'needs_enrichment',
'missing_fields': sorted({row.field_name for row in open_rows}),
'issues': [
{
'severity': 'blocking',
'field': row.field_name,
'line_index': row.position,
'reason': 'field_conflict',
'conflict_id': row.id,
}
for row in open_rows
],
'contract_version': 'shipping-order-extraction-v1',
}
step_payload['field_conflicts'] = {'open_count': len(open_rows)}
task.step_payload_json = step_payload
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
return {
'status': 'conflicted',
'reason': str(plan.get('reason') or 'field_value_conflict'),
'updated_line_indexes': sorted(updated_indexes),
'conflict_count': len(open_rows),
}
if not updated_indexes:
return {
'status': 'skipped',
'reason': 'no_fillable_fields',
'updated_line_indexes': [],
}
issues = reservation_gate_issues(target_lines)
open_rows = list_open_field_conflicts(task)
step_payload = dict(task.step_payload_json or {})
step_payload['parse_validation'] = {
'status': 'needs_review' if issues or open_rows else 'ready',
'issues': issues,
'contract_version': 'shipping-line-v1',
'resolution_source': source,
}
if open_rows:
step_payload['process_field_gate'] = {
'status': 'needs_enrichment',
'missing_fields': sorted({row.field_name for row in open_rows}),
'issues': [
{
'severity': 'blocking',
'field': row.field_name,
'line_index': row.position,
'reason': 'field_conflict',
'conflict_id': row.id,
}
for row in open_rows
],
'contract_version': 'shipping-order-extraction-v1',
}
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
elif issues:
step_payload['process_field_gate'] = {
'status': 'needs_enrichment',
'missing_fields': ['reservation_id'],
'issues': issues,
'contract_version': 'shipping-order-extraction-v1',
}
apply_task_transition(task, TaskTransition.RSV_REQUIRED)
else:
step_payload.pop('process_field_gate', None)
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
task.error_message = None
task.step_payload_json = step_payload
return {
'status': 'applied',
'reason': 'fields_backfilled',
'updated_line_indexes': sorted(updated_indexes),
'remaining_issue_count': len(issues) + len(open_rows),
}
def reconcile_exact_file_open_existing(
*,
task: ShippingTask,
candidate: ShippingNoticeCandidate,
candidate_summary: dict[str, Any],
duplicate_status: str,
duplicate_matches: list[dict[str, Any]],
verified_reservation_evidence: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""
exact_file/open_existing 通用字段对账入口(替代纯 Reservation 特例)。
保留原有前置校验语义,并对冲突落库 ShippingTaskFieldConflict。
"""
matched_task_nos = {
str(item.get('task_no') or '').strip().upper()
for item in duplicate_matches
if str(item.get('task_no') or '').strip()
}
if str(duplicate_status or '').strip() != 'exact_file':
return {'status': 'skipped', 'reason': 'duplicate_status_not_exact_file'}
if matched_task_nos != {str(task.task_no or '').strip().upper()}:
return {'status': 'skipped', 'reason': 'duplicate_target_not_unique'}
if not _target_is_safe(task):
return {'status': 'skipped', 'reason': 'target_task_not_safe'}
candidate_po = normalize_po_number(candidate_summary.get('po_number'))
task_po = normalize_po_number(task.po_number)
if not candidate_po or not task_po or candidate_po != task_po:
return {'status': 'skipped', 'reason': 'po_number_mismatch'}
plan = build_candidate_reconciliation_plan(
task=task,
candidate_summary=candidate_summary,
verified_reservation_evidence=verified_reservation_evidence,
)
# 兼容旧语义:仅 Reservation 已齐且无其他可填字段时视为 target_already_complete。
if plan.get('status') == 'skipped' and plan.get('reason') == 'no_fillable_fields':
lines = read_task_order_lines(task)
if lines and all(is_valid_reservation_id(line.get('reservation_id')) for line in lines):
return {'status': 'skipped', 'reason': 'target_already_complete'}
return {'status': 'skipped', 'reason': 'no_unique_empty_target_line'}
result = apply_candidate_reconciliation_plan(
task=task,
candidate=candidate,
plan=plan,
source='exact_file_candidate_reconciliation',
)
return result
@@ -0,0 +1,303 @@
"""
backend/app/services/shipping_notice/task_field_conflict_service.py
用途:订单字段冲突的创建、查询与人工解决。
依赖:ShippingTask、ShippingTaskFieldConflict、ShippingTaskLine、task_line_store、state_machine。
逻辑:对账模块写入 open 冲突;workspace API 查询/解决;解决后回写订单行并重算门禁。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import ShippingTask, ShippingTaskFieldConflict, ShippingTaskLine
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.task_line_store import read_task_order_lines, replace_task_order_lines
from app.services.shipping_notice.tool_common import log_task_event
def serialize_field_conflict(row: ShippingTaskFieldConflict) -> dict[str, Any]:
"""将冲突行投影为 API/前端可读字典。"""
return {
'id': row.id,
'task_id': row.task_id,
'line_id': row.line_id,
'position': row.position,
'field_name': row.field_name,
'existing_value': row.existing_value,
'incoming_value': row.incoming_value,
'existing_source': row.existing_source,
'incoming_source': row.incoming_source,
'existing_evidence': list(row.existing_evidence_json or []),
'incoming_evidence': list(row.incoming_evidence_json or []),
'status': row.status,
'resolved_value': row.resolved_value,
'resolved_by_id': row.resolved_by_id,
'resolved_at': row.resolved_at.isoformat() if row.resolved_at else None,
'resolution_reason': row.resolution_reason,
'conflict_version': row.conflict_version,
'created_at': row.created_at.isoformat() if row.created_at else None,
'updated_at': row.updated_at.isoformat() if row.updated_at else None,
}
def list_open_field_conflicts(task: ShippingTask) -> list[ShippingTaskFieldConflict]:
"""返回任务未解决字段冲突(open),按 position/field 排序。"""
rows = (
ShippingTaskFieldConflict.query.filter_by(task_id=int(task.id), status='open')
.order_by(
ShippingTaskFieldConflict.field_name.asc(),
ShippingTaskFieldConflict.id.asc(),
)
.all()
)
return sorted(rows, key=lambda row: (row.position is None, row.position or 0, row.field_name, row.id))
def upsert_open_field_conflict(
*,
task: ShippingTask,
field_name: str,
existing_value: Any,
incoming_value: Any,
existing_source: str | None = None,
incoming_source: str | None = None,
existing_evidence: list[dict[str, Any]] | None = None,
incoming_evidence: list[dict[str, Any]] | None = None,
position: int | None = None,
line_id: int | None = None,
) -> ShippingTaskFieldConflict:
"""
创建或刷新同一 (task, line, field) 的 open 冲突。
核心逻辑:已有 open 冲突则更新双方值/证据并递增 conflict_version;否则新建。
"""
query = ShippingTaskFieldConflict.query.filter_by(
task_id=int(task.id),
field_name=str(field_name),
status='open',
)
# 行级冲突优先按 position 定位,避免 line_id 重建或为空时多行同字段被压成一条。
if position is not None:
query = query.filter_by(position=int(position))
elif line_id is not None:
query = query.filter_by(line_id=int(line_id))
else:
query = query.filter(
ShippingTaskFieldConflict.line_id.is_(None),
ShippingTaskFieldConflict.position.is_(None),
)
row = query.first()
payload = {
'position': position,
'existing_value': None if existing_value in (None, '') else str(existing_value),
'incoming_value': None if incoming_value in (None, '') else str(incoming_value),
'existing_source': existing_source,
'incoming_source': incoming_source,
'existing_evidence_json': list(existing_evidence or []) or None,
'incoming_evidence_json': list(incoming_evidence or []) or None,
}
if row is None:
row = ShippingTaskFieldConflict(
task_id=int(task.id),
line_id=line_id,
field_name=str(field_name),
status='open',
conflict_version=1,
**payload,
)
db.session.add(row)
return row
for key, value in payload.items():
setattr(row, key, value)
row.conflict_version = int(row.conflict_version or 1) + 1
row.updated_at = datetime.utcnow()
return row
def _line_id_for_position(task: ShippingTask, position: int | None) -> int | None:
"""按 position 解析规范行主键;无规范行时返回 None。"""
if position is None:
return None
row = (
ShippingTaskLine.query.filter_by(task_id=int(task.id), position=int(position))
.first()
)
return int(row.id) if row else None
def resolve_field_conflict(
*,
task: ShippingTask,
conflict_id: int,
resolution: str,
resolved_value: Any = None,
expected_conflict_version: int | None = None,
expected_order_data_version: int | None = None,
resolved_by_id: int | None = None,
reason: str | None = None,
idempotency_key: str | None = None,
) -> dict[str, Any]:
"""
人工解决字段冲突并回写订单行。
核心逻辑:校验版本;按 keep_existing / take_incoming / custom 取值;
经 task_line_store 双写后标记 resolved,并回到 parse_review。
Args:
resolution: keep_existing | take_incoming | custom
expected_conflict_version / expected_order_data_version: 乐观锁;不匹配抛 409。
"""
conflict = (
ShippingTaskFieldConflict.query.filter_by(id=int(conflict_id), task_id=int(task.id))
.first()
)
if conflict is None:
raise NotFoundError('Field conflict not found', code='SHIPPING.FIELD_CONFLICT_NOT_FOUND')
# [STEP 1] 幂等:已解决且同键重复提交直接返回。
if conflict.status == 'resolved':
step_payload = dict(task.step_payload_json or {})
last_key = str((step_payload.get('last_conflict_resolve_idempotency_key') or '')).strip()
if idempotency_key and last_key and last_key == str(idempotency_key).strip():
return {
'conflict': serialize_field_conflict(conflict),
'task_no': task.task_no,
'order_data_version': task.order_data_version,
'idempotent_replay': True,
}
raise ConflictError(
'Field conflict already resolved',
code='SHIPPING.FIELD_CONFLICT_ALREADY_RESOLVED',
details={'conflict_id': conflict.id, 'status': conflict.status},
)
if expected_conflict_version is not None and int(conflict.conflict_version) != int(
expected_conflict_version
):
raise ConflictError(
'Field conflict version mismatch',
code='SHIPPING.FIELD_CONFLICT_VERSION_MISMATCH',
details={
'conflict_id': conflict.id,
'expected': expected_conflict_version,
'actual': conflict.conflict_version,
},
)
if expected_order_data_version is not None and int(task.order_data_version or 1) != int(
expected_order_data_version
):
raise ConflictError(
'Order data version mismatch',
code='SHIPPING.ORDER_DATA_VERSION_MISMATCH',
details={
'expected': expected_order_data_version,
'actual': task.order_data_version,
},
)
choice = str(resolution or '').strip().lower()
if choice == 'keep_existing':
value = conflict.existing_value
elif choice == 'take_incoming':
value = conflict.incoming_value
elif choice == 'custom':
value = None if resolved_value in (None, '') else str(resolved_value)
else:
raise ValidationError(
'resolution must be keep_existing, take_incoming or custom',
code='SHIPPING.INVALID_CONFLICT_RESOLUTION',
)
# [STEP 2] 行级冲突回写 lines;任务级冲突暂只关闭审计(当前仅行字段)。
before_lines = read_task_order_lines(task)
after_lines = [dict(item) for item in before_lines]
if conflict.position is not None and 0 <= int(conflict.position) < len(after_lines):
after_lines[int(conflict.position)][conflict.field_name] = value
replace_task_order_lines(task, after_lines, normalize=False)
conflict.status = 'resolved'
conflict.resolved_value = value
conflict.resolved_by_id = resolved_by_id
conflict.resolved_at = datetime.utcnow()
conflict.resolution_reason = str(reason or '').strip() or None
conflict.conflict_version = int(conflict.conflict_version or 1) + 1
conflict.updated_at = datetime.utcnow()
remaining = list_open_field_conflicts(task)
issues = reservation_gate_issues(read_task_order_lines(task))
step_payload = dict(task.step_payload_json or {})
step_payload['field_conflicts'] = {
'open_count': len(remaining),
'last_resolved_id': conflict.id,
}
if idempotency_key:
step_payload['last_conflict_resolve_idempotency_key'] = str(idempotency_key).strip()
if remaining:
step_payload['process_field_gate'] = {
'status': 'needs_enrichment',
'missing_fields': sorted({row.field_name for row in remaining}),
'issues': [
{
'severity': 'blocking',
'field': row.field_name,
'line_index': row.position,
'reason': 'field_conflict',
'conflict_id': row.id,
}
for row in remaining
],
'contract_version': 'shipping-order-extraction-v1',
}
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
elif issues:
step_payload['process_field_gate'] = {
'status': 'needs_enrichment',
'missing_fields': ['reservation_id'],
'issues': issues,
'contract_version': 'shipping-order-extraction-v1',
}
apply_task_transition(task, TaskTransition.RSV_REQUIRED)
else:
step_payload.pop('process_field_gate', None)
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
task.error_message = None
step_payload['parse_validation'] = {
'status': 'needs_review',
'issues': issues,
'contract_version': 'shipping-line-v1',
'resolution_source': 'field_conflict_resolve',
}
task.step_payload_json = step_payload
log_task_event(
task,
'field_conflict_resolved',
{
'conflict_id': conflict.id,
'field_name': conflict.field_name,
'position': conflict.position,
'resolution': choice,
'before_value': conflict.existing_value,
'after_value': value,
'reason': conflict.resolution_reason,
'resolved_by_id': resolved_by_id,
},
)
db.session.commit()
return {
'conflict': serialize_field_conflict(conflict),
'task_no': task.task_no,
'order_data_version': task.order_data_version,
'open_conflict_count': len(remaining),
'idempotent_replay': False,
}
def line_id_for_conflict_position(task: ShippingTask, position: int | None) -> int | None:
"""对外暴露 position→line_id 解析,供对账写入使用。"""
return _line_id_for_position(task, position)
@@ -0,0 +1,80 @@
"""
backend/app/services/shipping_notice/task_field_gate.py
用途:未解决订单字段冲突门禁,阻断库存/匹配/导出下游副作用。
依赖:task_field_conflict_service、i18n、tool_response、query_service.serialize_task_for_tool。
逻辑:inventory_workflow / inventory_rpa_workflow / fulfillment_workflow 在副作用前调用。
"""
from __future__ import annotations
from typing import Any
from app.models import ShippingTask
from app.services.shipping_notice.i18n import t
from app.services.shipping_notice.query_service import serialize_task_for_tool
from app.services.shipping_notice.task_field_conflict_service import (
list_open_field_conflicts,
serialize_field_conflict,
)
from app.services.shipping_notice.tool_response import tool_response
def open_field_conflict_issues(task: ShippingTask) -> list[dict[str, Any]]:
"""将 open 冲突投影为门禁 issue 列表。"""
return [
{
'severity': 'blocking',
'field': row.field_name,
'line_index': row.position,
'reason': 'field_conflict',
'conflict_id': row.id,
'existing_value': row.existing_value,
'incoming_value': row.incoming_value,
}
for row in list_open_field_conflicts(task)
]
def task_has_open_field_conflicts(task: ShippingTask) -> bool:
"""任务是否仍有未解决字段冲突。"""
return bool(list_open_field_conflicts(task))
def field_conflict_gate_response(
task: ShippingTask,
*,
lang: str,
forbidden_next_tools: list[str] | None = None,
) -> dict[str, Any] | None:
"""
存在 open 冲突时返回 needs_human,无副作用。
【AI 触发时机】:库存/RPA/匹配/导出/上传入口在产生副作用前调用。
"""
conflicts = list_open_field_conflicts(task)
if not conflicts:
return None
blocked = forbidden_next_tools or [
'ensure_inventory',
'parse_inventory',
'match_inventory',
'generate_shipment_excel',
'upload_to_freight',
]
return tool_response(
status='needs_human',
task=task,
message=t('workflow.gate.field_conflict_blocked', lang=lang).format(count=len(conflicts)),
data={
**serialize_task_for_tool(task),
'field_conflicts': {
'open_count': len(conflicts),
'items': [serialize_field_conflict(row) for row in conflicts],
'issues': open_field_conflict_issues(task),
},
},
checkpoint='parse_review',
stop_agent_turn=True,
forbidden_next_tools=blocked,
)
@@ -0,0 +1,423 @@
"""
backend/app/services/shipping_notice/task_line_store.py
用途:统一订单行读写与双写;在同一事务内维护规范表与 lines_json 快照。
依赖:ShippingTask、ShippingTaskLine、notice_lines.normalize_notice_lines、Flask current_app。
逻辑:task_workflow / open_existing 回填 / decision_workflow 等写入口委托本模块;
WRITE_MODE=json|dual|table,READ_MODE=json|shadow|table;默认 dual/shadow。
"""
from __future__ import annotations
import hashlib
import json
import logging
from decimal import Decimal, InvalidOperation
from typing import Any
from flask import current_app
from sqlalchemy import delete
from app import db
from app.models import ShippingTask, ShippingTaskLine
from app.services.shipping_notice.notice_lines import normalize_notice_lines
logger = logging.getLogger(__name__)
_STANDARD_FIELDS = (
'sku',
'qty',
'uom',
'reservation_id',
'source_type',
'hub_code',
'line_no',
'required_date',
'vendor_part_number',
'customer_sku',
'po_number',
'allocation_id',
'unit_price',
'amount',
'currency',
'remark',
)
def order_lines_write_mode() -> str:
"""读取订单行写模式:json / dual / table。"""
mode = str(current_app.config.get('SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE') or 'dual').strip().lower()
return mode if mode in {'json', 'dual', 'table'} else 'dual'
def order_lines_read_mode() -> str:
"""读取订单行读模式:json / shadow / table。"""
mode = str(current_app.config.get('SHIPPING_NOTICE_ORDER_LINES_READ_MODE') or 'shadow').strip().lower()
return mode if mode in {'json', 'shadow', 'table'} else 'shadow'
def _to_decimal(value: Any) -> Decimal | None:
"""将数量/金额转为 Decimal;非法值返回 None。"""
if value is None or value == '':
return None
try:
return Decimal(str(value))
except (InvalidOperation, ValueError):
return None
def _decimal_to_json_number(value: Decimal) -> int | str:
"""
将 Decimal 转为 JSON 友好数值。
核心逻辑:整数保持 int;非整数用去尾零十进制字符串,避免 float 精度假差异。
"""
normalized = value.normalize()
as_int = int(normalized)
if Decimal(as_int) == normalized:
return as_int
text = format(normalized, 'f')
if '.' in text:
text = text.rstrip('0').rstrip('.')
return text
def _json_safe(value: Any) -> Any:
"""把 Decimal 等转为 JSON 可序列化值,主要用于规范表→投影。"""
if isinstance(value, Decimal):
return _decimal_to_json_number(value)
return value
def line_to_json(line: ShippingTaskLine) -> dict[str, Any]:
"""
将规范行投影为历史兼容的 lines_json 元素。
Args:
line: ShippingTaskLine 实例。
Returns:
含标准字段与 extra_json 展开项的字典。
"""
payload: dict[str, Any] = {
'sku': line.sku,
'qty': _json_safe(line.qty),
}
for field in _STANDARD_FIELDS:
if field in {'sku', 'qty'}:
continue
value = getattr(line, field, None)
if value in (None, ''):
continue
payload[field] = _json_safe(value)
if isinstance(line.extra_json, dict):
for key, value in line.extra_json.items():
if key not in payload and value not in (None, ''):
payload[key] = value
return payload
# 影子对账时统一为字符串的标识类字段,避免 JSON number vs 规范表 str 假阳性。
_CHECKSUM_STRING_FIELDS = frozenset(
{
'sku',
'uom',
'reservation_id',
'source_type',
'hub_code',
'line_no',
'required_date',
'vendor_part_number',
'customer_sku',
'po_number',
'allocation_id',
'currency',
'remark',
}
)
def _canonicalize_line_for_checksum(line: dict[str, Any]) -> dict[str, Any]:
"""
将订单行投影规范为可比较形态。
核心逻辑:数值字段统一为去尾零十进制字符串;标识字段统一 strip 字符串;
忽略空值,避免 JSON number / Decimal / 规范表 str 往返假差异。
"""
payload: dict[str, Any] = {}
for key, value in line.items():
if value in (None, ''):
continue
if key in {'qty', 'unit_price', 'amount'}:
decimal_value = _to_decimal(value)
if decimal_value is None:
payload[key] = value
else:
normalized = format(decimal_value.normalize(), 'f')
if '.' in normalized:
normalized = normalized.rstrip('0').rstrip('.')
payload[key] = normalized
continue
if key in _CHECKSUM_STRING_FIELDS or isinstance(value, (str, int, float, bool)):
text = str(value).strip()
if text == '':
continue
payload[key] = text
continue
payload[key] = _json_safe(value)
return payload
def lines_checksum(lines: list[dict[str, Any]]) -> str:
"""计算订单行投影稳定 checksum,供影子校验与回填对账。"""
canonical_lines = [_canonicalize_line_for_checksum(dict(item)) for item in lines if isinstance(item, dict)]
canonical = json.dumps(canonical_lines, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
return hashlib.sha256(canonical.encode('utf-8')).hexdigest()
def _build_line_row(*, task_id: int, position: int, raw: dict[str, Any]) -> ShippingTaskLine:
"""从标准化订单行字典构建 ShippingTaskLine(未知字段进 extra_json)。"""
extra = {
key: value
for key, value in raw.items()
if key not in _STANDARD_FIELDS and value not in (None, '')
}
qty = _to_decimal(raw.get('qty'))
if qty is None or qty <= 0:
raise ValueError(f'invalid qty at position={position}')
return ShippingTaskLine(
task_id=task_id,
position=position,
sku=str(raw.get('sku') or '').strip(),
qty=qty,
uom=str(raw.get('uom') or '').strip() or None,
reservation_id=str(raw.get('reservation_id') or '').strip() or None,
source_type=str(raw.get('source_type') or '').strip() or None,
hub_code=str(raw.get('hub_code') or '').strip() or None,
line_no=str(raw.get('line_no') or '').strip() or None,
required_date=str(raw.get('required_date') or '').strip() or None,
vendor_part_number=str(raw.get('vendor_part_number') or '').strip() or None,
customer_sku=str(raw.get('customer_sku') or '').strip() or None,
po_number=str(raw.get('po_number') or '').strip() or None,
allocation_id=str(raw.get('allocation_id') or '').strip() or None,
unit_price=_to_decimal(raw.get('unit_price')),
amount=_to_decimal(raw.get('amount')),
currency=str(raw.get('currency') or '').strip() or None,
remark=str(raw.get('remark') or '').strip() or None,
extra_json=extra or None,
field_sources_json=None,
evidence_json=None,
schema_version='shipping-task-line-v1',
line_version=1,
)
def replace_task_order_lines(
task: ShippingTask,
lines: list[dict[str, Any]] | None,
*,
bump_version: bool = True,
normalize: bool = False,
) -> list[dict[str, Any]]:
"""
原子替换任务订单行。
核心逻辑:可选标准化 → 写 lines_json 与/或规范表 → 递增 order_data_version。
同一调用方事务内提交;失败时两侧一起回滚。
Args:
task: 目标任务(调用方应已持有合适行锁)。
lines: 新订单行列表;None/空表示清空。
bump_version: 是否递增乐观版本。
normalize: 是否先走 normalize_notice_lines;默认 False,以免丢掉未知字段。
Returns:
实际写入的 JSON 投影列表。
"""
raw_lines = list(lines or [])
normalized = normalize_notice_lines(raw_lines) if normalize else [
dict(item) for item in raw_lines if isinstance(item, dict)
]
write_mode = order_lines_write_mode()
# [STEP 1] 规范表外键需要稳定 task.id;新建任务须先 flush。
if write_mode in {'dual', 'table'} and task.id is None:
db.session.flush()
# [STEP 2] 先构造全部行再落库,避免非法行导致 JSON 已改、规范表半写。
built_rows: list[ShippingTaskLine] = []
if write_mode in {'dual', 'table'}:
built_rows = [
_build_line_row(task_id=int(task.id), position=position, raw=item)
for position, item in enumerate(normalized)
]
if write_mode in {'json', 'dual'}:
task.lines_json = normalized
if write_mode in {'dual', 'table'}:
# [STEP 3] 删除旧规范行;line_id FK 为 ON DELETE SET NULL,冲突审计保留。
from app.models import ShippingTaskFieldConflict
db.session.execute(
delete(ShippingTaskLine).where(ShippingTaskLine.task_id == int(task.id))
)
for row in built_rows:
db.session.add(row)
db.session.flush()
# [STEP 4] 按 position 重绑冲突到新行主键。
position_to_line_id = {
int(row.position): int(row.id)
for row in built_rows
if row.id is not None
}
conflicts = (
ShippingTaskFieldConflict.query.filter(
ShippingTaskFieldConflict.task_id == int(task.id),
ShippingTaskFieldConflict.position.isnot(None),
)
.execution_options(populate_existing=True)
.all()
)
for conflict in conflicts:
rebound = position_to_line_id.get(int(conflict.position))
if rebound is not None:
conflict.line_id = rebound
task.order_lines_migration_status = 'synced'
if 'order_lines' in task.__dict__:
db.session.expire(task, ['order_lines'])
if bump_version:
task.order_data_version = int(task.order_data_version or 1) + 1
return normalized
def clear_task_order_lines(task: ShippingTask, *, bump_version: bool = True) -> None:
"""清空任务订单行(JSON 与规范表按写模式同步)。"""
replace_task_order_lines(task, [], bump_version=bump_version, normalize=False)
def sync_task_order_lines_from_json(
task: ShippingTask,
*,
dry_run: bool = False,
) -> dict[str, Any]:
"""
将现有 lines_json 同步到规范表(历史回填专用)。
核心逻辑:不改写 lines_json、不递增 order_data_version;非法行返回 failed 原因。
幂等:两侧 checksum 已一致时标记 synced 并跳过。
Args:
task: 待回填任务。
dry_run: True 时只校验不写入。
Returns:
{status: synced|skipped|failed, reason?, line_count?, checksum?}
"""
json_lines = [dict(item) for item in (task.lines_json or []) if isinstance(item, dict)]
comparison = compare_task_order_line_projections(task)
if comparison['equal'] and task.order_lines_migration_status == 'synced':
return {
'status': 'skipped',
'reason': 'already_synced',
'line_count': comparison['json_count'],
'checksum': comparison['json_checksum'],
}
# [STEP 1] 先构造行对象以捕获非法 qty/sku,避免半写。
built_rows: list[ShippingTaskLine] = []
try:
for position, item in enumerate(json_lines):
built_rows.append(_build_line_row(task_id=int(task.id), position=position, raw=item))
except (ValueError, TypeError) as exc:
return {
'status': 'failed',
'reason': str(exc),
'line_count': len(json_lines),
'checksum': lines_checksum(json_lines),
}
if dry_run:
return {
'status': 'synced',
'reason': 'dry_run',
'line_count': len(built_rows),
'checksum': lines_checksum(json_lines),
}
db.session.execute(
delete(ShippingTaskLine).where(ShippingTaskLine.task_id == int(task.id))
)
for row in built_rows:
db.session.add(row)
task.order_lines_migration_status = 'synced'
if 'order_lines' in task.__dict__:
db.session.expire(task, ['order_lines'])
return {
'status': 'synced',
'line_count': len(built_rows),
'checksum': lines_checksum(json_lines),
}
def _table_order_lines_for_task(task: ShippingTask) -> list[dict[str, Any]]:
"""
读取规范表订单行投影。
核心逻辑:未落库(task.id 为空)时返回空列表,避免 int(None) 与无效查询。
"""
if task.id is None:
return []
table_rows = (
ShippingTaskLine.query.filter_by(task_id=int(task.id))
.order_by(ShippingTaskLine.position.asc())
.all()
)
return [line_to_json(row) for row in table_rows]
def read_task_order_lines(task: ShippingTask) -> list[dict[str, Any]]:
"""
按读模式返回订单行投影。
核心逻辑:json 直接读快照;table 读规范表;shadow 对外仍返回 JSON,并记录差异。
"""
json_lines = [dict(item) for item in (task.lines_json or []) if isinstance(item, dict)]
mode = order_lines_read_mode()
if mode == 'json':
return json_lines
table_lines = _table_order_lines_for_task(task)
if mode == 'table':
return table_lines
# shadow:对外仍读 JSON,差异只记日志不改响应。
json_checksum = lines_checksum(json_lines)
table_checksum = lines_checksum(table_lines)
if json_checksum != table_checksum:
logger.warning(
'shipping task line shadow mismatch task_no=%s json_count=%s table_count=%s '
'json_checksum=%s table_checksum=%s',
task.task_no,
len(json_lines),
len(table_lines),
json_checksum,
table_checksum,
)
return json_lines
def compare_task_order_line_projections(task: ShippingTask) -> dict[str, Any]:
"""比较 JSON 快照与规范表投影,返回差异摘要。"""
json_lines = [dict(item) for item in (task.lines_json or []) if isinstance(item, dict)]
table_lines = _table_order_lines_for_task(task)
json_checksum = lines_checksum(json_lines)
table_checksum = lines_checksum(table_lines)
return {
'task_no': task.task_no,
'json_count': len(json_lines),
'table_count': len(table_lines),
'json_checksum': json_checksum,
'table_checksum': table_checksum,
'equal': json_checksum == table_checksum,
}
@@ -2,8 +2,9 @@
services/shipping_notice/task_workflow.py
用途:发货通知任务/批次生命周期、解析与单头/订单行编辑的主编排入口。
依赖:query_service、tool_common、decision_workflow、progress_workflow、state_machine。
逻辑:tools.py 门面委托本模块;人工决策与自动推进分支已下沉到独立 workflow,本文件保留核心任务创建、解析和编辑入口。
依赖:query_service、tool_common、decision_workflow、progress_workflow、state_machine、task_line_store。
逻辑:tools.py 门面委托本模块;人工决策与自动推进分支已下沉到独立 workflow,本文件保留核心任务创建、解析和编辑入口;
订单行写/读路径统一经 task_line_store(双写 + read_task_order_lines)。
"""
from __future__ import annotations
@@ -38,6 +39,11 @@ from app.services.shipping_notice.decision_workflow import submit_decision
from app.services.shipping_notice.extract import extract_notice_fields
from app.services.shipping_notice.notice_lines import normalize_notice_lines
from app.services.shipping_notice.parse_summary import format_parse_summary
from app.services.shipping_notice.task_line_store import (
clear_task_order_lines,
read_task_order_lines,
replace_task_order_lines,
)
from app.services.shipping_notice.progress_workflow import auto_progress
from app.services.shipping_notice.query_service import (
TaskProjection,
@@ -85,6 +91,7 @@ EDITABLE_NOTICE_LINE_FIELDS = frozenset({
"required_date",
"uom",
"source_type",
"hub_code",
})
@@ -171,8 +178,8 @@ def _missing_process_field_issues(lines: list[Any]) -> list[dict[str, Any]]:
"""
检查 Task 进入库存链前必须补齐的订单行流程字段。
核心逻辑:所有入口只检查 Reservation ID;行级 Source Type 是可选库存源路由线索,
Hub Code 不属于新订单抽取契约,也不参与流程门禁。
核心逻辑:所有入口只检查 Reservation ID;行级 Source Type / Hub Code 是可选库存源路由线索,
缺失时不阻断进入库存链,但必须独立持久化以便工作台展示与人工修订。
Args:
lines: 已标准化的订单行。
@@ -716,7 +723,7 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
required_date = line_date
break
task.required_date = required_date or None
task.lines_json = lines
lines = replace_task_order_lines(task, lines, normalize=False)
task.parse_confidence = confidence
step_payload = dict(task.step_payload_json or {})
step_payload["parse_validation"] = {
@@ -1095,7 +1102,7 @@ def replace_task_notice(
task.ship_to = None
task.po_number = None
task.required_date = None
task.lines_json = []
clear_task_order_lines(task)
task.parse_confidence = None
task.review_status = None
task.pending_human_reason = None
@@ -1143,6 +1150,75 @@ def replace_task_notice(
)
def _assert_order_data_version(task: ShippingTask, payload: dict[str, Any]) -> dict[str, Any] | None:
"""
校验 expected_order_data_version;不匹配时返回 409 语义的 failed Tool 响应。
Args:
payload: 可含 expected_order_data_version。
Returns:
版本冲突时的 tool_response;通过则 None。
"""
raw = payload.get('expected_order_data_version')
if raw is None or raw == '':
return None
try:
expected = int(raw)
except (TypeError, ValueError):
return tool_response(status='failed', task=task, message='expected_order_data_version 非法')
actual = int(task.order_data_version or 1)
if expected != actual:
return tool_response(
status='failed',
task=task,
message='订单数据版本已变更,请刷新后重试。',
data={
**serialize_task_for_tool(task),
'error_code': 'SHIPPING.ORDER_DATA_VERSION_MISMATCH',
'expected_order_data_version': expected,
'actual_order_data_version': actual,
},
)
return None
def _notice_edit_idempotency_replay(
task: ShippingTask,
payload: dict[str, Any],
) -> dict[str, Any] | None:
"""同一 idempotency_key 重复提交时直接返回上次成功结果摘要。"""
key = str(payload.get('idempotency_key') or '').strip()
if not key:
return None
step_payload = dict(task.step_payload_json or {})
last = step_payload.get('last_notice_edit_idempotency')
if not isinstance(last, dict):
return None
if str(last.get('key') or '').strip() != key:
return None
return tool_response(
status='ok',
task=task,
message=str(last.get('message') or '操作已处理(幂等重放)。'),
data=serialize_task_for_tool(task),
)
def _remember_notice_edit_idempotency(
task: ShippingTask,
*,
key: str | None,
message: str,
) -> None:
"""把最近一次改单幂等键写入 step_payload,供重复点击短路。"""
text = str(key or '').strip()
if not text:
return
step_payload = dict(task.step_payload_json or {})
step_payload['last_notice_edit_idempotency'] = {'key': text, 'message': message}
task.step_payload_json = step_payload
def _commit_notice_edit(
task: ShippingTask,
*,
@@ -1152,10 +1228,11 @@ def _commit_notice_edit(
after_header: dict[str, Any] | None = None,
before_lines: list[dict[str, Any]] | None = None,
after_lines: list[dict[str, Any]] | None = None,
idempotency_key: str | None = None,
) -> dict[str, Any]:
# [STEP 1] 人工编辑后的业务值拥有最终优先级,但仍必须通过同一流程字段契约。
step_payload = dict(task.step_payload_json or {})
validation_issues = _missing_process_field_issues(list(task.lines_json or []))
validation_issues = _missing_process_field_issues(read_task_order_lines(task))
step_payload["parse_validation"] = {
"status": "needs_review" if validation_issues else "ready",
"issues": validation_issues,
@@ -1180,6 +1257,12 @@ def _commit_notice_edit(
TaskTransition.RSV_REQUIRED if validation_issues else TaskTransition.PARSE_NEEDS_REVIEW,
)
_reset_notice_edit_downstream(task)
message = (
"已更新订单字段,但仍有后续处理必需字段待补充。"
if validation_issues
else "已更新解析结果,请重新确认。"
)
_remember_notice_edit_idempotency(task, key=idempotency_key, message=message)
log_task_event(
task,
event_type,
@@ -1189,6 +1272,8 @@ def _commit_notice_edit(
"after_header": after_header,
"before_lines": before_lines,
"after_lines": after_lines,
"idempotency_key": str(idempotency_key or "").strip() or None,
"order_data_version": task.order_data_version,
},
)
sync_batch_after_task_change(task)
@@ -1196,11 +1281,7 @@ def _commit_notice_edit(
return tool_response(
status="ok",
task=task,
message=(
"已更新订单字段,但仍有后续处理必需字段待补充。"
if validation_issues
else "已更新解析结果,请重新确认。"
),
message=message,
data=serialize_task_for_tool(task),
)
@@ -1221,6 +1302,13 @@ def update_notice_fields(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message="未找到任务编号")
replay = _notice_edit_idempotency_replay(task, payload)
if replay is not None:
return replay
version_error = _assert_order_data_version(task, payload)
if version_error is not None:
return version_error
fields = payload.get("fields")
if not isinstance(fields, dict) or not fields:
return tool_response(status="failed", task=task, message="fields 不能为空")
@@ -1251,6 +1339,7 @@ def update_notice_fields(payload: dict[str, Any]) -> dict[str, Any]:
comment=str(payload.get("comment") or "").strip(),
before_header=before_header,
after_header=_notice_header_snapshot(task),
idempotency_key=str(payload.get("idempotency_key") or "").strip() or None,
)
@@ -1270,6 +1359,13 @@ def update_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message="未找到任务编号")
replay = _notice_edit_idempotency_replay(task, payload)
if replay is not None:
return replay
version_error = _assert_order_data_version(task, payload)
if version_error is not None:
return version_error
try:
line_index = int(payload.get("line_index"))
except (TypeError, ValueError):
@@ -1279,7 +1375,7 @@ def update_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
if not isinstance(patch, dict) or not patch:
return tool_response(status="failed", task=task, message="patch 不能为空")
lines = [dict(item) for item in (task.lines_json or []) if isinstance(item, dict)]
lines = read_task_order_lines(task)
if line_index < 0 or line_index >= len(lines):
return tool_response(status="failed", task=task, message="line_index 超出范围")
@@ -1312,13 +1408,14 @@ def update_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
data=serialize_task_for_tool(task),
)
task.lines_json = normalized_lines
normalized_lines = replace_task_order_lines(task, normalized_lines, normalize=False)
return _commit_notice_edit(
task,
event_type="notice_line_updated",
comment=str(payload.get("comment") or "").strip(),
before_lines=before_lines,
after_lines=[dict(item) for item in normalized_lines],
idempotency_key=str(payload.get("idempotency_key") or "").strip() or None,
)
@@ -1338,11 +1435,18 @@ def add_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message="未找到任务编号")
replay = _notice_edit_idempotency_replay(task, payload)
if replay is not None:
return replay
version_error = _assert_order_data_version(task, payload)
if version_error is not None:
return version_error
line = payload.get("line")
if not isinstance(line, dict) or not line:
return tool_response(status="failed", task=task, message="line 不能为空")
before_lines = [dict(item) for item in (task.lines_json or []) if isinstance(item, dict)]
before_lines = read_task_order_lines(task)
normalized_lines = normalize_notice_lines(before_lines + [line])
if len(normalized_lines) != len(before_lines) + 1:
return tool_response(
@@ -1352,13 +1456,14 @@ def add_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
data=serialize_task_for_tool(task),
)
task.lines_json = normalized_lines
normalized_lines = replace_task_order_lines(task, normalized_lines, normalize=False)
return _commit_notice_edit(
task,
event_type="notice_line_added",
comment=str(payload.get("comment") or "").strip(),
before_lines=before_lines,
after_lines=[dict(item) for item in normalized_lines],
idempotency_key=str(payload.get("idempotency_key") or "").strip() or None,
)
@@ -1378,25 +1483,33 @@ def remove_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message="未找到任务编号")
replay = _notice_edit_idempotency_replay(task, payload)
if replay is not None:
return replay
version_error = _assert_order_data_version(task, payload)
if version_error is not None:
return version_error
try:
line_index = int(payload.get("line_index"))
except (TypeError, ValueError):
return tool_response(status="failed", task=task, message="line_index 非法")
before_lines = [dict(item) for item in (task.lines_json or []) if isinstance(item, dict)]
before_lines = read_task_order_lines(task)
if line_index < 0 or line_index >= len(before_lines):
return tool_response(status="failed", task=task, message="line_index 超出范围")
if len(before_lines) <= 1:
return tool_response(status="failed", task=task, message="至少保留一条订单行,无法删除最后一行")
normalized_lines = [dict(item) for idx, item in enumerate(before_lines) if idx != line_index]
task.lines_json = normalized_lines
normalized_lines = replace_task_order_lines(task, normalized_lines, normalize=False)
return _commit_notice_edit(
task,
event_type="notice_line_removed",
comment=str(payload.get("comment") or "").strip(),
before_lines=before_lines,
after_lines=normalized_lines,
idempotency_key=str(payload.get("idempotency_key") or "").strip() or None,
)
@@ -1421,9 +1534,10 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
task.pending_human_reason = None
task.error_message = None
if not task.raw_content and not task.lines_json:
order_lines = read_task_order_lines(task)
if not task.raw_content and not order_lines:
task.process_status = "created"
elif task.lines_json:
elif order_lines:
if task.export_file_path:
task.process_status = "matched"
elif task.inventory_lines_json:
@@ -0,0 +1,178 @@
"""
backend/migrations/versions/d5e6f7a8b9c0_shipping_task_lines_and_conflicts.py
用途:新增规范订单行表、字段冲突表,并为 shipping_tasks 增加订单数据版本字段。
依赖:Alembic、SQLAlchemy;承接当前迁移 head c4d5e6f7a8b9。
逻辑:仅建空表与可空/默认字段,不改写既有 lines_json;应用未双写前新表为空不影响旧链路。
Revision ID: d5e6f7a8b9c0
Revises: c4d5e6f7a8b9
Create Date: 2026-07-16 12:00:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = 'd5e6f7a8b9c0'
down_revision = 'c4d5e6f7a8b9'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""创建规范订单行与冲突表,并为任务增加版本/迁移状态列。"""
op.add_column(
'shipping_tasks',
sa.Column('order_data_version', sa.Integer(), server_default=sa.text('1'), nullable=False),
)
op.add_column(
'shipping_tasks',
sa.Column(
'order_lines_migration_status',
sa.String(length=32),
server_default=sa.text("'pending'"),
nullable=False,
),
)
op.create_table(
'shipping_task_lines',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('task_id', sa.Integer(), nullable=False),
sa.Column('position', sa.Integer(), nullable=False),
sa.Column('sku', sa.String(length=128), nullable=False),
sa.Column('qty', sa.Numeric(precision=18, scale=6), nullable=False),
sa.Column('uom', sa.String(length=32), nullable=True),
sa.Column('reservation_id', sa.String(length=128), nullable=True),
sa.Column('source_type', sa.String(length=128), nullable=True),
sa.Column('hub_code', sa.String(length=64), nullable=True),
sa.Column('line_no', sa.String(length=64), nullable=True),
sa.Column('required_date', sa.String(length=32), nullable=True),
sa.Column('vendor_part_number', sa.String(length=128), nullable=True),
sa.Column('customer_sku', sa.String(length=128), nullable=True),
sa.Column('po_number', sa.String(length=128), nullable=True),
sa.Column('allocation_id', sa.String(length=128), nullable=True),
sa.Column('unit_price', sa.Numeric(precision=18, scale=6), nullable=True),
sa.Column('amount', sa.Numeric(precision=18, scale=6), nullable=True),
sa.Column('currency', sa.String(length=16), nullable=True),
sa.Column('remark', sa.Text(), nullable=True),
sa.Column('extra_json', sa.JSON(), nullable=True),
sa.Column('field_sources_json', sa.JSON(), nullable=True),
sa.Column('evidence_json', sa.JSON(), nullable=True),
sa.Column(
'schema_version',
sa.String(length=64),
server_default=sa.text("'shipping-task-line-v1'"),
nullable=False,
),
sa.Column('line_version', sa.Integer(), server_default=sa.text('1'), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.CheckConstraint('qty > 0', name='ck_shipping_task_lines_qty_positive'),
sa.ForeignKeyConstraint(['task_id'], ['shipping_tasks.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('task_id', 'position', name='uq_shipping_task_lines_task_position'),
)
op.create_index('ix_shipping_task_lines_task_id', 'shipping_task_lines', ['task_id'], unique=False)
op.create_index('ix_shipping_task_lines_reservation_id', 'shipping_task_lines', ['reservation_id'], unique=False)
op.create_index('ix_shipping_task_lines_sku', 'shipping_task_lines', ['sku'], unique=False)
op.create_index('ix_shipping_task_lines_created_at', 'shipping_task_lines', ['created_at'], unique=False)
op.create_table(
'shipping_task_field_conflicts',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('task_id', sa.Integer(), nullable=False),
sa.Column('line_id', sa.Integer(), nullable=True),
sa.Column('position', sa.Integer(), nullable=True),
sa.Column('field_name', sa.String(length=64), nullable=False),
sa.Column('existing_value', sa.Text(), nullable=True),
sa.Column('incoming_value', sa.Text(), nullable=True),
sa.Column('existing_source', sa.String(length=64), nullable=True),
sa.Column('incoming_source', sa.String(length=64), nullable=True),
sa.Column('existing_evidence_json', sa.JSON(), nullable=True),
sa.Column('incoming_evidence_json', sa.JSON(), nullable=True),
sa.Column('status', sa.String(length=32), server_default=sa.text("'open'"), nullable=False),
sa.Column('resolved_value', sa.Text(), nullable=True),
sa.Column('resolved_by_id', sa.Integer(), nullable=True),
sa.Column('resolved_at', sa.DateTime(), nullable=True),
sa.Column('resolution_reason', sa.Text(), nullable=True),
sa.Column('conflict_version', sa.Integer(), server_default=sa.text('1'), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.CheckConstraint(
"status IN ('open', 'resolved', 'dismissed')",
name='ck_shipping_task_field_conflicts_status',
),
sa.ForeignKeyConstraint(['line_id'], ['shipping_task_lines.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['resolved_by_id'], ['users.id']),
sa.ForeignKeyConstraint(['task_id'], ['shipping_tasks.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id'),
)
op.create_index(
'ix_shipping_task_field_conflicts_task_id',
'shipping_task_field_conflicts',
['task_id'],
unique=False,
)
op.create_index(
'ix_shipping_task_field_conflicts_task_status',
'shipping_task_field_conflicts',
['task_id', 'status'],
unique=False,
)
op.create_index(
'ix_shipping_task_field_conflicts_line_id',
'shipping_task_field_conflicts',
['line_id'],
unique=False,
)
op.create_index(
'ix_shipping_task_field_conflicts_created_at',
'shipping_task_field_conflicts',
['created_at'],
unique=False,
)
op.create_index(
'uq_shipping_task_field_conflicts_open_line_field',
'shipping_task_field_conflicts',
['task_id', 'line_id', 'field_name'],
unique=True,
postgresql_where=sa.text("status = 'open' AND line_id IS NOT NULL"),
sqlite_where=sa.text("status = 'open' AND line_id IS NOT NULL"),
)
op.create_index(
'uq_shipping_task_field_conflicts_open_task_field',
'shipping_task_field_conflicts',
['task_id', 'field_name'],
unique=True,
postgresql_where=sa.text("status = 'open' AND line_id IS NULL"),
sqlite_where=sa.text("status = 'open' AND line_id IS NULL"),
)
def downgrade() -> None:
"""移除规范订单行与冲突表,并回滚任务版本字段;不触碰 lines_json。"""
op.drop_index(
'uq_shipping_task_field_conflicts_open_task_field',
table_name='shipping_task_field_conflicts',
)
op.drop_index(
'uq_shipping_task_field_conflicts_open_line_field',
table_name='shipping_task_field_conflicts',
)
op.drop_index('ix_shipping_task_field_conflicts_created_at', table_name='shipping_task_field_conflicts')
op.drop_index('ix_shipping_task_field_conflicts_line_id', table_name='shipping_task_field_conflicts')
op.drop_index('ix_shipping_task_field_conflicts_task_status', table_name='shipping_task_field_conflicts')
op.drop_index('ix_shipping_task_field_conflicts_task_id', table_name='shipping_task_field_conflicts')
op.drop_table('shipping_task_field_conflicts')
op.drop_index('ix_shipping_task_lines_created_at', table_name='shipping_task_lines')
op.drop_index('ix_shipping_task_lines_sku', table_name='shipping_task_lines')
op.drop_index('ix_shipping_task_lines_reservation_id', table_name='shipping_task_lines')
op.drop_index('ix_shipping_task_lines_task_id', table_name='shipping_task_lines')
op.drop_table('shipping_task_lines')
op.drop_column('shipping_tasks', 'order_lines_migration_status')
op.drop_column('shipping_tasks', 'order_data_version')
@@ -0,0 +1,94 @@
"""
backend/migrations/versions/e6f7a8b9c0d1_shipping_field_conflict_line_set_null.py
用途:将字段冲突 line_id 外键改为 ON DELETE SET NULL,并增加按 position 的 open 唯一索引。
依赖:Alembic;承接 d5e6f7a8b9c0。
逻辑:避免双写重建 shipping_task_lines 时 CASCADE 删除冲突;支持多行同字段冲突并存。
Revision ID: e6f7a8b9c0d1
Revises: d5e6f7a8b9c0
Create Date: 2026-07-16 18:00:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = 'e6f7a8b9c0d1'
down_revision = 'd5e6f7a8b9c0'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""冲突 line_id 改为 SET NULL;收紧任务级唯一索引并补 position 级唯一索引。"""
with op.batch_alter_table('shipping_task_field_conflicts') as batch_op:
batch_op.drop_constraint(
'shipping_task_field_conflicts_line_id_fkey',
type_='foreignkey',
)
batch_op.create_foreign_key(
'shipping_task_field_conflicts_line_id_fkey',
'shipping_task_lines',
['line_id'],
['id'],
ondelete='SET NULL',
)
op.drop_index(
'uq_shipping_task_field_conflicts_open_task_field',
table_name='shipping_task_field_conflicts',
)
op.create_index(
'uq_shipping_task_field_conflicts_open_task_field',
'shipping_task_field_conflicts',
['task_id', 'field_name'],
unique=True,
postgresql_where=sa.text(
"status = 'open' AND line_id IS NULL AND position IS NULL"
),
sqlite_where=sa.text(
"status = 'open' AND line_id IS NULL AND position IS NULL"
),
)
op.create_index(
'uq_shipping_task_field_conflicts_open_position_field',
'shipping_task_field_conflicts',
['task_id', 'position', 'field_name'],
unique=True,
postgresql_where=sa.text("status = 'open' AND position IS NOT NULL"),
sqlite_where=sa.text("status = 'open' AND position IS NOT NULL"),
)
def downgrade() -> None:
"""回滚索引与 line_id CASCADE。"""
op.drop_index(
'uq_shipping_task_field_conflicts_open_position_field',
table_name='shipping_task_field_conflicts',
)
op.drop_index(
'uq_shipping_task_field_conflicts_open_task_field',
table_name='shipping_task_field_conflicts',
)
op.create_index(
'uq_shipping_task_field_conflicts_open_task_field',
'shipping_task_field_conflicts',
['task_id', 'field_name'],
unique=True,
postgresql_where=sa.text("status = 'open' AND line_id IS NULL"),
sqlite_where=sa.text("status = 'open' AND line_id IS NULL"),
)
with op.batch_alter_table('shipping_task_field_conflicts') as batch_op:
batch_op.drop_constraint(
'shipping_task_field_conflicts_line_id_fkey',
type_='foreignkey',
)
batch_op.create_foreign_key(
'shipping_task_field_conflicts_line_id_fkey',
'shipping_task_lines',
['line_id'],
['id'],
ondelete='CASCADE',
)
@@ -0,0 +1,147 @@
#!/usr/bin/env python3
"""
backend/scripts/backfill_shipping_task_lines.py
用途:将存量 ShippingTask.lines_json 幂等同步到 shipping_task_lines 规范表。
依赖:app.create_app、models.ShippingTask、task_line_store.sync_task_order_lines_from_json。
逻辑:运维 CLI;默认 dry-run;支持分页、断点续跑、单 Task 修复与失败汇总。
Usage:
cd backend
python scripts/backfill_shipping_task_lines.py --dry-run
python scripts/backfill_shipping_task_lines.py --apply
python scripts/backfill_shipping_task_lines.py --apply --task-no SN-xxx
python scripts/backfill_shipping_task_lines.py --apply --after-id 1200 --limit 200
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
BACKEND_ROOT = Path(__file__).resolve().parents[1]
if str(BACKEND_ROOT) not in sys.path:
sys.path.insert(0, str(BACKEND_ROOT))
from app import create_app, db # noqa: E402
from app.models import ShippingTask # noqa: E402
from app.services.shipping_notice.task_line_store import ( # noqa: E402
sync_task_order_lines_from_json,
)
def _query_tasks(*, after_id: int, limit: int, task_no: str | None) -> list[ShippingTask]:
"""按游标分页加载待回填任务。"""
query = ShippingTask.query.order_by(ShippingTask.id.asc())
if task_no:
query = query.filter(ShippingTask.task_no == task_no)
else:
query = query.filter(ShippingTask.id > after_id)
if limit > 0:
query = query.limit(limit)
return list(query.all())
def backfill_shipping_task_lines(
*,
dry_run: bool = True,
after_id: int = 0,
limit: int = 200,
task_no: str | None = None,
) -> dict[str, Any]:
"""
执行一页(或单 Task)订单行回填。
核心逻辑:逐任务调用 sync_task_order_lines_from_json;单任务失败隔离,
apply 模式下仅成功任务提交,失败任务 rollback 到 savepoint。
Returns:
含 counts、failures、last_id 的汇总字典。
"""
tasks = _query_tasks(after_id=after_id, limit=limit, task_no=task_no)
summary: dict[str, Any] = {
'dry_run': dry_run,
'scanned': len(tasks),
'synced': 0,
'skipped': 0,
'failed': 0,
'last_id': after_id,
'failures': [],
'results': [],
}
for task in tasks:
summary['last_id'] = int(task.id)
nested = db.session.begin_nested()
try:
result = sync_task_order_lines_from_json(task, dry_run=dry_run)
status = str(result.get('status') or 'failed')
entry = {
'task_id': task.id,
'task_no': task.task_no,
**result,
}
summary['results'].append(entry)
if status == 'synced':
summary['synced'] += 1
if not dry_run:
nested.commit()
else:
nested.rollback()
elif status == 'skipped':
summary['skipped'] += 1
nested.rollback()
else:
summary['failed'] += 1
summary['failures'].append(entry)
nested.rollback()
except Exception as exc: # noqa: BLE001 — 回填必须隔离单条失败
nested.rollback()
entry = {
'task_id': task.id,
'task_no': task.task_no,
'status': 'failed',
'reason': str(exc),
}
summary['failed'] += 1
summary['failures'].append(entry)
summary['results'].append(entry)
if not dry_run:
db.session.commit()
else:
db.session.rollback()
return summary
def main() -> int:
"""CLI 入口:解析参数并打印 JSON 汇总。"""
parser = argparse.ArgumentParser(description='Backfill shipping_task_lines from lines_json')
parser.add_argument('--dry-run', action='store_true', help='只校验不写入(默认)')
parser.add_argument('--apply', action='store_true', help='实际写入规范表')
parser.add_argument('--after-id', type=int, default=0, help='断点续跑游标(不含)')
parser.add_argument('--limit', type=int, default=200, help='本页处理数量;0 表示不限')
parser.add_argument('--task-no', type=str, default=None, help='仅处理指定 task_no')
args = parser.parse_args()
dry_run = not bool(args.apply)
if args.dry_run:
dry_run = True
app = create_app()
with app.app_context():
summary = backfill_shipping_task_lines(
dry_run=dry_run,
after_id=int(args.after_id or 0),
limit=int(args.limit),
task_no=(str(args.task_no).strip() or None) if args.task_no else None,
)
print(json.dumps(summary, ensure_ascii=False, indent=2))
return 1 if summary['failed'] else 0
if __name__ == '__main__':
raise SystemExit(main())
@@ -0,0 +1,99 @@
#!/usr/bin/env python3
"""
backend/scripts/verify_shipping_task_lines.py
用途:比对 ShippingTask.lines_json 与 shipping_task_lines 投影,输出影子差异报告。
依赖:app.create_app、models.ShippingTask、task_line_store.compare_task_order_line_projections。
逻辑:运维 CLI;切 READ_MODE=table 前必须全量 equal;支持分页与单 Task。
Usage:
cd backend
python scripts/verify_shipping_task_lines.py
python scripts/verify_shipping_task_lines.py --task-no SN-xxx
python scripts/verify_shipping_task_lines.py --after-id 1200 --limit 200
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
BACKEND_ROOT = Path(__file__).resolve().parents[1]
if str(BACKEND_ROOT) not in sys.path:
sys.path.insert(0, str(BACKEND_ROOT))
from app import create_app # noqa: E402
from app.models import ShippingTask # noqa: E402
from app.services.shipping_notice.task_line_store import ( # noqa: E402
compare_task_order_line_projections,
)
def _query_tasks(*, after_id: int, limit: int, task_no: str | None) -> list[ShippingTask]:
"""按游标分页加载待比对任务。"""
query = ShippingTask.query.order_by(ShippingTask.id.asc())
if task_no:
query = query.filter(ShippingTask.task_no == task_no)
else:
query = query.filter(ShippingTask.id > after_id)
if limit > 0:
query = query.limit(limit)
return list(query.all())
def verify_shipping_task_lines(
*,
after_id: int = 0,
limit: int = 200,
task_no: str | None = None,
) -> dict[str, Any]:
"""
比对一页(或单 Task)JSON 快照与规范表投影。
Returns:
含 scanned/equal/mismatch/mismatches/last_id 的汇总。
"""
tasks = _query_tasks(after_id=after_id, limit=limit, task_no=task_no)
summary: dict[str, Any] = {
'scanned': len(tasks),
'equal': 0,
'mismatch': 0,
'last_id': after_id,
'mismatches': [],
}
for task in tasks:
summary['last_id'] = int(task.id)
comparison = compare_task_order_line_projections(task)
if comparison.get('equal'):
summary['equal'] += 1
continue
summary['mismatch'] += 1
summary['mismatches'].append(comparison)
return summary
def main() -> int:
"""CLI 入口:输出 JSON 汇总;存在 mismatch 时退出码为 1。"""
parser = argparse.ArgumentParser(description='Verify shipping_task_lines vs lines_json')
parser.add_argument('--after-id', type=int, default=0)
parser.add_argument('--limit', type=int, default=200)
parser.add_argument('--task-no', type=str, default=None)
args = parser.parse_args()
app = create_app()
with app.app_context():
summary = verify_shipping_task_lines(
after_id=args.after_id,
limit=args.limit,
task_no=args.task_no,
)
print(json.dumps(summary, ensure_ascii=False, indent=2))
return 1 if summary['mismatch'] else 0
if __name__ == '__main__':
raise SystemExit(main())
@@ -151,8 +151,8 @@ S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD
assert rows[0]['source_type'] == 'VMI-FRA01'
assert rows[0]['customer_sku'] == 'TEMP-S000218922'
assert rows[0]['vendor_part_number'] == 'D4-A08AR12000001'
assert 'hub_code' not in rows[0]
assert 'hub_code' not in rows[2]
assert rows[0]['hub_code'] == 'FRA01'
assert rows[2]['hub_code'] == 'DUB'
fused = merge_attachment_candidate(
attachment_summary={
@@ -168,7 +168,7 @@ S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD
assert not fused['conflicts']
assert line['source_type'] == 'VMI-FRA01'
assert line['customer_sku'] == 'TEMP-S000218922'
assert 'hub_code' not in line
assert line['hub_code'] == 'FRA01'
conflict = merge_attachment_candidate(
attachment_summary={
@@ -419,7 +419,7 @@ def test_batch_upload_skips_cross_inventory_source_tasks(app, tmp_path):
batch=batch,
source_type="manual",
process_status="waiting_inventory",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
batch_index=1,
batch_total=2,
)
@@ -428,7 +428,7 @@ def test_batch_upload_skips_cross_inventory_source_tasks(app, tmp_path):
batch=batch,
source_type="manual",
process_status="waiting_inventory",
lines_json=[{"sku": "B001", "qty": 1}],
lines_json=[{"sku": "B001", "qty": 1, "reservation_id": "R-200"}],
batch_index=2,
batch_total=2,
)
@@ -730,7 +730,7 @@ def test_upload_failure_leaves_no_db_or_files(app, tmp_path, monkeypatch):
batch=batch,
source_type="manual",
process_status="waiting_inventory",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
batch_index=1,
batch_total=2,
)
@@ -739,7 +739,7 @@ def test_upload_failure_leaves_no_db_or_files(app, tmp_path, monkeypatch):
batch=batch,
source_type="manual",
process_status="waiting_inventory",
lines_json=[{"sku": "B001", "qty": 1}],
lines_json=[{"sku": "B001", "qty": 1, "reservation_id": "R-200"}],
batch_index=2,
batch_total=2,
)
@@ -877,7 +877,7 @@ def test_manual_upload_rejects_wrong_excel_warehouse(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
@@ -1000,7 +1000,7 @@ def test_manual_upload_csv_preserves_suffix_and_passes_identity(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
@@ -1026,7 +1026,7 @@ def test_manual_upload_rejects_xls_extension(app, tmp_path):
task_no="SN-GATE-UPLOAD-XLS",
source_type="pdf",
process_status="waiting_inventory",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
@@ -17,7 +17,7 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None:
"""
校验订单行与库存连接器的字段边界。
核心逻辑:订单行保留可选 source_type 且不暴露 hub_code;任务状态说明使用
核心逻辑:订单行保留可选 source_type 与独立 hub_code;任务状态说明使用
inventory_connector_type,并拒绝旧 inventory_source_type 命名。
Args:
@@ -30,8 +30,9 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None:
"application/json"
]["schema"]["properties"]["orders"]["items"]
line_properties = order_schema["properties"]["lines"]["items"]["properties"]
assert set(line_properties) == {"sku", "qty", "reservation_id", "source_type"}
assert set(line_properties) == {"sku", "qty", "reservation_id", "source_type", "hub_code"}
assert "可选订单路由线索" in line_properties["source_type"]["description"]
assert "Hub" in line_properties["hub_code"]["description"] or "hub" in line_properties["hub_code"]["description"].lower()
status_description = spec["paths"]["/tools/get_task_status"]["post"]["description"]
assert "inventory_connector_type" in status_description
@@ -36,6 +36,7 @@ from app.services.agent_registry.handlers.registry import get_handler
from app.services.chat.executors import stream_chat_via_executor
from app.services.chat.log_service import merge_chat_log_payload
from app.services.chat.stream_relay import iter_handler_preface_sse
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
from app.services.shipping_notice.order_extraction import (
EXTRACTION_CONTRACT_VERSION,
ORDER_EXTRACTION_FAILED_CODE,
@@ -57,6 +58,20 @@ from app.services.shipping_notice.query_service import resolve_order_extraction_
from app.services.shipping_notice.task_workflow import update_notice_line
def test_candidate_validation_marks_reservation_missing_when_any_line_lacks_it():
"""Reservation 是逐行匹配键;部分行缺失时整单摘要必须保留流程门禁。"""
assessment = assess_candidate_business_summary({
'po_number': '4510038672',
'lines': [
{'sku': 'SKU-A', 'qty': 1, 'reservation_id': 'R-100'},
{'sku': 'SKU-B', 'qty': 2},
],
})
assert assessment['can_create_task'] is True
assert assessment['missing_process_fields'] == ['reservation_id']
def _seed_extraction_input() -> tuple[User, ChatSession, ShippingNoticeIntake, ShippingNoticeDocument, str]:
"""
创建一封已完成上传预处理的邮件、单个附件和对应统一运行态上下文。
@@ -150,6 +165,16 @@ def _order(
line = {'sku': sku, 'qty': qty}
if include_process_fields:
line.update({'reservation_id': 'R-100', 'source_type': 'AWS Dublin'})
evidence = [
{'field': 'lines[0].sku', 'quote': f'SKU {sku}', 'document_id': document_id},
{'field': 'lines[0].qty', 'quote': f'QTY {qty}', 'document_id': document_id},
]
if include_process_fields:
evidence.append({
'field': 'lines[0].reservation_id',
'quote': 'R-100',
'document_id': document_id,
})
return {
'source_intake_no': intake_no,
'primary_document_id': document_id,
@@ -159,10 +184,7 @@ def _order(
'field_confidence': {'sku': confidence, 'qty': confidence},
'po_number': po_number,
'lines': [line],
'evidence': [
{'field': 'lines[0].sku', 'quote': f'SKU {sku}', 'document_id': document_id},
{'field': 'lines[0].qty', 'quote': f'QTY {qty}', 'document_id': document_id},
],
'evidence': evidence,
'conflicts': [],
}
@@ -211,7 +233,7 @@ def _add_extraction_intake(
content_hash=f'order-extraction-document-{suffix.lower()}',
classification='order_notice',
parse_status='parsed',
extracted_text=f'SKU SKU-{normalized} QTY 1',
extracted_text=f'SKU SKU-{normalized} QTY 1 RSV R-100',
)
db.session.add(document)
db.session.commit()
@@ -1231,6 +1253,8 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
db.session.add(existing)
db.session.commit()
document.extracted_text = f"{document.extracted_text}\nReservation ID 1000140351"
db.session.commit()
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
order = _order(
intake_no=intake.intake_no,
@@ -1242,6 +1266,7 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
)
order['lines'][0]['reservation_id'] = '1000140351'
order['lines'][0]['source_type'] = 'DBS DUB'
order['evidence'][-1]['quote'] = '1000140351'
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
@@ -1256,7 +1281,12 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
candidate = ShippingNoticeCandidate.query.filter_by(consumed_task_id=int(existing.id)).one()
candidate_line = candidate.structured_result_json['business_summary']['lines'][0]
assert candidate_line['source_type'] == 'DBS DUB'
assert existing.lines_json == [{'sku': 'P123456', 'qty': 24, 'uom': 'EA', 'reservation_id': '1000140351'}]
# 通用字段对账会同时补空的 Source Type 等可选字段;Reservation 必须落库。
assert existing.lines_json[0]['sku'] == 'P123456'
assert existing.lines_json[0]['qty'] == 24
assert existing.lines_json[0]['uom'] == 'EA'
assert existing.lines_json[0]['reservation_id'] == '1000140351'
assert existing.lines_json[0].get('source_type') == 'DBS DUB'
assert existing.process_status == 'pending_review'
assert existing.pending_human_reason == 'low_confidence'
assert 'process_field_gate' not in (existing.step_payload_json or {})
@@ -1266,7 +1296,73 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
event_type='reservation_backfilled_from_exact_file_candidate',
).one()
assert event.detail_json['updated_line_indexes'] == [0]
assert event.detail_json['review_preserved'] is True
def test_order_extraction_does_not_auto_create_with_unverified_reservation_evidence(app):
"""关键匹配键没有当前 Intake 原文证据时,Candidate 必须保留待审而不是自动建单。"""
with app.app_context():
user, _session, intake, document, runtime_context = _seed_extraction_input()
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
order = _order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000001',
sku='SKU-A',
qty=10,
include_process_fields=True,
)
order['evidence'] = [
item
for item in order['evidence']
if item['field'] != 'lines[0].reservation_id'
]
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [order],
})
assert result['created_count'] == 0
assert result['pending_count'] == 1
assert 'unverified_reservation_evidence' in result['pending_orders'][0]['reasons']
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
def test_order_extraction_backend_blocks_reservation_source_conflict(app):
"""即使 LLM 未声明冲突,后端也必须用明确表格列证据阻断不一致的 Reservation。"""
with app.app_context():
user, _session, intake, document, runtime_context = _seed_extraction_input()
document.extracted_text = (
"SKU\tReservation ID\tQty\n"
"SKU-A\tR-200\t10\n"
"LLM candidate quote R-100"
)
db.session.commit()
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
order = _order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000001',
sku='SKU-A',
qty=10,
include_process_fields=True,
)
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [order],
})
assert result['created_count'] == 0
assert result['pending_count'] == 1
assert 'blocking_conflict' in result['pending_orders'][0]['reasons']
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
assert candidate.conflicts_json[0]['reason'] == 'source_conflict'
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
@pytest.mark.parametrize(
@@ -1296,7 +1392,7 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states
db.session.add(task)
db.session.flush()
changed = backfill_exact_file_open_existing_reservations(
outcome = backfill_exact_file_open_existing_reservations(
task=task,
candidate=candidate,
candidate_summary={
@@ -1305,9 +1401,15 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states
},
duplicate_status='exact_file',
duplicate_matches=[{'task_no': task.task_no}],
verified_reservation_evidence=[{
'line_index': 0,
'reservation_id': '1000140351',
'document_id': 1,
'quote': '1000140351',
}],
)
assert changed is False
assert outcome['status'] == 'skipped'
assert 'reservation_id' not in task.lines_json[0]
assert ShippingTaskEvent.query.filter_by(
task_id=int(task.id),
@@ -1369,16 +1471,216 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
if task.task_no.endswith('AMBIGUOUS-TARGET')
else [{'task_no': task.task_no}]
),
verified_reservation_evidence=[{
'line_index': 0,
'reservation_id': '1000140351',
'document_id': 1,
'quote': '1000140351',
}],
)
for task in tasks
]
assert results == [False, False, False]
assert [item['status'] for item in results] == ['conflicted', 'skipped', 'skipped']
assert tasks[0].lines_json[0]['reservation_id'] == 'R-OLD'
assert all('reservation_id' not in line for line in tasks[1].lines_json)
assert 'reservation_id' not in tasks[2].lines_json[0]
def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(app):
"""目标行已有合法 Reservation 时,回填应跳过并标记 target_already_complete,而非对账失败。"""
with app.app_context():
task = ShippingTask(
task_no='SN-RSV-BACKFILL-ALREADY-COMPLETE',
po_number='4510038672',
source_type='manual',
process_status='pending_review',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[{'sku': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
)
candidate = ShippingNoticeCandidate(candidate_no='SNC-RSV-BACKFILL-ALREADY-COMPLETE')
db.session.add(task)
db.session.flush()
outcome = backfill_exact_file_open_existing_reservations(
task=task,
candidate=candidate,
candidate_summary={
'po_number': '4510038672',
'lines': [{'sku': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
},
duplicate_status='exact_file',
duplicate_matches=[{'task_no': task.task_no}],
verified_reservation_evidence=[{
'line_index': 0,
'reservation_id': '1000140351',
'document_id': 1,
'quote': '1000140351',
}],
)
assert outcome['status'] == 'skipped'
assert outcome['reason'] == 'target_already_complete'
assert task.lines_json[0]['reservation_id'] == '1000140351'
def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app):
"""已离开 rsv_req 的 exact_file 目标:应打开并消费 Candidate,但不得改写订单行。"""
with app.app_context():
user, session, intake, document, runtime_context = _seed_extraction_input()
batch = ShippingBatch(
batch_no='SB-ORDER-RSV-UNSAFE-OPEN-001',
user_id=int(user.id),
conversation_id=session.session_id,
file_count=1,
)
existing = ShippingTask(
task_no='SN-ORDER-RSV-UNSAFE-OPEN-001',
batch=batch,
user_id=int(user.id),
source_type='manual',
source_content_hash=document.content_hash,
po_number='4510038672',
process_status='waiting_inventory',
lines_json=[{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}],
)
db.session.add(existing)
db.session.commit()
document.extracted_text = f'{document.extracted_text}\nReservation ID 1000140351'
db.session.commit()
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
order = _order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510038672',
sku='P123456',
qty=24,
include_process_fields=True,
)
order['lines'][0]['reservation_id'] = '1000140351'
order['evidence'][-1]['quote'] = '1000140351'
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [order],
})
db.session.refresh(existing)
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
assert result['opened_existing_count'] == 1
assert result['pending_count'] == 0
assert candidate.consumed_task_id == int(existing.id)
assert existing.lines_json == [{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}]
assert existing.process_status == 'waiting_inventory'
assert result['opened_existing'][0]['reconciliation']['reason'] == 'target_task_not_safe'
def test_order_extraction_requires_verified_pair_after_reservation_adjudication(app, monkeypatch):
"""裁决改写 Reservation 后,必须按 (line_index, 新值) 核验证据,不能只认行号。"""
with app.app_context():
user, _session, intake, document, runtime_context = _seed_extraction_input()
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
order = _order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000001',
sku='SKU-A',
qty=10,
include_process_fields=True,
)
order['lines'][0]['reservation_id'] = '1000140351'
order['evidence'][-1]['quote'] = '1000140351'
def _rewrite_reservation(summary, *, documents):
rewritten = dict(summary)
lines = [dict(item) for item in (summary.get('lines') or []) if isinstance(item, dict)]
if lines:
lines[0]['reservation_id'] = '3000092917'
rewritten['lines'] = lines
return rewritten, []
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction.adjudicate_order_reservations',
_rewrite_reservation,
)
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [order],
})
assert result['created_count'] == 0
assert result['opened_existing_count'] == 0
assert result['pending_count'] == 1
assert 'unverified_reservation_evidence' in result['pending_orders'][0]['reasons']
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
assert candidate.selected is False
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app):
"""exact_file 打开已有任务但证据未核验时,Candidate 不得 selected,避免挡住同 Intake 其它 ready 单。"""
with app.app_context():
user, session, intake, document, runtime_context = _seed_extraction_input()
batch = ShippingBatch(
batch_no='SB-ORDER-RSV-UNVERIFIED-001',
user_id=int(user.id),
conversation_id=session.session_id,
file_count=1,
)
existing = ShippingTask(
task_no='SN-ORDER-RSV-UNVERIFIED-001',
batch=batch,
user_id=int(user.id),
source_type='manual',
source_content_hash=document.content_hash,
po_number='4510038672',
process_status='pending_review',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}],
)
db.session.add(existing)
db.session.commit()
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
order = _order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510038672',
sku='P123456',
qty=24,
include_process_fields=True,
)
order['lines'][0]['reservation_id'] = '1000140351'
order['evidence'] = [
item for item in order['evidence'] if item['field'] != 'lines[0].reservation_id'
]
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [order],
})
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
assert candidate.duplicate_resolution == 'open_existing'
assert candidate.selected is False
assert candidate.validation_status == 'needs_review'
assert candidate.consumed_task_id is None
assert result['opened_existing_count'] == 0
assert result['pending_count'] == 1
assert 'unverified_reservation_evidence' in result['pending_orders'][0]['reasons']
assert 'reservation_id' not in (existing.lines_json[0] or {})
def test_submit_order_extraction_rejects_changed_document_snapshot(app):
"""读取上下文后附件文本变化时,旧 LLM 结果不得覆盖新来源。"""
with app.app_context():
+33 -14
View File
@@ -716,22 +716,41 @@ def test_match_inventory_requires_reservation_id(app, client):
assert task is not None
task.lines_json = [{"sku": "A001", "qty": 1, "uom": "EA"}]
db.session.commit()
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={
from app.services.shipping_notice.inventory_workflow import (
ensure_inventory as ensure_inventory_service,
parse_inventory as parse_inventory_service,
upload_inventory_file as upload_inventory_file_service,
)
from io import BytesIO
from werkzeug.datastructures import FileStorage
direct_data = ensure_inventory_service({
"task_id": task_id,
"inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}],
},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
data = match_res.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "rsv_req"
})
assert direct_data["status"] == "needs_human", direct_data
assert direct_data.get("checkpoint") == "rsv_req"
assert not task.inventory_lines_json
parse_data = parse_inventory_service({
"task_id": task_id,
"inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}],
})
assert parse_data["status"] == "needs_human"
assert parse_data.get("checkpoint") == "rsv_req"
assert not task.inventory_lines_json
upload_data = upload_inventory_file_service(
task_id,
FileStorage(stream=BytesIO(b"sku,qty\nA001,1"), filename="inventory.csv"),
)
assert upload_data["status"] == "needs_human"
assert upload_data.get("checkpoint") == "rsv_req"
from app.services.shipping_notice.fulfillment_workflow import match_inventory as match_inventory_service
match_data = match_inventory_service({"task_id": task_id})
assert match_data["status"] == "needs_human"
assert match_data.get("checkpoint") == "rsv_req"
def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
@@ -0,0 +1,216 @@
"""
backend/tests/test_shipping_task_field_reconciliation.py
用途:验证通用字段对账、冲突落库/解决、版本冲突与下游门禁。
依赖:Flask testing app、task_candidate_reconciliation、task_field_conflict_service、field_conflict_gate。
逻辑:覆盖 Stage5 核心验收:空值自动补、双方不同落冲突、解决回写、409 版本、冲突阻断库存入口。
"""
from __future__ import annotations
from types import SimpleNamespace
from app import db
from app.models import ShippingTask, ShippingTaskFieldConflict
from app.services.shipping_notice.task_candidate_reconciliation import (
apply_candidate_reconciliation_plan,
build_candidate_reconciliation_plan,
reconcile_exact_file_open_existing,
)
from app.services.shipping_notice.task_field_conflict_service import resolve_field_conflict
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
from app.services.shipping_notice.task_line_store import replace_task_order_lines
from app.services.shipping_notice.task_workflow import update_notice_line
def _task(**kwargs) -> ShippingTask:
task = ShippingTask(
task_no=kwargs.pop('task_no', 'SN-RECON-001'),
source_type='manual',
process_status=kwargs.pop('process_status', 'pending_review'),
pending_human_reason=kwargs.pop('pending_human_reason', 'rsv_req'),
po_number=kwargs.pop('po_number', 'PO-100'),
lines_json=kwargs.pop('lines_json', [{'sku': 'A001', 'qty': 10}]),
order_data_version=1,
order_lines_migration_status='pending',
**kwargs,
)
db.session.add(task)
db.session.flush()
return task
def _candidate(summary_lines: list[dict], *, po_number: str = 'PO-100') -> SimpleNamespace:
"""测试用 Candidate 替身:只需要 candidate_no 与 summary。"""
return SimpleNamespace(
candidate_no='SNC-RECON-001',
summary_json={'po_number': po_number, 'lines': summary_lines},
)
def test_build_plan_fills_empty_and_conflicts_on_diff(app):
"""空字段自动进入 fills;双方非空不同进入 conflicts。"""
with app.app_context():
task = _task(lines_json=[
{'sku': 'A001', 'qty': 10, 'reservation_id': ''},
{'sku': 'B002', 'qty': 5, 'reservation_id': '3000000001'},
])
plan = build_candidate_reconciliation_plan(
task=task,
candidate_summary={
'lines': [
{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917', 'hub_code': 'H1'},
{'sku': 'B002', 'qty': 5, 'reservation_id': '3000000099'},
]
},
verified_reservation_evidence=[
{'line_index': 0, 'reservation_id': '3000092917'},
{'line_index': 1, 'reservation_id': '3000000099'},
],
)
assert plan['status'] == 'conflicted'
assert any(item['field_name'] == 'reservation_id' and item['position'] == 1 for item in plan['conflicts'])
assert any(item['field_name'] == 'reservation_id' and item['position'] == 0 for item in plan['fills'])
def test_apply_conflict_persists_field_conflict_and_blocks_gate(app):
"""冲突落库后库存门禁应阻断。"""
with app.app_context():
task = _task(lines_json=[{'sku': 'A001', 'qty': 10, 'reservation_id': '3000000001'}])
replace_task_order_lines(task, task.lines_json, normalize=False)
candidate = _candidate([{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
plan = build_candidate_reconciliation_plan(
task=task,
candidate_summary=candidate.summary_json,
verified_reservation_evidence=[{'line_index': 0, 'reservation_id': '3000092917'}],
)
result = apply_candidate_reconciliation_plan(task=task, candidate=candidate, plan=plan)
db.session.commit()
assert result['status'] == 'conflicted'
assert ShippingTaskFieldConflict.query.filter_by(task_id=task.id, status='open').count() == 1
gate = field_conflict_gate_response(task, lang='zh')
assert gate is not None
assert gate['status'] == 'needs_human'
def test_resolve_conflict_writes_line_and_is_idempotent(app):
"""解决冲突回写订单行;同幂等键可重放。"""
with app.app_context():
task = _task(lines_json=[{'sku': 'A001', 'qty': 10, 'reservation_id': '3000000001'}])
replace_task_order_lines(task, task.lines_json, normalize=False)
candidate = _candidate([{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
plan = build_candidate_reconciliation_plan(
task=task,
candidate_summary=candidate.summary_json,
verified_reservation_evidence=[{'line_index': 0, 'reservation_id': '3000092917'}],
)
apply_candidate_reconciliation_plan(task=task, candidate=candidate, plan=plan)
db.session.commit()
conflict = ShippingTaskFieldConflict.query.filter_by(task_id=task.id, status='open').one()
first = resolve_field_conflict(
task=task,
conflict_id=conflict.id,
resolution='take_incoming',
expected_conflict_version=conflict.conflict_version,
expected_order_data_version=task.order_data_version,
resolved_by_id=1,
idempotency_key='resolve-1',
)
assert first['idempotent_replay'] is False
task = db.session.get(ShippingTask, task.id)
assert task.lines_json[0]['reservation_id'] == '3000092917'
assert ShippingTaskFieldConflict.query.filter_by(task_id=task.id, status='open').count() == 0
replay = resolve_field_conflict(
task=task,
conflict_id=conflict.id,
resolution='take_incoming',
idempotency_key='resolve-1',
)
assert replay['idempotent_replay'] is True
def test_update_notice_line_version_mismatch(app):
"""改单携带过期 order_data_version 不得覆盖。"""
with app.app_context():
task = _task(
process_status='parsed',
pending_human_reason=None,
lines_json=[{'sku': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
)
replace_task_order_lines(task, task.lines_json, normalize=False)
db.session.commit()
resp = update_notice_line({
'task_id': task.task_no,
'line_index': 0,
'patch': {'hub_code': 'H9'},
'expected_order_data_version': 1,
})
# replace 已 bump version,再带 1 应失败;先读当前版本再测过期。
task = db.session.get(ShippingTask, task.id)
stale = int(task.order_data_version) - 1
resp = update_notice_line({
'task_id': task.task_no,
'line_index': 0,
'patch': {'hub_code': 'H8'},
'expected_order_data_version': stale,
})
assert resp['status'] == 'failed'
assert resp['data']['error_code'] == 'SHIPPING.ORDER_DATA_VERSION_MISMATCH'
def test_multiline_conflicts_persist_and_survive_line_replace(app):
"""多行同字段冲突应分别落库,且双写重建订单行后不得被抹掉。"""
with app.app_context():
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
task = _task(lines_json=[
{'sku': 'A001', 'qty': 10, 'reservation_id': '3000000001'},
{'sku': 'B002', 'qty': 5, 'reservation_id': '3000000002'},
])
replace_task_order_lines(task, task.lines_json, normalize=False)
candidate = _candidate([
{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917'},
{'sku': 'B002', 'qty': 5, 'reservation_id': '3000092918'},
])
plan = build_candidate_reconciliation_plan(
task=task,
candidate_summary=candidate.summary_json,
verified_reservation_evidence=[
{'line_index': 0, 'reservation_id': '3000092917'},
{'line_index': 1, 'reservation_id': '3000092918'},
],
)
assert plan['status'] == 'conflicted'
assert len(plan['conflicts']) == 2
apply_candidate_reconciliation_plan(task=task, candidate=candidate, plan=plan)
db.session.commit()
open_rows = ShippingTaskFieldConflict.query.filter_by(task_id=task.id, status='open').all()
assert len(open_rows) == 2
assert {row.position for row in open_rows} == {0, 1}
# 再次双写重建行主键后,冲突审计仍在。
replace_task_order_lines(task, task.lines_json, normalize=False)
db.session.commit()
open_rows = ShippingTaskFieldConflict.query.filter_by(task_id=task.id, status='open').all()
assert len(open_rows) == 2
assert all(row.line_id is not None for row in open_rows)
def test_reconcile_exact_file_open_existing_auto_fill(app):
"""安全态 exact_file 可自动补空 Reservation。"""
with app.app_context():
task = _task(lines_json=[{'sku': 'A001', 'qty': 10}])
replace_task_order_lines(task, task.lines_json, normalize=False)
candidate = _candidate([{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
result = reconcile_exact_file_open_existing(
task=task,
candidate=candidate,
candidate_summary=candidate.summary_json,
duplicate_status='exact_file',
duplicate_matches=[{'task_no': task.task_no}],
verified_reservation_evidence=[{'line_index': 0, 'reservation_id': '3000092917'}],
)
db.session.commit()
assert result['status'] == 'applied'
assert task.lines_json[0]['reservation_id'] == '3000092917'
@@ -0,0 +1,297 @@
"""
backend/tests/test_shipping_task_line_store.py
用途:验证订单行双写、历史回填、影子/表读与故障回滚。
依赖:Flask testing app、ShippingTask/ShippingTaskLine、task_line_store、backfill 脚本函数。
逻辑:覆盖双写原子性、未知字段 round-trip、dry-run/幂等回填、shadow 差异日志、table 读投影。
"""
from __future__ import annotations
from decimal import Decimal
from unittest.mock import patch
import pytest
from app import db
from app.models import ShippingTask, ShippingTaskLine
from app.services.shipping_notice.task_line_store import (
clear_task_order_lines,
compare_task_order_line_projections,
lines_checksum,
read_task_order_lines,
replace_task_order_lines,
sync_task_order_lines_from_json,
)
import importlib.util
from pathlib import Path
_BACKFILL_PATH = Path(__file__).resolve().parents[1] / 'scripts' / 'backfill_shipping_task_lines.py'
_BACKFILL_SPEC = importlib.util.spec_from_file_location(
'backfill_shipping_task_lines',
_BACKFILL_PATH,
)
assert _BACKFILL_SPEC and _BACKFILL_SPEC.loader
_BACKFILL_MODULE = importlib.util.module_from_spec(_BACKFILL_SPEC)
_BACKFILL_SPEC.loader.exec_module(_BACKFILL_MODULE)
backfill_shipping_task_lines = _BACKFILL_MODULE.backfill_shipping_task_lines
def _make_task(*, task_no: str = 'SN-LINE-STORE-001', lines: list | None = None) -> ShippingTask:
"""创建最小可落库任务,供双写测试复用。"""
task = ShippingTask(
task_no=task_no,
source_type='manual',
process_status='parsed',
lines_json=lines if lines is not None else [],
order_data_version=1,
order_lines_migration_status='pending',
)
db.session.add(task)
db.session.flush()
return task
def test_dual_write_replace_persists_json_and_table(app):
"""dual 写模式应在同一事务内更新 lines_json 与规范表,并保留未知字段。"""
with app.app_context():
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
app.config['SHIPPING_NOTICE_ORDER_LINES_READ_MODE'] = 'json'
task = _make_task()
version_before = int(task.order_data_version)
written = replace_task_order_lines(
task,
[
{
'sku': 'A001',
'qty': 10,
'reservation_id': '3000092917',
'hub_code': 'H1',
'custom_note': 'keep-me',
}
],
normalize=False,
)
db.session.commit()
assert written[0]['sku'] == 'A001'
assert task.lines_json[0]['custom_note'] == 'keep-me'
assert int(task.order_data_version) == version_before + 1
assert task.order_lines_migration_status == 'synced'
rows = ShippingTaskLine.query.filter_by(task_id=task.id).order_by(ShippingTaskLine.position).all()
assert len(rows) == 1
assert rows[0].sku == 'A001'
assert rows[0].qty == Decimal('10')
assert rows[0].reservation_id == '3000092917'
assert rows[0].hub_code == 'H1'
assert rows[0].extra_json == {'custom_note': 'keep-me'}
assert compare_task_order_line_projections(task)['equal'] is True
def test_dual_write_failure_rolls_back_both_sides(app):
"""构造行失败时不得留下半写规范行或 JSON。"""
with app.app_context():
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
task = _make_task(lines=[{'sku': 'OLD', 'qty': 1}])
db.session.commit()
with pytest.raises(ValueError, match='invalid qty'):
replace_task_order_lines(
task,
[{'sku': 'BAD', 'qty': 0, 'reservation_id': 'R-1'}],
normalize=False,
)
db.session.rollback()
task = db.session.get(ShippingTask, task.id)
assert task.lines_json == [{'sku': 'OLD', 'qty': 1}]
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
def test_clear_and_shadow_read(app, caplog):
"""清空走 store;shadow 模式对外仍读 JSON,并在不一致时打 warning。"""
with app.app_context():
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
task = _make_task()
replace_task_order_lines(task, [{'sku': 'A001', 'qty': 2}], normalize=False)
db.session.commit()
clear_task_order_lines(task)
db.session.commit()
assert task.lines_json == []
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
# 人为制造影子差异:只改 JSON,不改表。
task.lines_json = [{'sku': 'SHADOW', 'qty': 9}]
task.order_lines_migration_status = 'pending'
db.session.commit()
app.config['SHIPPING_NOTICE_ORDER_LINES_READ_MODE'] = 'shadow'
with caplog.at_level('WARNING'):
lines = read_task_order_lines(task)
assert lines == [{'sku': 'SHADOW', 'qty': 9}]
assert any('shadow mismatch' in message for message in caplog.messages)
def test_sync_from_json_backfill_idempotent_and_dry_run(app):
"""历史回填 dry-run 不落库;apply 幂等且不 bump order_data_version。"""
with app.app_context():
task = _make_task(
task_no='SN-LINE-BACKFILL-001',
lines=[
{
'sku': 'B002',
'qty': '3.50',
'source_type': 'HUB',
'legacy_flag': True,
}
],
)
db.session.commit()
version_before = int(task.order_data_version)
dry = sync_task_order_lines_from_json(task, dry_run=True)
assert dry['status'] == 'synced'
assert dry['reason'] == 'dry_run'
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
applied = sync_task_order_lines_from_json(task, dry_run=False)
db.session.commit()
assert applied['status'] == 'synced'
assert int(task.order_data_version) == version_before
assert task.order_lines_migration_status == 'synced'
row = ShippingTaskLine.query.filter_by(task_id=task.id).one()
assert row.qty == Decimal('3.50')
assert row.extra_json == {'legacy_flag': True}
again = sync_task_order_lines_from_json(task, dry_run=False)
assert again['status'] == 'skipped'
assert again['reason'] == 'already_synced'
def test_sync_rejects_invalid_historical_line(app):
"""非法历史行应返回 failed,并保留原 JSON / 空规范表。"""
with app.app_context():
task = _make_task(
task_no='SN-LINE-BAD-001',
lines=[{'sku': 'Z', 'qty': -1}],
)
db.session.commit()
result = sync_task_order_lines_from_json(task, dry_run=False)
assert result['status'] == 'failed'
assert 'invalid qty' in str(result.get('reason') or '')
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
assert task.lines_json == [{'sku': 'Z', 'qty': -1}]
def test_backfill_script_page_and_resume(app):
"""回填脚本支持 dry-run、apply、按 after_id 续跑,失败任务隔离。"""
with app.app_context():
good = _make_task(task_no='SN-BF-GOOD', lines=[{'sku': 'G1', 'qty': 1}])
bad = _make_task(task_no='SN-BF-BAD', lines=[{'sku': 'B1', 'qty': 0}])
db.session.commit()
dry_summary = backfill_shipping_task_lines(dry_run=True, after_id=0, limit=50)
assert dry_summary['scanned'] >= 2
assert ShippingTaskLine.query.count() == 0
apply_summary = backfill_shipping_task_lines(dry_run=False, after_id=0, limit=50)
assert apply_summary['synced'] >= 1
assert apply_summary['failed'] >= 1
assert any(item['task_no'] == 'SN-BF-BAD' for item in apply_summary['failures'])
good = db.session.get(ShippingTask, good.id)
bad = db.session.get(ShippingTask, bad.id)
assert good.order_lines_migration_status == 'synced'
assert ShippingTaskLine.query.filter_by(task_id=good.id).count() == 1
assert ShippingTaskLine.query.filter_by(task_id=bad.id).count() == 0
resume = backfill_shipping_task_lines(dry_run=False, after_id=int(good.id), limit=50)
assert all(item['task_id'] > good.id for item in resume['results'])
def test_json_write_mode_skips_table(app):
"""write=json 时只更新快照,不写规范表。"""
with app.app_context():
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'json'
task = _make_task(task_no='SN-JSON-ONLY')
replace_task_order_lines(task, [{'sku': 'J1', 'qty': 4}], normalize=False)
db.session.commit()
assert task.lines_json[0]['sku'] == 'J1'
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
assert task.order_lines_migration_status == 'pending'
def test_table_read_mode_returns_canonical_projection(app):
"""read=table 时以规范表投影为准,忽略仅存在于 JSON 的漂移。"""
with app.app_context():
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
app.config['SHIPPING_NOTICE_ORDER_LINES_READ_MODE'] = 'table'
task = _make_task(task_no='SN-TABLE-READ')
replace_task_order_lines(
task,
[{'sku': 'T1', 'qty': 5, 'reservation_id': '3000092917'}],
normalize=False,
)
db.session.commit()
# 人为制造 JSON 漂移:table 读路径不得返回漂移值。
task.lines_json = [{'sku': 'DRIFT', 'qty': 99}]
db.session.commit()
lines = read_task_order_lines(task)
assert lines == [{'sku': 'T1', 'qty': 5, 'reservation_id': '3000092917'}]
comparison = compare_task_order_line_projections(task)
assert comparison['equal'] is False
assert comparison['table_count'] == 1
def test_lines_checksum_stable_for_key_order(app):
"""checksum 对 dict key 顺序稳定,供影子对账。"""
left = [{'qty': 1, 'sku': 'A'}]
right = [{'sku': 'A', 'qty': 1}]
assert lines_checksum(left) == lines_checksum(right)
def test_lines_checksum_normalizes_id_and_qty_types(app):
"""checksum 忽略 reservation_id int/str 与 qty 1/1.0 的类型差异。"""
left = [{'sku': 'A', 'qty': 1, 'reservation_id': 3000092917, 'hub_code': 12}]
right = [{'sku': 'A', 'qty': 1.0, 'reservation_id': '3000092917', 'hub_code': '12'}]
assert lines_checksum(left) == lines_checksum(right)
def test_shadow_read_tolerates_unsaved_task(app):
"""未落库任务(id=None)在 shadow/table 读路径不得抛 TypeError。"""
with app.app_context():
app.config['SHIPPING_NOTICE_ORDER_LINES_READ_MODE'] = 'shadow'
task = ShippingTask(
task_no='SN-UNSAVED',
source_type='manual',
process_status='parsed',
lines_json=[{'sku': 'A001', 'qty': 1}],
)
assert read_task_order_lines(task) == [{'sku': 'A001', 'qty': 1}]
app.config['SHIPPING_NOTICE_ORDER_LINES_READ_MODE'] = 'table'
assert read_task_order_lines(task) == []
def test_replace_rolls_back_when_commit_fails_after_dual_write(app):
"""提交阶段失败时,两侧变更应随事务回滚(故障注入)。"""
with app.app_context():
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
task = _make_task(task_no='SN-FAULT-001', lines=[{'sku': 'OLD', 'qty': 1}])
db.session.commit()
task_id = task.id
replace_task_order_lines(task, [{'sku': 'NEW', 'qty': 2}], normalize=False)
with patch.object(db.session, 'commit', side_effect=RuntimeError('boom')):
with pytest.raises(RuntimeError, match='boom'):
db.session.commit()
db.session.rollback()
task = db.session.get(ShippingTask, task_id)
assert task.lines_json == [{'sku': 'OLD', 'qty': 1}]
assert ShippingTaskLine.query.filter_by(task_id=task_id).count() == 0
@@ -0,0 +1,181 @@
"""
backend/tests/test_shipping_task_lines_migration.py
用途:验证规范订单行与冲突表迁移可升级/降级,以及模型级唯一与 qty 约束。
依赖:Alembic Operations、SQLAlchemy、ShippingTaskLine 模型。
逻辑:在最小 shipping_tasks/users 历史上执行 d5e6f7a8b9c0;再在 Flask app 内断言 ORM 约束。
"""
from __future__ import annotations
import importlib
from decimal import Decimal
import pytest
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
from sqlalchemy.exc import IntegrityError
from app import db
from app.models import ShippingTask, ShippingTaskFieldConflict, ShippingTaskLine
def _task_lines_pre_migration_schema(engine: sa.Engine) -> None:
"""创建订单行迁移所需的最小历史表(含 connector 改名后的 shipping_tasks)。"""
metadata = sa.MetaData()
sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table(
'shipping_tasks',
metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('task_no', sa.String(length=64), nullable=False),
sa.Column('source_type', sa.String(length=32), nullable=False),
sa.Column('process_status', sa.String(length=32), nullable=False),
sa.Column('lines_json', sa.JSON(), nullable=True),
sa.Column('inventory_connector_type', sa.String(length=32), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
)
metadata.create_all(engine)
def test_shipping_task_lines_migration_upgrade_and_downgrade():
"""d5e6f7a8b9c0 应建立规范行/冲突表与任务版本字段,并能完整回滚且不改 lines_json。"""
engine = sa.create_engine('sqlite:///:memory:')
_task_lines_pre_migration_schema(engine)
module = importlib.import_module(
'migrations.versions.d5e6f7a8b9c0_shipping_task_lines_and_conflicts'
)
with engine.begin() as connection:
operations = Operations(MigrationContext.configure(connection, opts={'render_as_batch': True}))
original_op = module.op
module.op = operations
try:
connection.execute(
sa.text(
"INSERT INTO shipping_tasks "
"(id, task_no, source_type, process_status, lines_json, created_at, updated_at) "
"VALUES (1, 'SN-LINE-MIG-001', 'manual', 'parsed', :lines_json, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
),
{'lines_json': '[{"sku":"A001","qty":1}]'},
)
module.upgrade()
inspector = sa.inspect(connection)
assert {'shipping_task_lines', 'shipping_task_field_conflicts'} <= set(inspector.get_table_names())
task_columns = {column['name'] for column in inspector.get_columns('shipping_tasks')}
assert {'order_data_version', 'order_lines_migration_status', 'lines_json'} <= task_columns
row = connection.execute(sa.text(
"SELECT order_data_version, order_lines_migration_status, lines_json "
"FROM shipping_tasks WHERE id = 1"
)).one()
assert row[0] == 1
assert row[1] == 'pending'
assert 'A001' in str(row[2])
with pytest.raises(IntegrityError):
with connection.begin_nested():
connection.execute(sa.text(
"INSERT INTO shipping_task_lines "
"(id, task_id, position, sku, qty, schema_version, line_version, created_at, updated_at) "
"VALUES (1, 1, 0, 'A001', 0, 'shipping-task-line-v1', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
))
connection.execute(sa.text(
"INSERT INTO shipping_task_lines "
"(id, task_id, position, sku, qty, reservation_id, source_type, hub_code, "
"extra_json, schema_version, line_version, created_at, updated_at) "
"VALUES (1, 1, 0, 'A001', 1.5, '1000140351', 'DBS DUB', 'DUB1', "
"'{\"legacy_note\":\"kept\"}', 'shipping-task-line-v1', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
))
with pytest.raises(IntegrityError):
with connection.begin_nested():
connection.execute(sa.text(
"INSERT INTO shipping_task_lines "
"(id, task_id, position, sku, qty, schema_version, line_version, created_at, updated_at) "
"VALUES (2, 1, 0, 'B001', 2, 'shipping-task-line-v1', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
))
connection.execute(sa.text(
"INSERT INTO shipping_task_field_conflicts "
"(id, task_id, line_id, field_name, status, conflict_version, created_at, updated_at) "
"VALUES (1, 1, NULL, 'customer_name', 'open', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
))
with pytest.raises(IntegrityError):
with connection.begin_nested():
connection.execute(sa.text(
"INSERT INTO shipping_task_field_conflicts "
"(id, task_id, line_id, field_name, status, conflict_version, created_at, updated_at) "
"VALUES (2, 1, NULL, 'customer_name', 'open', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
))
module.downgrade()
inspector = sa.inspect(connection)
assert 'shipping_task_lines' not in inspector.get_table_names()
assert 'shipping_task_field_conflicts' not in inspector.get_table_names()
task_columns = {column['name'] for column in inspector.get_columns('shipping_tasks')}
assert 'order_data_version' not in task_columns
assert 'order_lines_migration_status' not in task_columns
assert 'lines_json' in task_columns
preserved = connection.execute(sa.text(
"SELECT lines_json FROM shipping_tasks WHERE id = 1"
)).scalar()
assert 'A001' in str(preserved)
finally:
module.op = original_op
def test_shipping_task_line_orm_constraints_and_cascade(app):
"""ORM 层应强制 qty>0、(task_id,position) 唯一,并在删除 Task 时级联清理行与冲突。"""
with app.app_context():
task = ShippingTask(
task_no='SN-LINE-ORM-001',
source_type='manual',
process_status='parsed',
lines_json=[{'sku': 'A001', 'qty': 1}],
)
db.session.add(task)
db.session.flush()
line = ShippingTaskLine(
task_id=int(task.id),
position=0,
sku='A001',
qty=Decimal('1'),
reservation_id='1000140351',
source_type='DBS DUB',
hub_code='DUB1',
extra_json={'legacy_note': 'kept'},
)
db.session.add(line)
db.session.flush()
conflict = ShippingTaskFieldConflict(
task_id=int(task.id),
line_id=int(line.id),
position=0,
field_name='reservation_id',
existing_value='1000140351',
incoming_value='3000092917',
status='open',
)
db.session.add(conflict)
db.session.commit()
with pytest.raises(IntegrityError):
db.session.add(ShippingTaskLine(
task_id=int(task.id),
position=0,
sku='B001',
qty=Decimal('2'),
))
db.session.flush()
db.session.rollback()
task = ShippingTask.query.filter_by(task_no='SN-LINE-ORM-001').one()
db.session.delete(task)
db.session.commit()
assert ShippingTaskLine.query.count() == 0
assert ShippingTaskFieldConflict.query.count() == 0
@@ -0,0 +1,228 @@
"""
backend/tests/test_shipping_task_parsed_projection.py
用途:验证 Task Detail / Candidate brief 对订单解析结果与门禁的持久只读投影。
依赖:内存数据库、ShippingTask / ShippingNoticeCandidate、query_service、document_candidate_persist。
逻辑:构造带 step_payload 与 source_candidate 的任务,断言 DETAIL 顶层字段与 Candidate brief 暴露证据。
"""
from __future__ import annotations
from app import db
from app.models import ShippingNoticeCandidate, ShippingTask
from app.services.shipping_notice.document_candidate_persist import _serialize_candidate_brief
from app.services.shipping_notice.query_service import serialize_task_detail
def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
"""Task Detail 必须稳定顶层返回 lines 门禁与来源 Candidate 证据投影。"""
with app.app_context():
candidate = ShippingNoticeCandidate(
candidate_no='SNC-PARSED-PROJECTION-001',
intake_id=1,
primary_document_id=1,
candidate_key='parsed-projection-1',
missing_fields_json=['hub_code'],
field_confidence_json={'sku': 0.95, 'qty': 0.9},
evidence_json=[{
'field': 'lines[0].reservation_id',
'line_index': 0,
'reservation_id': '1000140351',
'quote': '1000140351',
'document_id': 1,
}],
conflicts_json=[],
)
db.session.add(candidate)
db.session.flush()
task = ShippingTask(
task_no='SN-PARSED-PROJECTION-001',
source_type='manual',
process_status='pending_review',
po_number='4510038672',
source_candidate_id=int(candidate.id),
lines_json=[{
'sku': 'P123456',
'qty': 24,
'reservation_id': '1000140351',
'source_type': 'DBS DUB',
'hub_code': 'DUB1',
}],
step_payload_json={
'parse_validation': {
'status': 'ready',
'issues': [],
'contract_version': 'shipping-line-v1',
},
'process_field_gate': {
'status': 'ready',
'missing_fields': [],
'issues': [],
},
},
)
db.session.add(task)
db.session.commit()
detail = serialize_task_detail(task)
assert detail['lines'][0]['reservation_id'] == '1000140351'
assert detail['lines'][0]['hub_code'] == 'DUB1'
assert detail['parse_validation']['status'] == 'ready'
assert detail['process_field_gate']['status'] == 'ready'
assert detail['source_candidate']['candidate_no'] == 'SNC-PARSED-PROJECTION-001'
assert detail['source_candidate']['missing_fields'] == ['hub_code']
assert detail['source_candidate']['evidence'][0]['reservation_id'] == '1000140351'
def test_serialize_candidate_brief_exposes_evidence_and_missing_fields(app):
"""Candidate brief 必须暴露已落库的 evidence / missing_fields / field_confidence。"""
with app.app_context():
candidate = ShippingNoticeCandidate(
candidate_no='SNC-BRIEF-EVIDENCE-001',
intake_id=1,
primary_document_id=1,
candidate_key='brief-evidence-1',
missing_fields_json=['reservation_id'],
field_confidence_json={'sku': 0.88},
evidence_json=[{'field': 'lines[0].sku', 'quote': 'SKU-A', 'document_id': 1}],
conflicts_json=[{'field': 'reservation_id', 'reason': 'source_conflict'}],
structured_result_json={'business_summary': {'po_number': 'PO-1', 'lines': []}},
)
brief = _serialize_candidate_brief(candidate)
assert brief['missing_fields'] == ['reservation_id']
assert brief['field_confidence']['sku'] == 0.88
assert brief['evidence'][0]['quote'] == 'SKU-A'
assert brief['conflicts'][0]['reason'] == 'source_conflict'
def test_normalize_notice_line_keeps_hub_code_independent_of_source_type():
"""Hub Code 不得折叠进 source_type;两者应同时保留。"""
from app.services.shipping_notice.candidate_validation import normalize_candidate_business_summary
from app.services.shipping_notice.notice_lines import normalize_notice_line
line = normalize_notice_line({
'sku': 'P123456',
'qty': 24,
'reservation_id': '1000140351',
'source_type': 'DBS DUB',
'hub_code': 'DUB1',
'Hub Code': 'SHOULD_NOT_OVERRIDE_EXPLICIT',
})
assert line is not None
assert line['source_type'] == 'DBS DUB'
assert line['hub_code'] == 'DUB1'
summary = normalize_candidate_business_summary({
'po_number': '4510038672',
'lines': [{
'sku': 'P123456',
'qty': 24,
'reservation_id': '1000140351',
'source_type': 'VMI-FRA01',
'hub_code': 'FRA01',
}],
})
assert summary['lines'][0]['source_type'] == 'VMI-FRA01'
assert summary['lines'][0]['hub_code'] == 'FRA01'
def test_candidate_update_persists_hub_code_round_trip(app):
"""Candidate 人工修订保存后,hub_code 必须仍在 business_summary 中。"""
from app.models import Agent, ChatSession, FileAsset, ShippingNoticeDocument, ShippingNoticeIntake, User
from app.services.shipping_notice.candidate_service import update_candidate
with app.app_context():
user = User(username='hub-code-user', email='hub-code@example.com', password_hash='x')
agent = Agent(
name='Shipping Notice',
agent_code='shipping_notice_hub_code',
dify_app_id='shipping-hub-code-test',
dify_api_key='test-key',
)
db.session.add_all([user, agent])
db.session.flush()
session = ChatSession(
session_id='sess-hub-code',
user_id=int(user.id),
agent_id=int(agent.id),
title='Hub code',
)
asset = FileAsset(
asset_no='FA-HUB-CODE-001',
owner_user_id=int(user.id),
original_filename='order.pdf',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{user.id}/hub-code.pdf',
content_hash='hash-hub-code',
file_size=12,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add_all([session, asset])
db.session.flush()
intake = ShippingNoticeIntake(
intake_no='SI-HUB-CODE-001',
asset_id=int(asset.id),
user_id=int(user.id),
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
order_extraction_status='not_started',
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
intake_id=int(intake.id),
asset_id=int(asset.id),
document_type='attachment',
attachment_key='order.pdf',
filename='order.pdf',
content_hash='hash-hub-code-doc',
classification='order_notice',
parse_status='parsed',
extracted_text='SKU P123456 qty 24',
)
db.session.add(document)
db.session.flush()
candidate = ShippingNoticeCandidate(
candidate_no='SNC-HUB-CODE-001',
intake_id=int(intake.id),
primary_document_id=int(document.id),
candidate_key='hub-code-1',
validation_status='needs_review',
selected=True,
structured_result_json={
'business_summary': {
'po_number': '4510038672',
'lines': [{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}],
},
},
)
db.session.add(candidate)
db.session.commit()
updated = update_candidate(
user_id=int(user.id),
candidate_no='SNC-HUB-CODE-001',
business_summary={
'po_number': '4510038672',
'lines': [{
'sku': 'P123456',
'qty': 24,
'reservation_id': '1000140351',
'source_type': 'DBS DUB',
'hub_code': 'DUB1',
'uom': 'EA',
}],
},
)
line = updated['business_summary']['lines'][0]
assert line['source_type'] == 'DBS DUB'
assert line['hub_code'] == 'DUB1'
db.session.refresh(candidate)
persisted = candidate.structured_result_json['business_summary']['lines'][0]
assert persisted['hub_code'] == 'DUB1'
assert persisted['source_type'] == 'DBS DUB'
+1
View File
@@ -92,6 +92,7 @@
- 32 位十六进制内部主键和 UUID 不得进入库存匹配;数字型及 `AWS-311 / ORD-3002 / R-1` 等字母型业务编号按通用契约兼容,后续可按客户或来源 profile 收紧。
- 自动纠错必须具备表头列关系和唯一 SKU/APN/MPN 关联证据;拍平文本或多义匹配不得猜测,必须进入人工复核。
- 后端必须保留原始候选、修正值、原因与证据;任何 blocking 问题不得被 LLM 高置信度或人工“确认”动作绕过。
- 订单行持久化:Task 当前订单行以规范表 `shipping_task_lines` 为演进真相源;`lines_json` 在迁移窗口内保留为兼容快照与快速回滚。Candidate→既有 Task 仅允许空字段安全补齐,双方非空且不同时落字段冲突并阻断库存/匹配/导出;人工改单须带 `expected_order_data_version`。
- **同请求去重**:上传接入阶段按源文件 SHA-256 去重,相同内容只抽取、建任务一次。
- **建单幂等**:`ShippingBatch.create_idempotency_key` 防止双击、重试与并发重复建批;数据库唯一约束 `(user_id, create_idempotency_key)` 提供最终保护。
@@ -166,6 +166,7 @@ WYC26071501
- **Source Type** 仅辅助库存路由,可展示和修订;缺失时不会单独触发字段门禁。
- 邮件模板可以不同;系统按字段语义和表格列关系识别,不依赖固定列顺序。`Allocation ID`、`Parent allocation ID`、`Commodity group ID` 不属于 Reservation ID。
- AI 解析结果只是候选,后端会再次校验。若候选像 32 位内部主键、与原文列证据冲突或无法可靠对齐,系统会阻断并要求人工复核,不会把猜测值送入库存匹配。
- 建单后工作台会持久展示订单解析结果;若新订单与旧任务同 PO 但字段冲突,系统会标出冲突并停住后续库存步骤,需您选择保留旧值、采用新值或手工修正后再继续。
- **要求交期、供应商料号、币种** 按**明细行**解析与导出;若 PDF 仅有一个文档级交期或币种,系统会回填到各行。
- **单价、金额、币种** 主要用于展示与导出,**不参与**「够不够货」的自动比对。
- 若订单含 Reservation ID 而库存表未正确对应,系统会在「字段对齐」环节给出警告。
+11 -1
View File
@@ -4167,8 +4167,18 @@ Agent 状态输入标准化 -> 货代续办 Agent
| `review_status` | 人工确认状态 |
| `pending_human_reason` | 当前等待人工原因 |
| `match_status` | 匹配结果状态 |
| `lines_json` | 发货通知行项目 |
| `lines_json` | 发货通知行项目兼容快照(迁移窗口内与规范表双写;业务读经 `task_line_store`) |
| `order_data_version` | 订单行乐观版本;改单/冲突解决须携带 expected 版本 |
| `order_lines_migration_status` | 规范表回填状态:`pending/synced/failed` |
| `inventory_lines_json` | 任务级库存投影缓存;批次库存真相源为 `shipping_inventory_files.inventory_lines_json` |
规范订单行切读运维(`shipping_task_lines`):
1. 确认全实例 `WRITE_MODE=dual`,旧只写 JSON 实例已退出。
2. `python scripts/backfill_shipping_task_lines.py --apply` 分页跑完;失败 Task 隔离修复后重跑。
3. `python scripts/verify_shipping_task_lines.py` 全量 `mismatch=0`(checksum 已规范化 qty 与标识字段 int/str)。
4. 保持 `READ_MODE=shadow` 观察 ≥24h,shadow mismatch 日志应为 0。
5. 切 `READ_MODE=table`;异常时改回 `json` 或 `shadow`,本期不删 `lines_json`。
| `export_file_path` | 生成的 Excel 文件路径 |
| `freight_ref_no` | 货代上传回执号 |
| `upload_status` | 上传子状态 |
+3
View File
@@ -65,6 +65,9 @@
| 点击发送完整订单抽取 | 已实现(Dify 画布待手工配置) | 前端通过普通 Chatflow 发送 `shipping_intake_nos`;`agent_runtime_context` 触发固定分支;两个 Tool 读取不可变快照、接收 orders[],支持一附件多订单、SKU/Qty 证据/置信度门禁与幂等重放 |
| 订单识别生命周期反馈 | 已实现 | Handler 在 Dify 首帧前推送 `shipping_order_extraction_state=extracting`,terminal 后推送真实计数与失败状态;终态合并到 `ChatLog.payload`,聊天历史可恢复,处理中不伪造百分比 |
| 多订单 Candidate 判重与自动建批 | 已实现 | Candidate 身份/内容双指纹;高置信 SKU+Qty 订单自动建 Task,低置信/冲突/修订保留待处理;部分消费 Intake 不丢剩余订单;缺 Reservation 的 Task 停在自然对话补字段门禁,订单行 Source Type 仅作可选路由线索 |
| 订单解析结果持久只读展示 | 已实现 | Task Detail 顶层投影 `lines` / `parse_validation` / `process_field_gate` / `source_candidate`;右侧工作台与独立任务页共用解析卡,展示 Reservation/Source Type/Hub Code、门禁与证据;Candidate 审核非编辑态同步展示关键行 |
| 规范订单行双写与影子校验 | 已实现 | 默认 `WRITE_MODE=dual` + `READ_MODE=shadow`;解析/改单/回填/重解析经 `task_line_store` 同事务双写;历史回填与 `verify_shipping_task_lines` 支持干跑/续跑;shadow 对外仍读 JSON 并记 checksum;业务读路径统一走 store;观察窗口零差异后切 `READ_MODE=table`;`lines_json` 保留作回滚快照 |
| 订单字段对账与冲突复核 | 已实现 | Candidate→Task 字段级自动补空/冲突落库;未解决冲突阻断库存/匹配/导出;workspace 冲突查询与解决 API;改单支持 `expected_order_data_version` 与幂等键;工作台解析卡可解决冲突 |
| 库存 RPA 源 YAML 配置 | 已实现 | `backend/config/shipping_inventory_sources.yaml`,新增 Warehouse 只改 YAML |
| 订单解析阶段库存源判定 | 已实现 | `parse_notice` 内 adjudicate 写线索;订单行 `source_type` 可选,连接器字段为 `connector_type` / `inventory_connector_type`;低置信度先 `parse_review`,解析通过后再 `inventory_source_review`;稳定态 `resolved`/`user_confirmed` |
| 文件解析阶段问题清单 | 已实现 | 步骤 2 工作台/`ui_state.summary.issues` 一次列出解析复核、RSV、库存源门禁与 parse warnings |
+6 -2
View File
@@ -54,7 +54,7 @@
"post": {
"operationId": "submit_order_extraction",
"summary": "提交完整订单抽取结果,由 HXOPS 执行证据校验、订单级判重与自动建单",
"description": "只接受 get_order_extraction_context 的同一快照。HXOPS 仅在分类、SKU/Qty 置信度及原文证据均达标,且无阻断冲突/修订决策时自动建单;Reservation ID 允许缺失,订单行 Source Type 是可选路由线索。响应以持久化结果分别返回 created_count、opened_existing_count、pending_count、non_shipping_count;auto_created_count 仅为兼容字段且等于 created_count。",
"description": "只接受 get_order_extraction_context 的同一快照。HXOPS 仅在分类、SKU/Qty 置信度及原文证据均达标,且无阻断冲突/修订决策时自动建单;Reservation ID 允许缺失,订单行 Source Type / Hub Code 是可选路由线索并独立持久化。响应以持久化结果分别返回 created_count、opened_existing_count、pending_count、non_shipping_count;auto_created_count 仅为兼容字段且等于 created_count。",
"parameters": [],
"requestBody": {
"required": true,
@@ -166,7 +166,11 @@
},
"source_type": {
"type": "string",
"description": "可选订单路由线索;仅在原文有可靠证据时填写,不代表任务通知来源或已确认的库存连接器类型"
"description": "可选订单路由线索(库存来源提示);仅在原文有可靠证据时填写,不代表任务通知来源或已确认的库存连接器类型"
},
"hub_code": {
"type": "string",
"description": "可选 Hub/站点线索;与 source_type 独立落库,禁止折叠进 source_type"
}
},
"additionalProperties": true
+1
View File
@@ -59,6 +59,7 @@
- 库存 Excel 上传后保存为 `shipping_inventory_files` 批次库存快照,并通过 `shipping_task_inventory_links` 关联到本批任务。
- 字段映射与完整库存解析在库存快照层完成一次;每票仍使用自己的发货需求行独立执行库存匹配、Excel 生成与上传。
- `ShippingTask.inventory_lines_json` 仅作为任务侧投影缓存,批次库存真相源为 `shipping_inventory_files.inventory_lines_json`。
- **订单行双写与切读**:业务读写经 `task_line_store`;`WRITE_MODE=dual` 同事务维护 `shipping_task_lines` 与 `lines_json`;`READ_MODE=shadow|table`(默认 shared 为 shadow);切 `table` 前须 `verify_shipping_task_lines` 全量零差异并完成观察窗口;回滚只改 `READ_MODE=json`,本期不删 `lines_json`。字段冲突表 `shipping_task_field_conflicts` 与 `order_data_version` 支撑并发安全编辑。
- **库存源判定前移至订单解析**:`parse_notice` 根据 `shipping_inventory_sources.yaml` 与目的地字段自动 adjudicate;订单行 `source_type` 仅作为可选路由线索,库存连接器配置/API 分别使用 `connector_type` / `inventory_connector_type`,不得复用 `ShippingTask.source_type`;仅 `inventory_source_status` 为 `resolved` 或 `user_confirmed` 时允许 RPA 与后续步骤;`site_id` 与 `warehouse_id` 由配置生成,用户只确认 `source_code`。详见 [inventory_source_plan.md](features/shipping-notice/inventory_source_plan.md)。
- **建单防重复(第一阶段)**:`ShippingBatch.create_idempotency_key` + `(user_id, create_idempotency_key)` 唯一约束提供并发保护;`ShippingTask.source_content_hash` 记录源文件 SHA-256;Chat Turn 与 Workspace API 共用 `batch_from_notices` 幂等逻辑;与货代上传 `ShippingTask.idempotency_key` 语义分离。
+2
View File
@@ -46,4 +46,6 @@
| **发货通知** | **Candidate 安全门禁** | 空摘要、无效行、附件不完整、过期、选择漂移、无候选旧路径均不可建单。 | `test_shipping_notice_intakes.py` Candidate validation/gate 用例 | 非法摘要与异常 Intake | API 返回明确 400/409;不创建 Task;合法幂等重放不受影响。 |
| **发货通知** | **关键字段真值校验** | LLM 候选必须经后端格式、来源和列证据裁决;多模板字母/数字 ID 兼容,内部 hex/UUID 与来源冲突必须阻断。 | `test_shipping_notice_reservation_id.py`、`test_shipping_notice_extract.py`、`test_shipping_notice_tools.py` | External Reservation、COM ID、PR Number、AWS-311、32 位 hex、拍平文本、冲突 TSV | 有唯一列证据时纠正并留痕;无证据或冲突时进入 `rsv_req/parse_review`;确认与匹配旁路均不可绕过。 |
| **发货通知** | **Candidate 迁移往返** | 内容指纹、订单抽取状态与多 Candidate 唯一键迁移须可独立 upgrade/downgrade。 | `test_shipping_notice_candidate_migration.py` | 前一版本最小 schema;同 Document 多 Candidate | 新列/约束存在;安全场景完整降级;多 Candidate 场景明确拒绝降级。 |
| **发货通知** | **订单行双写与切读** | dual 写同事务更新 JSON+规范表;shadow 对外仍读 JSON;table 读以规范表为准;回填/校验可运维。 | `test_shipping_task_line_store.py`;脚本 `backfill_shipping_task_lines.py` / `verify_shipping_task_lines.py` | dual/shadow/table 配置;非法 qty;人为 JSON 漂移 | dual 成功落两侧;shadow 打 mismatch 日志;table 忽略漂移;verify mismatch 退出码 1。 |
| **发货通知** | **字段对账与冲突门禁** | Candidate 空字段可补齐;双方非空不同落冲突;未解决冲突阻断库存/RPA/匹配/导出;改单带版本。 | `test_shipping_task_field_reconciliation.py` | open_existing 补 Reservation;多行同字段冲突;行重建后冲突存活 | applied/conflicted 可区分;下游入口无副作用;resolve 后重算 Gate。 |
+69 -2
View File
@@ -352,10 +352,18 @@ export async function updateWorkspaceShippingNoticeFields(
taskNo: string,
fields: Partial<ShippingNoticeHeader>,
comment?: string,
options?: { expectedOrderDataVersion?: number; idempotencyKey?: string },
) {
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/update-notice-fields`,
jsonPost({ fields, ...(comment ? { comment } : {}) }),
jsonPost({
fields,
...(comment ? { comment } : {}),
...(options?.expectedOrderDataVersion != null
? { expected_order_data_version: options.expectedOrderDataVersion }
: {}),
...(options?.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}),
}),
);
return assertShippingOk(body);
}
@@ -373,14 +381,73 @@ export async function updateWorkspaceShippingNoticeLine(
lineIndex: number,
patch: Partial<ShippingNoticeLine> & { quantity?: number },
comment?: string,
options?: { expectedOrderDataVersion?: number; idempotencyKey?: string },
) {
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/update-notice-line`,
jsonPost({ line_index: lineIndex, patch, ...(comment ? { comment } : {}) }),
jsonPost({
line_index: lineIndex,
patch,
...(comment ? { comment } : {}),
...(options?.expectedOrderDataVersion != null
? { expected_order_data_version: options.expectedOrderDataVersion }
: {}),
...(options?.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}),
}),
);
return assertShippingOk(body);
}
/**
* 列出任务未解决字段冲突。
* @param taskNo - 发货任务编号
*/
export async function listWorkspaceShippingFieldConflicts(taskNo: string) {
return requestJson<{
task_no: string;
order_data_version: number;
open_count: number;
items: import('@/features/chat/types/shipping.api.types').ShippingFieldConflict[];
}>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/field-conflicts`);
}
/**
* 解决字段冲突(keep_existing / take_incoming / custom)。
*/
export async function resolveWorkspaceShippingFieldConflict(
taskNo: string,
conflictId: number,
payload: {
resolution: 'keep_existing' | 'take_incoming' | 'custom' | string;
resolvedValue?: string;
expectedConflictVersion?: number;
expectedOrderDataVersion?: number;
reason?: string;
idempotencyKey?: string;
},
) {
return requestJson<{
conflict: import('@/features/chat/types/shipping.api.types').ShippingFieldConflict;
order_data_version: number;
open_conflict_count: number;
idempotent_replay?: boolean;
}>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/field-conflicts/${conflictId}/resolve`,
jsonPost({
resolution: payload.resolution,
...(payload.resolvedValue != null ? { resolved_value: payload.resolvedValue } : {}),
...(payload.expectedConflictVersion != null
? { expected_conflict_version: payload.expectedConflictVersion }
: {}),
...(payload.expectedOrderDataVersion != null
? { expected_order_data_version: payload.expectedOrderDataVersion }
: {}),
...(payload.reason ? { reason: payload.reason } : {}),
...(payload.idempotencyKey ? { idempotency_key: payload.idempotencyKey } : {}),
}),
);
}
/**
* 为发货通知新增订单行。
* @param taskNo - 发货任务编号
@@ -27,6 +27,7 @@ import type {
ShippingTaskDetail,
ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import ShippingTaskParsedResultCard from '@/features/chat/components/ShippingTaskParsedResultCard.vue';
const props = defineProps<{
open: boolean;
@@ -631,6 +632,21 @@ const handleSwitchBatch = (batchNo: string) => {
</ul>
<div class="mt-1 font-normal text-slate-600">{{ diagnosis.advice }}</div>
</div>
<ShippingTaskParsedResultCard
v-if="isCurrentTask(task.task_no) && activeTaskDetail"
class="mb-3"
:task-no="activeTaskDetail.task_no"
:po-number="activeTaskDetail.po_number"
:lines="activeTaskDetail.lines"
:parse-validation="activeTaskDetail.parse_validation || activeTaskDetail.step_payload?.parse_validation || null"
:process-field-gate="activeTaskDetail.process_field_gate || null"
:source-candidate="activeTaskDetail.source_candidate || null"
:field-conflicts="activeTaskDetail.field_conflicts || []"
:order-data-version="activeTaskDetail.order_data_version"
:default-expanded="isAbnormalTask(task) || isWaitingHumanTask(task)"
compact
@refreshed="emit('focus-task', activeTaskDetail.task_no)"
/>
<div v-if="!resolveWorkspaceActionButtons(task).length" class="mb-3 text-xs leading-5 text-muted">
<span class="font-semibold text-secondary">{{ t('chat.shippingNoticeUi.suggestedAction') }}</span>
{{ resolveSuggestedAction(task) }}
@@ -0,0 +1,52 @@
<!--
features/chat/components/ShippingFieldEvidencePanel.vue
用途:只读展开订单字段级原文证据(Document + quote)。
依赖:shipping.api.types、vue-i18n。
逻辑:由 ShippingTaskParsedResultCard / Candidate 审核区传入 evidence;本组件不推导业务结论。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingFieldEvidenceItem } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
evidence?: ShippingFieldEvidenceItem[] | null;
compact?: boolean;
}>();
const { t } = useI18n();
const items = computed(() =>
(props.evidence || []).filter((item) => item && typeof item === 'object'),
);
</script>
<template>
<div v-if="items.length" class="space-y-2">
<div class="text-[11px] font-semibold uppercase tracking-wide text-muted">
{{ t('chat.shippingParsedResult.evidenceTitle') }}
</div>
<details
v-for="(item, index) in items"
:key="`${item.field || 'field'}-${item.document_id || index}`"
class="rounded-lg border border-default bg-surface px-2.5 py-2 text-xs"
:open="!compact && index === 0"
>
<summary class="cursor-pointer font-medium text-secondary">
<span class="font-mono">{{ item.field || t('chat.shippingParsedResult.unknownField') }}</span>
<span v-if="item.reservation_id" class="ml-2 text-muted">{{ item.reservation_id }}</span>
</summary>
<div class="mt-2 space-y-1 text-muted">
<div v-if="item.document_id != null">
{{ t('chat.shippingParsedResult.documentId', { id: item.document_id }) }}
</div>
<blockquote
v-if="item.quote"
class="rounded border border-slate-200 bg-slate-50 px-2 py-1.5 font-mono text-[11px] leading-5 text-slate-700"
>
{{ item.quote }}
</blockquote>
</div>
</details>
</div>
</template>
@@ -15,6 +15,7 @@ interface EditableCandidateLine {
qty: string;
reservation_id: string;
source_type: string;
hub_code: string;
uom: string;
}
@@ -46,7 +47,7 @@ watch(() => props.attachment.candidates, () => {
/**
* 将 Candidate 摘要投影为可编辑的 PO 与订单行。
* 核心逻辑:保留原始扩展字段,并显式映射 SKU、数量、Reservation ID、Source Type 与单位。
* 核心逻辑:保留原始扩展字段,并显式映射 SKU、数量、Reservation ID、Source Type、Hub Code 与单位。
* @param candidateNo - 待编辑的 Candidate 编号
* @returns 无返回值;Candidate 不存在时保持当前编辑状态
*/
@@ -64,6 +65,7 @@ function startEdit(candidateNo: string): void {
qty: String(line.qty ?? ''),
reservation_id: String(line.reservation_id || ''),
source_type: String(line.source_type || ''),
hub_code: String(line.hub_code || ''),
uom: String(line.uom || 'EA'),
})));
if (!editLines.length) addLine();
@@ -72,16 +74,16 @@ function startEdit(candidateNo: string): void {
/**
* 新增一条待修订订单行。
* 核心逻辑:创建带可选 Source Type 路由线索的空白草稿。
* 核心逻辑:创建带可选 Source Type / Hub Code 路由线索的空白草稿。
* @returns 无返回值
*/
function addLine(): void {
editLines.push({ source: {}, sku: '', qty: '', reservation_id: '', source_type: '', uom: 'EA' });
editLines.push({ source: {}, sku: '', qty: '', reservation_id: '', source_type: '', hub_code: '', uom: 'EA' });
}
/**
* 校验并提交 Candidate 修订。
* 核心逻辑:保留原始扩展字段,并将 Source Type 作为唯一可选库存路由线索提交。
* 核心逻辑:保留原始扩展字段;Source Type 与 Hub Code 分开提交,避免编辑时静默丢失 Hub Code。
* @returns 无返回值;校验失败时写入本地错误提示
*/
function saveEdit(): void {
@@ -95,6 +97,7 @@ function saveEdit(): void {
qty: Number(line.qty),
reservation_id: line.reservation_id.trim() || undefined,
source_type: line.source_type.trim() || undefined,
hub_code: line.hub_code.trim() || undefined,
uom: line.uom.trim() || 'EA',
};
});
@@ -116,6 +119,23 @@ function saveEdit(): void {
});
}
/**
* 非编辑态展示 Candidate 订单行摘要。
* @param candidate - 当前 Candidate
*/
function readonlyLines(candidate: typeof candidates.value[number]): Array<Record<string, unknown>> {
const lines = candidate.businessSummary?.lines;
return Array.isArray(lines)
? lines.filter((item): item is Record<string, unknown> => !!item && typeof item === 'object')
: [];
}
/** 将未知值格式化为表格占位文本。 */
function displayCell(value: unknown): string {
const text = String(value ?? '').trim();
return text || '—';
}
/** 对当前首个重复目标应用决策;强制新建时要求填写原因。 */
function resolveDuplicate(candidateNo: string, action: ShippingDuplicateAction): void {
const candidate = candidates.value.find((item) => item.candidateNo === candidateNo);
@@ -178,6 +198,38 @@ function submitForceCreate(candidateNo: string): void {
<div v-if="candidate.conflicts.length" class="mt-1 text-amber-700">
{{ t('chat.shippingCandidateConflictCount', { count: candidate.conflicts.length }) }}
</div>
<div
v-if="editingCandidateNo !== candidate.candidateNo && readonlyLines(candidate).length"
class="mt-2 overflow-x-auto rounded-lg border border-default bg-surface"
>
<table class="min-w-full text-[11px]">
<thead class="bg-surface-soft text-left text-muted">
<tr>
<th class="px-2 py-1">{{ t('chat.shippingCandidateSku') }}</th>
<th class="px-2 py-1">{{ t('chat.shippingCandidateQty') }}</th>
<th class="px-2 py-1">{{ t('chat.shippingCandidateReservation') }}</th>
<th class="px-2 py-1">{{ t('chat.shippingCandidateSourceType') }}</th>
<th class="px-2 py-1">{{ t('chat.shippingCandidateHubCode') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="(line, index) in readonlyLines(candidate)"
:key="`${candidate.candidateNo}-line-${index}`"
class="border-t border-default/60"
>
<td class="px-2 py-1 font-mono">{{ displayCell(line.sku) }}</td>
<td class="px-2 py-1">{{ displayCell(line.qty) }}</td>
<td class="px-2 py-1 font-mono">{{ displayCell(line.reservation_id) }}</td>
<td class="px-2 py-1">{{ displayCell(line.source_type) }}</td>
<td class="px-2 py-1 font-mono">{{ displayCell(line.hub_code) }}</td>
</tr>
</tbody>
</table>
</div>
<div v-if="(candidate.missingFields || []).length" class="mt-1 text-amber-700">
{{ t('chat.shippingCandidateMissingFields', { fields: (candidate.missingFields || []).join(', ') }) }}
</div>
<div v-if="candidate.duplicate?.blocking && !candidate.duplicateResolution" class="mt-2 flex flex-wrap items-center gap-2 text-amber-700">
<span>{{ t('chat.shippingCandidateDuplicate', { task: candidate.duplicate.matches[0]?.taskNo || '-' }) }}</span>
<button
@@ -212,11 +264,12 @@ function submitForceCreate(candidateNo: string): void {
<span class="text-muted">{{ t('chat.shippingCandidatePoNumber') }}</span>
<input v-model="editPoNumber" class="mt-1 w-full rounded border border-default bg-surface px-2 py-1 text-primary" />
</label>
<div v-for="(line, index) in editLines" :key="index" class="grid grid-cols-2 gap-2 rounded border border-default bg-surface p-2 md:grid-cols-5">
<div v-for="(line, index) in editLines" :key="index" class="grid grid-cols-2 gap-2 rounded border border-default bg-surface p-2 md:grid-cols-6">
<input v-model="line.sku" :placeholder="t('chat.shippingCandidateSku')" class="rounded border border-default px-2 py-1" />
<input v-model="line.qty" type="number" min="0.0001" step="any" :placeholder="t('chat.shippingCandidateQty')" class="rounded border border-default px-2 py-1" />
<input v-model="line.reservation_id" :placeholder="t('chat.shippingCandidateReservation')" class="rounded border border-default px-2 py-1" />
<input v-model="line.source_type" :placeholder="t('chat.shippingCandidateSourceType')" class="rounded border border-default px-2 py-1" />
<input v-model="line.hub_code" :placeholder="t('chat.shippingCandidateHubCode')" class="rounded border border-default px-2 py-1" />
<div class="flex gap-1">
<input v-model="line.uom" :placeholder="t('chat.shippingCandidateUom')" class="min-w-0 flex-1 rounded border border-default px-2 py-1" />
<button v-if="editLines.length > 1" type="button" class="text-red-600" @click="editLines.splice(index, 1)">×</button>
@@ -0,0 +1,111 @@
<!--
features/chat/components/ShippingTaskFieldConflictPanel.vue
用途:展示并解决任务级订单字段冲突(keep / take incoming)。
依赖:shipping.api.resolveWorkspaceShippingFieldConflict、vue-i18n、useMessage。
逻辑:由 ShippingTaskParsedResultCard 挂载;解决成功后 emit refreshed 让父级重拉 Task Detail。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { resolveWorkspaceShippingFieldConflict } from '@/features/chat/api/shipping.api';
import type { ShippingFieldConflict } from '@/features/chat/types/shipping.api.types';
import { useMessage } from '@/shared/composables/useMessage';
const props = defineProps<{
taskNo: string;
conflicts?: ShippingFieldConflict[] | null;
orderDataVersion?: number | null;
}>();
const emit = defineEmits<{
refreshed: [];
}>();
const { t } = useI18n();
const msg = useMessage();
const resolvingId = ref<number | null>(null);
const openConflicts = computed(() =>
(props.conflicts || []).filter((item) => String(item.status || '') === 'open'),
);
/**
* 解决单条冲突。
* 核心逻辑:携带 conflict_version 与 order_data_version;409 时提示刷新。
*/
async function resolveConflict(
conflict: ShippingFieldConflict,
resolution: 'keep_existing' | 'take_incoming',
) {
if (!props.taskNo || resolvingId.value != null) return;
resolvingId.value = conflict.id;
try {
await resolveWorkspaceShippingFieldConflict(props.taskNo, conflict.id, {
resolution,
expectedConflictVersion: conflict.conflict_version,
expectedOrderDataVersion: props.orderDataVersion ?? undefined,
idempotencyKey: `conflict-${conflict.id}-${resolution}-${conflict.conflict_version}`,
});
msg.success(t('chat.shippingFieldConflict.resolveSuccess'));
emit('refreshed');
} catch (err) {
msg.error(err instanceof Error ? err.message : t('chat.shippingFieldConflict.resolveFailed'));
} finally {
resolvingId.value = null;
}
}
</script>
<template>
<div
v-if="openConflicts.length"
class="space-y-2 rounded-lg border border-rose-200 bg-rose-50/80 px-2.5 py-2"
>
<div class="text-[11px] font-semibold text-rose-900">
{{ t('chat.shippingFieldConflict.title', { count: openConflicts.length }) }}
</div>
<div class="text-[11px] leading-5 text-rose-800">
{{ t('chat.shippingFieldConflict.hint') }}
</div>
<ul class="space-y-2">
<li
v-for="conflict in openConflicts"
:key="conflict.id"
class="rounded-md border border-rose-200 bg-white/90 px-2.5 py-2 text-[11px]"
>
<div class="font-medium text-rose-900">
<span v-if="conflict.position != null">#{{ Number(conflict.position) + 1 }} · </span>
<span class="font-mono">{{ conflict.field_name }}</span>
</div>
<div class="mt-1 grid gap-1 text-slate-700 sm:grid-cols-2">
<div>
<span class="text-muted">{{ t('chat.shippingFieldConflict.existing') }}:</span>
<span class="ml-1 font-mono">{{ conflict.existing_value || '—' }}</span>
</div>
<div>
<span class="text-muted">{{ t('chat.shippingFieldConflict.incoming') }}:</span>
<span class="ml-1 font-mono">{{ conflict.incoming_value || '—' }}</span>
</div>
</div>
<div class="mt-2 flex flex-wrap gap-2">
<button
type="button"
class="rounded border border-slate-300 bg-white px-2 py-1 text-[11px] font-medium hover:bg-slate-50 disabled:opacity-50"
:disabled="resolvingId != null"
@click="resolveConflict(conflict, 'keep_existing')"
>
{{ t('chat.shippingFieldConflict.keepExisting') }}
</button>
<button
type="button"
class="rounded border border-rose-300 bg-rose-100 px-2 py-1 text-[11px] font-medium text-rose-900 hover:bg-rose-200 disabled:opacity-50"
:disabled="resolvingId != null"
@click="resolveConflict(conflict, 'take_incoming')"
>
{{ t('chat.shippingFieldConflict.takeIncoming') }}
</button>
</div>
</li>
</ul>
</div>
</template>
@@ -0,0 +1,210 @@
<!--
features/chat/components/ShippingTaskParsedResultCard.vue
用途:任务详情持久只读展示订单解析行、流转门禁、字段冲突与来源证据。
依赖:ShippingFieldEvidencePanel、ShippingTaskFieldConflictPanel、shipping.api.types、vue-i18n。
逻辑:Drawer / ShippingNoticeView 共用;只解释后端 Gate,不自行推导可继续状态。
-->
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import ShippingFieldEvidencePanel from '@/features/chat/components/ShippingFieldEvidencePanel.vue';
import ShippingTaskFieldConflictPanel from '@/features/chat/components/ShippingTaskFieldConflictPanel.vue';
import type {
ShippingFieldConflict,
ShippingNoticeLine,
ShippingParseIssue,
ShippingParseValidation,
ShippingProcessFieldGate,
ShippingSourceCandidateProjection,
} from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
taskNo?: string | null;
poNumber?: string | null;
lines?: ShippingNoticeLine[] | null;
parseValidation?: ShippingParseValidation | null;
processFieldGate?: ShippingProcessFieldGate | null;
sourceCandidate?: ShippingSourceCandidateProjection | null;
fieldConflicts?: ShippingFieldConflict[] | null;
orderDataVersion?: number | null;
/** 阻断时默认展开;非阻断可折叠。 */
defaultExpanded?: boolean;
compact?: boolean;
}>();
const emit = defineEmits<{
refreshed: [];
}>();
const { t } = useI18n();
const expanded = ref(true);
watch(
() => props.defaultExpanded,
(value) => {
if (typeof value === 'boolean') expanded.value = value;
},
{ immediate: true },
);
const orderLines = computed(() => (props.lines || []).filter((line) => line && typeof line === 'object'));
const gateIssues = computed(() => {
const fromGate = Array.isArray(props.processFieldGate?.issues) ? props.processFieldGate?.issues : [];
const fromValidation = Array.isArray(props.parseValidation?.issues) ? props.parseValidation?.issues : [];
return [...fromGate, ...fromValidation] as ShippingParseIssue[];
});
const missingFields = computed(() => {
const gateMissing = Array.isArray(props.processFieldGate?.missing_fields)
? props.processFieldGate?.missing_fields || []
: [];
const candidateMissing = Array.isArray(props.sourceCandidate?.missing_fields)
? props.sourceCandidate?.missing_fields || []
: [];
return Array.from(new Set([...gateMissing, ...candidateMissing].map((item) => String(item)).filter(Boolean)));
});
const hasBlocking = computed(() =>
gateIssues.value.some((issue) => String(issue.severity || '') === 'blocking')
|| missingFields.value.includes('reservation_id')
|| String(props.processFieldGate?.status || '') === 'needs_enrichment'
|| String(props.parseValidation?.status || '') === 'needs_review'
|| (props.fieldConflicts || []).some((item) => String(item.status || '') === 'open'),
);
const statusLabel = computed(() => {
if (hasBlocking.value) return t('chat.shippingParsedResult.statusBlocked');
if (orderLines.value.length) return t('chat.shippingParsedResult.statusReady');
return t('chat.shippingParsedResult.statusEmpty');
});
const displayValue = (value: unknown) => {
const text = String(value ?? '').trim();
return text || '—';
};
/**
* 将门禁 reason 映射为用户可读文案。
* @param reason - 后端 issue.reason
*/
function issueReasonLabel(reason?: string | null): string {
const key = String(reason || '').trim();
if (key === 'missing') return t('chat.shippingParsedResult.issueMissing');
if (key === 'invalid_format') return t('chat.shippingParsedResult.issueInvalid');
if (key === 'source_conflict' || key === 'field_conflict') return t('chat.shippingParsedResult.issueConflict');
if (key === 'value_corrected') return t('chat.shippingParsedResult.issueCorrected');
return key || t('chat.shippingParsedResult.issueUnknown');
}
</script>
<template>
<section
class="rounded-xl border p-3 text-xs"
:class="hasBlocking
? 'border-amber-200 bg-amber-50/70'
: 'border-slate-200 bg-surface-soft/80'"
>
<button
type="button"
class="flex w-full items-start justify-between gap-2 text-left"
@click="expanded = !expanded"
>
<div>
<div class="text-[11px] font-bold uppercase tracking-wider text-muted">
{{ t('chat.shippingParsedResult.title') }}
</div>
<div v-if="taskNo" class="mt-0.5 font-mono text-[11px] text-secondary">{{ taskNo }}</div>
<div v-if="poNumber" class="mt-0.5 text-muted">PO {{ poNumber }}</div>
</div>
<span
class="rounded-full px-2 py-0.5 text-[10px] font-semibold"
:class="hasBlocking ? 'bg-amber-100 text-amber-800' : 'bg-emerald-100 text-emerald-700'"
>
{{ statusLabel }}
</span>
</button>
<div v-if="expanded" class="mt-3 space-y-3">
<div class="rounded-lg border border-slate-200/80 bg-white/80 px-2.5 py-2 text-[11px] leading-5 text-slate-700">
{{ t('chat.shippingParsedResult.impactHint') }}
</div>
<ShippingTaskFieldConflictPanel
v-if="taskNo"
:task-no="taskNo"
:conflicts="fieldConflicts || []"
:order-data-version="orderDataVersion"
@refreshed="emit('refreshed')"
/>
<div v-if="missingFields.length" class="space-y-1">
<div class="font-semibold text-amber-800">{{ t('chat.shippingParsedResult.missingFields') }}</div>
<div class="flex flex-wrap gap-1">
<span
v-for="field in missingFields"
:key="field"
class="rounded border border-amber-200 bg-amber-100 px-1.5 py-0.5 font-mono text-[10px] text-amber-900"
>
{{ field }}
</span>
</div>
</div>
<ul v-if="gateIssues.length" class="space-y-1.5">
<li
v-for="(issue, index) in gateIssues"
:key="`${issue.field}-${issue.line_index ?? index}`"
class="rounded-lg border px-2.5 py-2"
:class="String(issue.severity) === 'blocking'
? 'border-rose-200 bg-rose-50 text-rose-800'
: String(issue.reason) === 'value_corrected'
? 'border-sky-200 bg-sky-50 text-sky-800'
: 'border-amber-200 bg-amber-50 text-amber-800'"
>
<div class="font-medium">
<span v-if="issue.line_index != null">#{{ Number(issue.line_index) + 1 }} · </span>
<span class="font-mono">{{ issue.field }}</span>
<span class="ml-1">{{ issueReasonLabel(issue.reason) }}</span>
</div>
<div v-if="issue.sku" class="mt-0.5 text-[11px] opacity-80">SKU {{ issue.sku }}</div>
</li>
</ul>
<div v-if="orderLines.length" class="overflow-x-auto rounded-xl border border-default bg-white/90">
<table class="min-w-full text-sm">
<thead class="bg-surface text-left text-[11px] text-muted">
<tr>
<th class="px-2.5 py-2">#</th>
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.sku') }}</th>
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.qty') }}</th>
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.reservationId') }}</th>
<th class="px-2.5 py-2">{{ t('chat.shippingParsedResult.sourceType') }}</th>
<th class="px-2.5 py-2">{{ t('chat.shippingParsedResult.hubCode') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="(line, index) in orderLines"
:key="`${line.sku}-${index}`"
class="border-t border-default/60 text-xs"
>
<td class="px-2.5 py-2 text-muted">{{ index + 1 }}</td>
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.sku) }}</td>
<td class="px-2.5 py-2">{{ displayValue(line.qty) }}</td>
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.reservation_id) }}</td>
<td class="px-2.5 py-2">{{ displayValue(line.source_type) }}</td>
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.hub_code) }}</td>
</tr>
</tbody>
</table>
</div>
<div v-else class="text-muted">{{ t('chat.shippingParsedResult.noLines') }}</div>
<ShippingFieldEvidencePanel
:evidence="sourceCandidate?.evidence || []"
:compact="compact"
/>
</div>
</section>
</template>
@@ -6,6 +6,7 @@
*/
import {
addWorkspaceShippingNoticeLine,
getWorkspaceShippingTask,
removeWorkspaceShippingNoticeLine,
updateWorkspaceShippingNoticeFields,
updateWorkspaceShippingNoticeLine,
@@ -33,6 +34,16 @@ export interface ShippingParseReviewContext {
* @returns 复核卡片同步与编辑处理函数集合
*/
export function createShippingParseReviewHandlers(ctx: ShippingParseReviewContext) {
/**
* 读取任务当前 order_data_version,供改单乐观锁使用。
* @param taskId - 任务编号
*/
const resolveOrderDataVersion = async (taskId: string): Promise<number | undefined> => {
const detail = await getWorkspaceShippingTask(taskId).catch(() => null);
const version = detail?.order_data_version;
return typeof version === 'number' ? version : undefined;
};
const removeParseReviewMessageForTask = (taskId: string) => {
const normalized = String(taskId || '').trim().toUpperCase();
if (!normalized) return;
@@ -63,7 +74,11 @@ export function createShippingParseReviewHandlers(ctx: ShippingParseReviewContex
payload.saving = true;
const taskId = String(payload.taskId || '').trim().toUpperCase();
try {
await updateWorkspaceShippingNoticeFields(taskId, fields, '聊天区订单表修订');
const expectedOrderDataVersion = await resolveOrderDataVersion(taskId);
await updateWorkspaceShippingNoticeFields(taskId, fields, '聊天区订单表修订', {
expectedOrderDataVersion,
idempotencyKey: `parse-review-header-${taskId}-${expectedOrderDataVersion ?? 'na'}-${Date.now()}`,
});
await syncShippingParseReviewCard(taskId);
await ctx.refreshShippingActions();
return true;
@@ -86,7 +101,11 @@ export function createShippingParseReviewHandlers(ctx: ShippingParseReviewContex
payload.saving = true;
const taskId = String(payload.taskId || '').trim().toUpperCase();
try {
await updateWorkspaceShippingNoticeLine(taskId, lineIndex, patch, '聊天区订单表修订');
const expectedOrderDataVersion = await resolveOrderDataVersion(taskId);
await updateWorkspaceShippingNoticeLine(taskId, lineIndex, patch, '聊天区订单表修订', {
expectedOrderDataVersion,
idempotencyKey: `parse-review-line-${taskId}-${lineIndex}-${expectedOrderDataVersion ?? 'na'}`,
});
await syncShippingParseReviewCard(taskId);
await ctx.refreshShippingActions();
return true;
@@ -127,6 +127,11 @@ function mapServerCandidate(remote: ShippingNoticeCandidateResponse): ShippingNo
validationStatus: remote.validation_status,
selected: Boolean(remote.selected),
conflicts: remote.conflicts || [],
missingFields: Array.isArray(remote.missing_fields) ? remote.missing_fields.map((item) => String(item)) : [],
fieldConfidence: remote.field_confidence && typeof remote.field_confidence === 'object'
? remote.field_confidence
: {},
evidence: Array.isArray(remote.evidence) ? remote.evidence : [],
businessSummary: remote.business_summary || {},
duplicate,
duplicateResolution: remote.duplicate_resolution
@@ -179,12 +179,54 @@ export interface ShippingNoticeLine {
reservation_id?: string | null;
/** 可选库存路由线索,不代表任务通知来源或已确认的库存连接器类型。 */
source_type?: string | null;
/** 站点/Hub 线索;与 source_type 独立,编辑时必须显式保留。 */
hub_code?: string | null;
qty: number;
required_date?: string | null;
uom?: string | null;
line_no?: string | null;
}
export interface ShippingProcessFieldGate {
status?: 'needs_enrichment' | 'ready' | string;
missing_fields?: string[];
issues?: ShippingParseIssue[];
contract_version?: string;
}
export interface ShippingFieldEvidenceItem {
field?: string;
line_index?: number;
reservation_id?: string | null;
quote?: string | null;
document_id?: number | null;
[key: string]: unknown;
}
export interface ShippingSourceCandidateProjection {
candidate_no?: string | null;
missing_fields?: string[];
field_confidence?: Record<string, number | null | undefined>;
evidence?: ShippingFieldEvidenceItem[];
conflicts?: Array<Record<string, unknown>>;
}
export interface ShippingFieldConflict {
id: number;
task_id: number;
line_id?: number | null;
position?: number | null;
field_name: string;
existing_value?: string | null;
incoming_value?: string | null;
existing_source?: string | null;
incoming_source?: string | null;
status: 'open' | 'resolved' | 'dismissed' | string;
conflict_version: number;
resolved_value?: string | null;
resolution_reason?: string | null;
}
export interface ShippingMatchLineResult {
sku: string;
reservation_id?: string | null;
@@ -216,6 +258,12 @@ export interface ShippingTaskDetail extends ShippingTaskSummary {
line_results?: ShippingMatchLineResult[];
parse_confidence?: number | null;
error_message?: string | null;
/** 顶层稳定投影;同时仍可能出现在 step_payload 中。 */
parse_validation?: ShippingParseValidation | null;
process_field_gate?: ShippingProcessFieldGate | null;
source_candidate?: ShippingSourceCandidateProjection | null;
order_data_version?: number | null;
field_conflicts?: ShippingFieldConflict[] | null;
events: ShippingTaskEvent[];
ui_state?: ShippingTaskUiState;
}
@@ -426,6 +474,9 @@ export interface ShippingNoticeCandidateResponse {
validation_status: string;
selected: boolean;
conflicts?: Array<Record<string, unknown>>;
missing_fields?: string[];
field_confidence?: Record<string, number | null | undefined>;
evidence?: ShippingFieldEvidenceItem[];
business_summary?: Record<string, unknown> | null;
duplicate?: ShippingDuplicateResult | null;
duplicate_resolution?: {
@@ -73,6 +73,9 @@ export interface ShippingNoticeCandidate {
validationStatus: string;
selected: boolean;
conflicts: Array<Record<string, unknown>>;
missingFields?: string[];
fieldConfidence?: Record<string, number | null | undefined>;
evidence?: Array<Record<string, unknown>>;
businessSummary: Record<string, unknown>;
duplicate?: ShippingDuplicateResult;
duplicateResolution?: ShippingDuplicateResolution;
@@ -2,8 +2,8 @@
/**
* features/workspace/views/ShippingNoticeView.vue
* 用途:货代发货任务只读工作台,提供任务筛选、详情查看与跳转 Chat 继续处理入口。
* 依赖:ShippingWorkflowStepper、ShippingMatchResultCard、shipping.api。
* 逻辑:先拉取任务列表与详情,再以只读方式展示步骤、匹配结果和事件记录;所有写操作回到 Chat 主路径完成。
* 依赖:ShippingWorkflowStepper、ShippingMatchResultCard、ShippingTaskParsedResultCard、shipping.api。
* 逻辑:先拉取任务列表与详情,再以只读方式展示步骤、匹配结果、解析行和事件记录;所有写操作回到 Chat 主路径完成。
*/
import { computed, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
@@ -11,6 +11,7 @@ import { useI18n } from 'vue-i18n';
import { ArrowLeft, Download, ExternalLink, RefreshCw } from 'lucide-vue-next';
import ShippingWorkflowStepper from '@/features/chat/components/ShippingWorkflowStepper.vue';
import ShippingMatchResultCard from '@/features/chat/components/messages/ShippingMatchResultCard.vue';
import ShippingTaskParsedResultCard from '@/features/chat/components/ShippingTaskParsedResultCard.vue';
import { formatLocalDateTime } from '@/shared/utils/dateTime';
import {
getWorkspaceShippingTask,
@@ -510,25 +511,20 @@ onMounted(async () => {
:action-busy="false"
/>
<div v-if="detail.lines?.length">
<h3 class="mb-2 text-sm font-semibold text-secondary">{{ $t('workspace.shippingNotice.lines') }}</h3>
<div class="overflow-x-auto rounded-xl border border-default">
<table class="min-w-full text-sm">
<thead class="bg-surface-soft text-left text-xs text-muted">
<tr>
<th class="px-3 py-2">{{ $t('workspace.shippingNotice.columns.sku') }}</th>
<th class="px-3 py-2">{{ $t('workspace.shippingNotice.qty') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(line, idx) in detail.lines" :key="idx" class="border-t border-default/60">
<td class="px-3 py-2 font-mono">{{ line.sku || '—' }}</td>
<td class="px-3 py-2">{{ line.qty ?? '—' }}</td>
</tr>
</tbody>
</table>
</div>
</div>
<ShippingTaskParsedResultCard
v-if="detail.lines?.length || detail.process_field_gate || detail.parse_validation || detail.source_candidate || detail.field_conflicts?.length"
class="mt-3"
:task-no="detail.task_no"
:po-number="detail.po_number"
:lines="detail.lines"
:parse-validation="detail.parse_validation || detail.step_payload?.parse_validation || null"
:process-field-gate="detail.process_field_gate || null"
:source-candidate="detail.source_candidate || null"
:field-conflicts="detail.field_conflicts || []"
:order-data-version="detail.order_data_version"
:default-expanded="true"
@refreshed="detail?.task_no && loadDetail(detail.task_no)"
/>
<div v-if="detail.events?.length">
<h3 class="mb-2 text-sm font-semibold text-secondary">{{ $t('workspace.shippingNotice.events') }}</h3>
+31
View File
@@ -107,6 +107,8 @@
"shippingCandidateQty": "Quantity",
"shippingCandidateReservation": "Reservation ID",
"shippingCandidateSourceType": "Source Type (routing hint)",
"shippingCandidateHubCode": "Hub Code",
"shippingCandidateMissingFields": "Missing fields: {fields}",
"shippingCandidateUom": "UOM",
"shippingCandidateAddLine": "Add order line",
"shippingCandidateUpdateDone": "Order candidate changes were saved.",
@@ -161,6 +163,35 @@
"empty": "(empty)",
"unrecognized": "(unrecognized)"
},
"shippingParsedResult": {
"title": "Parsed order result",
"statusBlocked": "Blocked",
"statusReady": "Ready",
"statusEmpty": "No order lines",
"impactHint": "Reservation ID drives inventory matching; missing or invalid values block inventory and fulfillment. Source Type / Hub Code are optional routing hints for inventory-source selection and do not block when absent.",
"missingFields": "Missing fields",
"sourceType": "Source Type",
"hubCode": "Hub Code",
"noLines": "This task has no persisted order lines yet.",
"evidenceTitle": "Field evidence",
"unknownField": "Unknown field",
"documentId": "Document #{id}",
"issueMissing": "Missing",
"issueInvalid": "Invalid format",
"issueConflict": "Source conflict",
"issueCorrected": "Auto-corrected",
"issueUnknown": "Needs attention"
},
"shippingFieldConflict": {
"title": "Field conflicts to review ({count})",
"hint": "Non-empty differing values are never auto-overwritten. Keep the current value or take the candidate; the task returns to parse review.",
"existing": "Current",
"incoming": "Incoming",
"keepExisting": "Keep current",
"takeIncoming": "Take incoming",
"resolveSuccess": "Conflict resolved. Please reconfirm the parse result.",
"resolveFailed": "Failed to resolve conflict. Refresh and try again."
},
"shippingNoticeUi": {
"rpaModeBrowser": "Real RPA",
"rpaModeMock": "Mock RPA",
+5
View File
@@ -87,6 +87,11 @@
"SHIPPING_CUSTOMER_CONFIRMATION_LEGACY_UNSUPPORTED": "Customer confirmation is not supported for this legacy task.",
"SHIPPING_CUSTOMER_INACTIVE": "The selected customer is inactive.",
"SHIPPING_CUSTOMER_NUMBERED_CASE_LOCKED": "A numbered business case cannot silently change customer.",
"SHIPPING_FIELD_CONFLICT_NOT_FOUND": "Order field conflict not found.",
"SHIPPING_FIELD_CONFLICT_ALREADY_RESOLVED": "This field conflict is already resolved.",
"SHIPPING_FIELD_CONFLICT_VERSION_MISMATCH": "Field conflict version changed. Refresh and try again.",
"SHIPPING_ORDER_DATA_VERSION_MISMATCH": "Order data version changed. Refresh and try again.",
"SHIPPING_INVALID_CONFLICT_RESOLUTION": "Invalid conflict resolution.",
"SHIPPING_CASE_NOT_FOUND": "Shipping case not found.",
"SHIPPING_BUSINESS_NUMBER_DAILY_LIMIT_REACHED": "The customer's two-digit daily sequence is exhausted (01-99).",
"SHIPPING_BUSINESS_NUMBER_CUSTOMER_REQUIRED": "Confirm the standard customer before assigning a business number.",
+31
View File
@@ -107,6 +107,8 @@
"shippingCandidateQty": "จำนวน",
"shippingCandidateReservation": "Reservation ID",
"shippingCandidateSourceType": "ประเภทแหล่งที่มา (ข้อมูลช่วยกำหนดเส้นทาง)",
"shippingCandidateHubCode": "Hub Code",
"shippingCandidateMissingFields": "ฟิลด์ที่ต้องเติม: {fields}",
"shippingCandidateUom": "หน่วย",
"shippingCandidateAddLine": "เพิ่มรายการคำสั่งซื้อ",
"shippingCandidateUpdateDone": "บันทึกการแก้ไขรายการคำสั่งซื้อแล้ว",
@@ -161,6 +163,35 @@
"empty": "(ว่าง)",
"unrecognized": "(ไม่รู้จัก)"
},
"shippingParsedResult": {
"title": "ผลลัพธ์การแยกคำสั่งซื้อ",
"statusBlocked": "ถูกบล็อก",
"statusReady": "พร้อมดำเนินการ",
"statusEmpty": "ยังไม่มีรายการคำสั่งซื้อ",
"impactHint": "Reservation ID ใช้จับคู่สต็อก หากขาดหรือไม่ถูกต้องจะบล็อกขั้นตอนสต็อกและการส่งมอบ; Source Type / Hub Code เป็นข้อมูลช่วยเลือกแหล่งสต็อกแบบเลือกได้ หากขาดจะไม่บล็อก",
"missingFields": "ฟิลด์ที่ต้องเติม",
"sourceType": "Source Type",
"hubCode": "Hub Code",
"noLines": "งานนี้ยังไม่มีรายการคำสั่งซื้อที่บันทึกไว้",
"evidenceTitle": "หลักฐานฟิลด์",
"unknownField": "ฟิลด์ไม่ทราบ",
"documentId": "เอกสาร #{id}",
"issueMissing": "ขาดหาย",
"issueInvalid": "รูปแบบไม่ถูกต้อง",
"issueConflict": "แหล่งข้อมูลขัดแย้ง",
"issueCorrected": "แก้ไขอัตโนมัติแล้ว",
"issueUnknown": "ต้องตรวจสอบ"
},
"shippingFieldConflict": {
"title": "ฟิลด์ขัดแย้งที่ต้องตรวจ ({count})",
"hint": "ค่าเดิมและค่าใหม่ที่ไม่ว่างและต่างกันจะไม่ถูกเขียนทับอัตโนมัติ เลือกรักษาค่าเดิมหรือใช้ค่าใหม่ แล้วระบบจะกลับไปยืนยันการแยกวิเคราะห์",
"existing": "ค่าปัจจุบัน",
"incoming": "ค่าใหม่",
"keepExisting": "เก็บค่าปัจจุบัน",
"takeIncoming": "ใช้ค่าใหม่",
"resolveSuccess": "แก้ความขัดแย้งแล้ว กรุณายืนยันผลแยกวิเคราะห์อีกครั้ง",
"resolveFailed": "แก้ความขัดแย้งไม่สำเร็จ กรุณารีเฟรชแล้วลองใหม่"
},
"shippingNoticeUi": {
"rpaModeBrowser": "RPA จริง",
"rpaModeMock": "Mock RPA",
+5
View File
@@ -87,6 +87,11 @@
"SHIPPING_CUSTOMER_CONFIRMATION_LEGACY_UNSUPPORTED": "งานเดิมนี้ยังไม่รองรับการยืนยันลูกค้า",
"SHIPPING_CUSTOMER_INACTIVE": "ลูกค้าที่เลือกถูกปิดใช้งาน",
"SHIPPING_CUSTOMER_NUMBERED_CASE_LOCKED": "รายการธุรกิจที่มีเลขแล้วไม่สามารถเปลี่ยนลูกค้าโดยเงียบได้",
"SHIPPING_FIELD_CONFLICT_NOT_FOUND": "ไม่พบความขัดแย้งของฟิลด์คำสั่งซื้อ",
"SHIPPING_FIELD_CONFLICT_ALREADY_RESOLVED": "ความขัดแย้งนี้ถูกแก้ไขแล้ว",
"SHIPPING_FIELD_CONFLICT_VERSION_MISMATCH": "เวอร์ชันความขัดแย้งเปลี่ยนแล้ว กรุณารีเฟรชแล้วลองใหม่",
"SHIPPING_ORDER_DATA_VERSION_MISMATCH": "เวอร์ชันข้อมูลคำสั่งซื้อเปลี่ยนแล้ว กรุณารีเฟรชแล้วลองใหม่",
"SHIPPING_INVALID_CONFLICT_RESOLUTION": "วิธีแก้ความขัดแย้งไม่ถูกต้อง",
"SHIPPING_CASE_NOT_FOUND": "ไม่พบรายการธุรกิจ",
"SHIPPING_BUSINESS_NUMBER_DAILY_LIMIT_REACHED": "ลำดับรายวันแบบสองหลักของลูกค้าถูกใช้ครบแล้ว (01-99)",
"SHIPPING_BUSINESS_NUMBER_CUSTOMER_REQUIRED": "โปรดยืนยันลูกค้ามาตรฐานก่อนกำหนดหมายเลขธุรกิจ",
+31
View File
@@ -107,6 +107,8 @@
"shippingCandidateQty": "数量",
"shippingCandidateReservation": "Reservation ID",
"shippingCandidateSourceType": "来源类型(路由线索)",
"shippingCandidateHubCode": "Hub Code",
"shippingCandidateMissingFields": "待补字段:{fields}",
"shippingCandidateUom": "单位",
"shippingCandidateAddLine": "新增订单行",
"shippingCandidateUpdateDone": "订单候选修订已保存。",
@@ -161,6 +163,35 @@
"empty": "(空)",
"unrecognized": "(未识别)"
},
"shippingParsedResult": {
"title": "订单解析结果",
"statusBlocked": "流转阻断",
"statusReady": "可继续",
"statusEmpty": "暂无订单行",
"impactHint": "Reservation ID 用于库存匹配,缺失或非法时会阻断进入库存与履约;Source Type / Hub Code 是可选路由线索,用于库存源选择,缺失不阻断。",
"missingFields": "待补字段",
"sourceType": "Source Type",
"hubCode": "Hub Code",
"noLines": "当前任务尚无持久订单行。",
"evidenceTitle": "字段证据",
"unknownField": "未知字段",
"documentId": "文档 #{id}",
"issueMissing": "缺失",
"issueInvalid": "格式非法",
"issueConflict": "来源冲突",
"issueCorrected": "已自动纠正",
"issueUnknown": "需关注"
},
"shippingFieldConflict": {
"title": "字段冲突待复核({count})",
"hint": "新旧值均非空且不一致时不会自动覆盖。请选择保留原值或采用新值;解决后将回到解析确认。",
"existing": "当前值",
"incoming": "候选值",
"keepExisting": "保留当前值",
"takeIncoming": "采用候选值",
"resolveSuccess": "冲突已解决,请重新确认解析结果",
"resolveFailed": "解决冲突失败,请刷新后重试"
},
"shippingNoticeUi": {
"rpaModeBrowser": "真实 RPA",
"rpaModeMock": "Mock RPA",
+5
View File
@@ -87,6 +87,11 @@
"SHIPPING_CUSTOMER_CONFIRMATION_LEGACY_UNSUPPORTED": "该历史任务暂不支持客户确认。",
"SHIPPING_CUSTOMER_INACTIVE": "所选客户已停用。",
"SHIPPING_CUSTOMER_NUMBERED_CASE_LOCKED": "已编号业务单不能静默更换客户。",
"SHIPPING_FIELD_CONFLICT_NOT_FOUND": "订单字段冲突不存在。",
"SHIPPING_FIELD_CONFLICT_ALREADY_RESOLVED": "该字段冲突已解决。",
"SHIPPING_FIELD_CONFLICT_VERSION_MISMATCH": "字段冲突版本已变更,请刷新后重试。",
"SHIPPING_ORDER_DATA_VERSION_MISMATCH": "订单数据版本已变更,请刷新后重试。",
"SHIPPING_INVALID_CONFLICT_RESOLUTION": "冲突解决方式无效。",
"SHIPPING_CASE_NOT_FOUND": "业务单不存在。",
"SHIPPING_BUSINESS_NUMBER_DAILY_LIMIT_REACHED": "该客户当天两位业务流水已用完(01-99)。",
"SHIPPING_BUSINESS_NUMBER_CUSTOMER_REQUIRED": "请先确认标准客户再生成业务编号。",
+31
View File
@@ -107,6 +107,8 @@
"shippingCandidateQty": "數量",
"shippingCandidateReservation": "Reservation ID",
"shippingCandidateSourceType": "來源類型(路由線索)",
"shippingCandidateHubCode": "Hub Code",
"shippingCandidateMissingFields": "待補欄位:{fields}",
"shippingCandidateUom": "單位",
"shippingCandidateAddLine": "新增訂單行",
"shippingCandidateUpdateDone": "訂單候選修訂已儲存。",
@@ -161,6 +163,35 @@
"empty": "(空)",
"unrecognized": "(未辨識)"
},
"shippingParsedResult": {
"title": "訂單解析結果",
"statusBlocked": "流轉阻斷",
"statusReady": "可繼續",
"statusEmpty": "暫無訂單行",
"impactHint": "Reservation ID 用於庫存匹配,缺失或非法時會阻斷進入庫存與履約;Source Type / Hub Code 是可選路由線索,用於庫存源選擇,缺失不阻斷。",
"missingFields": "待補欄位",
"sourceType": "Source Type",
"hubCode": "Hub Code",
"noLines": "目前任務尚無持久訂單行。",
"evidenceTitle": "欄位證據",
"unknownField": "未知欄位",
"documentId": "文件 #{id}",
"issueMissing": "缺失",
"issueInvalid": "格式非法",
"issueConflict": "來源衝突",
"issueCorrected": "已自動糾正",
"issueUnknown": "需關注"
},
"shippingFieldConflict": {
"title": "欄位衝突待覆核({count})",
"hint": "新舊值均非空且不一致時不會自動覆蓋。請選擇保留原值或採用新值;解決後將回到解析確認。",
"existing": "目前值",
"incoming": "候選值",
"keepExisting": "保留目前值",
"takeIncoming": "採用候選值",
"resolveSuccess": "衝突已解決,請重新確認解析結果",
"resolveFailed": "解決衝突失敗,請重新整理後再試"
},
"shippingNoticeUi": {
"rpaModeBrowser": "真實 RPA",
"rpaModeMock": "Mock RPA",
+5
View File
@@ -87,6 +87,11 @@
"SHIPPING_CUSTOMER_CONFIRMATION_LEGACY_UNSUPPORTED": "該歷史任務暫不支援客戶確認。",
"SHIPPING_CUSTOMER_INACTIVE": "所選客戶已停用。",
"SHIPPING_CUSTOMER_NUMBERED_CASE_LOCKED": "已編號業務單不能靜默更換客戶。",
"SHIPPING_FIELD_CONFLICT_NOT_FOUND": "訂單欄位衝突不存在。",
"SHIPPING_FIELD_CONFLICT_ALREADY_RESOLVED": "該欄位衝突已解決。",
"SHIPPING_FIELD_CONFLICT_VERSION_MISMATCH": "欄位衝突版本已變更,請重新整理後再試。",
"SHIPPING_ORDER_DATA_VERSION_MISMATCH": "訂單資料版本已變更,請重新整理後再試。",
"SHIPPING_INVALID_CONFLICT_RESOLUTION": "衝突解決方式無效。",
"SHIPPING_CASE_NOT_FOUND": "業務單不存在。",
"SHIPPING_BUSINESS_NUMBER_DAILY_LIMIT_REACHED": "該客戶當天兩位業務流水已用完(01-99)。",
"SHIPPING_BUSINESS_NUMBER_CUSTOMER_REQUIRED": "請先確認標準客戶再產生業務編號。",