fix(shipping-notice): 有效订单值视图贯通履约链并补全行结案豁免
- 新增 effective_order_view:冻结快照+人工修正按(行position×field_id)对位叠加,整行替换后行级叠加保守跳过 - 库存匹配(order_field_purposes)、Excel值(export)、通知行物化(notice_line_service.line_overrides)统一消费有效值 - 行结案close_unfulfillable端到端豁免:聚合/match_completed/整单建通知/滚动导出四处剔除结案行(含有库存结案行) - 结案决定落库后触发Gate重算(trigger=line_fulfillment_closed),对齐放行路径 - 兜底匹配分支切有效视图基线;全结案聚合口径与门禁一致(unfulfillable) - 预约门禁断言更新为有效视图契约;文档同步technical.md/funclist(含结案时序规约)
This commit is contained in:
1 parent
0333d713e0
commit
051f80e1e9
17 files changed
+2212
-43
No files matched your search
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
services/shipping_notice/effective_order_view.py
|
||||
|
||||
用途:向履约链提供「冻结快照 + 冻结后人工修正」的有效订单值视图。
|
||||
依赖:export.order_field_id_values(冻结投影)、ShippingOrderFieldValue/ShippingOrderLine/
|
||||
ShippingOrderTask/ShippingOrderSnapshot(修正事实与行对位)。
|
||||
逻辑:快照仍是审计锚点,本模块把当前 accepted Extraction 的 FieldValue 按(行 position × field_id)
|
||||
对位叠加到快照投影上,供库存匹配、Excel 导出与 Notice 行物化统一消费;整行替换(增删行)
|
||||
后 position 不再可比,行级叠加保守跳过(保持冻结值),由后续行集有效视图统一承接。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.export import order_field_id_values
|
||||
|
||||
|
||||
def _owner_task(task: Any) -> Any:
|
||||
"""与 export.order_field_id_values 同源的任务归属解析(Notice → OT;OT 原样返回)。"""
|
||||
order_task_id = getattr(task, 'order_task_id', None)
|
||||
if order_task_id:
|
||||
return db.session.get(ShippingOrderTask, order_task_id)
|
||||
return task
|
||||
|
||||
|
||||
def effective_order_field_values(task: Any) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
"""
|
||||
返回叠加了冻结后人工修正的订单 Header/Line 有效值(形状同 order_field_id_values)。
|
||||
|
||||
核心逻辑:以冻结快照为基线;当前 accepted Extraction 的 FieldValue 按(行 position ×
|
||||
field_id)对位覆盖。当前 Extraction 与快照 Extraction 不同(发生过整行替换)时跳过
|
||||
行级叠加,避免错位污染匹配键;单头值不受行替换影响,始终叠加最新已接受值。
|
||||
|
||||
Args:
|
||||
task: ShippingNotice 或 ShippingOrderTask。
|
||||
Returns:
|
||||
(header dict[field_id, value], lines list[dict[field_id, value]])。
|
||||
"""
|
||||
header, lines = order_field_id_values(task)
|
||||
owner = _owner_task(task)
|
||||
current_id = getattr(owner, 'current_order_extraction_id', None)
|
||||
if current_id is None:
|
||||
return header, lines
|
||||
snapshot = (
|
||||
db.session.get(ShippingOrderSnapshot, int(owner.order_snapshot_id))
|
||||
if getattr(owner, 'order_snapshot_id', None) else None
|
||||
)
|
||||
header = dict(header)
|
||||
lines = [dict(row) for row in lines]
|
||||
values = ShippingOrderFieldValue.query.filter_by(extraction_id=int(current_id)).all()
|
||||
# [STEP 1] 单头修正:整行替换会把单头决定复制到新 Extraction(见 task_order_field_editor),
|
||||
# 因此单头值始终以当前 Extraction 的已接受值为准。
|
||||
for item in values:
|
||||
if item.line_id is None:
|
||||
header[str(item.field_id)] = item.value_json
|
||||
# [STEP 2] 行级修正:仅在当前 Extraction 即冻结来源 Extraction 时按 position 对位。
|
||||
if snapshot is not None and int(current_id) == int(snapshot.extraction_id):
|
||||
position_by_line_id = {
|
||||
int(row.id): int(row.position)
|
||||
for row in ShippingOrderLine.query.filter_by(extraction_id=int(current_id)).all()
|
||||
}
|
||||
overlay_by_index: dict[int, dict[str, Any]] = {}
|
||||
for item in values:
|
||||
if item.line_id is None:
|
||||
continue
|
||||
index = position_by_line_id.get(int(item.line_id))
|
||||
if index is None:
|
||||
continue
|
||||
overlay_by_index.setdefault(index, {})[str(item.field_id)] = item.value_json
|
||||
for index, row in enumerate(lines):
|
||||
row.update(overlay_by_index.get(index, {}))
|
||||
return header, lines
|
||||
|
||||
|
||||
def _coerce_qty(value: Any) -> Decimal | None:
|
||||
"""把字段值安全转为数量;空/非法值返回 None。"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
try:
|
||||
return Decimal(str(value).replace(',', '').strip())
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def effective_line_facts_for_notice(owner: ShippingOrderTask) -> dict[int, dict[str, Any]]:
|
||||
"""
|
||||
按 snapshot_line_id 返回 Notice 行物化所需的有效事实(强类型键 + 完整字段值)。
|
||||
|
||||
核心逻辑:经 effective_order_field_values 取有效值后,按冻结履约规则的
|
||||
required_field_ids 把 part_number/reservation_id/qty 三个用途键解析为强类型事实;
|
||||
缺少规则映射时对应键为 None(由消费方回退冻结列)。
|
||||
|
||||
Args:
|
||||
owner: 已冻结订单的 ShippingOrderTask。
|
||||
Returns:
|
||||
{snapshot_line_id: {'part_number', 'reservation_id', 'qty', 'field_values'}}。
|
||||
Raises:
|
||||
ValueError: 任务没有冻结快照。
|
||||
"""
|
||||
snapshot = (
|
||||
db.session.get(ShippingOrderSnapshot, int(owner.order_snapshot_id))
|
||||
if getattr(owner, 'order_snapshot_id', None) else None
|
||||
)
|
||||
if snapshot is None:
|
||||
raise ValueError('任务没有可用于通知行物化的冻结订单快照')
|
||||
_header, lines = effective_order_field_values(owner)
|
||||
required_ids = (snapshot.rule_versions_json or {}).get('fulfillment_rule', {}).get('required_field_ids')
|
||||
required_ids = required_ids if isinstance(required_ids, dict) else {}
|
||||
part_fid = str(required_ids.get('part_number') or '')
|
||||
rsv_fid = str(required_ids.get('reservation_id') or '')
|
||||
qty_fid = str(required_ids.get('qty') or '')
|
||||
facts: dict[int, dict[str, Any]] = {}
|
||||
for line_orm, values in zip(snapshot.lines, lines, strict=True):
|
||||
facts[int(line_orm.id)] = {
|
||||
'part_number': values.get(part_fid) if part_fid else None,
|
||||
'reservation_id': values.get(rsv_fid) if rsv_fid else None,
|
||||
'qty': _coerce_qty(values.get(qty_fid)) if qty_fid else None,
|
||||
'field_values': dict(values),
|
||||
}
|
||||
return facts
|
||||
@@ -142,7 +142,10 @@ def _source_notice_for_order_facts(notice: ShippingNotice) -> ShippingNotice:
|
||||
|
||||
|
||||
def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
"""从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。"""
|
||||
"""从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。
|
||||
|
||||
库存匹配/Excel 消费方应改用 effective_order_view.effective_order_field_values 获取含冻结后修正的有效值。
|
||||
"""
|
||||
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
|
||||
assert_task_not_supersession_blocked(task)
|
||||
owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task
|
||||
@@ -779,7 +782,8 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
|
||||
if snapshot is None:
|
||||
raise ValueError('任务没有可用于导出的冻结订单快照')
|
||||
header_values, all_line_values = order_field_id_values(task)
|
||||
from app.services.shipping_notice.effective_order_view import effective_order_field_values
|
||||
header_values, all_line_values = effective_order_field_values(task)
|
||||
profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {}
|
||||
match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else []
|
||||
line_inventory_fields = _inventory_fields_by_mode(mappings, 'line')
|
||||
@@ -814,6 +818,26 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
for source_index, line in enumerate(snapshot.lines)
|
||||
if source_index in release_overrides_by_source_line
|
||||
}
|
||||
# [STEP 1] 已结案(close_unfulfillable)行不再有履约要求:即使预约仍有库存,
|
||||
# 也必须从滚动导出资格中剔除(与上方放行查询同源同口径:只认活动决定)。
|
||||
closed_snapshot_line_ids = set()
|
||||
if source_notice.id is not None:
|
||||
closed_rows = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
|
||||
)
|
||||
.all()
|
||||
)
|
||||
closed_snapshot_line_ids = {
|
||||
int(snapshot.lines[int(decision.line_index)].id)
|
||||
for decision in closed_rows
|
||||
if decision.line_index is not None
|
||||
and 0 <= int(decision.line_index) < len(snapshot.lines)
|
||||
}
|
||||
selected_snapshot_line_ids = {
|
||||
int(row.snapshot_line_id)
|
||||
for row in ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).all()
|
||||
@@ -824,6 +848,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
source_notice,
|
||||
released_snapshot_line_ids=released_snapshot_line_ids,
|
||||
selected_snapshot_line_ids=selected_snapshot_line_ids or None,
|
||||
closed_snapshot_line_ids=closed_snapshot_line_ids,
|
||||
)
|
||||
except ConflictError:
|
||||
raise
|
||||
|
||||
@@ -718,12 +718,47 @@ def _released_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]:
|
||||
}
|
||||
|
||||
|
||||
def _closed_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]:
|
||||
"""读取当前任务已结案(close_unfulfillable)的冻结行 ID,供满足性与聚合豁免共用。
|
||||
|
||||
核心逻辑:与 ``_released_snapshot_line_ids_for_task`` 同源同口径——只认活动决定,
|
||||
经 line_index 映射快照行;结案行不再是履约要求,在满足性/建单/导出各处按豁免处理。
|
||||
"""
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
|
||||
if task.id is None:
|
||||
return set()
|
||||
if not getattr(task, 'order_snapshot_id', None):
|
||||
return set()
|
||||
decisions = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
|
||||
)
|
||||
.all()
|
||||
)
|
||||
from app.models import ShippingOrderSnapshot
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
|
||||
if snapshot is None:
|
||||
return set()
|
||||
return {
|
||||
int(snapshot.lines[int(row.line_index)].id)
|
||||
for row in decisions
|
||||
if row.line_index is not None
|
||||
and 0 <= int(row.line_index) < len(snapshot.lines)
|
||||
}
|
||||
|
||||
|
||||
def match_completed(task: ShippingNotice) -> bool:
|
||||
"""
|
||||
STP 整单满足性门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时通过。
|
||||
|
||||
核心逻辑:该函数只代表整单满足性,不代表滚动 Excel 是否存在可导出行。
|
||||
已人工放行的短缺行视同满足(与 ``_recompute_task_match_aggregate`` 同源)。
|
||||
已人工放行的短缺行视同满足;已结案(close_unfulfillable)行不再是履约要求,
|
||||
从覆盖校验与逐行判定中双重豁免;全部行结案时无剩余履约内容,按不通过处理。
|
||||
"""
|
||||
from app.models import ShippingNoticeLineInventoryMatch
|
||||
|
||||
@@ -738,17 +773,23 @@ def match_completed(task: ShippingNotice) -> bool:
|
||||
db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
|
||||
if getattr(task, 'order_snapshot_id', None) else None
|
||||
)
|
||||
expected_line_ids = {int(line.id) for line in getattr(snapshot, 'lines', []) or []}
|
||||
closed_ids = _closed_snapshot_line_ids_for_task(task)
|
||||
expected_line_ids = {int(line.id) for line in getattr(snapshot, 'lines', []) or []} - closed_ids
|
||||
if not expected_line_ids:
|
||||
# 全部行已结案:订单无剩余履约内容,不得自动进入建通知/Excel(应走作废流程)。
|
||||
return False
|
||||
current_line_ids = {
|
||||
int(row.snapshot_line_id)
|
||||
for row in rows
|
||||
if getattr(row, 'snapshot_line_id', None) is not None
|
||||
}
|
||||
# 满足性必须覆盖冻结订单的全部项次;仅有部分当前 Match 不能代表整单可履约。
|
||||
if expected_line_ids and current_line_ids != expected_line_ids:
|
||||
} - closed_ids
|
||||
# 满足性必须覆盖剩余待履约的全部项次;仅有部分当前 Match 不能代表整单可履约。
|
||||
if current_line_ids != expected_line_ids:
|
||||
return False
|
||||
released_ids = _released_snapshot_line_ids_for_task(task)
|
||||
for row in rows:
|
||||
if getattr(row, 'snapshot_line_id', None) is not None and int(row.snapshot_line_id) in closed_ids:
|
||||
continue
|
||||
result = str(row.match_result or '').strip()
|
||||
shortage = _line_shortage_qty(getattr(row, 'shortage_qty', None))
|
||||
if result == 'matched' and shortage <= 0:
|
||||
@@ -823,6 +864,7 @@ def exportable_snapshot_line_ids(task: ShippingNotice) -> set[int]:
|
||||
_verification, line_ids = current_available_snapshot_line_ids(
|
||||
_source_notice_for_order_facts(task),
|
||||
released_snapshot_line_ids=_released_snapshot_line_ids_for_export(task),
|
||||
closed_snapshot_line_ids=_closed_snapshot_line_ids_for_task(task),
|
||||
)
|
||||
except ConflictError:
|
||||
return set()
|
||||
@@ -1344,6 +1386,8 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
|
||||
核心逻辑:与 ``match_completed`` 同款放行语义——已人工放行(release_inventory_shortage)
|
||||
且仍有缺口的行视同满足,不再计入 has_block/缺货;否则会与 Excel 门禁分裂,
|
||||
出现"Gate 认为满足、任务却仍标 unfulfillable"的矛盾。
|
||||
已结案(close_unfulfillable)行不再是履约要求:不阻断、不进缺货列表,
|
||||
但也不计入满足(结案行非可履约内容),全结案 ⇒ unfulfillable,与 match_completed 口径一致。
|
||||
"""
|
||||
rows = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
@@ -1353,6 +1397,7 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
|
||||
if not rows:
|
||||
return 'unfulfillable', []
|
||||
released_snapshot_line_ids = _released_snapshot_line_ids_for_task(task)
|
||||
closed_snapshot_line_ids = _closed_snapshot_line_ids_for_task(task)
|
||||
has_ok = False
|
||||
has_block = False
|
||||
shortages: list[dict[str, Any]] = []
|
||||
@@ -1378,7 +1423,12 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
|
||||
# 已审计放行的短缺行视同满足:不阻断、不进入缺货列表。
|
||||
shortage = _line_shortage_qty(shortage_qty)
|
||||
released = entry['snapshot_line_id'] in released_snapshot_line_ids
|
||||
if match_result == 'matched' and shortage <= 0:
|
||||
closed = entry['snapshot_line_id'] in closed_snapshot_line_ids
|
||||
if closed:
|
||||
# [BE-结案-豁免] 结案行不再是履约要求:不阻断、不进缺货列表,
|
||||
# 但也不计入满足(非可履约内容);全结案 ⇒ 无可履约内容 ⇒ unfulfillable。
|
||||
entry['line_status'] = 'closed'
|
||||
elif match_result == 'matched' and shortage <= 0:
|
||||
entry['line_status'] = 'ok'
|
||||
has_ok = True
|
||||
elif released and shortage > 0:
|
||||
@@ -1390,21 +1440,25 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
|
||||
has_block = True
|
||||
shortages.append(entry)
|
||||
line_results.append(entry)
|
||||
owner = _workflow_owner(task)
|
||||
if hasattr(owner, 'step_payload_json'):
|
||||
payload = dict(owner.step_payload_json or {})
|
||||
payload['current_match_projection'] = {
|
||||
'match_status': 'partial' if has_block and has_ok else ('unfulfillable' if has_block else 'fulfillable'),
|
||||
'line_results': line_results,
|
||||
'shortage': {'lines': shortages},
|
||||
}
|
||||
owner.step_payload_json = payload
|
||||
# 结案行既不计满足也不阻断:无 ok 且无 block(如全结案)时无可履约内容 ⇒ unfulfillable,
|
||||
# 与 match_completed 的整单口径保持一致,避免 Gate 同步误判满足后空转编排。
|
||||
if has_block and has_ok:
|
||||
status = 'partial'
|
||||
elif has_block:
|
||||
status = 'unfulfillable'
|
||||
else:
|
||||
elif has_ok:
|
||||
status = 'fulfillable'
|
||||
else:
|
||||
status = 'unfulfillable'
|
||||
owner = _workflow_owner(task)
|
||||
if hasattr(owner, 'step_payload_json'):
|
||||
payload = dict(owner.step_payload_json or {})
|
||||
payload['current_match_projection'] = {
|
||||
'match_status': status,
|
||||
'line_results': line_results,
|
||||
'shortage': {'lines': shortages},
|
||||
}
|
||||
owner.step_payload_json = payload
|
||||
return status, shortages
|
||||
|
||||
|
||||
@@ -1615,7 +1669,11 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if lang:
|
||||
inv_payload["lang"] = lang
|
||||
return ensure_inventory(inv_payload)
|
||||
_order_header_values, order_field_lines = order_field_id_values(task)
|
||||
# [STEP 2] 兜底匹配基线读取有效视图(冻结快照 + 冻结后人工修正):
|
||||
# 匹配身份键(料号/预约等字段值)必须与展示值(__required_qty/__display_part_number)
|
||||
# 同源,否则出现"按冻结料号匹配、却展示有效料号"的混合投影。
|
||||
from app.services.shipping_notice.effective_order_view import effective_order_field_values
|
||||
_order_header_values, order_field_lines = effective_order_field_values(task)
|
||||
purpose_lines = task_line_purpose_values(task, required={'part_number', 'quantity', 'reservation_id'})
|
||||
for index, order_line in enumerate(order_field_lines):
|
||||
purpose_line = purpose_lines[index] if index < len(purpose_lines) else {}
|
||||
@@ -2039,6 +2097,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
_verification, available_line_ids = current_available_snapshot_line_ids(
|
||||
_source_notice_for_order_facts(task),
|
||||
closed_snapshot_line_ids=_closed_snapshot_line_ids_for_task(task),
|
||||
)
|
||||
except ConflictError:
|
||||
available_line_ids = set()
|
||||
|
||||
@@ -21,6 +21,7 @@ def replace_notice_lines_from_snapshot(
|
||||
snapshot: ShippingOrderSnapshot,
|
||||
snapshot_line_ids: set[int] | None = None,
|
||||
inventory_facts_by_snapshot_line_id: dict[int, dict[str, Any]] | None = None,
|
||||
line_overrides: dict[int, dict[str, Any]] | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
用 Snapshot 行替换指定 Notice 的 shipping_notice_lines。
|
||||
@@ -29,6 +30,10 @@ def replace_notice_lines_from_snapshot(
|
||||
notice_id: shipping_notices.id。
|
||||
snapshot: 已 flush 且带 lines 的 Snapshot。
|
||||
snapshot_line_ids: 仅写入本次发货通知选中的冻结行;为空时兼容整单冻结。
|
||||
inventory_facts_by_snapshot_line_id: 行级库存事实(来源/文件/仓库)。
|
||||
line_overrides: effective_order_view.effective_line_facts_for_notice 的输出,
|
||||
按 snapshot_line_id 携带冻结后人工修正;仅非 None 值覆盖快照列,
|
||||
缺失或 None 时回退冻结快照值。
|
||||
|
||||
Returns:
|
||||
写入行数。
|
||||
@@ -44,6 +49,7 @@ def replace_notice_lines_from_snapshot(
|
||||
continue
|
||||
notice_position += 1
|
||||
inventory_facts = dict(inventory_facts_by_snapshot_line_id.get(int(line.id)) or {})
|
||||
override = (line_overrides or {}).get(int(line.id)) or {}
|
||||
rows.append(
|
||||
ShippingNoticeLine(
|
||||
notice_id=int(notice_id),
|
||||
@@ -51,13 +57,17 @@ def replace_notice_lines_from_snapshot(
|
||||
position=notice_position - 1,
|
||||
# 发货通知项次按当前通知单重新从 1 编排。
|
||||
line_no=notice_position,
|
||||
part_number=getattr(line, 'part_number', None),
|
||||
reservation_id=getattr(line, 'reservation_id', None),
|
||||
required_qty=getattr(line, 'qty', None),
|
||||
part_number=override.get('part_number')
|
||||
if override.get('part_number') is not None else getattr(line, 'part_number', None),
|
||||
reservation_id=override.get('reservation_id')
|
||||
if override.get('reservation_id') is not None else getattr(line, 'reservation_id', None),
|
||||
required_qty=override.get('qty')
|
||||
if override.get('qty') is not None else getattr(line, 'qty', None),
|
||||
inventory_source_code=inventory_facts.get('inventory_source_code'),
|
||||
inventory_file_id=inventory_facts.get('inventory_file_id'),
|
||||
inventory_warehouse_id=inventory_facts.get('inventory_warehouse_id'),
|
||||
field_values_json=dict(getattr(line, 'field_values_json', None) or {}),
|
||||
field_values_json=dict(override['field_values'])
|
||||
if override.get('field_values') else dict(getattr(line, 'field_values_json', None) or {}),
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/order_field_purposes.py
|
||||
|
||||
用途:将冻结订单 Snapshot 按冻结货代策略能力投影给履约链。
|
||||
依赖:冻结履约策略、export.order_field_id_values、ShippingNotice。
|
||||
依赖:冻结履约策略、effective_order_view.effective_order_field_values、ShippingNotice。
|
||||
逻辑:路由、门禁、匹配和展示只通过固定规则冻结的 stable field_id 定位字段,禁止读取 Schema business_purpose 或任务行固定列。
|
||||
"""
|
||||
|
||||
@@ -12,7 +12,8 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingOrderSnapshot, ShippingNotice
|
||||
from app.services.shipping_notice.export import _source_notice_for_order_facts, order_field_id_values
|
||||
from app.services.shipping_notice.effective_order_view import effective_order_field_values
|
||||
from app.services.shipping_notice.export import _source_notice_for_order_facts
|
||||
|
||||
|
||||
_PURPOSE_BY_CAPABILITY = {
|
||||
@@ -47,9 +48,9 @@ def task_line_purpose_field_ids(task: ShippingNotice, *, required: set[str] | No
|
||||
|
||||
|
||||
def task_line_purpose_values(task: ShippingNotice, *, required: set[str] | None = None) -> list[dict[str, Any]]:
|
||||
"""按订单行位置返回用途键值,值只来自冻结 Snapshot。"""
|
||||
"""按订单行位置返回用途键值,值来自冻结 Snapshot 叠加冻结后人工修正的有效视图(effective_order_view)。"""
|
||||
purpose_ids = task_line_purpose_field_ids(task, required=required)
|
||||
_header, lines = order_field_id_values(task)
|
||||
_header, lines = effective_order_field_values(task)
|
||||
return [
|
||||
{purpose: line.get(field_id) for purpose, field_id in purpose_ids.items()}
|
||||
for line in lines
|
||||
|
||||
@@ -426,12 +426,20 @@ def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[s
|
||||
]
|
||||
|
||||
|
||||
def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, actor_id: int) -> None:
|
||||
def _sync_confirmed_task_fulfillment_gates(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
actor_id: int,
|
||||
trigger: str = 'inventory_shortage_released',
|
||||
) -> None:
|
||||
"""
|
||||
短缺放行后同步正式 OT Gate,并异步触发唯一明细的独立 Notice/Excel 创建。
|
||||
短缺放行/行结案后同步正式 OT Gate,并异步触发唯一明细的独立 Notice/Excel 创建。
|
||||
|
||||
核心逻辑:Gate 重投影不改写库存事实;复用既有 auto-fulfill Job,由 Job 再判断
|
||||
是否恰好只有一条开放且可履约的明细。多条明细不会自动合并,仍由用户勾选创建 wave。
|
||||
|
||||
Args:
|
||||
trigger: 编排触发标签(放行 inventory_shortage_released / 结案 line_fulfillment_closed)。
|
||||
"""
|
||||
task_id = getattr(case, 'confirmed_task_id', None)
|
||||
if task_id is None:
|
||||
@@ -469,7 +477,7 @@ def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, act
|
||||
|
||||
submit_auto_progress(
|
||||
task=task,
|
||||
trigger='inventory_shortage_released',
|
||||
trigger=trigger,
|
||||
operator_id=actor_id,
|
||||
commit=False,
|
||||
)
|
||||
@@ -480,7 +488,7 @@ def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, act
|
||||
|
||||
enqueue_post_ot_auto_fulfill_job(
|
||||
task_no=str(task.task_no),
|
||||
trigger='inventory_shortage_released',
|
||||
trigger=trigger,
|
||||
commit=False,
|
||||
)
|
||||
|
||||
@@ -1239,8 +1247,13 @@ def decide_review_line_fulfillment(
|
||||
db.session.add(row)
|
||||
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
|
||||
db.session.flush()
|
||||
if code == DECISION_RELEASE_SHORTAGE:
|
||||
_sync_confirmed_task_fulfillment_gates(case=case, actor_id=int(user_id))
|
||||
if code in {DECISION_RELEASE_SHORTAGE, DECISION_CLOSE}:
|
||||
# [BE-结案-豁免] 结案与放行同为库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
|
||||
_sync_confirmed_task_fulfillment_gates(
|
||||
case=case,
|
||||
actor_id=int(user_id),
|
||||
trigger='inventory_shortage_released' if code == DECISION_RELEASE_SHORTAGE else 'line_fulfillment_closed',
|
||||
)
|
||||
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
|
||||
@@ -277,6 +277,7 @@ def current_available_snapshot_line_ids(
|
||||
*,
|
||||
released_snapshot_line_ids: set[int] | None = None,
|
||||
selected_snapshot_line_ids: set[int] | None = None,
|
||||
closed_snapshot_line_ids: set[int] | None = None,
|
||||
) -> tuple[ShippingInventoryVerification, set[int]]:
|
||||
"""
|
||||
取得最新核验中可导出的冻结订单行。
|
||||
@@ -288,6 +289,7 @@ def current_available_snapshot_line_ids(
|
||||
task: 当前正式发货任务。
|
||||
released_snapshot_line_ids: 已审计短缺放行对应的冻结订单行 ID 集合。
|
||||
selected_snapshot_line_ids: 独立通知已固化的冻结行 ID;提供时仅返回该集合。
|
||||
closed_snapshot_line_ids: 已结案冻结行 ID;无论库存状态一律从可导出集合剔除。
|
||||
|
||||
Returns:
|
||||
(最新核验轮次, 本次可导出的冻结订单行 ID)。
|
||||
@@ -323,10 +325,11 @@ def current_available_snapshot_line_ids(
|
||||
ShippingReservation.status.in_({'available', 'pending'}),
|
||||
).all() if reservation_ids else []
|
||||
selected_ids = {int(item) for item in (selected_snapshot_line_ids or set())}
|
||||
closed_ids = {int(item) for item in (closed_snapshot_line_ids or set())}
|
||||
line_ids = {
|
||||
item.snapshot_line_id for item in reservations
|
||||
if not selected_ids or int(item.snapshot_line_id) in selected_ids
|
||||
}
|
||||
} - closed_ids
|
||||
if not line_ids:
|
||||
raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY')
|
||||
return verification, line_ids
|
||||
|
||||
@@ -18,6 +18,7 @@ from app.models import (
|
||||
ShippingOrderTask,
|
||||
ShippingOrderSnapshot,
|
||||
)
|
||||
from app.services.shipping_notice.effective_order_view import effective_line_facts_for_notice
|
||||
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
|
||||
|
||||
@@ -34,6 +35,10 @@ def create_shipping_notice_after_inventory_gate(
|
||||
【触发时机】:库存准备成功、所有目标订单行匹配成功或已人工放行,且即将生成 Excel 时。
|
||||
不得在接收解析或订单复核确认阶段调用。
|
||||
|
||||
核心逻辑:通知行物化使用 effective_order_view 的有效行事实,携带冻结后人工修正值。
|
||||
已结案(close_unfulfillable)行从目标行集剔除,不参与门禁也不写入通知行;
|
||||
全部行结案时 target_ids 为空仍按门禁未通过拒绝。
|
||||
|
||||
Args:
|
||||
order_task: 已冻结订单快照的 OT。
|
||||
snapshot_line_ids: 可选的本次通知行集合;为空表示整单。
|
||||
@@ -87,10 +92,15 @@ def create_shipping_notice_after_inventory_gate(
|
||||
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
|
||||
from app.services.shipping_notice.fulfillment_workflow import (
|
||||
_closed_snapshot_line_ids_for_task,
|
||||
_released_snapshot_line_ids_for_task,
|
||||
)
|
||||
released_ids = _released_snapshot_line_ids_for_task(order_task)
|
||||
# [BE-结案-豁免] 结案行不再是履约要求:从目标行集剔除,不参与门禁、不物化为通知行。
|
||||
closed_ids = _closed_snapshot_line_ids_for_task(order_task)
|
||||
target_ids = (selected_ids or {int(line.id) for line in snapshot.lines}) - closed_ids
|
||||
if not target_ids or any(
|
||||
int(line_id) not in by_line
|
||||
or (
|
||||
@@ -154,7 +164,9 @@ def create_shipping_notice_after_inventory_gate(
|
||||
replace_notice_lines_from_snapshot(
|
||||
notice_id=int(notice.id),
|
||||
snapshot=snapshot,
|
||||
snapshot_line_ids=selected_ids,
|
||||
# [BE-结案-豁免] 物化行集必须与门禁通过的 target_ids 一致:结案行不写入通知行。
|
||||
snapshot_line_ids=target_ids,
|
||||
inventory_facts_by_snapshot_line_id=inventory_facts_by_snapshot_line_id,
|
||||
line_overrides=effective_line_facts_for_notice(order_task),
|
||||
)
|
||||
return notice
|
||||
Reference in new issue
Block a user