feat(shipping-order): 增加客户事实、编辑窗口与正式通知创建服务
This commit is contained in:
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):
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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']
|
||||
Reference in new issue
Block a user