Merge branch 'hugo-auto-transfer' into test
This commit is contained in:
commit
570d1c605c
30 files changed
+1913
-93
No files matched your search
@@ -20,7 +20,7 @@ from flask import Blueprint, Response, current_app, g, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
|
||||
@@ -2198,6 +2198,88 @@ def workspace_confirm_shipping_order_review_customer(case_no: str):
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/customer/rebind',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_rebind_shipping_order_review_customer(case_no: str):
|
||||
"""
|
||||
确认客户改绑:直接修改已确认的客户识别结果并刷新订单快照客户。
|
||||
|
||||
Body: customer_id, expected_order_data_version, reason?
|
||||
仅当订单编辑窗 header 可编辑(任一通知无 Export Artifact 且无活动 Gate Attempt,
|
||||
即发货通知/Excel 未产生)时允许;版本乐观锁与状态守卫在服务层 fail-closed。
|
||||
"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
customer_id = int(data.get('customer_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Customer id is required',
|
||||
code='SHIPPING.CUSTOMER_REBIND_CUSTOMER_REQUIRED',
|
||||
details={'field': 'customer_id'},
|
||||
) from exc
|
||||
try:
|
||||
expected_order_data_version = int(data.get('expected_order_data_version'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Expected order data version is required',
|
||||
code='SHIPPING.CUSTOMER_REBIND_VERSION_REQUIRED',
|
||||
details={'field': 'expected_order_data_version'},
|
||||
) from exc
|
||||
|
||||
from app.services.shipping_notice.customer_resolution_service import rebind_confirmed_customer
|
||||
from app.services.shipping_notice.order_review_customer_service import (
|
||||
project_review_case_customer_resolution,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
|
||||
|
||||
case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
|
||||
if case is None:
|
||||
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
formal = resolve_formal_ot(case)
|
||||
if not formal.get('has_formal_ot') or formal.get('task') is None:
|
||||
raise ConflictError(
|
||||
'A formal order task is required before rebinding customer',
|
||||
code='SHIPPING.FORMAL_OT_REQUIRED',
|
||||
details={'task_missing': bool(formal.get('task_missing'))},
|
||||
)
|
||||
|
||||
result = rebind_confirmed_customer(
|
||||
task=formal['task'],
|
||||
new_customer_id=customer_id,
|
||||
actor_id=int(user.id),
|
||||
expected_order_data_version=expected_order_data_version,
|
||||
reason=str(data.get('reason') or '').strip() or None,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
resolution = result['resolution']
|
||||
rebind_record = next(
|
||||
(
|
||||
item.get('rebind') for item in (resolution.evidence_json or [])
|
||||
if isinstance(item, dict) and item.get('rebind')
|
||||
),
|
||||
None,
|
||||
) or {}
|
||||
refreshed_case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
|
||||
return _ok({
|
||||
'case': serialize_review_case(refreshed_case) if refreshed_case is not None else None,
|
||||
'customer_resolution': (
|
||||
project_review_case_customer_resolution(refreshed_case)
|
||||
if refreshed_case is not None else None
|
||||
),
|
||||
'rebind': {
|
||||
'previous_customer_id': rebind_record.get('previous_customer_id'),
|
||||
'customer_id': int(resolution.confirmed_customer_id),
|
||||
'snapshot_id': int(result['snapshot'].id),
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/reservation/revalidate',
|
||||
methods=['POST'],
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
"""
|
||||
services/shipping_notice/customer_resolution_service.py
|
||||
|
||||
用途:提供订单任务的唯一客户识别结果读取与确认入口。
|
||||
依赖:ShippingCustomerShadowResolution、ShippingOrderTask、ShippingOrderCandidate、ShippingCustomer。
|
||||
用途:提供订单任务的唯一客户识别结果读取、确认与确认后改绑入口。
|
||||
依赖:ShippingCustomerShadowResolution、ShippingOrderTask、ShippingOrderCandidate、ShippingCustomer、
|
||||
ShippingNotice、ShippingOrderSnapshot、order_edit_window_service、order_freeze_service、audit_service。
|
||||
逻辑:客户身份来自已发布规则生成的证据快照;订单字段(包括 bill_to)只能作为证据,
|
||||
不能承担客户角色或流程门禁真相。
|
||||
不能承担客户角色或流程门禁真相。确认后改绑(rebind_confirmed_customer)仅在订单
|
||||
编辑窗 header 可编辑(无 Export Artifact 且无活动 Gate Attempt)时允许直接修改
|
||||
确认结果,并原地刷新冻结快照客户(快照表 uq task_id 唯一约束决定不可另建新行)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,7 +17,14 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import ShippingCustomer, ShippingCustomerShadowResolution, ShippingOrderCandidate, ShippingOrderTask
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingNotice,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
|
||||
|
||||
def resolution_for_task(task: Any) -> ShippingCustomerShadowResolution | None:
|
||||
@@ -74,3 +84,265 @@ def confirm_customer_resolution(
|
||||
resolution.status = 'confirmed'
|
||||
db.session.flush()
|
||||
return resolution
|
||||
|
||||
|
||||
# 改绑后 audit 事件类型:已纳入 progress_audit_contract.REVIEW_WORKBENCH_AUDIT_EVENT_TYPES
|
||||
# 冻结字典(review_* snake_case 命名;review_customer_confirmed 专指首次确认,改绑独立成码)。
|
||||
REBIND_AUDIT_EVENT_TYPE = 'review_customer_rebound'
|
||||
|
||||
|
||||
def _order_notice_for_task(task: Any) -> ShippingNotice | None:
|
||||
"""回读该正式订单的任一通知作为编辑窗谓词入口;editable_scope 会按 order_task_id 聚合全部通知。"""
|
||||
return (
|
||||
ShippingNotice.query
|
||||
.filter(ShippingNotice.order_task_id == int(task.id))
|
||||
.order_by(ShippingNotice.id.asc())
|
||||
.first()
|
||||
) if getattr(task, 'id', None) is not None else None
|
||||
|
||||
|
||||
def _review_case_no_for_task(task: Any) -> str | None:
|
||||
"""
|
||||
经建单确认修订反查正式任务所属复核 Case 编号(order_edit_window_service 同款反查模式)。
|
||||
|
||||
核心逻辑:ShippingOrderReviewConfirmedRevision.case_id → ShippingOrderReviewCase.case_no,
|
||||
取最新一条修订;无修订(历史数据)时返回 None,审计事件照常落库。
|
||||
"""
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewConfirmedRevision
|
||||
|
||||
if getattr(task, 'id', None) is None:
|
||||
return None
|
||||
row = (
|
||||
db.session.query(ShippingOrderReviewCase.case_no)
|
||||
.join(
|
||||
ShippingOrderReviewConfirmedRevision,
|
||||
ShippingOrderReviewConfirmedRevision.case_id == ShippingOrderReviewCase.id,
|
||||
)
|
||||
.filter(ShippingOrderReviewConfirmedRevision.task_id == int(task.id))
|
||||
.order_by(ShippingOrderReviewConfirmedRevision.id.desc())
|
||||
.first()
|
||||
)
|
||||
return str(row[0]).strip() or None if row is not None else None
|
||||
|
||||
|
||||
def _assert_rebind_window_open(task: Any) -> None:
|
||||
"""
|
||||
改绑编辑窗守卫(fail-closed):header 不可编辑即拒绝,不区分原因放行。
|
||||
|
||||
核心逻辑:editable_scope(order_task)['header'] = 全部通知无 Export Artifact 且无活动
|
||||
Gate Attempt;尚无通知的未发货订单视为可编辑。details 区分 excel_exists / active_attempt
|
||||
供前端定位(“已产生发货通知/Excel,请先走撤销流程” vs 系统处理中)。
|
||||
"""
|
||||
from app.services.shipping_notice import order_edit_window_service as order_edit_window
|
||||
|
||||
notice = _order_notice_for_task(task)
|
||||
if notice is None:
|
||||
return
|
||||
scope = order_edit_window.editable_scope(notice)
|
||||
if bool(scope.get('header')):
|
||||
return
|
||||
excel_exists = any(
|
||||
order_edit_window._notice_has_export_artifact(item)
|
||||
for item in order_edit_window._order_notices(notice)
|
||||
)
|
||||
active_attempt = order_edit_window.order_has_active_attempt(notice)
|
||||
raise ConflictError(
|
||||
'Customer rebind is blocked after shipping notice or Excel generation',
|
||||
code='SHIPPING.CUSTOMER_REBIND_BLOCKED',
|
||||
details={'excel_exists': excel_exists, 'active_attempt': active_attempt},
|
||||
)
|
||||
|
||||
|
||||
def rebind_allowed_for_task(task: Any) -> bool:
|
||||
"""
|
||||
判定正式任务当前是否允许改绑确认客户(工作台「修改客户」按钮谓词,只读 fail-closed)。
|
||||
|
||||
核心逻辑:识别结果已确认,且编辑窗 header 可编辑(全部通知无 Export Artifact 且
|
||||
无活动 Gate Attempt)。与 rebind_confirmed_customer 守卫①②同源;并发语义由 API 层
|
||||
expected_order_data_version 承担,此处为只读投影不下发并发状态。
|
||||
|
||||
Args:
|
||||
task: 正式任务(ShippingOrderTask/ShippingNotice,按 resolution_for_task 语义解析)。
|
||||
|
||||
Returns:
|
||||
True 表示当前可改绑;False 表示未确认、Excel 已产生或存在活动 Attempt。
|
||||
"""
|
||||
row = resolution_for_task(task)
|
||||
if row is None or row.status != 'confirmed' or not row.confirmed_customer_id:
|
||||
return False
|
||||
notice = _order_notice_for_task(task)
|
||||
if notice is None:
|
||||
return True
|
||||
from app.services.shipping_notice import order_edit_window_service as order_edit_window
|
||||
|
||||
return bool(order_edit_window.editable_scope(notice).get('header'))
|
||||
|
||||
|
||||
def _append_rebind_audit(
|
||||
*,
|
||||
task: Any,
|
||||
previous_customer_id: int,
|
||||
new_customer: ShippingCustomer,
|
||||
actor_id: int,
|
||||
reason: str | None,
|
||||
) -> None:
|
||||
"""写改绑审计事件:before/after 携带原/新确认客户(键须命中审计快照白名单),并挂 review_case_no 供 Case 时间线查询。"""
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
task_no = str(getattr(task, 'task_no', '') or '')
|
||||
version = int(getattr(task, 'order_data_version', 0) or 1)
|
||||
append_shipping_audit_event(
|
||||
event_type=REBIND_AUDIT_EVENT_TYPE,
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=task_no,
|
||||
task_no=task_no,
|
||||
review_case_no=_review_case_no_for_task(task),
|
||||
actor_type='user',
|
||||
actor_id=int(actor_id),
|
||||
action='rebind_confirmed_customer',
|
||||
result='success',
|
||||
reason=str(reason or '').strip() or None,
|
||||
before={'previous_value': previous_customer_id, 'task_no': task_no, 'order_data_version': version},
|
||||
after={'new_value': int(new_customer.id), 'task_no': task_no, 'order_data_version': version},
|
||||
metadata={
|
||||
'previous_customer_id': int(previous_customer_id),
|
||||
'confirmed_customer_id': int(new_customer.id),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _refresh_frozen_snapshot_customer(task: Any, customer: ShippingCustomer) -> ShippingOrderSnapshot | None:
|
||||
"""
|
||||
原地刷新冻结快照的订购客户事实(customer_id / 客户简称)。
|
||||
|
||||
核心逻辑:快照表对 task_id 有唯一约束(uq_shipping_order_snapshots_task),且快照行身份
|
||||
被 Notice 行 / 波次行 / 库存匹配以 snapshot_line_id 引用,因此改绑不能删行重建,只能按
|
||||
新客户刷新客户身份字段;单头模板文本(customer_code/customer_name 等单据原文事实)不动。
|
||||
"""
|
||||
snapshot_id = getattr(task, 'order_snapshot_id', None)
|
||||
if not snapshot_id:
|
||||
return None
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id))
|
||||
if snapshot is None:
|
||||
return None
|
||||
snapshot.customer_id = int(customer.id)
|
||||
snapshot.customer_short_code_snapshot = str(getattr(customer, 'short_code', None) or '')
|
||||
db.session.flush()
|
||||
return snapshot
|
||||
|
||||
|
||||
def rebind_confirmed_customer(
|
||||
task: Any,
|
||||
*,
|
||||
new_customer_id: int,
|
||||
actor_id: int,
|
||||
expected_order_data_version: int,
|
||||
reason: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
确认客户改绑:直接修改已确认的客户识别结果并刷新冻结快照客户。
|
||||
|
||||
核心逻辑:守卫顺序固定 fail-closed——⓪客户端乐观锁版本比较(expected_order_data_version
|
||||
必填,与任务当前 order_data_version 不一致即 409,写任何数据之前执行,保证冲突零副作用;
|
||||
freeze 对已冻结任务幂等早退、不重复做版本校验,故版本比较只在此处);①识别结果已确认
|
||||
(未确认走既有确认流程);②订单编辑窗 header 可编辑(任一通知无 Export Artifact 且无
|
||||
活动 Gate Attempt,即发货通知/Excel 未产生);③新客户存在、启用且 ≠ 当前确认客户。
|
||||
通过后更新确认结果(追加 rebind 证据记录,保持 evidence_json 与 identity_rule_set_checksum
|
||||
非空冻结契约)、写审计、原地刷新快照客户,最后按 freeze 契约复核并返回快照。
|
||||
|
||||
Args:
|
||||
task: 正式订单任务 ShippingOrderTask(经 candidate_id 反查唯一识别结果)。
|
||||
new_customer_id: 目标标准客户 id;必须存在且启用。
|
||||
actor_id: 执行改绑的用户 id(必填,审计与 manual 冻结要求)。
|
||||
expected_order_data_version: 客户端读到的订单数据版本;与任务当前版本不一致时拒绝,
|
||||
防止并发编辑被静默覆盖(对齐 wave 路由 expected_draft_version 模式)。
|
||||
reason: 可选改绑原因;进入证据记录、审计与确认原因链。
|
||||
|
||||
Returns:
|
||||
dict: {'resolution': 更新后的识别结果行, 'snapshot': 客户已刷新的冻结快照}。
|
||||
|
||||
Raises:
|
||||
ValidationError: 缺少执行人(SHIPPING.CUSTOMER_REBIND_ACTOR_REQUIRED,内部调用契约)。
|
||||
ConflictError: 订单数据版本不一致(SHIPPING.ORDER_DATA_VERSION_MISMATCH)、识别结果
|
||||
未确认(SHIPPING.CUSTOMER_RESOLUTION_REQUIRED)、编辑窗关闭
|
||||
(SHIPPING.CUSTOMER_REBIND_BLOCKED,details 含 excel_exists/active_attempt)、
|
||||
新客户停用(SHIPPING.CUSTOMER_INACTIVE)或与当前客户相同
|
||||
(SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER)。
|
||||
NotFoundError: 目标客户不存在(SHIPPING.CUSTOMER_NOT_FOUND)。
|
||||
"""
|
||||
if not actor_id:
|
||||
# 内部调用契约缺失(非编辑窗状态),与 SHIPPING.CUSTOMER_REBIND_BLOCKED 的 A 管控语义区分。
|
||||
raise ValidationError('Customer rebind requires an operator', code='SHIPPING.CUSTOMER_REBIND_ACTOR_REQUIRED')
|
||||
|
||||
# [STEP 1] 守卫⓪:客户端版本比较在写任何数据之前执行;freeze 幂等早退不重复校验。
|
||||
actual_version = int(getattr(task, 'order_data_version', 0) or 1)
|
||||
if actual_version != int(expected_order_data_version):
|
||||
raise ConflictError(
|
||||
'Order data version has changed',
|
||||
code='SHIPPING.ORDER_DATA_VERSION_MISMATCH',
|
||||
details={'expected': int(expected_order_data_version), 'actual': actual_version},
|
||||
)
|
||||
|
||||
# [STEP 2] 守卫①:识别结果已确认(未确认走既有识别候选确认流程,不在此补确认)。
|
||||
resolution = resolution_for_task(task)
|
||||
if (
|
||||
resolution is None or str(resolution.status or '') != 'confirmed'
|
||||
or resolution.confirmed_customer_id is None
|
||||
):
|
||||
raise ConflictError(
|
||||
'Confirmed customer resolution is required before rebind',
|
||||
code='SHIPPING.CUSTOMER_RESOLUTION_REQUIRED',
|
||||
)
|
||||
|
||||
# [STEP 3] 守卫②:编辑窗 header 谓词(发货通知/Excel 已产生或系统处理中即拒绝)。
|
||||
_assert_rebind_window_open(task)
|
||||
|
||||
# [STEP 4] 守卫③:新客户存在、启用且 ≠ 当前确认客户。
|
||||
customer = db.session.get(ShippingCustomer, int(new_customer_id))
|
||||
if customer is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
if str(customer.status or '') != 'active':
|
||||
raise ConflictError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE')
|
||||
previous_customer_id = int(resolution.confirmed_customer_id)
|
||||
if int(customer.id) == previous_customer_id:
|
||||
raise ConflictError(
|
||||
'Rebind target equals the current confirmed customer',
|
||||
code='SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER',
|
||||
)
|
||||
|
||||
# [STEP 5] 更新确认结果:追加 rebind 证据记录(保留原识别证据;checksum 契约不动)。
|
||||
resolution.confirmed_customer_id = int(customer.id)
|
||||
resolution.evidence_json = [
|
||||
*(list(resolution.evidence_json or [])),
|
||||
{
|
||||
'source': 'manual_rebind',
|
||||
'rebind': {
|
||||
'previous_customer_id': previous_customer_id,
|
||||
'new_customer_id': int(customer.id),
|
||||
'actor_id': int(actor_id),
|
||||
'reason': str(reason or '').strip() or None,
|
||||
'rebound_at': datetime.utcnow().isoformat(),
|
||||
},
|
||||
},
|
||||
]
|
||||
db.session.flush()
|
||||
|
||||
# [STEP 6] 审计:before/after 携带原/新确认客户(与业务写入同事务,挂 review_case_no)。
|
||||
_append_rebind_audit(
|
||||
task=task, previous_customer_id=previous_customer_id,
|
||||
new_customer=customer, actor_id=int(actor_id), reason=reason,
|
||||
)
|
||||
|
||||
# [STEP 7] 快照客户刷新 + freeze 契约复核:manual 冻结校验 actor_id;已冻结任务走幂等
|
||||
# 早退返回当前快照(不重复版本校验——版本一致性已由守卫⓪保证)。
|
||||
snapshot = _refresh_frozen_snapshot_customer(task, customer)
|
||||
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
|
||||
|
||||
snapshot = freeze_order_snapshot(
|
||||
task,
|
||||
actor_id=int(actor_id),
|
||||
expected_order_data_version=int(expected_order_data_version),
|
||||
freeze_mode='manual',
|
||||
)
|
||||
db.session.flush()
|
||||
return {'resolution': resolution, 'snapshot': snapshot}
|
||||
@@ -2,8 +2,10 @@
|
||||
services/shipping_notice/inventory_routing_engine.py
|
||||
|
||||
用途:执行已发布的通用库存源路由规则并生成可解释的 Source 候选。
|
||||
依赖:库存路由模型、冻结订单 Snapshot、routing_operators。
|
||||
逻辑:只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。
|
||||
依赖:库存路由模型、冻结订单 Snapshot、routing_operators、inventory_source_repository。
|
||||
逻辑:行级评估先做「库存源线索直连」(冻结行 inventory_source_hint 经精确/唯一后缀解析启用源,
|
||||
命中即 resolved,跳过全部规则层——含预约单号兜底规则;未命中 fail-open 落回规则层);
|
||||
随后只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。
|
||||
多候选为建单前正常结果(can_build=True);零候选或 require_manual_review 才阻断建单。
|
||||
输出附带规则版本与命中规则摘要,供建单前重路由审计与前端展示;可用性过滤由资格服务完成。
|
||||
"""
|
||||
@@ -15,6 +17,7 @@ from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventoryRoutingRule, ShippingOrderSnapshot
|
||||
from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources
|
||||
from app.services.shipping_notice.routing_operators import matches_operator
|
||||
|
||||
|
||||
@@ -88,6 +91,55 @@ def _matched_rule_summaries(rules: list[ShippingInventoryRoutingRule]) -> tuple[
|
||||
)
|
||||
|
||||
|
||||
def _resolve_source_from_hint(line_source_hint: str) -> str | None:
|
||||
"""
|
||||
库存源线索 → 启用源解析:精确 source_code 相等优先,否则启用源中唯一后缀命中。
|
||||
|
||||
无命中或多命中(后缀撞源)返回 None——调用方 fail-open 落回规则层,不以线索阻断流程。
|
||||
"""
|
||||
code = str(line_source_hint or '').strip().upper()
|
||||
if not code:
|
||||
return None
|
||||
enabled_codes = [
|
||||
normalized
|
||||
for normalized in (
|
||||
str(item.get('source_code') or '').strip().upper()
|
||||
for item in list_database_inventory_sources(enabled_only=True)
|
||||
)
|
||||
if normalized
|
||||
]
|
||||
if code in enabled_codes:
|
||||
return code
|
||||
suffix_hits = [item for item in enabled_codes if item.endswith(code)]
|
||||
return suffix_hits[0] if len(suffix_hits) == 1 else None
|
||||
|
||||
|
||||
def _hint_routing_result(source_code: str) -> InventoryRoutingResult:
|
||||
"""线索直连结果:resolved 单源,evidence 标明来源供审计追溯。"""
|
||||
return InventoryRoutingResult(
|
||||
'resolved',
|
||||
(source_code,),
|
||||
(),
|
||||
{'reason': 'inventory_source_hint', 'raw_source_codes': [source_code]},
|
||||
matched_rules=(),
|
||||
)
|
||||
|
||||
|
||||
def _resolve_snapshot_line_source_hint(*, task: Any, line: dict[str, Any]) -> str | None:
|
||||
"""从冻结 Snapshot 行的强类型线索列读取并解析线索;行缺失或不可解析返回 None。"""
|
||||
snapshot_id = getattr(task, 'order_snapshot_id', None)
|
||||
if not snapshot_id:
|
||||
return None
|
||||
snapshot = ShippingOrderSnapshot.query.get(int(snapshot_id))
|
||||
if snapshot is None:
|
||||
return None
|
||||
position = int(line.get('_position', 0))
|
||||
target = next((item for item in snapshot.lines if item.position == position), None)
|
||||
if target is None:
|
||||
return None
|
||||
return _resolve_source_from_hint(str(getattr(target, 'inventory_source_hint', '') or ''))
|
||||
|
||||
|
||||
def _condition_value(condition: Any, *, task: Any, line: dict[str, Any] | None) -> Any:
|
||||
"""只读取冻结 Snapshot;履约路由不得回读动态 FieldValue。"""
|
||||
if condition.source_kind != 'order_field':
|
||||
@@ -232,14 +284,22 @@ def evaluate_inventory_source_rules(
|
||||
"""
|
||||
评估已发布规则并返回最高优先级的 Source 候选集合(冻结 Snapshot 路径)。
|
||||
|
||||
核心逻辑:行级评估先做库存源线索直连(冻结行 inventory_source_hint 列 → 精确/唯一后缀
|
||||
解析启用源,命中即 resolved,优先于包括预约单号兜底在内的全部规则层);未命中 fail-open
|
||||
落回规则层。任务级评估无线索语义,维持原行为。
|
||||
|
||||
Args:
|
||||
task: 已解析的货代任务(须有 order_snapshot_id)。
|
||||
line: 行级规则的订单行;任务级规则传 None。
|
||||
line: 行级规则的订单行;任务级规则传 None。须含 `_position`(`_task_routing_lines` 产物)。
|
||||
now: 测试可注入的评估时间,默认当前 UTC 时间。
|
||||
|
||||
Returns:
|
||||
InventoryRoutingResult: 含 status / source_codes / matched_rules / can_build。
|
||||
"""
|
||||
if line is not None:
|
||||
hint_code = _resolve_snapshot_line_source_hint(task=task, line=line)
|
||||
if hint_code:
|
||||
return _hint_routing_result(hint_code)
|
||||
scope = 'line' if line is not None else 'task'
|
||||
return _evaluate_with_reader(
|
||||
scope=scope,
|
||||
@@ -254,11 +314,15 @@ def evaluate_inventory_source_rules_for_field_values(
|
||||
line_field_values: dict[str, Any] | None = None,
|
||||
scope: str | None = None,
|
||||
now: datetime | None = None,
|
||||
line_source_hint: str | None = None,
|
||||
) -> InventoryRoutingResult:
|
||||
"""
|
||||
基于 field_id→值映射评估路由(建单前 Draft / 资格服务)。
|
||||
基于 field_id→值 映射评估路由(建单前 Draft / 资格评估)。
|
||||
|
||||
核心逻辑:未传 scope 时,有 line_field_values 则评 line,否则评 task;
|
||||
核心逻辑:行级评估先做库存源线索直连(调用方从 Draft 行取 `inventory_source_hint` 值
|
||||
传入;精确/唯一后缀解析启用源,命中即 resolved,优先于全部规则层);未命中 fail-open
|
||||
落回规则层。任务级评估(line_field_values=None)忽略线索,维持原行为。
|
||||
未传 scope 时,有 line_field_values 则评 line,否则评 task;
|
||||
不依赖 ShippingNotice / Snapshot,便于复核草稿阶段投影候选。
|
||||
|
||||
Args:
|
||||
@@ -266,6 +330,7 @@ def evaluate_inventory_source_rules_for_field_values(
|
||||
line_field_values: Line 字段值;行级规则必填。
|
||||
scope: 显式规则作用域 ``line`` / ``task``;缺省按是否有行值推断。
|
||||
now: 可选评估时间。
|
||||
line_source_hint: Draft 行的库存源线索原始值;任务级评估或不传时忽略。
|
||||
|
||||
Returns:
|
||||
InventoryRoutingResult。
|
||||
@@ -274,6 +339,10 @@ def evaluate_inventory_source_rules_for_field_values(
|
||||
resolved_scope = scope or ('line' if line_field_values is not None else 'task')
|
||||
if resolved_scope not in {'line', 'task'}:
|
||||
raise ValueError('inventory routing scope must be line or task')
|
||||
if resolved_scope == 'line':
|
||||
hint_code = _resolve_source_from_hint(line_source_hint or '')
|
||||
if hint_code:
|
||||
return _hint_routing_result(hint_code)
|
||||
line_values = dict(line_field_values or {}) if resolved_scope == 'line' else None
|
||||
return _evaluate_with_reader(
|
||||
scope=resolved_scope,
|
||||
|
||||
@@ -290,6 +290,8 @@ def project_line_inventory_candidates(
|
||||
header_field_values=header_ids,
|
||||
line_field_values=line_ids,
|
||||
scope='line',
|
||||
# [线索直连] Draft 行的库存源线索经引擎精确/唯一后缀解析启用源,命中即优先于全部规则层。
|
||||
line_source_hint=str(line_by_code.get('inventory_source_hint') or '').strip() or None,
|
||||
)
|
||||
task_result = evaluate_inventory_source_rules_for_field_values(
|
||||
header_field_values=header_ids,
|
||||
|
||||
@@ -118,7 +118,25 @@ def _order_snapshot_line_ids(notice: ShippingNotice) -> list[str]:
|
||||
return sorted(set(keys), key=lambda value: int(value))
|
||||
|
||||
|
||||
def editable_scope(order_task: ShippingNotice) -> dict[str, Any]:
|
||||
def _resolve_scope_notice(task: ShippingNotice | ShippingOrderTask) -> ShippingNotice | None:
|
||||
"""编辑窗身份归一:主通知原样返回;传入 OT 时按 order_task_id 反查任一同单通知。
|
||||
|
||||
产物(Export Artifact)与 Attempt 都挂在通知上——OT 身份直接参与谓词会因
|
||||
查不到产物而恒判可编辑(用户报告:Excel 已产生仍显示出单工具条)。
|
||||
"""
|
||||
task_id = getattr(task, 'id', None)
|
||||
if isinstance(task, ShippingNotice) or task_id is None:
|
||||
# 主通知原样返回;未落库的 OT 不可能有通知,视同"Excel 从未生成"。
|
||||
return task if isinstance(task, ShippingNotice) else None
|
||||
return (
|
||||
ShippingNotice.query
|
||||
.filter(ShippingNotice.order_task_id == int(task_id))
|
||||
.order_by(ShippingNotice.id.asc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def editable_scope(order_task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]:
|
||||
"""
|
||||
计算确认后订单的编辑窗矩阵(D10 / §3.1)。
|
||||
|
||||
@@ -127,20 +145,24 @@ def editable_scope(order_task: ShippingNotice) -> dict[str, Any]:
|
||||
行未入波次 → 无活动 Attempt(不受首单 Excel 限制)。
|
||||
|
||||
Args:
|
||||
order_task: 正式订单的主 ShippingNotice(含 order_task_id 可回读同订单全部通知)。
|
||||
order_task: 主 ShippingNotice 或正式 OT(OT 自动按 order_task_id 归一到主通知)。
|
||||
|
||||
Returns:
|
||||
dict: {'header': bool, 'lines': {snapshot_line_id: bool}},同构供 ui_state.edit_window 下发。
|
||||
"""
|
||||
notices = _order_notices(order_task)
|
||||
notice = _resolve_scope_notice(order_task)
|
||||
if notice is None:
|
||||
# 尚未产生任何通知(Excel 从未生成):无产物、无活动 Attempt,视为可编辑。
|
||||
return {'header': True, 'lines': {}}
|
||||
notices = _order_notices(notice)
|
||||
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))
|
||||
wave_notice_map = _wave_line_to_notice_map(_review_case_id_for_notice(notice))
|
||||
lines: dict[str, bool] = {}
|
||||
for snapshot_line_id in _order_snapshot_line_ids(order_task):
|
||||
for snapshot_line_id in _order_snapshot_line_ids(notice):
|
||||
wave_task_id = wave_notice_map.get(snapshot_line_id)
|
||||
if wave_task_id is None:
|
||||
# 未入波次行:不受首单 Excel 限制,仅受活动 Attempt 影响。
|
||||
|
||||
@@ -15,15 +15,21 @@ from typing import Any
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingOrderCandidate,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.candidate_qualification_service import (
|
||||
resolve_review_case_customer_resolved,
|
||||
)
|
||||
from app.services.shipping_notice.customer_resolution_service import confirm_customer_resolution
|
||||
from app.services.shipping_notice.customer_resolution_service import (
|
||||
confirm_customer_resolution,
|
||||
rebind_allowed_for_task,
|
||||
resolution_for_task,
|
||||
)
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
assert_case_is_current_workflow_version,
|
||||
)
|
||||
@@ -160,19 +166,45 @@ def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> di
|
||||
)
|
||||
)
|
||||
]
|
||||
# [STEP 2] 已确认(含改绑)后以确认结果与客户主数据为权威展示:识别候选显示在改绑后会 stale。
|
||||
confirmed_task = (
|
||||
db.session.get(ShippingOrderTask, int(case.confirmed_task_id))
|
||||
if getattr(case, 'confirmed_task_id', None) else None
|
||||
)
|
||||
resolution_row = resolution_for_task(confirmed_task) if confirmed_task is not None else None
|
||||
confirmed_customer_id = (
|
||||
getattr(resolution_row, 'confirmed_customer_id', None)
|
||||
if resolution_row is not None and resolution_row.status == 'confirmed'
|
||||
else (getattr(shadow, 'confirmed_customer_id', None) if shadow is not None else None)
|
||||
)
|
||||
confirmed_customer = (
|
||||
db.session.get(ShippingCustomer, int(confirmed_customer_id))
|
||||
if confirmed_customer_id else None
|
||||
)
|
||||
|
||||
return {
|
||||
'resolved': bool(resolved),
|
||||
'status': status,
|
||||
'role': 'customer',
|
||||
'extraction_id': int(extraction.id) if extraction is not None else None,
|
||||
'raw_name': None,
|
||||
'customer_id': getattr(shadow, 'confirmed_customer_id', None) or display_match.get('customer_id'),
|
||||
'standard_name': display_match.get('standard_name'),
|
||||
'short_code': display_match.get('short_code'),
|
||||
'customer_id': confirmed_customer_id or display_match.get('customer_id'),
|
||||
'standard_name': (
|
||||
confirmed_customer.standard_name if confirmed_customer is not None
|
||||
else display_match.get('standard_name')
|
||||
),
|
||||
'short_code': (
|
||||
confirmed_customer.short_code if confirmed_customer is not None
|
||||
else display_match.get('short_code')
|
||||
),
|
||||
'candidates': list(display_match.get('candidates') or []),
|
||||
'input_values': input_values,
|
||||
'evidence': evidence,
|
||||
'match': display_match,
|
||||
# 「修改客户」按钮谓词:仅已确认且无 Export Artifact/活动 Attempt 时可改绑(A 管控)。
|
||||
'rebind_allowed': (
|
||||
rebind_allowed_for_task(confirmed_task) if confirmed_task is not None else False
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -120,6 +120,7 @@ REVIEW_WORKBENCH_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'review_field_changed',
|
||||
'review_field_updated',
|
||||
'review_customer_confirmed',
|
||||
'review_customer_rebound',
|
||||
'review_duplicate_resolved',
|
||||
'review_conflict_resolved',
|
||||
'review_qualification_evaluated',
|
||||
|
||||
@@ -1162,6 +1162,13 @@ def _build_stage_context(
|
||||
}
|
||||
|
||||
|
||||
def _build_edit_window(task: ShippingNotice) -> dict[str, Any]:
|
||||
"""二期编辑窗(D10)谓词:header/lines 可编辑矩阵,工作台以此隐藏/禁用出单入口。"""
|
||||
from app.services.shipping_notice import order_edit_window_service as order_edit_window
|
||||
|
||||
return order_edit_window.editable_scope(task)
|
||||
|
||||
|
||||
def build_task_ui_state(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
@@ -1269,6 +1276,10 @@ def build_task_ui_state(
|
||||
)
|
||||
if include_stage_context else None
|
||||
)
|
||||
edit_window = (
|
||||
_build_edit_window(task)
|
||||
if include_stage_context else None
|
||||
)
|
||||
reason = None
|
||||
if isinstance(process_gate, dict) and process_gate.get("blocking_reason_code"):
|
||||
reason = {
|
||||
@@ -1290,6 +1301,9 @@ def build_task_ui_state(
|
||||
"actions": actions,
|
||||
# 仅正式详情按需返回的工作面只读事实;不产生状态、权限或动作。
|
||||
**({'stage_context': stage_context} if stage_context is not None else {}),
|
||||
# 二期编辑窗门控矩阵(无 Export Artifact 且无活动 Attempt 才可编辑);
|
||||
# 波次出单工具条与字段编辑守卫的数据源,禁止再次静默丢失。
|
||||
**({'edit_window': edit_window} if edit_window is not None else {}),
|
||||
"reason": reason,
|
||||
# OT 与 Notice 字段不完全同构:禁止硬读 Notice 专属列。
|
||||
"lifecycle_status": getattr(task, "lifecycle_status", None) or getattr(task, "status", None),
|
||||
|
||||
Reference in new issue
Block a user