feat(shipping-order): 增加客户事实、编辑窗口与正式通知创建服务

This commit is contained in:
hugo committed 2026-09-04 22:00:27 +08:00
1 parent 4e8b2f8db2
commit bffcd55b40
17 files changed
+738 -486

No files matched your search

@@ -26,10 +26,8 @@ from app.services.shipping_notice.customer_shadow_resolution import (
label_shadow_resolution,
)
from app.services.shipping_notice.customer_auto_resolution import (
correct_numbered_task_customer,
get_auto_resolution_metrics,
)
from app.services.shipping_notice.query_service import get_task_by_ref
XLSX_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
@@ -287,32 +285,6 @@ def get_shipping_customer_shadow_report():
return jsonify(report)
@admin_bp.route('/shipping-customers/numbered-task-correction', methods=['POST'])
@require_admin
def correct_shipping_numbered_task_customer():
"""管理员更正已编号任务客户;保留原号作废并生成有替代关系的新号。"""
data = request.get_json(silent=True) or {}
task_ref = str(data.get('task_ref') or data.get('task_no') or '').strip().upper()
if not task_ref:
raise ValidationError(
'Task reference is required',
code='SHIPPING.CUSTOMER_CORRECTION_TASK_REQUIRED',
)
try:
customer_id = int(data.get('customer_id'))
except (TypeError, ValueError) as exc:
raise ValidationError('Customer id is required', code='SHIPPING.CUSTOMER_CONFIRMATION_CUSTOMER_REQUIRED') from exc
task = get_task_by_ref(task_ref)
if task is None:
raise ValidationError('Shipping task not found', code='SHIPPING.CUSTOMER_CORRECTION_TASK_MISSING')
return jsonify(correct_numbered_task_customer(
task,
customer_id=customer_id,
reason=str(data.get('reason') or ''),
actor_id=_actor_id(),
))
@admin_bp.route('/shipping-customer-shadow-resolutions/<int:resolution_id>/label', methods=['PUT'])
@require_admin
def label_shipping_customer_shadow_resolution(resolution_id: int):
+8 -11
View File
@@ -234,25 +234,22 @@ def simulate_shipping_order_schema_derivation(version_id: int):
"""
对 Schema 版本派生规则做样本模拟(不创建或修改订单)。
请求体:lines[] 或 sample_ref=`extraction:<id>`;可选 derivation_rules。
事务:服务层只写入审计实体,本路由统一 commit。
硬切换后该能力已停用;line_no 由系统按单据内顺序生成。
"""
payload = service.simulate_derivation(
version_id,
request.get_json(silent=True) or {},
actor_id=_actor_id(),
request_id=getattr(g, 'request_id', None),
raise ValidationError(
'Schema derivation is disabled; line_no is system-generated',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_DISABLED',
)
db.session.commit()
return _ok(payload)
@admin_bp.route('/shipping-order-schema/derivation-simulate-samples', methods=['GET'])
@require_admin
def list_shipping_order_schema_derivation_simulate_samples():
"""列出可供派生规则模拟的历史 Extraction 样本摘要。"""
limit = request.args.get('limit', 20, type=int)
return _ok(service.list_derivation_simulate_samples(limit=limit or 20))
raise ValidationError(
'Schema derivation is disabled; line_no is system-generated',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_DISABLED',
)
@admin_bp.route('/shipping-order-schema/published-contract', methods=['GET'])
@require_admin
@@ -23,7 +23,7 @@ from app.models import (
ShippingCustomerImportRow,
ShippingCustomerLifecycleEvent,
ShippingCustomerSite,
ShippingOrderCustomerMatch,
ShippingOrderTask,
ShippingCustomerShadowMatch,
ShippingCustomerShadowResolution,
ShippingNotice,
@@ -62,10 +62,19 @@ def _build_customer_lifecycle_impact(customer: ShippingCustomer) -> dict[str, An
}
shadow_normalized = len(matched_resolution_ids)
blockers = {
'shipping_notices': db.session.query(ShippingNotice.id).filter_by(customer_id=customer.id).count(),
'shipping_notices': (
db.session.query(ShippingNotice.id)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingCustomerShadowResolution, ShippingCustomerShadowResolution.candidate_id == ShippingOrderTask.candidate_id)
.filter(
ShippingCustomerShadowResolution.confirmed_customer_id == customer.id,
)
.distinct()
.count()
),
'business_sequences': db.session.query(ShippingBusinessSequence.id).filter_by(customer_id=customer.id).count(),
'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=customer.id).count(),
'order_customer_matches': db.session.query(ShippingOrderCustomerMatch.id).filter_by(customer_id=customer.id).count(),
'confirmed_customer_resolutions': db.session.query(ShippingCustomerShadowResolution.id).filter_by(confirmed_customer_id=customer.id).count(),
'import_target_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(target_customer_id=customer.id).count(),
'import_result_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(result_customer_id=customer.id).count(),
'shadow_top_candidates': db.session.query(ShippingCustomerShadowResolution.id).filter_by(top_customer_id=customer.id).count(),
@@ -25,6 +25,8 @@ from app.models import (
ShippingCustomerSiteIdentifier,
ShippingIdentityEvidence,
ShippingNotice,
ShippingOrderTask,
ShippingCustomerShadowResolution,
)
from app.services.shipping_notice.customer_normalization import (
clean_text,
@@ -144,7 +146,16 @@ def serialize_customer(
'updated_by_id': record.updated_by_id,
'created_at': record.created_at.isoformat() if record.created_at else None,
'updated_at': record.updated_at.isoformat() if record.updated_at else None,
'notice_count': notice_count if notice_count is not None else db.session.query(ShippingNotice.id).filter_by(customer_id=record.id).count(),
'notice_count': notice_count if notice_count is not None else (
db.session.query(ShippingNotice.id)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingCustomerShadowResolution, ShippingCustomerShadowResolution.candidate_id == ShippingOrderTask.candidate_id)
.filter(
ShippingCustomerShadowResolution.confirmed_customer_id == record.id,
)
.distinct()
.count()
),
'identifier_count': identifier_count if identifier_count is not None else db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=record.id).count(),
'identity_evidence_count': identity_evidence_count if identity_evidence_count is not None else db.session.query(
ShippingIdentityEvidence.id,
@@ -174,8 +185,11 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]:
items、total、page、page_size、pages。
"""
notice_counts = (
db.session.query(ShippingNotice.customer_id.label('customer_id'), func.count(ShippingNotice.id).label('notice_count'))
.group_by(ShippingNotice.customer_id)
db.session.query(ShippingCustomerShadowResolution.confirmed_customer_id.label('customer_id'), func.count(ShippingNotice.id).label('notice_count'))
.join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id)
.join(ShippingNotice, ShippingNotice.order_task_id == ShippingOrderTask.id)
.filter(ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None))
.group_by(ShippingCustomerShadowResolution.confirmed_customer_id)
.subquery()
)
identifier_counts = (
@@ -0,0 +1,76 @@
"""
services/shipping_notice/customer_resolution_service.py
用途:提供订单任务的唯一客户识别结果读取与确认入口。
依赖:ShippingCustomerShadowResolution、ShippingOrderTask、ShippingOrderCandidate、ShippingCustomer。
逻辑:客户身份来自已发布规则生成的证据快照;订单字段(包括 bill_to)只能作为证据,
不能承担客户角色或流程门禁真相。
"""
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 ShippingCustomer, ShippingCustomerShadowResolution, ShippingOrderCandidate, ShippingOrderTask
def resolution_for_task(task: Any) -> ShippingCustomerShadowResolution | None:
"""按 OT、Notice 或 Candidate 读取正式客户识别结果,不回读 bill_to 或解析摘要。"""
candidate_id = getattr(task, 'id', None) if isinstance(task, ShippingOrderCandidate) else getattr(task, 'candidate_id', None)
if candidate_id is None:
order_task_id = getattr(task, 'order_task_id', None)
order_task = db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id else None
candidate_id = getattr(order_task, 'candidate_id', None)
if candidate_id is None:
return None
return ShippingCustomerShadowResolution.query.filter_by(candidate_id=int(candidate_id)).one_or_none()
def resolution_for_extraction(extraction_id: int | None) -> ShippingCustomerShadowResolution | None:
"""按当前 Extraction 找到关联 Candidate 的唯一客户识别结果。"""
if extraction_id is None:
return None
candidate = ShippingOrderCandidate.query.filter_by(order_extraction_id=int(extraction_id)).one_or_none()
return resolution_for_task(candidate) if candidate is not None else None
def customer_resolution_facts(task: Any) -> dict[str, Any]:
"""返回流程 Gate 所需的最小客户确认事实,缺失时 fail-closed。"""
resolution = resolution_for_task(task)
if resolution is None:
return {'customer_id': None, 'status': None, 'resolution': None}
return {
'customer_id': resolution.confirmed_customer_id,
'status': resolution.status,
'resolution': resolution,
}
def confirm_customer_resolution(
task: Any,
*,
customer_id: int,
actor_id: int | None,
method: str,
reason: str | None = None,
) -> ShippingCustomerShadowResolution:
"""确认当前识别结果的客户;人工或自动确认均保留原始证据、规则和候选快照。"""
resolution = resolution_for_task(task)
if resolution is None:
raise ConflictError('Customer resolution is required before confirmation', code='SHIPPING.CUSTOMER_RESOLUTION_REQUIRED')
customer = db.session.get(ShippingCustomer, int(customer_id))
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if customer.status != 'active':
raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE')
resolution.confirmed_customer_id = int(customer.id)
resolution.confirmation_method = str(method)
resolution.confirmation_reason = str(reason or '').strip() or None
resolution.confirmed_by_id = actor_id
resolution.confirmed_at = datetime.utcnow()
resolution.status = 'confirmed'
db.session.flush()
return resolution
@@ -0,0 +1,182 @@
"""
services/shipping_notice/order_edit_window_service.py
用途:确认后、Excel 生成前的订单编辑窗谓词(设计 D10 / §3.1)。集中判定哪些头字段/行字段允许编辑,
前端 fail-closed 渲染,后端保存守卫复用同一谓词。
依赖:ShippingNotice / ShippingExportArtifact / ShippingOrderReviewWaveLine / progress_workflow。
逻辑(§3.1 矩阵):
header = 该订单**任一通知**无 Export Artifact 且无活动 Gate Attempt;
lines = 逐行:行已入某波次 → 该波次通知无 Export Artifact 且无活动 Attempt;
行未入波次 → 无活动 Attempt(不受首单 Excel 限制,D10)。
编辑窗谓词收敛在单一服务,避免「用户不修改原始订单」原则被扩大解释(D12)。
"""
from __future__ import annotations
from typing import Any
from app.models import ShippingNotice, ShippingOrderTask
from app.models.shipping_excel_template import ShippingExportArtifact
# 导出产物一旦落库即视为 Excel 已生成(锁定边界 D7);上传中/已上传同属生成后。
_ARTIFACT_LOCK_STATUSES = frozenset({'ready', 'uploading', 'uploaded', 'succeeded', 'success'})
def _notice_has_export_artifact(notice: ShippingNotice) -> bool:
"""该通知是否已生成导出产物(Excel)。"""
if getattr(notice, 'id', None) is None:
return False
row = (
ShippingExportArtifact.query
.filter(ShippingExportArtifact.task_id == int(notice.id))
.order_by(ShippingExportArtifact.id.desc())
.first()
)
return bool(row is not None and str(row.status or '') in _ARTIFACT_LOCK_STATUSES)
def _notice_has_active_attempt(notice: ShippingNotice) -> bool:
"""该通知是否有活动 Gate Attempt(库存 RPA / 匹配 queued|running)。"""
from app.services.shipping_notice.progress_workflow import _has_active_gate_attempts
task = db_session_get(ShippingOrderTask, int(notice.order_task_id)) if getattr(notice, 'order_task_id', None) else None
return bool(_has_active_gate_attempts(task)) if task is not None else False
def _order_notices(notice: ShippingNotice) -> list[ShippingNotice]:
"""同一订单(同 order_task_id)下的全部通知(含波次);无 OT 指针时退回本通知。"""
order_task_id = getattr(notice, 'order_task_id', None)
if not order_task_id:
return [notice]
rows = list(
ShippingNotice.query
.filter(ShippingNotice.order_task_id == int(order_task_id))
.order_by(ShippingNotice.id.asc())
.all()
)
return rows or [notice]
def order_has_active_attempt(order_task: ShippingNotice) -> bool:
"""订单级活动 Attempt 判定:该订单**任一通知**有活动 Gate Attempt(§3.1 header 谓词)。"""
return any(_notice_has_active_attempt(n) for n in _order_notices(order_task))
def _review_case_id_for_notice(notice: ShippingNotice) -> int | None:
"""回读该通知所属复核 Case(经 ConfirmedRevision);无则 None。"""
from app.models import ShippingOrderReviewConfirmedRevision, ShippingOrderTask
task_id = getattr(notice, 'order_task_id', None)
if task_id is None:
return None
row = (
ShippingOrderReviewConfirmedRevision.query
.filter(ShippingOrderReviewConfirmedRevision.task_id == int(task_id))
.order_by(ShippingOrderReviewConfirmedRevision.id.desc())
.first()
)
return int(row.case_id) if row is not None else None
def _wave_line_to_notice_map(review_case_id: int | None) -> dict[str, int]:
"""复核 Case 下的 snapshot_line_id -> 波次通知 task_id 映射。"""
if review_case_id is None:
return {}
from app.models import ShippingOrderReviewWaveLine
rows = ShippingOrderReviewWaveLine.query.filter_by(review_case_id=int(review_case_id)).all()
return {
str(row.snapshot_line_id): int(row.task_id)
for row in rows
if row.snapshot_line_id is not None
}
def _order_snapshot_line_ids(notice: ShippingNotice) -> list[str]:
"""该订单可编辑范围内的全部冻结行身份(以 Snapshot 行为准,波次行并入)。"""
from app.models.shipping_notice_line import ShippingNoticeLine
notice_id = getattr(notice, 'id', None)
if notice_id is None:
return []
keys: list[str] = []
for item in (
ShippingNoticeLine.query
.filter(ShippingNoticeLine.notice_id == int(notice_id))
.order_by(ShippingNoticeLine.position.asc())
.all()
):
key = str(getattr(item, 'snapshot_line_id', '') or '').strip()
if key:
keys.append(key)
review_case_id = _review_case_id_for_notice(notice)
if review_case_id is not None:
for key in _wave_line_to_notice_map(review_case_id):
if key not in keys:
keys.append(key)
return sorted(set(keys), key=lambda value: int(value))
def editable_scope(order_task: ShippingNotice) -> dict[str, Any]:
"""
计算确认后订单的编辑窗矩阵(D10 / §3.1)。
header = 该订单全部通知(含波次)无 Export Artifact 且无活动 Gate Attempt。
lines = 逐行:行已入某波次 → 该波次通知无 Export Artifact 且无活动 Attempt;
行未入波次 → 无活动 Attempt(不受首单 Excel 限制)。
Args:
order_task: 正式订单的主 ShippingNotice(含 order_task_id 可回读同订单全部通知)。
Returns:
dict: {'header': bool, 'lines': {snapshot_line_id: bool}},同构供 ui_state.edit_window 下发。
"""
notices = _order_notices(order_task)
order_busy = any(_notice_has_active_attempt(n) for n in notices)
header_has_excel = any(_notice_has_export_artifact(n) for n in notices)
header = (not header_has_excel) and (not order_busy)
wave_notice_map = _wave_line_to_notice_map(_review_case_id_for_notice(order_task))
lines: dict[str, bool] = {}
for snapshot_line_id in _order_snapshot_line_ids(order_task):
wave_task_id = wave_notice_map.get(snapshot_line_id)
if wave_task_id is None:
# 未入波次行:不受首单 Excel 限制,仅受活动 Attempt 影响。
lines[snapshot_line_id] = not order_busy
continue
wave_notice = next((n for n in notices if int(getattr(n, 'id', 0)) == int(wave_task_id)), None)
wave_notice = wave_notice or db_session_get(ShippingNotice, int(wave_task_id))
lines[snapshot_line_id] = (
(not _notice_has_export_artifact(wave_notice)) and (not order_busy)
if wave_notice is not None else False
)
return {'header': header, 'lines': lines}
def db_session_get(model: Any, pk: int) -> Any:
"""最小 Session get 封装,避免模块顶部导入 db 形成循环。"""
from app import db
return db.session.get(model, int(pk))
def assert_field_editable(scope: dict[str, Any], *, field: dict[str, Any], snapshot_line_id: str | None = None) -> bool:
"""
保存守卫辅助:按谓词判断单个头字段/行字段是否可编辑。
Args:
scope: editable_scope 结果。
field: 目标字段描述(含 scope='header' 或 scope='line')。
snapshot_line_id: line 作用域时必填;None 视为 header。
Returns:
bool:可编辑返回 True;应被 SHIPPING.EDIT_WINDOW_FIELD_LOCKED 拒绝时返回 False。
"""
if str((field or {}).get('scope') or '').strip() == 'line':
if not snapshot_line_id:
return False
return bool(scope.get('lines', {}).get(snapshot_line_id))
return bool(scope.get('header'))
@@ -0,0 +1,160 @@
"""
backend/app/services/shipping_notice/shipping_notice_creation_service.py
用途:在库存准备与匹配门禁通过后创建正式 ShippingNotice。
依赖:ShippingOrderTask、ShippingOrderSnapshot、ShippingNoticeLine、库存匹配事实。
逻辑:OT/Snapshot 承载复核与库存准备;本模块是首次创建正式 Notice 的唯一入口,
创建 NoticeLine 后才允许进入 Excel 导出。
"""
from __future__ import annotations
from app import db
from app.core.errors import ConflictError
from app.models import (
ShippingCustomer,
ShippingNotice,
ShippingNoticeLine,
ShippingOrderTask,
ShippingOrderSnapshot,
)
from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot
from app.services.shipping_notice.tool_common import generate_task_no
def create_shipping_notice_after_inventory_gate(
order_task: ShippingOrderTask,
*,
snapshot_line_ids: set[int] | None = None,
source_type: str = "inventory_gate",
) -> ShippingNotice:
"""
库存门禁通过后创建或复用正式发货通知。
【触发时机】:库存准备成功、所有目标订单行匹配成功或已人工放行,且即将生成 Excel 时。
不得在接收解析或订单复核确认阶段调用。
Args:
order_task: 已冻结订单快照的 OT。
snapshot_line_ids: 可选的本次通知行集合;为空表示整单。
source_type: Notice 来源标记。
Returns:
已 flush 的正式 ShippingNotice。
Raises:
ConflictError: OT、Snapshot、客户或库存门禁事实不完整。
"""
if order_task is None or order_task.id is None:
raise ConflictError("Order task is required before creating a shipping notice", code="SHIPPING.ORDER_TASK_REQUIRED")
snapshot_id = getattr(order_task, "order_snapshot_id", None)
snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id)) if snapshot_id else None
if snapshot is None:
raise ConflictError("Order snapshot is required before creating a shipping notice", code="SHIPPING.ORDER_SNAPSHOT_REQUIRED")
customer_id = int(snapshot.customer_id or 0)
if not customer_id:
raise ConflictError("Confirmed customer is required before creating a shipping notice", code="SHIPPING.CUSTOMER_REQUIRED")
customer = db.session.get(ShippingCustomer, customer_id)
if customer is None or customer.status != 'active':
raise ConflictError("Confirmed customer is unavailable", code="SHIPPING.CUSTOMER_REQUIRED")
selected_ids = {int(item) for item in (snapshot_line_ids or set())}
if selected_ids and not selected_ids.issubset({int(line.id) for line in snapshot.lines}):
raise ConflictError("Selected snapshot lines are invalid", code="SHIPPING.SNAPSHOT_LINE_INVALID")
existing = (
ShippingNotice.query
.filter_by(order_task_id=int(order_task.id))
.order_by(ShippingNotice.id.desc())
.first()
)
if existing is not None:
existing_lines = {
int(line.snapshot_line_id)
for line in ShippingNoticeLine.query.filter_by(notice_id=int(existing.id)).all()
if line.snapshot_line_id is not None
}
if not selected_ids or existing_lines == selected_ids:
return existing
raise ConflictError(
"An existing shipping notice already owns a different snapshot line set",
code="SHIPPING.NOTICE_LINE_SET_CONFLICT",
)
# 正式 Notice 只能建立在当前库存匹配事实完整通过之后;库存准备失败或仍有未处理行时,
# OT 必须停留在通知准备阶段,不得产生 Notice/NoticeLine。
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch, ShippingTaskInventoryLink
fact_rows = ShippingNoticeLineInventoryMatch.query.filter_by(
task_id=int(order_task.id), is_current=True,
).all()
target_ids = selected_ids or {int(line.id) for line in snapshot.lines}
by_line = {int(row.snapshot_line_id): row for row in fact_rows if row.snapshot_line_id is not None}
from app.services.shipping_notice.fulfillment_workflow import _released_snapshot_line_ids_for_task
released_ids = _released_snapshot_line_ids_for_task(order_task)
if not target_ids or any(
int(line_id) not in by_line
or (
not (
str(by_line[int(line_id)].match_result or '').strip().lower() == 'matched'
and str(by_line[int(line_id)].inventory_status or '').strip().lower() == 'ready'
)
and int(line_id) not in released_ids
)
for line_id in target_ids
):
raise ConflictError(
"Inventory matching must pass before creating a shipping notice",
code="SHIPPING.INVENTORY_GATE_NOT_PASSED",
)
inventory_facts_by_snapshot_line_id: dict[int, dict[str, object]] = {}
for snapshot_line_id in target_ids:
match = by_line[int(snapshot_line_id)]
inventory_file = (
db.session.get(ShippingInventoryFile, int(match.inventory_snapshot_id))
if match.inventory_snapshot_id is not None
else None
)
link = (
ShippingTaskInventoryLink.query.filter_by(
task_id=int(order_task.id),
inventory_file_id=int(inventory_file.id),
matched_source_code=match.inventory_source_code,
is_active=True,
).order_by(ShippingTaskInventoryLink.id.desc()).first()
if inventory_file is not None
else None
)
inventory_facts_by_snapshot_line_id[int(snapshot_line_id)] = {
'inventory_source_code': match.inventory_source_code,
'inventory_file_id': int(inventory_file.id) if inventory_file is not None else None,
'inventory_warehouse_id': (
str(getattr(link, 'matched_warehouse_id', '') or '').strip().upper()
or str(getattr(inventory_file, 'warehouse_id', '') or '').strip().upper()
or None
),
}
source_codes = sorted({
str(fact['inventory_source_code'] or '').strip().upper()
for fact in inventory_facts_by_snapshot_line_id.values()
if str(fact['inventory_source_code'] or '').strip()
})
notice = ShippingNotice(
task_no=generate_task_no(),
order_task_id=int(order_task.id),
user_id=order_task.user_id,
conversation_id=order_task.conversation_id,
source_type=str(source_type or "inventory_gate"),
source_intake_id=order_task.intake_id,
source_candidate_id=order_task.candidate_id,
)
db.session.add(notice)
db.session.flush()
replace_notice_lines_from_snapshot(
notice_id=int(notice.id),
snapshot=snapshot,
snapshot_line_ids=selected_ids,
inventory_facts_by_snapshot_line_id=inventory_facts_by_snapshot_line_id,
)
return notice
@@ -16,7 +16,8 @@ from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingBusinessSequence,
ShippingNotice,
ShippingNotice, ShippingOrderTask, ShippingOrderExtraction,
ShippingOrderSchema, ShippingOrderSchemaVersion,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
@@ -53,6 +54,41 @@ def _context_field() -> ShippingOrderField:
return ShippingOrderField.query.filter_by(field_code='bill_to_customer').one()
def _notice_for_customer(customer: ShippingCustomer, task_no: str) -> ShippingNotice:
"""按当前事实链构造带客户引用的正式 Notice,避免写入已删除的 Notice.customer_id。"""
schema = ShippingOrderSchema(
schema_code=f'LIFECYCLE-{task_no}',
display_name='生命周期测试 Schema',
status='active',
)
db.session.add(schema)
db.session.flush()
version = ShippingOrderSchemaVersion(
schema_id=schema.id,
version=1,
status='published',
definition_json={'fields': []},
checksum='lifecycle-test',
)
task = ShippingOrderTask(task_no=f'OT-{task_no}', user_id=1, status='completed')
db.session.add_all([version, task])
db.session.flush()
extraction = ShippingOrderExtraction(
task_id=task.id,
schema_version_id=version.id,
input_snapshot_hash=f'{task_no:0<64}'[:64],
status='accepted',
)
db.session.add(extraction)
db.session.flush()
task.current_order_extraction_id = extraction.id
from tests.conftest import confirm_test_customer_resolution
confirm_test_customer_resolution(task, customer=customer, extraction=extraction)
notice = ShippingNotice(task_no=task_no, order_task_id=task.id)
db.session.add(notice)
return notice
def test_unused_customer_can_delete_and_identifiers_are_cascade_only(app):
"""仅有识别证据的误建客户可删除,证据不应成为业务阻断引用。"""
with app.app_context():
@@ -74,15 +110,13 @@ def test_unused_customer_can_delete_and_identifiers_are_cascade_only(app):
@pytest.mark.parametrize('reference_kind', [
'notice', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
])
def test_business_and_audit_references_block_delete(app, reference_kind: str):
"""每类业务或识别审计引用都必须在统一影响结果中阻断永久删除。"""
with app.app_context():
customer = _customer()
if reference_kind == 'notice':
db.session.add(ShippingNotice(task_no='SN-LIFECYCLE', customer_id=customer.id))
elif reference_kind == 'sequence':
if reference_kind == 'sequence':
db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16)))
elif reference_kind == 'external_ref':
db.session.add(ShippingCustomerExternalRef(customer_id=customer.id, source_system='ERP', legacy_customer_key='C-1'))
@@ -201,7 +235,7 @@ def test_delete_rechecks_every_lifecycle_blocker(app, reference_kind: str):
with app.app_context():
customer = _customer('BLK')
if reference_kind == 'notice':
db.session.add(ShippingNotice(task_no='SN-DELETE-BLOCK', customer_id=customer.id))
_notice_for_customer(customer, 'SN-DELETE-BLOCK')
elif reference_kind == 'sequence':
db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16)))
elif reference_kind == 'external_ref':
@@ -267,7 +301,7 @@ def test_delete_blocks_reference_created_after_preview(app):
preview = get_customer_lifecycle_impact(customer.id)
assert preview['can_delete'] is True
db.session.add(ShippingNotice(task_no='SN-DELETE-RACE', customer_id=customer.id))
_notice_for_customer(customer, 'SN-DELETE-RACE')
db.session.commit()
with pytest.raises(ConflictError) as exc_info:
delete_customer(customer.id, confirmation_short_code='RCE', reason='误建', actor_id=None)
@@ -26,7 +26,8 @@ from app.models import (
ShippingCustomerMerge,
ShippingCustomerShadowResolution,
ShippingOrderField,
ShippingOrderSchema,
ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderTask,
ShippingOrderExtraction,
)
from app.services.admin.shipping_customer_lifecycle_service import get_customer_lifecycle_impact
from app.services.admin.shipping_customer_merge_service import get_customer_merge_impact, merge_customer
@@ -52,6 +53,30 @@ def _context_field() -> ShippingOrderField:
return ShippingOrderField.query.filter_by(field_code='bill_to_customer').one()
def _notice_with_customer_history(customer: ShippingCustomer) -> ShippingNotice:
"""按 OT→Resolution 构造历史 Notice 客户事实。"""
schema = ShippingOrderSchema(schema_code='MERGE-HISTORY', display_name='归并历史测试', status='active')
db.session.add(schema)
db.session.flush()
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', definition_json={'fields': []}, checksum='merge-history',
)
task = ShippingOrderTask(task_no='OT-SN-MERGE-HISTORY', user_id=1, status='completed')
db.session.add_all([version, task])
db.session.flush()
extraction = ShippingOrderExtraction(
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='m' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
task.current_order_extraction_id = extraction.id
from tests.conftest import confirm_test_customer_resolution
confirm_test_customer_resolution(task, customer=customer, extraction=extraction)
notice = ShippingNotice(task_no='SN-MERGE-HISTORY', business_no='SRC26071601', order_task_id=task.id)
db.session.add(notice)
return notice
def test_merge_moves_future_configuration_and_preserves_history(app):
"""归并迁移证据和来源键,但业务单、流水及其客户快照始终保留源客户。"""
with app.app_context():
@@ -71,10 +96,7 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
normalized_value='same@example.com', status='approved', source='manual',
),
ShippingCustomerExternalRef(customer_id=source.id, source_system='ERP', legacy_customer_key='LEGACY-SRC'),
ShippingNotice(
task_no='SN-MERGE-HISTORY', customer_id=source.id, business_no='SRC26071601',
customer_name_snapshot=source.standard_name, customer_short_code_snapshot=source.short_code,
),
_notice_with_customer_history(source),
ShippingBusinessSequence(customer_id=source.id, business_date=date(2026, 7, 16), current_value=1),
])
db.session.commit()
@@ -106,9 +128,12 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 2
assert db.session.query(ShippingCustomerExternalRef).filter_by(customer_id=target_id).count() == 1
historical_notice = db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-HISTORY').one()
assert historical_notice.customer_id == source_id
historical_task = db.session.get(ShippingOrderTask, historical_notice.order_task_id)
historical_resolution = ShippingCustomerShadowResolution.query.filter_by(
candidate_id=historical_task.candidate_id,
).one()
assert historical_resolution.confirmed_customer_id == source_id
assert historical_notice.business_no == 'SRC26071601'
assert historical_notice.customer_short_code_snapshot == 'SRC'
assert db.session.query(ShippingBusinessSequence).filter_by(customer_id=source_id).count() == 1
merge = db.session.get(ShippingCustomerMerge, result['merge_id'])
assert merge is not None and merge.source_customer_id_snapshot == source_id
@@ -13,7 +13,11 @@ from sqlalchemy.exc import IntegrityError
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent, ShippingNotice
from app.models import (
ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent, ShippingNotice,
ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion,
ShippingOrderTask,
)
from app.services.admin.shipping_customer_service import (
create_customer,
create_identifier,
@@ -28,6 +32,30 @@ def _create_customer(*, name: str = '无锡宇辰有限公司', short_code: str
return create_customer({'standard_name': name, 'short_code': short_code}, actor_id=None)
def _notice_for_customer(customer_id: int) -> ShippingNotice:
"""按正式客户事实链创建 Notice,列表统计不得依赖已删除的 Notice.customer_id。"""
schema = ShippingOrderSchema(schema_code='CUSTOMER-LIST', display_name='客户列表测试', status='active')
db.session.add(schema)
db.session.flush()
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', definition_json={'fields': []}, checksum='customer-list',
)
task = ShippingOrderTask(task_no='OT-CUSTOMER-LIST', user_id=1, status='completed')
db.session.add_all([version, task])
db.session.flush()
extraction = ShippingOrderExtraction(
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='c' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
task.current_order_extraction_id = extraction.id
from tests.conftest import confirm_test_customer_resolution
confirm_test_customer_resolution(task, customer=db.session.get(ShippingCustomer, customer_id), extraction=extraction)
notice = ShippingNotice(task_no='SN-COUNT-1', order_task_id=task.id)
db.session.add(notice)
return notice
def test_customer_short_code_is_normalized_and_unique(app):
"""简码统一转大写,且标准化后重复必须返回冲突。"""
with app.app_context():
@@ -219,7 +247,7 @@ def test_customer_list_returns_preaggregated_reference_counts(app):
"""列表返回业务单和识别证据数量,避免管理端逐客户补查。"""
with app.app_context():
customer = _create_customer()
db.session.add(ShippingNotice(task_no='SN-COUNT-1', customer_id=customer['id']))
_notice_for_customer(customer['id'])
db.session.add(ShippingCustomerIdentifier(
customer_id=customer['id'],
identifier_type='name_alias',
+105 -49
View File
@@ -22,6 +22,11 @@ from app.models import (
ShippingOrderField,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingOrderTask,
ShippingOrderExtraction,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingNoticeLineInventoryMatch,
ShippingNotice,
User,
)
@@ -65,6 +70,98 @@ def _headers(username: str, role: str) -> dict[str, str]:
return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'}
def _notice_with_customer(*, task_no: str, customer_id: int, business_no: str | None = None) -> ShippingNotice:
"""创建由已确认客户识别结果支撑的正式 Notice,避免回写 bill_to 或旧匹配表。"""
_identity_field()
user = User.query.filter_by(username='shipping-admin').one()
version = ShippingOrderSchemaVersion.query.filter_by(status='published').order_by(
ShippingOrderSchemaVersion.id.desc(),
).first()
asset = FileAsset(
asset_no=f'FA-{task_no}', owner_user_id=user.id, original_filename='notice.pdf',
storage_provider='minio', storage_bucket='test', storage_key=f'{task_no}.pdf',
content_hash=f'{task_no:0<64}'[:64], file_size=1, upload_status='uploaded', lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
intake = ShippingOrderIntake(
intake_no=f'INTAKE-{task_no}', asset_id=asset.id, user_id=user.id, parser_version='v6', parse_status='parsed',
)
db.session.add(intake)
db.session.flush()
document = ShippingOrderDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='file',
filename='notice.pdf', classification='order_notice', parse_status='parsed',
)
db.session.add(document)
db.session.flush()
candidate = ShippingOrderCandidate(
candidate_no=f'CANDIDATE-{task_no}', intake_id=intake.id, primary_document_id=document.id,
candidate_key='document:1', validation_status='ready', selected=True,
)
db.session.add(candidate)
db.session.flush()
task = ShippingOrderTask(
task_no=task_no, user_id=user.id, intake_id=intake.id, candidate_id=candidate.id,
status='ready', current_step='customer_review',
)
db.session.add(task)
db.session.flush()
extraction = ShippingOrderExtraction(
task_id=task.id,
schema_version_id=version.id,
input_snapshot_hash=('a' * 64),
status='accepted',
)
db.session.add(extraction)
db.session.flush()
task.current_order_extraction_id = extraction.id
candidate.order_extraction_id = extraction.id
db.session.add(ShippingCustomerShadowResolution(
candidate_id=candidate.id,
intake_id=intake.id,
resolution_version='test-v1',
status='confirmed',
evidence_json=[],
candidate_matches_json=[],
confirmed_customer_id=customer_id,
confirmation_method='manual',
))
snapshot = ShippingOrderSnapshot(
task_id=task.id,
extraction_id=extraction.id,
schema_version_id=version.id,
order_data_version=1,
header_values_json={},
source_manifest_json={},
rule_versions_json={},
)
db.session.add(snapshot)
db.session.flush()
task.order_snapshot_id = snapshot.id
snapshot_line = ShippingOrderSnapshotLine(
snapshot_id=snapshot.id,
position=0,
line_no=1,
part_number='TEST-PART',
qty=1,
)
db.session.add(snapshot_line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id,
snapshot_line_id=snapshot_line.id,
line_no=1,
match_result='matched',
inventory_status='ready',
is_current=True,
))
notice = ShippingNotice(task_no=task_no, business_no=business_no, order_task_id=task.id)
db.session.add(notice)
db.session.flush()
return notice
def test_shipping_customer_admin_crud_uses_standard_contract(app, client):
"""管理员可创建和查询客户,校验失败返回标准错误 envelope。"""
app.config['AUTH_JWT_REQUIRED'] = False
@@ -327,7 +424,7 @@ def test_shipping_customer_delete_api_rejects_invalid_confirmation_and_blockers(
customer = ShippingCustomer(standard_name='有业务客户', short_code='BLK', status='active')
db.session.add(customer)
db.session.flush()
db.session.add(ShippingNotice(task_no='SN-DELETE-API', customer_id=customer.id))
_notice_with_customer(task_no='SN-DELETE-API', customer_id=customer.id)
db.session.commit()
customer_id = customer.id
@@ -346,7 +443,7 @@ def test_shipping_customer_delete_api_rejects_invalid_confirmation_and_blockers(
assert blocked.status_code == 409
error = parse_api_error(blocked.get_json())
assert error['code'] == 'SHIPPING.CUSTOMER_DELETE_BLOCKED'
assert error['details']['blockers']['business_cases'] == 1
assert error['details']['blockers']['shipping_notices'] == 1
def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(app, client):
@@ -363,7 +460,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(
customer_id=source.id, identifier_type='name_alias', raw_value='Source Alias',
normalized_value='SOURCEALIAS', status='approved', source='manual',
),
ShippingNotice(task_no='SN-MERGE-API', customer_id=source.id, business_no='SRC26071601'),
_notice_with_customer(task_no='SN-MERGE-API', customer_id=source.id, business_no='SRC26071601'),
])
db.session.commit()
source_id = source.id
@@ -382,7 +479,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(
headers=admin_headers,
)
assert preview.status_code == 200
assert parse_api_data(preview.get_json())['historical_references']['business_cases'] == 1
assert parse_api_data(preview.get_json())['historical_references']['shipping_notices'] == 1
response = client.post(
f'/api/admin/shipping-customers/{source_id}/merge',
@@ -396,7 +493,10 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(
with app.app_context():
assert db.session.get(ShippingCustomer, source_id).status == 'merged'
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 1
assert db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-API').one().customer_id == source_id
notice = db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-API').one()
task = db.session.get(ShippingOrderTask, notice.order_task_id)
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
assert resolution.confirmed_customer_id == source_id
def test_shipping_customer_merge_api_validates_target_confirmation_and_reason(app, client):
@@ -507,47 +607,3 @@ def test_shipping_customer_shadow_report_and_label_api(app, client):
headers=_headers('shipping-user', 'user'),
)
assert forbidden.status_code == 403
def test_shipping_customer_numbered_correction_api_preserves_old_number(app, client):
"""管理员纠错 API 作废原号并返回替代新号,普通用户不可调用。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
wrong = ShippingCustomer(standard_name='错误客户', short_code='OLD', status='active')
correct = ShippingCustomer(standard_name='正确客户', short_code='NEW', status='active')
db.session.add_all([wrong, correct])
db.session.flush()
task = ShippingNotice(
task_no='SN-CORRECTION-API',
source_type='manual', customer_resolution_status='pending',
)
db.session.add(task)
db.session.commit()
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
confirm_task_customer(task, customer_id=wrong.id, actor_id=None)
old_business_no = task.business_no
correct_id = correct.id
forbidden = client.post(
'/api/admin/shipping-customers/numbered-task-correction',
json={'task_ref': old_business_no, 'customer_id': correct_id, 'reason': '客户错误'},
headers=_headers('shipping-user', 'user'),
)
assert forbidden.status_code == 403
response = client.post(
'/api/admin/shipping-customers/numbered-task-correction',
json={'task_ref': old_business_no, 'customer_id': correct_id, 'reason': '客户错误'},
headers=_headers('shipping-admin', 'admin'),
)
assert response.status_code == 200
payload = parse_api_data(response.get_json())
assert payload['old_business_no'] == old_business_no
assert payload['new_business_no'].startswith('NEW')
with app.app_context():
old_notice = ShippingNotice.query.filter_by(business_no=old_business_no).one()
replacement = ShippingNotice.query.filter_by(supersedes_task_id=old_notice.id).one()
assert old_notice.lifecycle_status == 'voided'
assert replacement.business_no == payload['new_business_no']
@@ -8,10 +8,6 @@
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import type {
ShippingOrderDerivationRule,
ShippingOrderDerivationSimulateRequest,
ShippingOrderDerivationSimulateResult,
ShippingOrderDerivationSimulateSampleItem,
ShippingOrderField,
ShippingOrderFieldConfig,
ShippingOrderSchemaAuditEventPage,
@@ -158,13 +154,12 @@ export const getShippingOrderExtractionAudit = (extractionId: number) =>
auth(),
);
/** 整体保存草稿字段配置、自动建单策略、派生规则及每个字段的版本纳入状态。 */
/** 整体保存草稿字段配置、自动建单策略及每个字段的版本纳入状态。 */
export const saveShippingOrderSchemaDraft = (
versionId: number,
payload: {
fields: ShippingOrderFieldConfig[];
auto_creation_policy?: { enabled: boolean };
derivation_rules?: ShippingOrderDerivationRule[];
change_note?: string;
expected_lock_version: number;
},
@@ -177,34 +172,6 @@ export const saveShippingOrderSchemaDraft = (
},
);
/**
* 对 Schema 版本派生规则做样本模拟(不改订单)。
* @param versionId - Schema 版本 ID
* @param payload - 样本行与可选规则覆盖 / sample_ref
*/
export const simulateShippingOrderSchemaDerivation = (
versionId: number,
payload: ShippingOrderDerivationSimulateRequest,
) =>
requestJson<ShippingOrderDerivationSimulateResult>(
`/api/admin/shipping-order-schema/versions/${versionId}/simulate-derivation`,
{
method: 'POST',
body: JSON.stringify(payload),
...jsonAuth(),
},
);
/**
* 列出可供派生规则模拟的历史 Extraction 样本。
* @param limit - 返回条数上限
*/
export const listShippingOrderSchemaDerivationSimulateSamples = (limit = 20) =>
requestJson<{ items: ShippingOrderDerivationSimulateSampleItem[] }>(
`/api/admin/shipping-order-schema/derivation-simulate-samples?limit=${limit}`,
auth(),
);
/** 删除错误草稿;发布版本由服务端拒绝删除。 */
export const deleteShippingOrderSchemaDraft = (versionId: number) =>
requestJson<void>(`/api/admin/shipping-order-schema/versions/${versionId}`, {
@@ -75,7 +75,8 @@ export function useOrderProfileValueAdapter(options: UseOrderProfileValueAdapter
const profileId = computed(() => Number(toValue(options.profileId) || 0));
const saveState = computed(() => toValue(options.saveState));
const readonly = computed(() => saveState.value === 'readonly');
const loading = ref(true);
// 坐标模板不会启用该 adapter;初始状态必须是非加载,避免共享画布误显示 XFA loading。
const loading = ref(false);
const loadError = ref(false);
const lockVersion = ref(0);
const schemaFields = ref<ShippingOrderFieldConfig[]>([]);
@@ -977,7 +978,10 @@ export function useOrderProfileValueAdapter(options: UseOrderProfileValueAdapter
const enabled = computed(() => toValue(options.enabled) !== false);
watch(enabled, (isEnabled) => {
if (isEnabled && profileId.value > 0) void load();
if (isEnabled && profileId.value > 0) {
loading.value = true;
void load();
}
}, { immediate: true });
watch(diagnosticsOpen, async (open) => {
@@ -3,7 +3,7 @@
用途:单一发货订单 Schema 的版本采用与版本级识别规则编辑;字段身份由全局字段资产库维护。
依赖:shipping-order-schema.api、shipping-field-assets.api、FieldImpactDrawer、版本/审计抽屉组件、Vue I18n。
逻辑:左侧勾选采用资产目录,右侧编辑已采用字段规则;草稿保存/发布与历史追溯由服务端冻结。无多族切换。
「Schema 级策略」分组收纳自动建单总开关与字段派生规则;仅草稿可改,随保存/发布生效;支持样本模拟。
「Schema 级策略」仅收纳自动建单总开关;订单项次由系统按单据内顺序生成。
-->
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
@@ -26,8 +26,6 @@ import {
listShippingOrderSchemaVersions,
publishShippingOrderSchemaDraft,
saveShippingOrderSchemaDraft,
simulateShippingOrderSchemaDerivation,
listShippingOrderSchemaDerivationSimulateSamples,
} from '@/features/admin/api/shipping-order-schema.api';
import FieldImpactDrawer from '@/features/admin/modules/shipping-field-assets/components/FieldImpactDrawer.vue';
import SchemaExtractionAuditDrawer from '@/features/admin/modules/shipping-order-schema/components/SchemaExtractionAuditDrawer.vue';
@@ -36,9 +34,6 @@ import SchemaVersionHistoryDrawer from '@/features/admin/modules/shipping-order-
import SchemaVersionUsageDrawer from '@/features/admin/modules/shipping-order-schema/components/SchemaVersionUsageDrawer.vue';
import type { ShippingFieldAsset, ShippingFieldAssetImpact } from '@/features/admin/types/shipping-field-assets.types';
import type {
ShippingOrderDerivationRule,
ShippingOrderDerivationSimulateResult,
ShippingOrderDerivationSimulateSampleItem,
ShippingOrderField,
ShippingOrderFieldConfig,
ShippingOrderExtractionAudit,
@@ -75,20 +70,6 @@ const autoCreationConfirmOpen = ref(false);
const pendingAutoCreationEnabled = ref(false);
const changeNote = ref('');
const selectedDraftFieldId = ref<string | null>(null);
const derivationRules = ref<ShippingOrderDerivationRule[]>([]);
const derivationPanelOpen = ref(true);
const simulateOpen = ref(false);
const simulating = ref(false);
const simulateMode = ref<'history' | 'inline'>('history');
const simulateSamples = ref<ShippingOrderDerivationSimulateSampleItem[]>([]);
const simulateSampleRef = ref('');
const simulateSamplesLoading = ref(false);
const simulateSampleJson = ref(`[
{"customer_po_line_no": "00010", "line_no": null},
{"customer_po_line_no": "00020", "line_no": "20"},
{"customer_po_line_no": "ABC", "line_no": null}
]`);
const simulateResult = ref<ShippingOrderDerivationSimulateResult | null>(null);
const fieldSearch = ref('');
const expandedGroups = reactive<Record<AdoptionGroupKey, boolean>>({
headerStandard: true,
@@ -271,19 +252,6 @@ const syncDraftFields = (): void => {
autoCreationEnabled.value = typeof draftPolicy === 'boolean'
? draftPolicy
: state.value?.schema?.auto_creation_policy?.enabled === true;
const sourceRules = draft.value?.definition?.derivation_rules
|| published.value?.definition?.derivation_rules
|| [];
derivationRules.value = sourceRules.length
? sourceRules.map((rule) => ({ ...rule }))
: [{
rule_id: 'R-LINE-NO-FROM-CUSTOMER-PO',
enabled: false,
source_field_code: 'customer_po_line_no',
target_field_code: 'line_no',
strategy: 'copy_if_empty',
scope: 'line',
}];
const existing = draft.value?.definition?.fields || published.value?.definition?.fields || [];
const byId = new Map(existing.map((item) => [item.field_id, item]));
draftFields.value = (state.value?.fields || [])
@@ -441,7 +409,7 @@ const toggleAdoption = (field: ShippingOrderField, enabled: boolean): void => {
}
};
/** 保存草稿的全部已采用字段规则、派生规则与自动建单策略;未采用字段不会进入发布契约。 */
/** 保存草稿的全部已采用字段规则与自动建单策略;订单项次不属于可编辑 Schema 配置。 */
const saveDraft = async (): Promise<void> => {
if (!draft.value) return;
saving.value = true;
@@ -450,16 +418,12 @@ const saveDraft = async (): Promise<void> => {
const saved = await saveShippingOrderSchemaDraft(draft.value.id, {
fields,
auto_creation_policy: { enabled: autoCreationEnabled.value },
derivation_rules: derivationRules.value.map((item) => ({ ...item })),
change_note: changeNote.value,
expected_lock_version: draft.value.lock_version,
});
if (state.value) {
state.value.versions = state.value.versions.map((item) => (item.id === saved.id ? saved : item));
}
if (saved.definition?.derivation_rules) {
derivationRules.value = saved.definition.derivation_rules.map((item) => ({ ...item }));
}
message.success(t('admin.shippingOrderSchema.draftSaved'));
} catch (error) {
await handleWriteError(error);
@@ -468,82 +432,6 @@ const saveDraft = async (): Promise<void> => {
}
};
/**
* 切换派生规则启用状态(仅草稿可改)。
* @param index - 规则下标
* @param event - checkbox 事件
*/
const onDerivationEnabledChange = (index: number, event: Event): void => {
if (!draft.value) return;
const checked = (event.target as HTMLInputElement).checked;
const current = derivationRules.value[index];
if (!current) return;
derivationRules.value[index] = { ...current, enabled: checked };
};
/**
* 打开派生规则模拟弹窗并加载历史 Extraction 样本列表。
*/
const openDerivationSimulate = async (): Promise<void> => {
simulateResult.value = null;
simulateMode.value = 'history';
simulateOpen.value = true;
simulateSamplesLoading.value = true;
try {
const response = await listShippingOrderSchemaDerivationSimulateSamples(20);
simulateSamples.value = response.items || [];
simulateSampleRef.value = simulateSamples.value[0]?.sample_ref || '';
if (!simulateSamples.value.length) {
simulateMode.value = 'inline';
}
} catch (error) {
await handleWriteError(error);
simulateMode.value = 'inline';
} finally {
simulateSamplesLoading.value = false;
}
};
/**
* 运行派生规则模拟:优先使用历史 Extraction 样本,亦可手工 JSON。
*/
const runDerivationSimulate = async (): Promise<void> => {
if (!draft.value && !published.value) return;
const versionId = draft.value?.id || published.value?.id;
if (!versionId) return;
simulating.value = true;
try {
if (simulateMode.value === 'history') {
if (!simulateSampleRef.value) {
message.error(t('admin.shippingOrderSchema.derivationSimulateSampleRequired'));
return;
}
simulateResult.value = await simulateShippingOrderSchemaDerivation(versionId, {
sample_ref: simulateSampleRef.value,
derivation_rules: derivationRules.value,
});
return;
}
const lines = JSON.parse(simulateSampleJson.value) as Array<Record<string, string | number | null>>;
if (!Array.isArray(lines)) {
throw new Error('invalid sample');
}
simulateResult.value = await simulateShippingOrderSchemaDerivation(versionId, {
lines,
derivation_rules: derivationRules.value,
sample_ref: 'schema-admin-inline-sample',
});
} catch (error) {
if (error instanceof SyntaxError || (error instanceof Error && error.message === 'invalid sample')) {
message.error(t('admin.shippingOrderSchema.derivationSimulateSampleInvalid'));
} else {
await handleWriteError(error);
}
} finally {
simulating.value = false;
}
};
/**
* 拦截自动建单开关变更:仅草稿可改,且须二次确认;确认后仅写入本地,随保存草稿/发布生效。
* @param event - checkbox change 事件
@@ -1049,48 +937,6 @@ onMounted(async () => {
</label>
<p class="schema-gate-note">{{ t('admin.shippingOrderSchema.effectiveReservationGate') }}</p>
<details class="derivation-panel" :open="derivationPanelOpen" @toggle="derivationPanelOpen = ($event.target as HTMLDetailsElement).open">
<summary>
<strong>{{ t('admin.shippingOrderSchema.derivationRulesTitle') }}</strong>
<span>{{ t('admin.shippingOrderSchema.derivationRulesHint') }}</span>
</summary>
<div class="derivation-toolbar">
<button
type="button"
class="btn-secondary btn-sm"
:disabled="simulating || (!draft && !published)"
@click="openDerivationSimulate"
>
{{ t('admin.shippingOrderSchema.derivationSimulate') }}
</button>
</div>
<table class="derivation-table">
<thead>
<tr>
<th>{{ t('admin.shippingOrderSchema.derivationEnabled') }}</th>
<th>{{ t('admin.shippingOrderSchema.derivationSource') }}</th>
<th>{{ t('admin.shippingOrderSchema.derivationTarget') }}</th>
<th>{{ t('admin.shippingOrderSchema.derivationStrategy') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(rule, index) in derivationRules" :key="rule.rule_id">
<td>
<input
type="checkbox"
:checked="rule.enabled"
:disabled="!draft || saving"
@change="onDerivationEnabledChange(index, $event)"
>
</td>
<td><code>{{ rule.source_field_code }}</code></td>
<td><code>{{ rule.target_field_code }}</code></td>
<td>{{ t('admin.shippingOrderSchema.derivationStrategyCopyIfEmpty') }}</td>
</tr>
</tbody>
</table>
<p class="derivation-note">{{ t('admin.shippingOrderSchema.derivationRulesNote') }}</p>
</details>
</section>
<div class="schema-workbench">
@@ -1508,96 +1354,6 @@ onMounted(async () => {
</section>
</div>
<div v-if="simulateOpen" class="impact-overlay" @click.self="simulateOpen = false">
<section class="impact-dialog derivation-simulate-dialog">
<header>
<h2>{{ t('admin.shippingOrderSchema.derivationSimulateTitle') }}</h2>
<button type="button" class="btn-ghost btn-sm" @click="simulateOpen = false">{{ t('common.close') }}</button>
</header>
<p class="simulate-hint">{{ t('admin.shippingOrderSchema.derivationSimulateNoMutate') }}</p>
<div class="simulate-mode-row">
<label>
<input v-model="simulateMode" type="radio" value="history">
{{ t('admin.shippingOrderSchema.derivationSimulateModeHistory') }}
</label>
<label>
<input v-model="simulateMode" type="radio" value="inline">
{{ t('admin.shippingOrderSchema.derivationSimulateModeInline') }}
</label>
</div>
<label v-if="simulateMode === 'history'" class="simulate-sample">
<span>{{ t('admin.shippingOrderSchema.derivationSimulateHistorySample') }}</span>
<select v-model="simulateSampleRef" :disabled="simulateSamplesLoading || !simulateSamples.length">
<option disabled value="">
{{ simulateSamplesLoading
? t('admin.shippingOrderSchema.derivationSimulateSamplesLoading')
: t('admin.shippingOrderSchema.derivationSimulateSamplesEmpty') }}
</option>
<option
v-for="item in simulateSamples"
:key="item.sample_ref"
:value="item.sample_ref"
>
{{ t('admin.shippingOrderSchema.derivationSimulateSampleOption', {
id: item.extraction_id,
lines: item.line_count,
status: item.status,
}) }}
</option>
</select>
</label>
<label v-else class="simulate-sample">
<span>{{ t('admin.shippingOrderSchema.derivationSimulateSample') }}</span>
<textarea v-model="simulateSampleJson" rows="8" />
</label>
<footer>
<button type="button" class="btn-secondary" @click="simulateOpen = false">{{ t('common.cancel') }}</button>
<button type="button" class="btn-primary" :disabled="simulating" @click="runDerivationSimulate">
{{ t('admin.shippingOrderSchema.derivationSimulateRun') }}
</button>
</footer>
<div v-if="simulateResult" class="simulate-result">
<p>
{{ t('admin.shippingOrderSchema.derivationSimulateSummary', {
version: simulateResult.schema_version,
checksum: simulateResult.rules_checksum.slice(0, 12),
derived: simulateResult.derived_count,
skipped: simulateResult.skipped_count,
}) }}
</p>
<div class="simulate-result-scroll" data-testid="derivation-simulate-result-scroll">
<table class="derivation-table">
<thead>
<tr>
<th>#</th>
<th>{{ t('admin.shippingOrderSchema.derivationSource') }}</th>
<th>{{ t('admin.shippingOrderSchema.derivationBefore') }}</th>
<th>{{ t('admin.shippingOrderSchema.derivationAfter') }}</th>
<th>{{ t('admin.shippingOrderSchema.derivationResult') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in simulateResult.results" :key="`${row.line_index}-${row.rule_id}`">
<td>{{ row.line_index + 1 }}</td>
<td>{{ row.before_source ?? '—' }}</td>
<td>{{ row.before_target ?? '—' }}</td>
<td>{{ row.after_target ?? '—' }}</td>
<td>
<template v-if="row.status === 'derived'">
{{ t('admin.shippingOrderSchema.derivationStatusDerived') }}
</template>
<template v-else>
{{ t('admin.shippingOrderSchema.derivationStatusSkipped', { reason: row.skip_reason || '' }) }}
</template>
</td>
</tr>
</tbody>
</table>
</div>
<p class="muted">{{ t('admin.shippingOrderSchema.derivationSimulateNoMutate') }}</p>
</div>
</section>
</div>
<div v-if="profileImpactOpen && profileImpact" class="impact-overlay" @click.self="profileImpactOpen = false">
<section class="impact-dialog">
@@ -1725,38 +1481,6 @@ onMounted(async () => {
.auto-creation-switch small { color: #64748b; font-size: 11px; }
.auto-creation-effective { display: block; color: #0f766e; }
.schema-gate-note { margin: 0 0 12px; color: #475569; font-size: 12px; line-height: 1.5; }
.derivation-panel { margin: 0 0 8px; border: 1px solid #dbe6ef; border-radius: 8px; background: #fff; padding: 12px 14px; }
.derivation-panel summary { cursor: pointer; display: grid; gap: 4px; color: #334155; }
.derivation-panel summary span { color: #64748b; font-size: 12px; }
.derivation-toolbar { display: flex; justify-content: flex-end; margin: 12px 0; }
.derivation-table { width: 100%; border-collapse: collapse; font-size: 12px; }
.derivation-table th, .derivation-table td { border-bottom: 1px solid #e2e8f0; padding: 8px 6px; text-align: left; vertical-align: middle; }
.derivation-note { margin: 10px 0 0; color: #64748b; font-size: 12px; }
.simulate-hint { margin: 0 0 10px; color: #64748b; font-size: 12px; }
.simulate-mode-row { display: flex; gap: 16px; margin-bottom: 10px; font-size: 13px; color: #334155; }
.simulate-mode-row label { display: inline-flex; align-items: center; gap: 6px; }
.derivation-simulate-dialog {
max-width: 760px;
width: min(760px, 92vw);
overflow: auto;
align-content: start;
}
.simulate-sample { display: grid; gap: 8px; margin: 12px 0; color: #475569; font-size: 13px; }
.simulate-sample textarea,
.simulate-sample select { width: 100%; font-size: 12px; border: 1px solid #cbd5e1; border-radius: 8px; padding: 10px; box-sizing: border-box; }
.simulate-sample textarea { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
.simulate-result { margin-top: 14px; display: grid; gap: 10px; min-width: 0; }
.simulate-result-scroll {
max-width: 100%;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
border: 1px solid #e2e8f0;
border-radius: 8px;
}
.simulate-result-scroll .derivation-table {
margin: 0;
min-width: 520px;
}
.muted { margin: 0; color: #64748b; font-size: 12px; }
.field-panel { display: flex; min-width: 0; min-height: 0; flex-direction: column; border-right: 1px solid #e5ebf1; background: #fbfcfe; }
.panel-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 16px 16px 10px; }
@@ -1,4 +1,4 @@
/**
/**
* features/admin/stores/admin-nav.store.ts
* 管理后台导航 UI 状态(侧栏折叠、报表/企微子菜单展开、角标)。
*
@@ -20,6 +20,8 @@ export const useAdminNavStore = defineStore('adminNav', () => {
const reportsExpanded = ref(false);
/** 企业微信子菜单:默认折叠 */
const wecomExpanded = ref(false);
/** 货代管理子菜单:默认折叠;父项点击仅展开/收起,子项负责导航 */
const shippingMenuExpanded = ref(false);
/** 「用户审批」导航角标:pending 注册用户数 */
const pendingApprovalsCount = ref(0);
/** 「权限申请」导航角标:pending 权限申请数 */
@@ -88,6 +90,7 @@ export const useAdminNavStore = defineStore('adminNav', () => {
sidebarCollapsed,
reportsExpanded,
wecomExpanded,
shippingMenuExpanded,
pendingApprovalsCount,
pendingRequestsCount,
toggleSidebar,
@@ -91,69 +91,9 @@ export interface ShippingOrderSchemaVersion {
definition?: {
fields: ShippingOrderFieldConfig[];
auto_creation_policy?: { enabled: boolean };
derivation_rules?: ShippingOrderDerivationRule[];
derivation_rules_checksum?: string;
};
}
/** Schema 级明细字段派生规则(首期仅 copy_if_empty → line_no)。 */
export interface ShippingOrderDerivationRule {
rule_id: string;
enabled: boolean;
source_field_code: string;
target_field_code: string;
strategy: 'copy_if_empty';
scope: 'line';
}
export interface ShippingOrderDerivationSimulateRequest {
lines?: Array<Record<string, string | number | null | undefined>>;
derivation_rules?: ShippingOrderDerivationRule[];
/** 可追溯样本;`extraction:<id>` 时后端加载历史明细,可省略 lines。 */
sample_ref?: string;
}
export interface ShippingOrderDerivationSimulateSampleItem {
sample_ref: string;
extraction_id: number;
line_count: number;
status: string;
schema_version_id: number;
created_at?: string | null;
}
export interface ShippingOrderDerivationSimulateResult {
schema_version_id: number;
schema_version: number;
schema_version_status: string;
rules_checksum: string;
rules: ShippingOrderDerivationRule[];
derived_count: number;
skipped_count: number;
results: Array<{
line_index: number;
rule_id: string;
source_field_code: string;
target_field_code: string;
strategy: string;
before_source: unknown;
before_target: unknown;
after_target: unknown;
status: 'derived' | 'skipped';
skip_reason: string | null;
}>;
lines_after: Array<Record<string, unknown>>;
sample_ref?: string | null;
sample_source?: {
kind?: string;
extraction_id?: number;
schema_version_id?: number;
intake_id?: number;
status?: string;
} | null;
mutates_orders: boolean;
}
export interface SchemaVersionActor {
id: number;
display_name: string;
@@ -266,7 +206,7 @@ export interface ShippingOrderExtractionAudit {
raw_llm_output: unknown;
normalized_result: unknown;
validation_result: unknown;
lines: Array<{ id: number; position: number; line_key?: string | null }>;
lines: Array<{ id: number; position: number; line_no: number }>;
observations: Array<Record<string, unknown>>;
decisions: Array<Record<string, unknown>>;
field_values: Array<Record<string, unknown>>;
@@ -0,0 +1,61 @@
/**
* features/shipping-progress/stageMapping.spec.ts
* 用途:验收「处理阶段 → 5 业务标签」唯一前端映射。
* 依赖:Vitest、stageMapping、SHIPPING_PROCESSING_STAGES。
* 逻辑:15 阶全部映射且与后端 LIFECYCLE_STAGE_BY_PROCESSING_STAGE 方向一致;
* 未知/非法阶段 clamp 到 intake_parse;5 段标签 i18n 键齐全。
*/
import { describe, expect, it } from 'vitest';
import { SHIPPING_PROCESSING_STAGES } from '@/features/chat/types/shipping.api.types';
import {
LIFECYCLE_STAGE_CODES,
LIFECYCLE_STAGE_LABEL_KEYS,
mapProcessingStageToLifecycle,
SHIPPING_STAGE_TO_LIFECYCLE,
} from './stageMapping';
describe('stageMapping', () => {
it('将全部 15 阶处理阶段映射到 5 段业务标签且不漂移', () => {
// 权威方向:后端 lifecycle_projection.LIFECYCLE_STAGE_BY_PROCESSING_STAGE。
const expected: Record<string, string> = {
upload_received: 'intake_parse',
email_parsing: 'intake_parse',
document_parsing: 'intake_parse',
email_adjudicating: 'intake_parse',
candidate_creating: 'intake_parse',
customer_resolving: 'order_review',
duplicate_checking: 'order_review',
inventory_source_resolving: 'order_review',
waiting_review: 'order_review',
order_creating: 'fulfillment_prep',
inventory_fetching: 'fulfillment_prep',
inventory_matching: 'fulfillment_prep',
excel_generating: 'fulfillment_prep',
freight_uploading: 'freight_upload',
completed: 'upload_complete',
};
for (const stage of SHIPPING_PROCESSING_STAGES) {
expect(SHIPPING_STAGE_TO_LIFECYCLE[stage]).toBe(expected[stage]);
expect(LIFECYCLE_STAGE_CODES).toContain(SHIPPING_STAGE_TO_LIFECYCLE[stage]);
}
});
it('过渡态归入对应业务标签(库存准备/充足性→通知准备;人工上传交接→货代上传)', () => {
expect(mapProcessingStageToLifecycle('inventory_preparation')).toBe('fulfillment_prep');
expect(mapProcessingStageToLifecycle('inventory_sufficiency')).toBe('fulfillment_prep');
expect(mapProcessingStageToLifecycle('manual_upload_handoff')).toBe('freight_upload');
});
it('未知/非法阶段 clamp 到 intake_parse 安全兜底', () => {
expect(mapProcessingStageToLifecycle('bogus_stage')).toBe('intake_parse');
expect(mapProcessingStageToLifecycle('')).toBe('intake_parse');
expect(mapProcessingStageToLifecycle(null)).toBe('intake_parse');
expect(mapProcessingStageToLifecycle(undefined)).toBe('intake_parse');
});
it('5 段业务标签 i18n key 后缀齐全', () => {
for (const code of LIFECYCLE_STAGE_CODES) {
expect(LIFECYCLE_STAGE_LABEL_KEYS[code]).toBeTruthy();
}
});
});