fix(shipping-notice): 打通短缺放行链路的证据读点、决策码迁移与整单放行导出

生产实证(OT-20261027-4BD4CEFF):料号兜底自动放行不触发的根因是 s18 改名
漏迁移放行证据读点,getattr(source,'parsing_profile') 恒 None,致自动/人工
放行全部静默失败。三段修复:

1. 放行证据解析改读 source.onhand_report_config.parsing_profile
   (与 require_source_profile 同口径)。
2. 补批次 S 漏网迁移 s20a1b2c3d4e:复核行决策码 inventory→onhand 值替换,
   重建 ck_shipping_review_line_decisions_code(dev 往返验证后已应用 prod)。
3. 导出链回链 OT:_notice_source_code/_notice_inventory_file_id 纳入已审计
   放行行事实(整单放行不再报「库存源不存在」/丢证据快照);
   prepare_export_match_inputs 放行/结案决定 join 按 confirmed_task_id(OT) 回链。

回归:test_export_released_shortage_only_notice_resolves_source_and_rows
(先红后绿)等 117 项全绿。
This commit is contained in:
hugo committed 2026-10-27 16:07:41 +08:00
1 parent 440afe097f
commit f5611d6783
4 files changed
+222 -15

No files matched your search

+58 -10
View File
@@ -46,26 +46,56 @@ from app.path_utils import resolve_backend_relative_path
from app.services.file_assets.storage import file_asset_storage
def _released_line_indexes_for_task(order_task_id: int) -> set[int]:
"""按正式 OT 身份读取已审计短缺放行的行号集合(复核 Case 的 confirmed_task_id 恒为 OT id)。"""
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
rows = (
ShippingOrderReviewLineDecision.query
.join(
ShippingOrderReviewCase,
ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id,
)
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(order_task_id),
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage',
ShippingOrderReviewLineDecision.line_index.isnot(None),
)
.all()
)
return {int(row.line_index) for row in rows}
def _notice_source_code(task: ShippingNotice) -> str | None:
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。
匹配事实的 task_id 挂在正式 OT 上:传 Notice 时取 order_task_id,
传 OT 本身时取 id(整单 ODM 候选投影会在物化前以 OT 调用)。
已审计短缺放行行(release_onhand_shortage)的 match_result 恒为 not_found
(如预约键 0 命中的料号兜底行),其事实源码与 matched 行同票参与唯一性
裁决;只按 matched 过滤会让「整单放行」的单永远解析不到库存源
(回归 OT-20261027-4BD4CEFF)。
"""
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
if task_id is None:
return None
task_id = int(task_id)
released_line_indexes = _released_line_indexes_for_task(task_id)
codes = [
str(row[0]).strip().upper()
for row in db.session.query(ShippingNoticeLineOnhandMatch.source_code).filter(
for row in db.session.query(
ShippingNoticeLineOnhandMatch.source_code,
ShippingNoticeLineOnhandMatch.match_result,
ShippingNoticeLineOnhandMatch.line_index,
).filter(
ShippingNoticeLineOnhandMatch.task_id == task_id,
ShippingNoticeLineOnhandMatch.is_current.is_(True),
ShippingNoticeLineOnhandMatch.match_result == 'matched',
ShippingNoticeLineOnhandMatch.source_code.isnot(None),
).distinct().all()
if row[0]
).all()
if row[0] and (row[1] == 'matched' or (row[2] is not None and int(row[2]) in released_line_indexes))
]
codes = list(dict.fromkeys(codes))
return codes[0] if len(codes) == 1 else None
@@ -87,19 +117,31 @@ def _notice_chosen_odm(task: ShippingNotice) -> str | None:
def _notice_inventory_file_id(task: ShippingNotice) -> int | None:
"""从 Notice 行级匹配读取本次导出的唯一库存文件。"""
"""从 Notice 行级匹配读取本次导出的唯一库存文件。
已审计短缺放行行(not_found 事实)的证据快照与 matched 行同票:整单放行时
库存证据文件仍必须落 Artifact 审计,否则证据流断链(回归 OT-20261027-4BD4CEFF)。
"""
task_id = getattr(task, 'order_task_id', None)
if task_id is None:
return None
task_id = int(task_id)
released_line_indexes = _released_line_indexes_for_task(task_id)
ids = [
int(row[0]) for row in db.session.query(ShippingNoticeLineOnhandMatch.onhand_snapshot_id).filter(
int(row[0]) for row in db.session.query(
ShippingNoticeLineOnhandMatch.onhand_snapshot_id,
ShippingNoticeLineOnhandMatch.match_result,
ShippingNoticeLineOnhandMatch.line_index,
).filter(
ShippingNoticeLineOnhandMatch.task_id == task_id,
ShippingNoticeLineOnhandMatch.is_current.is_(True),
ShippingNoticeLineOnhandMatch.match_result == 'matched',
ShippingNoticeLineOnhandMatch.onhand_snapshot_id.isnot(None),
).distinct().all()
).all()
if row[0] is not None and (
row[1] == 'matched' or (row[2] is not None and int(row[2]) in released_line_indexes)
)
]
ids = list(dict.fromkeys(ids))
return ids[0] if len(ids) == 1 else None
@@ -799,8 +841,14 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
header_inventory_fields = _inventory_fields_by_mode(mappings, 'header')
# [STEP 1] 短缺放行的人工字段仅从该行的活动决定审计快照读取,
# 只能补模板行级库存字段,不能污染快照或任务级库存输入。
# [身份口径] 复核 Case.confirmed_task_id 恒为正式 OT id;本函数入参可能是
# 换绑后的 Notice,必须经 order_task_id 回链 OT,否则放行/结案决定恒查空,
# 放行行进不了导出资格、结案行漏剔除(与 _facts_order_task 同款键位纪律)。
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
order_task_id_for_decisions = int(
getattr(source_notice, 'order_task_id', None) or source_notice.id
)
release_overrides_by_source_line: dict[int, dict[str, Any]] = {}
released_source_line_indexes: set[int] = set()
if source_notice.id is not None:
@@ -808,7 +856,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
ShippingOrderReviewLineDecision.query
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
ShippingOrderReviewCase.confirmed_task_id == order_task_id_for_decisions,
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage',
)
@@ -835,7 +883,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
ShippingOrderReviewLineDecision.query
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
ShippingOrderReviewCase.confirmed_task_id == order_task_id_for_decisions,
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
)
@@ -414,7 +414,11 @@ def _shortage_release_required_fields(
source_code=resolved_source_code, enabled=True,
).first()
template = getattr(source, 'excel_template', None) if source is not None else None
profile = getattr(source, 'parsing_profile', None) if source is not None else None
# [s18 改名] 解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系
# (与 freight_rpa.parsing_profile.require_source_profile 同口径);
# 站点行 getattr 读法会静默得 None,曾致短缺放行(自动+人工)全部失败。
release_config = getattr(source, 'onhand_report_config', None) if source is not None else None
profile = release_config.parsing_profile if release_config is not None else None
if template is None or profile is None:
raise ConflictError(
'Inventory source export template is unavailable',
@@ -0,0 +1,75 @@
"""
migrations/versions/s20a1b2c3d4e_review_line_decision_code_rename.py
用途:批次 S 漏网补丁——复核行决定表的决策码迁移。
s17b(表改名)/s17c(枚举数据替换)/s18 均未覆盖
shipping_order_review_line_decisions.decision_code:旧码数据不搬、
ck_shipping_review_line_decisions_code 不重建,导致新代码写入
release_onhand_shortage / wait_onhand 时撞 prod 旧 CHECK
(IntegrityError,自动放行被吞、人工放行报错)。
依赖:alembic.op、SQLAlchemy;down_revision 为 mh23e4f5a6b7(现仓库唯一 head)。
逻辑:先 drop 旧 CHECK(否则新码 UPDATE 直接违约),再做两次精确值替换
(release_inventory_shortage→release_onhand_shortage、
wait_inventory→wait_onhand,其余码不变),最后按
models/shipping_order_review_line_decision.py 的现行码集重建同名 CHECK。
line_status 的 CHECK 已是新集(released_shortage 早已在列),本迁移不动。
snapshot_json 内的历史码是审计快照,按不可变原则不改写。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "s20a1b2c3d4e"
down_revision = "mh23e4f5a6b7"
branch_labels = None
depends_on = None
_TABLE = "shipping_order_review_line_decisions"
_CHECK = "ck_shipping_review_line_decisions_code"
# 与模型 CheckConstraint 逐字一致的新码集(升级方向)
_NEW_CODES = (
"'wait_onhand', 'use_new_inventory_file', 'change_inventory_source', "
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_onhand_shortage'"
)
# hg1i2j3k4l5m 时的旧码集(降级方向)
_OLD_CODES = (
"'wait_inventory', 'use_new_inventory_file', 'change_inventory_source', "
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_inventory_shortage'"
)
# 旧码 → 新码(词根 inventory→onhand 的两个改名对;升级方向)
_UPDATES_UP: tuple[tuple[str, str], ...] = (
("release_inventory_shortage", "release_onhand_shortage"),
("wait_inventory", "wait_onhand"),
)
def upgrade() -> None:
# [STEP 1] 先摘旧 CHECK:旧码集不含新码,先改值必违约。
op.drop_constraint(_CHECK, _TABLE, type_="check")
# [STEP 2] 精确值替换(只碰两个改名对,其余决策码保持原值)。
for old, new in _UPDATES_UP:
op.execute(
sa.text(
f"UPDATE {_TABLE} SET decision_code = :new WHERE decision_code = :old"
).bindparams(old=old, new=new)
)
# [STEP 3] 按模型现行码集重建同名 CHECK。
op.create_check_constraint(_CHECK, _TABLE, f"decision_code IN ({_NEW_CODES})")
def downgrade() -> None:
# [STEP 1] 先摘新 CHECK,再把新码精确换回旧码。
op.drop_constraint(_CHECK, _TABLE, type_="check")
for old, new in _UPDATES_UP:
op.execute(
sa.text(
f"UPDATE {_TABLE} SET decision_code = :old WHERE decision_code = :new"
).bindparams(old=old, new=new)
)
# [STEP 2] 恢复旧码集 CHECK。
op.create_check_constraint(_CHECK, _TABLE, f"decision_code IN ({_OLD_CODES})")
+84 -4
View File
@@ -142,7 +142,7 @@ def _freeze_export_snapshot(
def _materialize_export_notice(
*, ot: ShippingOrderTask, snapshot: ShippingOrderSnapshot, inventory_file: FreightRpaOnhandReportFile,
source_code: str, notice_no: str,
source_code: str, notice_no: str, match_result: str = 'matched',
) -> ShippingNotice:
"""从 OT 的冻结快照构造正式 Notice、NoticeLine、匹配事实与活动库存链接。
@@ -168,7 +168,8 @@ def _materialize_export_notice(
for line in snapshot.lines:
db.session.add(ShippingNoticeLineOnhandMatch(
task_id=ot.id, snapshot_line_id=line.id, line_no=line.line_no,
match_result='matched', onhand_status='ready',
line_index=int(line.line_no) - 1,
match_result=match_result, onhand_status='ready',
onhand_snapshot_id=inventory_file.id, source_code=source_code,
is_current=True, detail_json={},
))
@@ -922,6 +923,8 @@ def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch
def _build_multi_odm_notice(
*, tmp_path, odm_values=None, customer_odm_ids=None, choice_odm=None, line_specs=None,
released_shortage: bool = False, unreleased_shortage: bool = False,
order_part: str = 'PN-A', inventory_part: str | None = None,
):
"""
构造「订单行命中多个 ODM ID」的整单导出场景;须在 app_context 内调用。
@@ -931,6 +934,11 @@ def _build_multi_odm_notice(
line_specs: 多订单行场景 [{'part': 料号, 'odm_values': [...]}];提供时忽略 odm_values。
customer_odm_ids: 客户数据的 ODM ID 范围(None = 不限定)。
choice_odm: 整单用户选择(写入 OT.chosen_odm_id)
released_shortage: True 时唯一行构造为短缺放行场景——订单料号不在库存行
(匹配键 0 命中)、事实落 not_found、并落已确认复核 Case 的系统放行决定
(release_field_values 携带 ODM 证据值),整单无任何 matched 事实。
unreleased_shortage: True 时事实落 not_found 但不落放行决定(未放行短缺)。
order_part / inventory_part: 订单行与库存行的料号(放行场景两者必须不同)。
Returns:
(notice, customer)。
"""
@@ -979,7 +987,7 @@ def _build_multi_odm_notice(
task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted',
)
db.session.add(extraction); db.session.flush()
specs = line_specs or [{'part': 'PN-A', 'odm_values': odm_values}]
specs = line_specs or [{'part': order_part, 'odm_values': odm_values}]
snapshot_lines = []
for index, spec in enumerate(specs, start=1):
order_line = ShippingOrderLine(extraction_id=extraction.id, position=index, line_no=index)
@@ -998,7 +1006,7 @@ def _build_multi_odm_notice(
inventory_rows = []
for spec in specs:
for odm in spec['odm_values']:
inventory_rows.append({_inventory_field_id('part_number'): spec['part'], _inventory_field_id('odm_id'): odm})
inventory_rows.append({_inventory_field_id('part_number'): inventory_part or spec['part'], _inventory_field_id('odm_id'): odm})
inventory_file = FreightRpaOnhandReportFile(
onhand_file_no='SIF-ODMSCOPE', user_id=None, source_file_name='odm-scope.xlsx',
storage_path=str(tmp_path / 'odm-scope.xlsx'),
@@ -1014,7 +1022,25 @@ def _build_multi_odm_notice(
)
notice = _materialize_export_notice(
ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='ODMSCOPE', notice_no='TASK-ODMSCOPE',
match_result='not_found' if (released_shortage or unreleased_shortage) else 'matched',
)
if released_shortage:
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
case = ShippingOrderReviewCase(
case_no='CASE-ODMSCOPE-RELEASE', run_id=931, unit_id=932, document_id=933,
owner_user_id=1, status='confirmed', confirmed_task_id=int(ot.id),
)
db.session.add(case); db.session.flush()
db.session.add(ShippingOrderReviewLineDecision(
review_case_id=case.id, draft_line_id='line-1', line_index=0,
decision_code='release_onhand_shortage', decision_source='system',
line_status='released_shortage', is_active=True,
snapshot_json={
'release_field_values': {str(_inventory_field_id('odm_id')): 'ODM-1'},
'release_evidence_scope': 'part_fallback',
},
))
db.session.flush()
if choice_odm is not None:
for match in ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(ot.id), is_current=True).all():
match.chosen_odm_id = choice_odm
@@ -1113,6 +1139,60 @@ def test_export_keeps_conflict_when_odm_scope_cannot_decide(app, tmp_path):
generate_shipment_excel(task)
def test_export_released_shortage_only_notice_resolves_source_and_rows(app, tmp_path):
"""整单短缺放行(0 条 matched 事实)也能解析库存源并按放行证据导出。
回归 OT-20261027-4BD4CEFF:预约键 0 命中→料号兜底自动放行后,行事实恒为
not_found;_notice_source_code 只认 matched 会让整单放行的单报
「库存源不存在或已停用」;prepare_export_match_inputs 的放行决定 join 须按
confirmed_task_id(OT) 回链,Notice 身份调用不得丢放行行。
"""
from app.services.shipping_notice.export import _notice_source_code, prepare_export_match_inputs
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
notice, _customer = _build_multi_odm_notice(
tmp_path=tmp_path, released_shortage=True,
order_part='PN-GONE', inventory_part='PN-OTHER', odm_values=['ODM-1'],
)
# 断言意图 1:源解析把放行行事实与 matched 行同票,整单放行也能拿到唯一源。
assert _notice_source_code(notice) == 'ODMSCOPE'
# 断言意图 2:以 Notice 身份准备导出输入,放行决定经 OT 回链可查到,
# 放行行进入导出行集并携带审计补录值(无 matched 事实也不报「没有匹配」)。
inputs = prepare_export_match_inputs(notice)
assert inputs['released_snapshot_line_ids']
assert inputs['released_export_line_indexes'] == {0}
assert list(inputs['release_overrides_by_line'][0].values()) == ['ODM-1']
assert [row['__order_line_index'] for row in inputs['line_values']] == [0]
# 断言意图 3:整单放行时证据快照仍落 Artifact 审计(matched-only 不再断证据链)。
assert inputs['verification'] is not None
path, _filename_value, _artifact = generate_shipment_excel(notice)
workbook = load_workbook(path, data_only=True)
try:
assert workbook['Detail'].cell(2, 1).value == 'ODM-1'
finally:
workbook.close()
def test_unreleased_shortage_notice_still_lacks_source(app, tmp_path):
"""未放行的短缺行不得参与源解析:matched-only 语义对未放行场景保持不变。"""
from app.services.shipping_notice.export import _notice_source_code
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
notice, _customer = _build_multi_odm_notice(
tmp_path=tmp_path, unreleased_shortage=True,
order_part='PN-GONE', inventory_part='PN-OTHER', odm_values=['ODM-1'],
)
# 断言意图:not_found 且无放行决定的事实不充当导出源依据(fail-closed 不变)。
assert _notice_source_code(notice) is None
def test_notice_odm_options_and_choice_roundtrip(app, tmp_path):
"""整单候选按客户范围逐行投影;合法选择落库并回显,非法选择有明确错误。"""
from app.core.errors import AppError