refactor(shipping-inventory): 统一库存准备事实来源与门禁状态

This commit is contained in:
hugo committed 2026-09-04 20:23:00 +08:00
1 parent 761a06e21a
commit eb55f407ae
62 files changed
+4242 -1471

No files matched your search

@@ -35,15 +35,24 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
result = process_rpa_report_inventory_batch(dict(job.payload_json or {}))
result_data = result.get('data') if isinstance(result, dict) else None
transport_status = str(
result.get('status') if isinstance(result, dict) else ''
).strip().lower()
result_status = str(
(result_data or {}).get('result_status') if isinstance(result_data, dict) else ''
).strip().lower()
if result_status in {'failed', 'partial_failed'}:
if transport_status == 'failed' or result_status in {'failed', 'partial_failed'}:
failed_items = result_data.get('failed') if isinstance(result_data, dict) else []
first_error = failed_items[0].get('error') if isinstance(failed_items, list) and failed_items and isinstance(failed_items[0], dict) else None
from app.services.shipping_notice.inventory_rpa_workflow import settle_failed_inventory_callback
settle_failed_inventory_callback(
dict(job.payload_json or {}),
error=str(first_error or (result or {}).get('message') or 'inventory_callback_processing_failed'),
)
fail_job(
job.id,
error=str(first_error or f'inventory_callback_business_{result_status}'),
error=str(first_error or (result or {}).get('message') or f'inventory_callback_business_{result_status or transport_status}'),
result={'status': 'processed', 'callback_result': result},
retryable=False,
owned_attempt=owned_attempt,
@@ -84,6 +84,18 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
attempt_id = int(payload.get('attempt_id') or 0)
raw_job_id = payload.get('job_id')
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
external_wait_poll_gate_id = int(payload.get('external_wait_poll_gate_id') or 0)
if external_wait_poll_gate_id and job is not None:
from app.services.shipping_notice.process_gate_job_service import run_inventory_external_wait_poll
result = run_inventory_external_wait_poll(gate_id=external_wait_poll_gate_id)
finish_job(job.id, result=result, owned_attempt=int(job.attempts or 0))
if str(result.get('gate_status') or '') == 'waiting_external':
gate = db.session.get(ShippingProcessGate, external_wait_poll_gate_id)
if gate is not None and gate.latest_attempt_id:
schedule_waiting_external_poll(attempt_id=int(gate.latest_attempt_id))
db.session.commit()
return
if attempt_id <= 0 or job is None:
raise RuntimeError('missing_attempt_id_or_job_id')
+2 -2
View File
@@ -32,7 +32,7 @@ class ShippingReservation(Base):
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
snapshot_line_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_snapshot_lines.id'), nullable=False)
reservation_id: Mapped[str] = mapped_column(String(64), nullable=False)
po_number_normalized: Mapped[str] = mapped_column(String(255), nullable=False)
@@ -59,7 +59,7 @@ class ShippingInventoryVerification(Base):
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True)
@@ -5,7 +5,7 @@ models/shipping_inventory_candidates.py
InventoryCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源),
同时 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze'] 保存
同一时刻的完整不可变副本,用于审计与回滚。
依赖:Base、ShippingNotice、ShippingProcessExecution、ShippingOrderReviewCase、users、
依赖:Base、ShippingOrderTask、ShippingProcessExecution、ShippingOrderReviewCase、users、
ShippingInventoryRoutingRule(可选外键,路由规则版本)。
逻辑:建单前复核阶段(review_case 绑定)或建单后正式推进阶段(task 绑定)都可冻结;
input_fingerprint 相同的重复 freeze 直接返回旧 set_id(幂等);
@@ -81,7 +81,7 @@ class ShippingInventoryCandidateSet(Base):
id: Mapped[int] = mapped_column(primary_key=True)
set_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=True,
ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=True,
)
review_case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=True,
@@ -2,7 +2,7 @@
models/shipping_inventory_preparation.py
用途:表达一次任务级库存准备轮次及逐库存源状态。
依赖:ShippingNotice、RecoveryPlan、RPA Attempt、InventoryFile、TaskInventoryLink、Base。
依赖:ShippingOrderTask、RecoveryPlan、RPA Attempt、InventoryFile、TaskInventoryLink、Base。
逻辑:PreparationAttempt 聚合多个 SourceAttempt,支持有效源复用和问题源单独重拉。
"""
@@ -31,7 +31,7 @@ class ShippingInventoryPreparationAttempt(Base):
)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=False)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=False)
execution_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_executions.id', ondelete='SET NULL'), nullable=True)
gate_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', ondelete='SET NULL'), nullable=True, index=True)
recovery_plan_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_recovery_plans.id', ondelete='SET NULL'), nullable=True)
@@ -37,7 +37,7 @@ class ShippingNoticeLineInventoryMatch(Base):
__table_args__ = (
UniqueConstraint(
'task_id',
'line_key',
'snapshot_line_id',
'inventory_snapshot_id',
name='uq_shipping_notice_line_inv_match_task_line_snap',
),
@@ -45,7 +45,7 @@ class ShippingNoticeLineInventoryMatch(Base):
Index(
'uq_shipping_notice_line_inv_match_current',
'task_id',
'line_key',
'snapshot_line_id',
unique=True,
postgresql_where=text('is_current IS TRUE'),
),
@@ -70,14 +70,19 @@ class ShippingNoticeLineInventoryMatch(Base):
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notices.id', ondelete='CASCADE'),
ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'),
nullable=False,
)
review_case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='SET NULL'),
nullable=True,
)
line_key: Mapped[str] = mapped_column(String(64), nullable=False)
snapshot_line_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_snapshot_lines.id', ondelete='CASCADE'),
nullable=False,
index=True,
)
line_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'),
+2 -2
View File
@@ -2,7 +2,7 @@
models/shipping_process_gate.py
用途:门禁级中断恢复的持久化模型——Execution / Gate / Attempt。
依赖:SQLAlchemy Base、ReviewCase、ShippingNotice、Job;状态枚举与 process_gate_contract 对齐。
依赖:SQLAlchemy Base、ReviewCase、ShippingOrderTask、Job;状态枚举与 process_gate_contract 对齐。
逻辑:Execution 为业务恢复真相;Gate 保存当前门禁状态;Attempt 不可变执行尝试并承载租约。
由领域服务独占写入;Job 仅调度。
co8e9f0a1b2c:已移除对 shipping_notice_workflow_* 的硬外键(无历史兼容)。
@@ -74,7 +74,7 @@ class ShippingProcessExecution(Base):
ForeignKey('shipping_order_review_cases.id'), nullable=True,
)
task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notices.id'), nullable=True,
ForeignKey('shipping_order_tasks.id'), nullable=True,
)
# 绑定候选版本,防止旧 callback/job 写入新候选链。
candidate_set_id: Mapped[Optional[int]] = mapped_column(
@@ -39,7 +39,7 @@ class ShippingTemporaryInventorySession(Base):
analysis_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True,
)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True, index=True)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True, index=True)
declared_intent: Mapped[str] = mapped_column(String(32), nullable=False, default='inventory_candidate')
file_classification_status: Mapped[str] = mapped_column(String(32), nullable=False, default='created')
status: Mapped[str] = mapped_column(String(32), nullable=False, default='created')
@@ -19,6 +19,7 @@ from app.models import (
ShippingOrderField,
ShippingInventoryParsingProfile,
ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis,
ShippingNoticeLine, ShippingNoticeLineInventoryMatch,
ShippingExcelTemplate,
ShippingInventorySourceParsingBindingAudit,
ShippingReceiptReportConfig,
@@ -497,7 +498,11 @@ def delete_source(source_id: int) -> None:
for candidates in [(rule.action_payload_json or {}).get('source_codes', [])]
if isinstance(candidates, list)
)
has_task = ShippingNotice.query.filter_by(inventory_source_code=source_code).count() > 0
has_task = db.session.query(ShippingNoticeLine.id).filter(
ShippingNoticeLine.inventory_source_code == source_code,
).first() is not None or db.session.query(ShippingNoticeLineInventoryMatch.id).filter(
ShippingNoticeLineInventoryMatch.inventory_source_code == source_code,
).first() is not None
has_export_run = any(
source_code in {str(code).strip().upper() for code in source_codes}
for run in ScheduleRun.query.all()
File diff suppressed because it is too large. Load diff
@@ -193,7 +193,7 @@ def _collect_order_line_candidates(
line_codes = list(task_level_source_codes_ordered)
line_projections.append({
'line_key': f'{task.id}:{line_no}',
# 该阶段只产生候选投影;冻结档建立后由 snapshot_line_id 作为唯一行身份。
'line_index': idx,
'line_no': line_no,
'source_line_no': source_line_no,
@@ -276,19 +276,13 @@ def _invalidate_task_candidate_outputs(
ShippingUploadAttempt,
)
task.match_status = None
task.shortage_json = None
task.line_results_json = None
task.export_file_path = None
task.export_file_name = None
task.upload_status = None
payload = dict(task.step_payload_json or {})
payload.pop('line_inventory_resolutions', None)
payload.pop('resolved_ok_source_codes', None)
payload.pop('excel_binding_source_code', None)
payload.pop('multi_source_excel_block', None)
task.step_payload_json = payload
if task.__class__.__name__ != 'ShippingOrderTask':
task.step_payload_json = payload if task.__class__.__name__ != 'ShippingOrderTask' else {key: value for key, value in payload.items() if key in {'current_step_progress', 'parse_validation'}}
(
session.query(ShippingNoticeLineInventoryMatch)
@@ -306,12 +300,18 @@ def _invalidate_task_candidate_outputs(
)
.update({'status': 'superseded', 'updated_at': datetime.utcnow()}, synchronize_session=False)
)
artifact_ids = [
row[0] for row in session.query(ShippingExportArtifact.id).filter(
ShippingExportArtifact.task_id == int(task.id),
ShippingExportArtifact.status.in_(('ready', 'uploading')),
notice_ids = [
int(row.id)
for row in session.query(ShippingNotice.id).filter(
ShippingNotice.order_task_id == int(task.id),
).all()
]
artifact_ids = [
row[0] for row in session.query(ShippingExportArtifact.id).filter(
ShippingExportArtifact.task_id.in_(notice_ids),
ShippingExportArtifact.status.in_(('ready', 'uploading')),
).all()
] if notice_ids else []
if artifact_ids:
session.query(ShippingExportArtifact).filter(
ShippingExportArtifact.id.in_(artifact_ids),
@@ -358,6 +358,7 @@ def freeze_candidates_for_task(
execution_id: int | None = None,
frozen_by_id: int | None = None,
line_projections: list[dict[str, Any]] | None = None,
preserve_empty_line_candidates: bool = False,
session: Session | None = None,
) -> CandidateFreezeResult:
"""
@@ -370,7 +371,6 @@ def freeze_candidates_for_task(
[STEP 2] 构建 input_fingerprint,查找是否已有幂等冻结 Set——命中则直接复用。
[STEP 3] 写 Set → Source(保序)→ Line(行级候选有序列表)三张表。
[STEP 4] 同步写 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze']。
[STEP 5] 回填 task.inventory_source_status='candidates_frozen'(调用方负责 commit)。
Args:
task: 已 flush 的 ShippingNotice(有 id 字段)。
@@ -380,6 +380,8 @@ def freeze_candidates_for_task(
execution_id: 可选的 ProcessExecution 绑定 ID。
frozen_by_id: 人工覆盖冻结时的操作人 ID。
line_projections: STP 阶段已算出的行级候选投影(缺省时逐行 evaluate_inventory_source_rules)。
preserve_empty_line_candidates: 仅人工逐项选源时为 True;保留尚未选择源的
Snapshot 行为空列表,使 Gate 能继续阻断而不会误触发整单库存准备。
session: 可选的 SQLAlchemy Session(缺省用 db.session)。
Returns:
@@ -421,18 +423,14 @@ def freeze_candidates_for_task(
continue
codes_raw = item.get('candidate_inventory_source_codes') or []
codes = [str(c or '').strip().upper() for c in codes_raw if str(c or '').strip()]
if not codes:
if not codes and not preserve_empty_line_candidates:
codes = list(task_source_codes_ordered)
line_index = item.get('line_index')
try:
line_no = int(item.get('line_no') or 0)
except (TypeError, ValueError):
line_no = 0
if line_no <= 0:
try:
line_no = int(line_index) + 1
except (TypeError, ValueError):
line_no = len(signatures) + 1
raise ValueError('候选行缺少持久化 line_no,禁止从 line_index 派生项次')
signatures.append((
line_no,
str(item.get('source_line_no') or '').strip() or None,
@@ -599,22 +597,22 @@ def freeze_candidates_for_task(
if getattr(task, 'id', None) is not None:
task.active_inventory_candidate_set_id = int(new_set.id)
# 新版本不能让旧候选链中的 queued Job/未完成 Gate 继续写事实。
from app.services.shipping_notice.auto_progress_controller import (
supersede_auto_progress_for_candidate_refreeze,
)
# 人工逐项选源正由当前 GateAttempt 执行时,不能把它自己 supersede,
# 否则选源已落库但 Attempt 无法完成。该 Execution 只更新候选版本,仍停在
# routing Gate;所有项次选完后才进入库存准备。其他重冻结仍取消旧链。
current_execution_id = getattr(task, 'active_process_execution_id', None)
if execution_id is not None and int(current_execution_id or 0) == int(execution_id):
from app.models import ShippingProcessExecution
supersede_auto_progress_for_candidate_refreeze(task)
current_execution = session.get(ShippingProcessExecution, int(execution_id))
if current_execution is not None:
current_execution.candidate_set_id = int(new_set.id)
else:
from app.services.shipping_notice.auto_progress_controller import (
supersede_auto_progress_for_candidate_refreeze,
)
# [STEP 5] 回填 task 字段(幂等覆盖)
task.inventory_source_status = 'candidates_frozen'
task.inventory_source_method = (
'manual_override_freeze' if frozen_by_id is not None
else (adjudication.method or 'rule_evaluation_freeze')
)
task.inventory_source_config_version = config_version
task.inventory_routing_fingerprint = routing_fingerprint
# 保留 step_payload_json 中已有 inventory_source_resolution,调用方可追加细节
supersede_auto_progress_for_candidate_refreeze(task)
return CandidateFreezeResult(
candidate_set_id=new_set.id,
@@ -624,3 +622,204 @@ def freeze_candidates_for_task(
manifest_snapshot_sha256=manifest_sha256,
set_version=set_version,
)
def freeze_manual_line_source_selection(
task: ShippingNotice,
*,
line_no: int,
source_code: str,
actor_id: int | None,
reason: str | None,
execution_id: int | None,
session: Session | None = None,
) -> tuple[CandidateFreezeResult, bool]:
"""
将通知准备的人工选源冻结为新的 CandidateSet 版本。
核心逻辑:以冻结 Snapshot 的全量 line_no 为骨架,继承当前候选行的选择后仅替换目标项次。
没有自动候选时也会先创建全量 CandidateLine;未选源项保持空数组,只有每一项都有源时才返回
``all_lines_selected=True``,调用方据此允许进入库存准备/RPA。
Args:
task: 已冻结订单对应的 OT。
line_no: 用户选择库存源的 Snapshot 项次,必须存在。
source_code: 已启用库存源编码。
actor_id: 操作人,用于候选源与候选行审计。
reason: 人工选择原因。
execution_id: 当前流程 Execution,用于绑定候选版本。
session: 可选数据库会话。
Returns:
(CandidateFreezeResult, all_lines_selected)。
Raises:
ValueError: OT 未冻结 Snapshot 或项次不存在。
"""
session = session or db.session
snapshot = (
session.query(ShippingOrderSnapshot)
.filter(ShippingOrderSnapshot.task_id == int(task.id))
.one_or_none()
)
if snapshot is None:
raise ValueError('人工选源前必须先冻结订单 Snapshot')
snapshot_lines = sorted(list(snapshot.lines or []), key=lambda row: int(row.line_no))
wanted_line = int(line_no)
if not any(int(row.line_no) == wanted_line for row in snapshot_lines):
raise ValueError('未找到该订单项次')
active_set = (
session.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id))
if task.active_inventory_candidate_set_id is not None else None
)
existing_codes = {
int(row.line_no): [str(code).strip().upper() for code in (row.source_codes_json or []) if str(code).strip()]
for row in (active_set.lines if active_set is not None else [])
}
line_projections: list[dict[str, Any]] = []
for row in snapshot_lines:
current_line_no = int(row.line_no)
codes = [source_code] if current_line_no == wanted_line else existing_codes.get(current_line_no, [])
line_projections.append({
'line_no': current_line_no,
'source_line_no': str(row.line_no),
'part_number': row.part_number,
'reservation_id': row.reservation_id,
'candidate_inventory_source_codes': codes,
})
source_codes = []
for projection in line_projections:
for code in projection['candidate_inventory_source_codes']:
if code not in source_codes:
source_codes.append(code)
adjudication = InventorySourceAdjudication(
status='manual',
method='manual_line_selection',
config_version=inventory_sources_runtime_version(),
routing_fingerprint=compute_routing_fingerprint(extract_routing_context(task)),
candidates=[{'source_code': code} for code in source_codes],
evidence=[{'line_no': wanted_line, 'source_code': source_code, 'reason': reason or '人工指定库存源'}],
reason='manual_line_selection',
)
result = freeze_candidates_for_task(
task,
adjudication=adjudication,
execution_id=execution_id,
frozen_by_id=actor_id,
line_projections=line_projections,
preserve_empty_line_candidates=True,
session=session,
)
return result, all(bool(item['candidate_inventory_source_codes']) for item in line_projections)
def freeze_wave_notice_routing(
notice: ShippingNotice,
*,
source_notice: ShippingNotice | None = None,
) -> CandidateFreezeResult | None:
"""
按波次自身行重跑库存源路由并冻结候选集(设计 D8:波次不再继承首通知源)。
【AI 触发时机】建波次通知(post_ot_fulfillment_wave)且在写入波次 ShippingNoticeLine 后调用;
仅当波次行需要独立路由(不同行可能不同仓)时使用。
核心逻辑:以订单级 header(field_id 值)+ 波次行 ShippingNoticeLine.field_values_json
逐行调用 ``evaluate_inventory_source_rules_for_field_values(scope='line')`` 得到行级候选;
以全波次行候选并集作为任务级候选集,调用 ``freeze_candidates_for_task`` 冻结 Set/Source/Line
(候选快照已在本地,后续匹配不重复 RPA)。
Args:
notice: 已 flush 且已写入波次行的波次通知。
source_notice: 订单首个冻结通知(提供订单级 header 事实);缺省用 notice。
Returns:
CandidateFreezeResult;无任何波次行候选时返回 None(交由无候选阻断,不冻结)。
"""
from app.models.shipping_notice_line import ShippingNoticeLine
from app.services.shipping_notice.export import order_field_id_values
from app.services.shipping_notice.inventory_routing_engine import (
evaluate_inventory_source_rules_for_field_values,
)
src = source_notice or notice
try:
header, _full_lines = order_field_id_values(src)
except ValueError:
header = {}
wave_lines = (
ShippingNoticeLine.query.filter_by(notice_id=int(notice.id)).order_by(ShippingNoticeLine.position).all()
if getattr(notice, 'id', None) is not None
else []
)
# [回退] 与首单路径一致(_collect_order_line_candidates):行级无规则命中时回退到订单级 task 候选集,
# 避免波次行「一条规则都不命中」时被算成无候选而卡死。
task_result = evaluate_inventory_source_rules_for_field_values(
header_field_values=header, scope='task',
)
task_source_codes = [str(c or '').strip().upper() for c in (getattr(task_result, 'source_codes', None) or []) if str(c or '').strip()]
line_projections: list[dict[str, Any]] = []
task_codes: list[str] = []
seen: set[str] = set()
for idx, line in enumerate(wave_lines):
line_values = dict(getattr(line, 'field_values_json', None) or {})
line_result = evaluate_inventory_source_rules_for_field_values(
header_field_values=header,
line_field_values=line_values,
scope='line',
)
resolved = str(getattr(line_result, 'status', '') or '') == 'resolved' and bool(getattr(line_result, 'source_codes', None))
if resolved:
codes = [str(c or '').strip().upper() for c in (getattr(line_result, 'source_codes', None) or []) if str(c or '').strip()]
else:
codes = list(task_source_codes)
if not codes:
codes = list(task_source_codes)
for code in codes:
if code not in seen:
seen.add(code)
task_codes.append(code)
line_projections.append({
'line_index': idx,
'line_no': idx + 1,
'source_line_no': str(getattr(line, 'line_no', None) or '').strip() or None,
'part_number': str(getattr(line, 'part_number', None) or '').strip() or None,
'reservation_id': str(getattr(line, 'reservation_id', None) or '').strip() or None,
'candidate_inventory_source_codes': codes,
'selection_mode': 'line_rule' if resolved else 'task_fallback',
'routing_status': str(getattr(line_result, 'status', '') or ''),
'matched_rule_ids': list(getattr(line_result, 'matched_rules', ()) or ()),
})
if not task_codes:
return None
from app.services.shipping_notice.inventory_source_rules import (
InventorySourceAdjudication,
_candidate,
compute_routing_fingerprint,
extract_routing_context,
)
candidates = []
for code in task_codes:
src_cfg = get_database_inventory_source(code)
if src_cfg:
candidates.append(_candidate(src_cfg))
adjudication = InventorySourceAdjudication(
status='candidates_frozen',
method='wave_line_routing',
config_version=inventory_sources_runtime_version(),
routing_fingerprint=compute_routing_fingerprint(extract_routing_context(notice)),
candidates=candidates,
)
return freeze_candidates_for_task(
notice,
adjudication=adjudication,
line_projections=line_projections,
)
@@ -2,9 +2,9 @@
services/shipping_notice/inventory_candidate_projection.py
用途:统一读取正式 CandidateSet 真相,并投影为任务/工作台/聊天共用的候选事实 DTO。
依赖:ShippingNotice、ShippingInventoryCandidateSet/Source/Line、ShippingNoticeLineInventoryMatch、
依赖:ShippingOrderTask、ShippingInventoryCandidateSet/Source/Line、ShippingNoticeLineInventoryMatch、
ShippingTaskInventoryRpaAttempt。
逻辑:正式 Task 一律通过 active_inventory_candidate_set_id 读取当前 frozen Set;缺失、
逻辑:正式 OT 一律通过 active_inventory_candidate_set_id 读取当前 frozen Set;缺失、
坏链、旧版本匹配引用或越界匹配统一产出 fail-closed 诊断,供 Gate / Projection / API 复用。
"""
@@ -21,7 +21,7 @@ from app.models import (
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
ShippingInventoryFile,
ShippingNotice,
ShippingOrderTask,
ShippingNoticeLineInventoryMatch,
ShippingTaskInventoryRpaAttempt,
)
@@ -55,7 +55,7 @@ def _normalized_codes(codes: list[Any] | None) -> list[str]:
def _candidate_set_filter(
task: ShippingNotice,
task: ShippingOrderTask,
*,
include_drafts: bool = False,
session: Session | None = None,
@@ -83,14 +83,14 @@ def _candidate_set_filter(
def get_active_candidate_set(
task: ShippingNotice,
task: ShippingOrderTask,
*,
session: Session | None = None,
) -> ShippingInventoryCandidateSet | None:
"""
读取正式 Task 当前 frozen CandidateSet。
核心逻辑:严格依赖 ShippingNotice.active_inventory_candidate_set_id;
核心逻辑:严格依赖 ShippingOrderTask.active_inventory_candidate_set_id;
指针为空、坏链、跨 Task、非 frozen 均返回 None,由上层映射阻断。
"""
candidate_set_id = getattr(task, 'active_inventory_candidate_set_id', None)
@@ -107,7 +107,7 @@ def get_active_candidate_set(
def get_active_candidate_sources(
task: ShippingNotice,
task: ShippingOrderTask,
*,
session: Session | None = None,
) -> list[ShippingInventoryCandidateSource]:
@@ -129,7 +129,7 @@ def get_active_candidate_sources(
def get_active_candidate_lines(
task: ShippingNotice,
task: ShippingOrderTask,
*,
session: Session | None = None,
) -> list[ShippingInventoryCandidateLine]:
@@ -150,8 +150,51 @@ def get_active_candidate_lines(
return list(rows)
def active_inventory_runtime_facts(
task: ShippingOrderTask,
*,
session: Session | None = None,
) -> dict[str, Any]:
"""
读取通知准备的当前运行事实,替代 OT 上的库存路由和快照投影列。
核心逻辑:库存源只读当前 CandidateSet/Source;库存文件只读 active Link;配置版本
取 CandidateSource 的冻结版本,不能回读 Task 的可变历史字段。
Args:
task: 当前订单任务。
session: 可选数据库会话。
Returns:
source_codes、source_config_version、inventory_file_id 与 active_link 等当前事实。
"""
from app.models import ShippingTaskInventoryLink
sess = _session(session)
candidate_set = get_active_candidate_set(task, session=sess)
sources = get_active_candidate_sources(task, session=sess)
source_codes = [str(row.source_code or '').strip().upper() for row in sources if str(row.source_code or '').strip()]
versions = [str(row.source_config_version or '').strip() for row in sources if str(row.source_config_version or '').strip()]
link = (
sess.query(ShippingTaskInventoryLink)
.filter(ShippingTaskInventoryLink.task_id == int(task.id), ShippingTaskInventoryLink.is_active.is_(True))
.order_by(ShippingTaskInventoryLink.id.desc())
.first()
if getattr(task, 'id', None) is not None else None
)
return {
'candidate_set': candidate_set,
'candidate_set_id': getattr(candidate_set, 'id', None),
'source_codes': source_codes,
'source_config_version': versions[0] if len(set(versions)) == 1 and versions else None,
'active_link': link,
'inventory_file_id': getattr(link, 'inventory_file_id', None),
'inventory_file': getattr(link, 'inventory_file', None),
}
def get_candidate_set_by_version(
task: ShippingNotice,
task: ShippingOrderTask,
version: int,
*,
include_drafts: bool = False,
@@ -271,7 +314,7 @@ def _candidate_lines_for_set(
def build_inventory_candidate_blocking_reason(
code: str,
*,
task: ShippingNotice,
task: ShippingOrderTask,
details: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""构造统一 blocking_reason DTO。"""
@@ -293,7 +336,7 @@ def build_inventory_candidate_primary_action(code: str = 'retry_with_latest_rule
}
def _latest_attempts_by_source(task: ShippingNotice, source_codes: list[str], *, session: Session | None = None) -> dict[str, dict[str, Any]]:
def _latest_attempts_by_source(task: ShippingOrderTask, source_codes: list[str], *, session: Session | None = None) -> dict[str, dict[str, Any]]:
"""查询任务下每个候选源的最新 Attempt 摘要。"""
task_no = str(getattr(task, 'task_no', '') or '').strip()
if not task_no or not source_codes:
@@ -346,7 +389,7 @@ def _classify_sources(source_codes: list[str], attempt_map: dict[str, dict[str,
return prepared, pending, failed
def _current_match_rows(task: ShippingNotice, *, session: Session | None = None) -> list[ShippingNoticeLineInventoryMatch]:
def _current_match_rows(task: ShippingOrderTask, *, session: Session | None = None) -> list[ShippingNoticeLineInventoryMatch]:
"""读取任务当前生效的行级匹配事实。"""
if getattr(task, 'id', None) is None:
return []
@@ -367,7 +410,7 @@ def _current_match_rows(task: ShippingNotice, *, session: Session | None = None)
def project_inventory_candidate_detail(
task: ShippingNotice,
task: ShippingOrderTask,
*,
version: str | int = 'current',
session: Session | None = None,
@@ -426,7 +469,7 @@ def project_inventory_candidate_detail(
def project_inventory_candidate_facts(
task: ShippingNotice,
task: ShippingOrderTask,
*,
session: Session | None = None,
include_history: bool = False,
@@ -493,14 +536,20 @@ def project_inventory_candidate_facts(
allowed_codes = _normalized_codes(getattr(row, 'allowed_source_codes_snapshot', None))
serialized = {
'id': int(row.id),
'line_key': str(row.line_key or ''),
'snapshot_line_id': int(row.snapshot_line_id),
'line_no': int(row.line_no),
'line_index': getattr(row, 'line_index', None),
'disposition': dict(getattr(row, 'detail_json', None) or {}).get('disposition'),
'candidate_set_id': getattr(row, 'candidate_set_id', None),
'candidate_set_version': getattr(row, 'candidate_set_version', None),
'candidate_line_id': getattr(row, 'candidate_line_id', None),
'allowed_source_codes_snapshot': allowed_codes,
'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None),
# [Approach 1] 行匹配记录未回填源、但行允许源为单一源时(如 shortages 匹配、覆写单源),
# 用该单一源回填 resolved_inventory_source_code,保证行级源诚实展示(D7 Excel 前可改)。
'resolved_inventory_source_code': (
getattr(row, 'inventory_source_code', None)
or (allowed_codes[0] if len(allowed_codes) == 1 else None)
),
'inventory_file_no': getattr(row, 'matched_file_no', None),
'inventory_snapshot_id': getattr(row, 'inventory_snapshot_id', None),
'inventory_row_ref': (dict(getattr(row, 'detail_json', None) or {}).get('inventory_row_ref')),
@@ -19,7 +19,15 @@ from werkzeug.datastructures import FileStorage
from app import db
from app.core.errors import AppError
from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink
from app.models import (
ShippingInventoryFile,
ShippingNotice,
ShippingNoticeLineInventoryMatch,
ShippingOrderSnapshot,
ShippingTaskEvent,
ShippingTaskInventoryLink,
)
from app.services.shipping_notice.tool_common import task_event_task_id
from app.services.shipping_notice.export import _storage_root
from app.services.shipping_notice.inventory_snapshot import (
parse_inventory_excel_with_meta,
@@ -29,10 +37,14 @@ from app.services.shipping_notice.inventory_source_gate import (
is_inventory_source_stable,
task_inventory_identity,
)
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
from app.services.shipping_notice.inventory_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
)
def _can_relink_inventory(task: ShippingNotice) -> bool:
"""判断任务是否允许被新的批次库存快照影响;终态任务不能回退。"""
return str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'} \
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
return not has_verified_upload_success(task) \
and str(getattr(task, 'lifecycle_status', None) or '').strip().lower() not in {'voided', 'archived', 'deleted'}
@@ -130,10 +142,15 @@ def delete_inventory_storage_path(storage_path: str | Path | None) -> None:
def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFile | None:
"""读取任务当前 active link 指向的库存快照。"""
if task.id is None:
task_id = getattr(task, 'id', None)
if task_id is None:
return None
link = (
ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True)
ShippingTaskInventoryLink.query.filter_by(
task_id=int(task_id),
is_active=True,
invalidated_at=None,
)
.order_by(ShippingTaskInventoryLink.id.desc())
.first()
)
@@ -162,24 +179,33 @@ def resolve_task_inventory_download(task: ShippingNotice) -> tuple[Path, str] |
return path, filename
def read_inventory_file_lines(inv_file: ShippingInventoryFile) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""读取库存文件的唯一行事实;缓存为空时按已发布解析方案解析并固化到文件层。"""
cached_rows = [
row for row in (inv_file.inventory_lines_json or []) if isinstance(row, dict)
]
if cached_rows:
return cached_rows, {'source': 'inventory_file_cache'}
rows, column_meta = parse_inventory_snapshot_file(inv_file)
rows = [row for row in rows if isinstance(row, dict)]
if rows:
inv_file.inventory_lines_json = rows
inv_file.line_count = len(rows)
db.session.flush()
return rows, column_meta
def active_inventory_lines_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
"""读取任务活动库存快照;已有 JSON 是快照事实,禁止读取时被物理文件静默覆盖。"""
"""读取任务活动库存文件的行事实;解析失败由调用方 Gate 转为可解释状态。"""
inv_file = active_inventory_file_for_task(task)
if inv_file and isinstance(inv_file.inventory_lines_json, list):
rows = [row for row in inv_file.inventory_lines_json if isinstance(row, dict)]
if not rows and Path(inv_file.storage_path).is_file():
try:
reparsed, _meta = parse_inventory_snapshot_file(inv_file)
if reparsed:
inv_file.inventory_lines_json = reparsed
inv_file.line_count = len(reparsed)
db.session.flush()
rows = reparsed
except Exception: # noqa: BLE001
# 解析失败时保留原快照,交由上层 Gate 报告可解释错误。
pass
if inv_file is None:
return []
try:
rows, _column_meta = read_inventory_file_lines(inv_file)
return rows
return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
except (OSError, ValueError, AppError):
return []
def resolve_inventory_lines_for_execution(
@@ -195,7 +221,7 @@ def resolve_inventory_lines_for_execution(
legacy_payload_lines: 旧 Tool 请求携带的库存行;仅无活动 Link 的历史任务允许使用。
Returns:
本次执行使用的库存行;不会回写 ``ShippingNotice.inventory_lines_json``。
本次执行使用的库存行;不会回写任务或通知单的库存行缓存。
"""
if active_inventory_file_for_task(task) is not None:
return active_inventory_lines_for_task(task)
@@ -203,7 +229,7 @@ def resolve_inventory_lines_for_execution(
rows = [row for row in legacy_payload_lines if isinstance(row, dict)]
if rows:
return rows
return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
return []
def has_uploaded_inventory_file(task: ShippingNotice) -> bool:
@@ -214,6 +240,60 @@ def has_uploaded_inventory_file(task: ShippingNotice) -> bool:
return False
def has_ready_inventory_file_for_task(task: ShippingNotice) -> bool:
"""判断 OT 是否已绑定一份有效且已解析的库存文件。"""
inv_file = active_inventory_file_for_task(task)
return bool(
inv_file is not None
and str(inv_file.snapshot_status or '').strip().lower() == 'ready'
and inv_file.invalidated_at is None
and int(inv_file.line_count or 0) > 0
)
def current_inventory_matches_for_task(task: ShippingNotice) -> list[ShippingNoticeLineInventoryMatch]:
"""读取 OT 当前有效的行级库存匹配事实。"""
task_id = getattr(task, 'id', None)
if task_id is None:
return []
return ShippingNoticeLineInventoryMatch.query.filter_by(
task_id=int(task_id), is_current=True,
).all()
def inventory_matches_complete_for_task(task: ShippingNotice) -> bool:
"""判断当前 Match 是否已覆盖冻结订单全部项次且不在准备中。"""
task_id = getattr(task, 'id', None)
snapshot_id = getattr(task, 'order_snapshot_id', None)
if task_id is None or not snapshot_id:
return False
snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id))
if snapshot is None or not snapshot.lines:
return False
matches = {
int(row.snapshot_line_id): row
for row in current_inventory_matches_for_task(task)
if row.snapshot_line_id is not None
}
expected = {int(line.id) for line in snapshot.lines}
return set(matches) == expected and all(
str(row.match_result or '').strip().lower() != 'preparing'
for row in matches.values()
)
def current_inventory_matches_have_shortage(task: ShippingNotice) -> bool:
"""判断当前行级匹配中是否存在尚未满足的缺口或匹配失败。"""
for row in current_inventory_matches_for_task(task):
try:
shortage = float(row.shortage_qty or 0)
except (TypeError, ValueError):
shortage = 0.0
if str(row.match_result or '').strip().lower() != 'matched' or shortage > 0:
return True
return False
def _same_stable_inventory_identity(lhs: ShippingNotice, rhs: ShippingNotice) -> bool:
"""判断两票任务是否具备相同且稳定的库存源身份,供批次库存快照共用。"""
if not is_inventory_source_stable(lhs) or not is_inventory_source_stable(rhs):
@@ -314,9 +394,11 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
mapping_source='parsing_profile',
mapping_confirmed=True,
source_code=source_code,
source_type=str(task.inventory_connector_type or "").strip() or None,
source_type=str(
(get_database_inventory_source(source_code) or {}).get('connector_type') or ''
).strip() or None,
warehouse_id=warehouse_id,
source_config_version=task.inventory_source_config_version or inventory_sources_runtime_version(),
source_config_version=inventory_sources_runtime_version(),
source_query_json={'trigger_type': 'manual_upload'},
identity_status="pending",
snapshot_status="ready",
@@ -442,7 +524,7 @@ def replace_task_inventory_link(
db.session.add(new_link)
db.session.add(
ShippingTaskEvent(
task_id=task.id,
task_id=task_event_task_id(task),
event_type="inventory_file_linked",
detail_json={
"inventory_file_no": inv_file.inventory_file_no,
@@ -524,8 +606,6 @@ def apply_inventory_parse_result_to_linked_tasks(
continue
if not _can_relink_inventory(link.task):
continue
link.task.inventory_snapshot_id = inv_file.id
link.task.inventory_lines_json = inventory_lines
linked_tasks.append(link.task)
return linked_tasks
@@ -569,7 +649,8 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) ->
task = link.task
if not link.is_active or not task:
continue
if task.task_no in task_nos and not task.match_status and str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'}:
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
if task.task_no in task_nos and not current_inventory_matches_for_task(task) and not has_verified_upload_success(task):
set_task_step_progress(
task,
step_key="step5_match_inventory",
@@ -65,7 +65,7 @@ def inventory_loaded_response(
mapping_confirmed=True,
)
else:
task.inventory_lines_json = inventory_lines
raise ValueError('OT 库存解析结果必须先绑定到有效库存文件')
# [BE-放行-恢复] 库存内容已重新载入/复用,旧匹配结果必然失效:清空任务级派生状态,
# 强制 Gate 链路在下一轮重新匹配,避免复用旧快照的短缺/匹配结果而造成"库存已刷新
@@ -73,9 +73,6 @@ def inventory_loaded_response(
for affected in [task, *linked_tasks]:
if affected is None:
continue
affected.match_status = None
affected.line_results_json = None
affected.shortage_json = None
try:
order_lines = task_line_purpose_values(task)
@@ -16,16 +16,19 @@ from app.models import (
ShippingInventoryFile,
ShippingInventoryPreparationAttempt,
ShippingInventoryPreparationSourceAttempt,
ShippingNotice,
ShippingOrderTask,
ShippingOrderCandidate,
ShippingTaskInventoryLink,
)
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
from app.services.shipping_notice.inventory_combination_fingerprint import build_inventory_combination_fingerprint
from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts
def create_inventory_preparation_round(
*, task: ShippingNotice, execution_id: int | None, recovery_plan_id: int | None,
*, task: ShippingOrderTask, execution_id: int | None, recovery_plan_id: int | None,
action_code: str, source_codes: list[str] | None = None, operation_id: str | None = None,
gate_attempt_id: int | None = None,
) -> ShippingInventoryPreparationAttempt:
@@ -50,8 +53,7 @@ def create_inventory_preparation_round(
db.session.flush()
codes = [str(code).strip().upper() for code in (source_codes or []) if str(code).strip()]
if not codes:
codes = [str(getattr(task, 'inventory_source_code', '') or '').strip().upper()]
codes = [code for code in codes if code]
codes = task_frozen_inventory_source_codes(task)
active_file = active_inventory_file_for_task(task)
for source_code in codes:
reusable, _reuse_reasons = check_inventory_snapshot_reusable(
@@ -76,8 +78,14 @@ def create_inventory_preparation_round(
)
db.session.add(source)
db.session.flush()
source_candidate = (
db.session.query(ShippingOrderCandidate)
.filter(ShippingOrderCandidate.consumed_task_id == int(task.id))
.order_by(ShippingOrderCandidate.id.desc())
.first()
)
round_row.combination_input_fingerprint = build_inventory_combination_fingerprint(
task_snapshot_fingerprint=str(getattr(task, 'content_fingerprint', '') or ''),
task_snapshot_fingerprint=str(getattr(source_candidate, 'content_fingerprint', '') or ''),
candidate_freeze_fingerprint=str(getattr(getattr(task, 'active_inventory_candidate_set', None), 'input_fingerprint', '') or ''),
sources=[
{
@@ -99,7 +107,7 @@ def create_inventory_preparation_round(
for item in round_row.source_attempts
],
reservation_version=str(getattr(task, 'order_data_version', '') or ''),
matching_rule_version=str(getattr(task, 'inventory_source_config_version', '') or ''),
matching_rule_version=str(active_inventory_runtime_facts(task).get('source_config_version') or ''),
)
db.session.flush()
return round_row
@@ -313,9 +313,25 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor
"inventory_rpa_wait_rechecked",
{"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
)
# [STEP] 单次 RPA 触发已超时且无更晚成功回执:不做自动重试,记录超时失败并落
# rpa_exhausted 人工接管;两个事件供审计/前端识别“等待超时 → 重试耗尽”。
log_task_event(
task,
"inventory_rpa_failed",
{
"error": "timeout",
"elapsed_seconds": elapsed,
"timeout_seconds": timeout_seconds,
},
)
log_task_event(
task,
"inventory_rpa_exhausted",
{"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
)
db.session.flush()
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
_set_workflow_error(task, "RPA 库存导出等待超时,请选择重新获取库存或上传库存 Excel")
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
_set_workflow_error(task, "RPA 库存导出等待超时,已停止自动重试,请选择重新获取库存或上传库存 Excel")
db.session.commit()
return tool_response(
status="needs_human",
@@ -18,7 +18,9 @@ from sqlalchemy import event as _sa_event
from sqlalchemy.orm import Session
from app import db
from app.core.errors import AppError
from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink
from app.services.shipping_notice.tool_common import task_event_task_id
from app.services.shipping_notice.inventory_file_store import (
_can_relink_inventory,
generate_inventory_file_no,
@@ -468,24 +470,24 @@ def link_snapshot_to_task(
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
source = get_database_inventory_source(task.inventory_source_code)
source = get_database_inventory_source(inv_file.source_code)
if source is None:
return None
resolved_warehouse_id = inv_file.warehouse_id
if str(source.get('warehouse_resolution_mode') or '').strip().lower() == 'inventory_match':
from app.services.shipping_notice.inventory_warehouse_resolution import resolve_dynamic_warehouse
lines = [row for row in (inv_file.inventory_lines_json or []) if isinstance(row, dict)]
if not lines and Path(inv_file.storage_path).is_file():
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
lines, _column_meta = parse_inventory_snapshot_file(inv_file)
inv_file.inventory_lines_json = lines
inv_file.line_count = len(lines)
try:
lines, _column_meta = read_inventory_file_lines(inv_file)
except (OSError, ValueError, AppError):
lines = []
resolution = resolve_dynamic_warehouse(
task=task,
inventory_lines=lines,
fallback_warehouse_id=inv_file.warehouse_id,
source_code=inv_file.source_code,
)
if not resolution.warehouse_id:
# identity_status 受数据库枚举约束,仅保存状态;具体动态仓解析原因
@@ -513,10 +515,6 @@ def link_snapshot_to_task(
if not identity_ok:
return None
# 动态 Source 不预维护 Warehouse;以已校验库存文件的 Warehouse 固化本任务身份。
if not task.inventory_warehouse_id:
task.inventory_warehouse_id = resolved_warehouse_id
link = replace_task_inventory_link(task, inv_file, role=role)
link.link_reason = reason
link.matched_warehouse_id = resolved_warehouse_id
@@ -533,10 +531,9 @@ def link_snapshot_to_task(
"inventory_file_no": inv_file.inventory_file_no,
"trigger_type": (inv_file.source_query_json or {}).get("trigger_type"),
}
task.inventory_snapshot_id = inv_file.id
db.session.add(
ShippingTaskEvent(
task_id=task.id,
task_id=task_event_task_id(task),
event_type="inventory_snapshot_linked",
detail_json={
"inventory_file_no": inv_file.inventory_file_no,
@@ -574,7 +571,7 @@ def link_snapshot_to_task_for_preparation(
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
source = get_database_inventory_source(task.inventory_source_code)
source = get_database_inventory_source(inv_file.source_code)
if (
source is None
or str(source.get('warehouse_resolution_mode') or '').strip().lower() != 'inventory_match'
@@ -595,7 +592,6 @@ def link_snapshot_to_task_for_preparation(
'inventory_file_no': inv_file.inventory_file_no,
'identity_status': inv_file.identity_status,
}
task.inventory_snapshot_id = inv_file.id
return link
@@ -1,8 +1,8 @@
"""
services/shipping_notice/inventory_source_gate.py
用途:库存源稳定性门禁、独立字段写入与路由指纹管理。
依赖:inventory_source_rules、inventory_source_repository、models.ShippingNotice、core.errors。
用途:库存源稳定性门禁;路由真相由 CandidateSet 承接,库存文件由 Link 承接。
依赖:inventory_source_rules、inventory_source_repository、models.ShippingOrderTask、core.errors。
逻辑:动态订单抽取先裁决线索;STP 建单可冻结单/多候选(candidates_frozen 视为可进入库存准备);
解析确认通过后未稳定才进入 inventory_source_review;RPA/库存/匹配/导出统一经本模块硬门禁。
"""
@@ -12,7 +12,7 @@ from __future__ import annotations
from typing import Any
from app.core.errors import AppError
from app.models import ShippingNotice
from app.models import ShippingOrderTask
from app.services.shipping_notice.inventory_source_rules import (
InventorySourceAdjudication,
adjudicate_inventory_source,
@@ -29,8 +29,6 @@ from app.services.shipping_notice.inventory_source_repository import (
)
STABLE_INVENTORY_SOURCE_STATUSES = frozenset({"resolved", "candidates_frozen"})
INVENTORY_SOURCE_ERROR_CODES = {
"unresolved": "SHIPPING.INVENTORY_SOURCE_UNRESOLVED",
"ambiguous": "SHIPPING.INVENTORY_SOURCE_AMBIGUOUS",
@@ -42,7 +40,7 @@ INVENTORY_SOURCE_ERROR_CODES = {
}
def is_inventory_source_stable(task: ShippingNotice) -> bool:
def is_inventory_source_stable(task: ShippingOrderTask) -> bool:
"""
判断任务库存源是否稳定,可供后续库存/RPA/匹配流程使用。
@@ -50,135 +48,81 @@ def is_inventory_source_stable(task: ShippingNotice) -> bool:
STP 多候选冻结(candidates_frozen)在候选非空且各候选源存在时视为稳定。
不比对全局配置版本 hash 或路由指纹——无关库存源的改动不使本任务失效。
"""
status = str(task.inventory_source_status or "").strip()
if status not in STABLE_INVENTORY_SOURCE_STATUSES:
return False
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
if status == "candidates_frozen":
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
codes = task_frozen_inventory_source_codes(task)
return bool(codes) and all(get_database_inventory_source(code) for code in codes)
code = str(task.inventory_source_code or "").strip().upper()
if not code:
codes = task_frozen_inventory_source_codes(task)
lines = get_active_candidate_lines(task)
if not codes or not lines or any(not list(row.source_codes_json or []) for row in lines):
return False
connector_type = str(task.inventory_connector_type or "").strip()
if not connector_type:
return False
source = get_database_inventory_source(code)
if not source:
return False
if connector_type != str(source.get("connector_type") or "").strip():
return False
mode = str(source.get('warehouse_resolution_mode') or '').strip().lower()
fixed_warehouse = str(source.get('fixed_warehouse_id') or '').strip().upper()
task_warehouse = str(task.inventory_warehouse_id or '').strip().upper()
if mode == 'fixed' and task_warehouse != fixed_warehouse:
return False
for code in codes:
source = get_database_inventory_source(code)
if not source:
return False
if str(source.get('warehouse_resolution_mode') or '').strip().lower() == 'fixed' and not str(source.get('fixed_warehouse_id') or '').strip():
return False
return True
def routing_fingerprint_changed(task: ShippingNotice, context: dict[str, Any]) -> bool:
def routing_fingerprint_changed(task: ShippingOrderTask, context: dict[str, Any]) -> bool:
"""比较当前路由上下文与任务已存指纹,判断库存源裁决是否因事实变化失效。"""
previous = str(task.inventory_routing_fingerprint or "").strip()
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
current = get_active_candidate_set(task)
previous = str((getattr(current, 'routing_rule_version_json', None) or {}).get('routing_fingerprint') or '').strip()
if not previous:
return False
return previous != compute_routing_fingerprint(context)
def inventory_source_config_changed(task: ShippingNotice) -> bool:
def inventory_source_config_changed(task: ShippingOrderTask) -> bool:
"""
配置变更判定(档位一收窄):仅当任务实际选中的库存源自身不再可用时才算配置已变。
核心逻辑:不再比对全局配置版本 hash——无关库存源的改动不影响本任务;
只检查任务冻结时选中的源(或冻结候选集)当前是否仍可用(存在且启用、驱动一致)。
"""
status = str(task.inventory_source_status or "").strip()
if status not in STABLE_INVENTORY_SOURCE_STATUSES:
# 未稳定任务沿用旧语义:已有裁决状态即视为需要重新裁决。
return bool(status)
return not is_inventory_source_stable(task)
def apply_destination_fields(task: ShippingNotice, context: dict[str, Any]) -> None:
"""将标准化目的地线索写入任务独立字段。"""
task.destination_code = str(context.get("destination_code") or "").strip().upper() or None
task.destination_city = str(context.get("destination_city") or "").strip() or None
task.destination_country = str(context.get("destination_country") or "").strip().upper() or None
task.warehouse_hint = str(context.get("warehouse_hint") or "").strip() or None
def clear_inventory_source_confirmation(task: ShippingNotice) -> None:
def clear_inventory_source_confirmation(task: ShippingOrderTask) -> None:
"""路由指纹或配置版本变化时清除历史人工确认信息及过期 RPA 参数。"""
task.inventory_source_confirmed_by = None
task.inventory_source_confirmed_at = None
if str(task.inventory_source_status or "").strip() == "user_confirmed":
task.inventory_source_status = "unresolved"
task.inventory_source_method = None
payload = dict(task.step_payload_json or {})
payload = dict(getattr(task, 'step_payload_json', None) or {})
payload.pop("rpa_inventory_source", None)
task.step_payload_json = payload
def apply_inventory_source_adjudication(
task: ShippingNotice,
task: ShippingOrderTask,
adjudication: InventorySourceAdjudication,
*,
execution_id: int | None = None,
) -> None:
"""
将裁决结果写入任务独立字段,并同步候选/证据到 step_payload_json。
核心逻辑:正式身份以独立字段为准;JSON 仅承载展示与审计辅助信息。
将裁决结果冻结为 CandidateSet;无候选时由 Gate 保存阻断事实。
Args:
execution_id: 可选;传给 ``freeze_candidates_for_task``,使重冻结不撤销当前
正在执行的门禁链(否则会误 supersede 活动 Execution)。
"""
context = extract_routing_context(task)
fingerprint = adjudication.routing_fingerprint or compute_routing_fingerprint(context)
task.inventory_routing_fingerprint = fingerprint
apply_destination_fields(task, context)
task.inventory_source_status = adjudication.status
task.inventory_source_method = adjudication.method or None
task.inventory_source_config_version = adjudication.config_version or inventory_sources_runtime_version()
if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code:
task.inventory_source_code = adjudication.source_code
task.inventory_connector_type = adjudication.connector_type
task.inventory_warehouse_id = adjudication.warehouse_id or None
elif adjudication.status not in STABLE_INVENTORY_SOURCE_STATUSES:
task.inventory_source_code = None
task.inventory_connector_type = None
task.inventory_warehouse_id = None
payload = dict(task.step_payload_json or {})
payload.pop("rpa_inventory_source", None)
task.step_payload_json = payload
payload = dict(task.step_payload_json or {})
payload["inventory_source_resolution"] = {
"status": adjudication.status,
"method": adjudication.method,
"reason": adjudication.reason,
"destination_candidates": adjudication.destination_candidates,
"candidates": adjudication.candidates,
"evidence": adjudication.evidence,
"conflicts": adjudication.conflicts,
"config_version": adjudication.config_version,
"routing_fingerprint": fingerprint,
}
if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code:
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
rpa_source = task_rpa_inventory_source(task)
if rpa_source:
payload["rpa_inventory_source"] = rpa_source
else:
payload.pop("rpa_inventory_source", None)
task.step_payload_json = payload
if any(str(item.get('source_code') or '').strip() for item in (adjudication.candidates or []) if isinstance(item, dict)):
freeze_candidates_for_task(
task, adjudication=adjudication, execution_id=execution_id,
)
def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySourceAdjudication:
def adjudicate_and_apply_inventory_source(
task: ShippingOrderTask,
*,
execution_id: int | None = None,
) -> InventorySourceAdjudication:
"""
对任务执行库存源裁决并写入独立字段。
【AI 触发时机】:订单抽取提交完成后由后端编排调用;重解析时同样调用以刷新裁决。
【AI 触发时机】:订单抽取提交完成后由后端编排调用;重解析时同样调用以刷新裁决;
库存准备 Gate 在任务尚无冻结候选源时补裁决(传入当前 execution_id 以避免撤销活动链)。
Args:
execution_id: 可选;透传给冻结服务,使重冻结不撤销当前正在执行的门禁链。
"""
context = extract_routing_context(task)
if inventory_source_config_changed(task) or routing_fingerprint_changed(task, context):
@@ -201,7 +145,9 @@ def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySour
)
):
try:
freeze_result = freeze_candidates_for_task(task, adjudication=adjudication)
freeze_result = freeze_candidates_for_task(
task, adjudication=adjudication, execution_id=execution_id,
)
# 冻结成功后升级裁决为 candidates_frozen;apply_inventory_source_adjudication 会再写一次字段,
# 但冻结服务已写好 task.status=method=config=fingerprint,结果一致。
evidence_merged = list(adjudication.evidence or [])
@@ -232,12 +178,12 @@ def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySour
# 保留原 ambiguous 让下游 is_inventory_source_stable 正确进入规则重算阻断。
pass
apply_inventory_source_adjudication(task, adjudication)
apply_inventory_source_adjudication(task, adjudication, execution_id=execution_id)
return adjudication
def transition_task_to_inventory_source_review(
task: ShippingNotice,
task: ShippingOrderTask,
adjudication: InventorySourceAdjudication,
*,
error_message: str | None = None,
@@ -251,9 +197,11 @@ def transition_task_to_inventory_source_review(
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
task.current_step = "step2_parse_confirm"
# OT 的流程阶段字段是 stage;current_step 属于已创建 Notice 的历史工作流,
# 不能在通知准备前写入 OT。
task.stage = "inventory_source_resolving"
task.error_message = error_message or "无法根据发货通知唯一确定库存查询来源"
payload = dict(task.step_payload_json or {})
payload = dict(getattr(task, 'step_payload_json', None) or {})
payload["inventory_source_resolution"] = {
"status": adjudication.status,
"method": adjudication.method,
@@ -268,7 +216,7 @@ def transition_task_to_inventory_source_review(
task.step_payload_json = payload
def ensure_inventory_source_review_state(task: ShippingNotice) -> InventorySourceAdjudication:
def ensure_inventory_source_review_state(task: ShippingOrderTask) -> InventorySourceAdjudication:
"""
对已通过解析确认但库存源仍不稳定的任务,补做规则裁决并落库到内部恢复检查点。
@@ -282,7 +230,7 @@ def ensure_inventory_source_review_state(task: ShippingNotice) -> InventorySourc
def assert_inventory_source_gate(
task: ShippingNotice,
task: ShippingOrderTask,
*,
operation: str = "continue",
) -> None:
@@ -307,36 +255,67 @@ def assert_inventory_source_gate(
)
if is_inventory_source_stable(task):
return
status = str(task.inventory_source_status or "unresolved").strip()
code = INVENTORY_SOURCE_ERROR_CODES.get(status, INVENTORY_SOURCE_ERROR_CODES["gate_blocked"])
reason_by_status = {
"conflicted": "inventory_source_conflicted",
"changed": "inventory_source_changed",
"identity_mismatch": "inventory_source_identity_mismatch",
}
code = INVENTORY_SOURCE_ERROR_CODES['unresolved']
raise AppError(
code=code,
message="库存源尚未确定,无法继续后续流程",
http_status=409,
details={
"operation": operation,
"inventory_source_status": status,
"inventory_source_status": 'unresolved',
"task_no": task.task_no,
"reason_code": reason_by_status.get(status, "require_manual_review"),
"reason_code": "require_manual_review",
},
)
def task_inventory_identity(task: ShippingNotice) -> dict[str, str | None]:
"""返回任务当前正式库存身份;多候选冻结时 source 摘要可为空。"""
def task_inventory_identity(task: ShippingOrderTask) -> dict[str, str | None]:
"""返回库存执行身份;固定仓来自配置,动态仓仅来自已验证库存 Link。"""
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
source_codes = task_frozen_inventory_source_codes(task)
source_code = source_codes[0] if len(source_codes) == 1 else None
source = get_database_inventory_source(source_code) if source_code else None
return {
"inventory_source_code": str(task.inventory_source_code or "").strip().upper() or None,
"inventory_warehouse_id": str(task.inventory_warehouse_id or "").strip().upper() or None,
"inventory_source_code": source_code,
"inventory_warehouse_id": resolve_inventory_source_warehouse_id(task, source=source),
}
def resolve_inventory_source_warehouse_id(
task: ShippingOrderTask,
*,
source: dict[str, Any] | None,
) -> str | None:
"""解析库存执行仓库:固定仓读 Source 配置,动态仓只读有效库存 Link。"""
if not source:
return None
mode = str(source.get('warehouse_resolution_mode') or '').strip().lower()
if mode == 'fixed':
return str(source.get('fixed_warehouse_id') or '').strip().upper() or None
task_id = getattr(task, 'id', None)
source_code = str(source.get('source_code') or '').strip().upper()
if not task_id or not source_code:
return None
from app.models import ShippingTaskInventoryLink
link = ShippingTaskInventoryLink.query.filter_by(
task_id=int(task_id),
matched_source_code=source_code,
is_active=True,
).order_by(ShippingTaskInventoryLink.id.desc()).first()
if link is None:
return None
return (
str(link.matched_warehouse_id or '').strip().upper()
or str(getattr(link.inventory_file, 'warehouse_id', '') or '').strip().upper()
or None
)
def inventory_identities_match(
task: ShippingNotice,
task: ShippingOrderTask,
*,
source_code: str | None,
warehouse_id: str | None,
@@ -344,8 +323,7 @@ def inventory_identities_match(
"""
校验库存文件 Source;固定仓严格匹配,动态仓允许从库存文件中解析。
核心逻辑:单源任务要求与 task.inventory_source_code 一致;
candidates_frozen 时允许文件源属于冻结候选集合。
核心逻辑:单源任务要求与唯一 CandidateSource 一致;多源允许文件源属于当前 CandidateSet。
"""
if not is_inventory_source_stable(task):
return False
@@ -15,7 +15,8 @@ from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Any
from app.models import ShippingNotice
from app import db
from app.models import ShippingNotice, ShippingOrderSnapshot
from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules
from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity
from app.services.shipping_notice.inventory_source_repository import (
@@ -49,17 +50,26 @@ InventorySourceResolution = InventorySourceAdjudication
def extract_routing_context(task: ShippingNotice) -> dict[str, Any]:
"""投影任务字段为路由审计上下文,不依赖 YAML 目的地别名。"""
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
"""从冻结订单(冻结前为当前 Extraction)读取路由审计上下文。"""
header = current_header_field_values_or_empty(task)
snapshot_id = getattr(task, 'order_snapshot_id', None)
snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id)) if snapshot_id else None
if snapshot is not None:
fields = list((getattr(snapshot.schema_version, 'definition_json', None) or {}).get('fields') or [])
frozen_values = dict(snapshot.header_values_json or {})
header = {
str(field.get('field_code') or ''): frozen_values.get(str(field.get('field_id') or ''))
for field in fields
if field.get('scope') == 'header' and str(field.get('field_code') or '')
}
return {
'destination_code': task.destination_code,
'destination_city': task.destination_city,
'destination_country': task.destination_country,
'warehouse_hint': task.warehouse_hint,
'destination_code': header.get('destination_code'),
'destination_city': header.get('destination_city'),
'destination_country': header.get('destination_country'),
'warehouse_hint': header.get('warehouse_hint'),
'customer_code': header.get('customer_code'),
'customer_name': header.get('customer_name') or header.get('bill_to_customer'),
'order_type': payload.get('order_type'),
'customer_name': header.get('customer_name'),
'order_type': header.get('order_type'),
'destination_candidates': [],
}
@@ -165,7 +175,7 @@ def resolve_ambiguous_source_from_ready_snapshots(
if len(order_keys) != len(order_lines):
return adjudication
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot
matched: list[tuple[dict[str, Any], Any]] = []
@@ -179,12 +189,10 @@ def resolve_ambiguous_source_from_ready_snapshots(
if snapshot is None:
checked.append({'source_code': source_code, 'snapshot': 'missing'})
continue
lines = [row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)]
if not lines:
try:
lines, _column_meta = parse_inventory_snapshot_file(snapshot)
except (OSError, ValueError):
lines = []
try:
lines, _column_meta = read_inventory_file_lines(snapshot)
except (OSError, ValueError):
lines = []
inventory_keys = {
key for row in lines
if isinstance(row, dict) and (key := _snapshot_match_key(row))
@@ -251,10 +259,7 @@ def resolve_inventory_source(task: ShippingNotice) -> InventorySourceAdjudicatio
def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None:
"""按任务 Source 或冻结多候选中的首个可用源读取 RPA/快照配置。"""
primary = get_database_inventory_source(task.inventory_source_code)
if primary is not None:
return primary
"""按当前冻结 CandidateSet 的首个可用源读取 RPA/快照配置。"""
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
for code in task_frozen_inventory_source_codes(task):
@@ -265,7 +270,7 @@ def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None:
def save_task_rpa_inventory_source(task: ShippingNotice, source: dict[str, Any], *, resolution: InventorySourceAdjudication | None = None) -> None:
"""持久化规则裁决结果;禁止根据调用方传入 source_code 人工覆盖。"""
"""持久化规则裁决结果到 CandidateSet;禁止调用方直接写 OT。"""
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
del source
@@ -19,7 +19,7 @@ from typing import Any
from flask import current_app
from werkzeug.datastructures import FileStorage
from app.models import ShippingInventoryFile, ShippingNotice
from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.export import _storage_root
from app.services.shipping_notice.inventory_file_store import inventory_storage_suffix_for_path
_TASK_INVENTORY_SUFFIXES = (".xls", ".xlsx", ".csv")
@@ -163,7 +163,7 @@ def install_task_inventory_attachment_from_file(
def rebuild_task_inventory_attachment_from_snapshot(
task: ShippingNotice | str,
task: ShippingOrderTask | ShippingNotice | str,
inv_file: ShippingInventoryFile,
) -> Path:
"""
@@ -177,7 +177,7 @@ def rebuild_task_inventory_attachment_from_snapshot(
Returns:
重建后的任务正式附件路径。
"""
task_no = task.task_no if isinstance(task, ShippingNotice) else str(task or "").strip()
task_no = str(getattr(task, "task_no", task) or "").strip()
if not task_no:
raise ValueError("task_no is required")
storage_path = Path(str(inv_file.storage_path or ""))
@@ -29,9 +29,9 @@ def _key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None:
return values if values and all(values) else None
def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any]], fallback_warehouse_id: str | None = None) -> WarehouseResolution:
def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any]], fallback_warehouse_id: str | None = None, source_code: str | None = None) -> WarehouseResolution:
"""按站点已发布解析方案为全部订单行寻找唯一 Warehouse。"""
source = ShippingInventorySource.query.filter_by(source_code=task.inventory_source_code).first()
source = ShippingInventorySource.query.filter_by(source_code=source_code).first()
definition = source.parsing_profile.definition_json if source and source.parsing_profile else {}
match_keys = definition.get('match_keys') if isinstance(definition, dict) else []
order_fields = [str(item.get('order_field_id') or '') for item in match_keys if isinstance(item, dict)]
@@ -13,7 +13,7 @@ from typing import Any
from app import db
from app.core.errors import AppError
from app.models import ShippingNotice
from app.models import ShippingOrderTask
from app.services.shipping_notice.constants import (
CP_INVENTORY_SOURCE_REVIEW,
)
@@ -52,7 +52,7 @@ def parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | Non
return None
def _reservation_gate_response(task: ShippingNotice, *, lang: str) -> dict[str, Any] | None:
def _reservation_gate_response(task: ShippingOrderTask, *, lang: str) -> dict[str, Any] | None:
"""
库存入口统一检查订单侧 Reservation ID。
@@ -86,7 +86,7 @@ def _reservation_gate_response(task: ShippingNotice, *, lang: str) -> dict[str,
)
def _inventory_source_gate_response(task: ShippingNotice, *, operation: str, lang: str) -> dict[str, Any] | None:
def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str, lang: str) -> dict[str, Any] | None:
"""
库存相关 Tool 入口统一门禁;未稳定时返回 needs_human 响应。
核心逻辑:先拦客户与 Reservation,再检查库存源稳定性;仅捕获预期 AppError。
@@ -112,6 +112,43 @@ def _inventory_source_gate_response(task: ShippingNotice, *, operation: str, lan
reservation_gate = _reservation_gate_response(task, lang=lang)
if reservation_gate is not None:
return reservation_gate
if operation == "ensure_inventory":
# [STEP 0A] 库存准备只能消费已经冻结的路由事实;不得在本阶段补做裁决或
# 触发 RPA。CandidateSet、Source、Line 任一缺失都必须停留在 routing Gate。
from app.services.shipping_notice.inventory_candidate_projection import (
get_active_candidate_lines,
get_active_candidate_set,
get_active_candidate_sources,
)
candidate_set = get_active_candidate_set(task)
sources = get_active_candidate_sources(task)
lines = get_active_candidate_lines(task)
invalid_lines = [
line for line in lines
if not list(getattr(line, "source_codes_json", None) or [])
]
if (
not task.order_snapshot_id
or candidate_set is None
or str(getattr(candidate_set, "lifecycle_status", "") or "").lower() != "frozen"
or not sources
or not lines
or invalid_lines
):
return tool_response(
status="needs_human",
task=task,
message="库存源候选集尚未冻结完成,暂不能准备库存。",
data={
**serialize_task_for_tool(task),
"error_code": "SHIPPING.INVENTORY_SOURCE_ROUTING_REQUIRED",
"checkpoint": CP_INVENTORY_SOURCE_REVIEW,
},
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
forbidden_next_tools=["ensure_inventory", "match_inventory", "generate_shipment_excel"],
)
if is_inventory_source_stable(task):
return None
try:
@@ -138,7 +175,8 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
gate_resp = _inventory_source_gate_response(task, operation="upload_inventory_file", lang=lang)
if gate_resp is not None:
return gate_resp
if str(getattr(task, 'upload_status', None) or '').strip().lower() in {'uploaded', 'succeeded', 'success'} or str(getattr(task, 'lifecycle_status', None) or '').strip().lower() in {'voided', 'archived', 'deleted'}:
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
if has_verified_upload_success(task) or str(getattr(task, 'lifecycle_status', None) or '').strip().lower() in {'voided', 'archived', 'deleted'}:
return tool_response(
status="failed",
task=task,
@@ -267,6 +305,9 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# [STEP 1] 优先接受当前请求直接携带的库存明细。
# 这条路径用于小表/结构化库存输入,能直接跳过上传与 RPA 等外围链路。
mode = str(payload.get("mode") or "auto").strip().lower()
# 只读轮询开关:poll_inventory_preparation 查询路径传 False——轮询只消费 RPA Attempt 事实,
# 禁止在查询中自动新建 Attempt;重试必须由用户显式动作(mode='retry_rpa')发起。
allow_auto_retry = bool(payload.get('allow_auto_retry', True))
inventory_lines = parse_inventory_lines(payload)
if inventory_lines:
return inventory_loaded_response(
@@ -290,7 +331,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# [STEP] STP 多候选:准备全部冻结源快照;缺文件则停在库存等待,不隐式触发 RPA。
frozen_codes = task_frozen_inventory_source_codes(task)
if len(frozen_codes) > 1 or str(task.inventory_source_status or '').strip() == 'candidates_frozen':
if len(frozen_codes) >= 1:
prep = prepare_candidate_inventory_lines(task)
if prep.get('status') == 'blocked' and prep.get('error_code') == 'inventory_candidates_missing':
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
@@ -319,7 +360,70 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
},
},
)
if prep.get('status') == 'missing_files':
if prep.get('status') in {'missing_files', 'partial_missing'}:
# [STEP] 缺失源自动批次探测(设计 D3/D4):不再停在 needs_human;
# 已有 ready 快照的源由 ensure_all_required_sources_prepared 复用,
# 仅缺失源进入单批次 trigger;回调后由下一轮 ensure 继续推进匹配。
from app.services.shipping_notice.per_source_rpa_service import (
ensure_all_required_sources_prepared,
)
probe = ensure_all_required_sources_prepared(task, mode=mode, allow_auto_retry=allow_auto_retry)
if probe.pending_source_codes:
apply_task_transition(task, TaskTransition.RPA_PENDING)
task.error_message = None
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="running",
message="已触发库存获取,等待各库存源回调。",
progress_percent=60,
detail="等待库存 RPA 回调",
)
db.session.commit()
return tool_response(
status="running",
task=task,
message="已触发库存获取,等待各库存源回调。",
data={
**serialize_task_for_tool(task),
'rpa': {'pending_source_codes': list(probe.pending_source_codes)},
},
)
if probe.all_prepared:
# 探测期间快照已就绪(竞态收敛):重载一次候选行后走正常加载。
prep = prepare_candidate_inventory_lines(task)
else:
# 探测无 pending(trigger 写入失败/无可用源):明确 needs_human 兜底。
log_task_event(task, "inventory_probe_failed", {
'failed_source_codes': list(probe.failed_source_codes or []),
})
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="needs_human",
message="库存 RPA 未能为全部库存源生成结果。",
progress_percent=100,
detail="请重新获取库存或上传库存 Excel。",
)
db.session.commit()
return tool_response(
# [只读轮询失败语义] poll(allow_auto_retry=False)查询到源失败事实时
# 返回 status='failed'(executor 映射为 blocked_retryable),
# 不伪装成人工阻断;显式路径维持 needs_human。
status="failed" if not allow_auto_retry else "needs_human",
task=task,
message="库存 RPA 未能为全部库存源生成结果。",
data={
**serialize_task_for_tool(task),
'blocking_reason': {'code': 'inventory_preparation_failed'},
'poll_read_only': not allow_auto_retry,
},
)
if prep.get('status') in {'missing_files', 'partial_missing'}:
# 防御:探测后仍缺失(如快照在探测窗口内失效),不得带着残缺数据进入匹配。
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
@@ -343,32 +447,6 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
'missing_source_codes': prep.get('missing_source_codes') or [],
},
)
if prep.get('status') == 'partial_missing':
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="needs_human",
message=t("workflow.inventory.unavailable", lang=lang),
progress_percent=0,
detail=t("workflow.inventory.unavailable", lang=lang),
)
log_task_event(task, "inventory_candidate_files_partial", {
'missing_source_codes': prep.get('missing_source_codes') or [],
'loaded_source_codes': prep.get('loaded_source_codes') or [],
})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=t("workflow.inventory.unavailable", lang=lang),
data={
**serialize_task_for_tool(task),
'missing_source_codes': prep.get('missing_source_codes') or [],
'loaded_source_codes': prep.get('loaded_source_codes') or [],
},
)
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
return inventory_loaded_response(
@@ -391,11 +469,13 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# 否则任务会错误停在人审且没有可执行的恢复动作。
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
return ensure_inventory_via_rpa(task, mode=mode)
return ensure_inventory_via_rpa(task, mode=mode, allow_auto_retry=allow_auto_retry)
# [STEP 3] 最后处理已有任务库存与彻底缺库存两种兜底分支。
# 已有库存则推进到 inventory_ready;仍无库存则明确停在人审提示用户补数据。
if task.inventory_lines_json:
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
if has_ready_inventory_file_for_task(task):
apply_task_transition(task, TaskTransition.INVENTORY_READY)
db.session.commit()
return tool_response(
@@ -3,7 +3,7 @@ services/shipping_notice/line_inventory_match_persistence.py
用途:inventory_matching 完成后把逐行结果写入 OT 行库存匹配事实表(Slice 1)。
依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。
逻辑:由 fulfillment_workflow.match_inventory 调用;按 draft line_key(行序)落库;
逻辑:由 fulfillment_workflow.match_inventory 调用;按冻结订单行 snapshot_line_id 落库;
新快照新增行并切换 is_current;不覆盖历史快照事实。
"""
@@ -26,19 +26,6 @@ from app.services.shipping_notice.inventory_candidate_projection import (
)
def _draft_line_keys_by_index(case: ShippingOrderReviewCase | None) -> dict[int, str]:
"""Case 草稿行序 → line_key。"""
if case is None or case.current_draft is None:
return {}
out: dict[int, str] = {}
for idx, line in enumerate(list(case.current_draft.lines_json or [])):
if not isinstance(line, dict):
continue
key = str(line.get('line_key') or '').strip() or f'line-{idx + 1}'
out[idx] = key
return out
def resolve_review_case_for_task(task: ShippingNotice) -> ShippingOrderReviewCase | None:
"""
反查确认到该 OT 的 Review Case。
@@ -85,6 +72,24 @@ def map_disposition_to_match_codes(
return 'result_missing', 'unavailable'
def _line_resolved_source_code(task: ShippingNotice, result: dict[str, Any]) -> str | None:
"""
行级已定源:优先取匹配结果,缺失时回退到任务级已定源(Approach 1)。
核心逻辑:匹配未回填源时,只有当前 CandidateSet 恰有一个源才回填;
不从 OT 读取任务级库存源投影。
"""
src = str(result.get('resolved_inventory_source_code') or '')[:64] or None
if src:
return src
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
source_codes = task_frozen_inventory_source_codes(task)
if len(source_codes) == 1:
return source_codes[0][:64]
return None
def persist_line_inventory_match_facts(
*,
task: ShippingNotice,
@@ -95,14 +100,15 @@ def persist_line_inventory_match_facts(
"""
将 match_order_lines_across_candidates 结果持久化为当前事实。
核心逻辑:按 line_index 解析 draft line_key;同快照幂等更新;否则新增并切换 is_current;
核心逻辑:按冻结订单行项次解析 snapshot_line_id;同快照幂等更新;否则新增并切换 is_current;
无 inventory_snapshot_id 时禁止写入 ready/not_found;单位写入事实列。
"""
case = resolve_review_case_for_task(task)
keys_by_index = _draft_line_keys_by_index(case)
snap_id = inventory_snapshot_id
if snap_id is None and getattr(task, 'inventory_snapshot_id', None) is not None:
snap_id = int(task.inventory_snapshot_id)
if snap_id is None:
from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts
snap_id = active_inventory_runtime_facts(task).get('inventory_file_id')
# 匹配器结果可能未回填 inventory_file_no,但当前快照本身已是行匹配的
# 正式文件身份。持久化必须补齐,避免“有快照却无行级下载证据”。
snapshot_file_no = None
@@ -129,6 +135,12 @@ def persist_line_inventory_match_facts(
int(row.line_no): row
for row in get_active_candidate_lines(task)
}
from app.models import ShippingOrderSnapshot
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) if task.order_snapshot_id else None
snapshot_lines_by_no = {
int(line.line_no): line for line in (snapshot.lines if snapshot is not None else [])
if str(getattr(line, 'line_no', '') or '').isdigit()
}
for result in line_results:
try:
@@ -136,15 +148,11 @@ def persist_line_inventory_match_facts(
except (TypeError, ValueError):
continue
res = res_by_index.get(index) or {}
# Case 草稿 line_key 是订单明细的正式身份;匹配器临时 line-1 只能兜底,
# 禁止覆盖 machine-1 等正式键,否则事实已落库但工作台无法关联显示。
line_key = str(
keys_by_index.get(index)
or res.get('line_key')
or f'line-{index + 1}'
).strip()
if not line_key:
line_no = index + 1
snapshot_line = snapshot_lines_by_no.get(line_no)
if snapshot_line is None:
continue
snapshot_line_id = int(snapshot_line.id)
match_result, inventory_status = map_disposition_to_match_codes(
disposition=str(result.get('disposition') or res.get('disposition') or ''),
@@ -192,7 +200,8 @@ def persist_line_inventory_match_facts(
ShippingNoticeLineInventoryMatch.query
.filter_by(
task_id=int(task.id),
line_key=line_key,
snapshot_line_id=snapshot_line_id,
line_no=line_no,
inventory_snapshot_id=int(snap_id),
)
.first()
@@ -200,7 +209,7 @@ def persist_line_inventory_match_facts(
if existing is None and snap_id is None:
existing = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), line_key=line_key, is_current=True)
.filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True)
.filter(ShippingNoticeLineInventoryMatch.inventory_snapshot_id.is_(None))
.first()
)
@@ -208,18 +217,17 @@ def persist_line_inventory_match_facts(
if existing is None:
(
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), line_key=line_key, is_current=True)
.filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True)
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
)
# Draft line_key 发生过版本切换时,按稳定 line_index 关闭旧键事实,
# 避免同一订单行同时存在两个 current 投影。
# 同一订单行按稳定 line_index 关闭旧事实,避免多个 current 投影。
(
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), line_index=index, is_current=True)
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
)
# [T6 E1] 行级证据哈希:SHA256(source_code|file_no|row_index|reservation_id|part_number)
src_code = str(result.get('resolved_inventory_source_code') or '')[:64] or None
src_code = _line_resolved_source_code(task, result)
file_no = str(result.get('inventory_file_no') or snapshot_file_no or '')[:128] or None
row_index_raw = result.get('inventory_row_index') or result.get('inventory_row_ref')
try:
@@ -249,7 +257,8 @@ def persist_line_inventory_match_facts(
row = ShippingNoticeLineInventoryMatch(
task_id=int(task.id),
review_case_id=int(case.id) if case is not None else None,
line_key=line_key,
snapshot_line_id=snapshot_line_id,
line_no=line_no,
line_index=index,
candidate_set_id=(
int(current_candidate_set.id)
@@ -301,7 +310,7 @@ def persist_line_inventory_match_facts(
written.append(row)
else:
# [T6 E1] 更新分支:同样重算 evidence_ref、matched_file_no、matched_row_index
src_code = str(result.get('resolved_inventory_source_code') or '')[:64] or None
src_code = _line_resolved_source_code(task, result)
file_no = str(result.get('inventory_file_no') or snapshot_file_no or '')[:128] or None
row_index_raw = result.get('inventory_row_index') or result.get('inventory_row_ref')
try:
@@ -374,14 +383,13 @@ def persist_line_inventory_match_facts(
ShippingNoticeLineInventoryMatch.query
.filter(
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
ShippingNoticeLineInventoryMatch.line_key == line_key,
ShippingNoticeLineInventoryMatch.snapshot_line_id == snapshot_line_id,
ShippingNoticeLineInventoryMatch.id != int(existing.id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
)
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
)
# Draft line_key 发生过版本切换时,更新已有新键也必须关闭旧键;
# 否则旧 key 会与新 key 同时进入 current 投影,导致订单明细不确定。
# 同一订单行更新时关闭旧事实,保证 current 投影唯一。
(
ShippingNoticeLineInventoryMatch.query
.filter(
@@ -414,8 +414,8 @@ def resolve_allowed_actions(
return [*inv, *line]
def load_current_match_facts_by_task(task_id: int | None) -> dict[str, dict[str, Any]]:
"""加载 OT 当前行匹配事实,键为 line_key。"""
def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str, Any]]:
"""加载 OT 当前行匹配事实,键为冻结订单行 ID。"""
if task_id is None:
return {}
rows = (
@@ -423,15 +423,27 @@ def load_current_match_facts_by_task(task_id: int | None) -> dict[str, dict[str,
.filter_by(task_id=int(task_id), is_current=True)
.all()
)
out: dict[str, dict[str, Any]] = {}
out: dict[int, dict[str, Any]] = {}
for row in rows:
key = str(row.line_key or '').strip()
if not key:
if row.snapshot_line_id is None:
continue
out[key] = serialize_match_fact(row)
out[int(row.snapshot_line_id)] = serialize_match_fact(row)
return out
def aggregate_match_status_for_task(task_id: int | None) -> str | None:
"""根据当前行级 Match 聚合任务匹配状态,禁止读取 OT/Notice 缓存字段。"""
facts = list(load_current_match_facts_by_task(task_id).values())
if not facts:
return None
blocked = any(
str(row.get('match_result') or '').strip().lower() != 'matched'
or str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}
for row in facts
)
return 'unfulfillable' if blocked else 'fulfillable'
def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any]:
"""将 ORM 行序列化为投影输入。"""
snapshot = (
@@ -442,7 +454,8 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any
'id': int(row.id),
'task_id': int(row.task_id),
'review_case_id': int(row.review_case_id) if row.review_case_id is not None else None,
'line_key': str(row.line_key),
'snapshot_line_id': int(row.snapshot_line_id),
'line_no': int(row.line_no),
'line_index': row.line_index,
'inventory_snapshot_id': (
int(row.inventory_snapshot_id) if row.inventory_snapshot_id is not None else None
@@ -27,6 +27,7 @@ from app.models import (
ShippingOrderReviewLineDecision,
ShippingOrderReviewWaveLine,
ShippingNotice,
ShippingOrderTask,
ShippingTaskInventoryRpaAttempt,
)
from app.services.shipping_notice.workflow_ledger_service import (
@@ -236,15 +237,16 @@ def _release_fact_identity(fact: dict[str, Any] | None) -> tuple[int | None, int
def _resolve_shortage_release_inventory_source(
*,
fact_source_code: Any,
task_source_code: Any,
snapshot_source_code: Any,
candidate_source_codes: set[str] | None = None,
) -> str | None:
"""按行事实、OT、快照顺序恢复短缺放行所需的库存源。"""
for value in (fact_source_code, task_source_code, snapshot_source_code):
"""按行事实、库存文件、唯一冻结候选源顺序恢复短缺放行所需的库存源。"""
for value in (fact_source_code, snapshot_source_code):
normalized = str(value or '').strip().upper()
if normalized:
return normalized
return None
codes = candidate_source_codes or set()
return next(iter(codes)) if len(codes) == 1 else None
def _is_shortage_match_fact(fact: Any) -> bool:
@@ -285,9 +287,6 @@ def _has_terminal_inventory_rpa_failure(
source_codes = {str(item or '').strip().upper() for item in task_frozen_inventory_source_codes(task)}
except Exception: # noqa: BLE001 - 放行资格宁可拒绝,不能因冻结读取异常绕过。
source_codes = set()
source_code = str(getattr(task, 'inventory_source_code', '') or '').strip().upper()
if source_code:
source_codes.add(source_code)
rows = attempts if attempts is not None else (
ShippingTaskInventoryRpaAttempt.query
.filter_by(task_no=task_no)
@@ -326,15 +325,21 @@ def _shortage_release_required_fields(
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
)
snapshot = db.session.get(ShippingInventoryFile, int(inventory_snapshot_id)) if inventory_snapshot_id is not None else None
if inventory_snapshot_id is not None and (snapshot is None or not isinstance(snapshot.inventory_lines_json, list)):
if inventory_snapshot_id is not None and snapshot is None:
raise ConflictError(
'Current inventory snapshot is unavailable',
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
)
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
resolved_source_code = _resolve_shortage_release_inventory_source(
fact_source_code=inventory_source_code,
task_source_code=getattr(task, 'inventory_source_code', None),
snapshot_source_code=getattr(snapshot, 'source_code', None) if snapshot is not None else None,
candidate_source_codes={
str(code or '').strip().upper()
for code in task_frozen_inventory_source_codes(task)
if str(code or '').strip()
},
)
if not resolved_source_code:
raise ConflictError(
@@ -366,7 +371,7 @@ def _shortage_release_required_fields(
and str(item.get('source_key') or '').strip().isdigit()
}
labels = {str(row.id): str(row.display_name or '').strip() for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()} if field_ids else {}
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels) + _release_template_system_fields(mappings=mappings, warehouse_id=getattr(task, 'inventory_warehouse_id', None))
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels)
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
match_keys = definition.get('match_keys') if isinstance(definition.get('match_keys'), list) else []
expected = [
@@ -378,9 +383,17 @@ def _shortage_release_required_fields(
'Inventory matching keys are unavailable',
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
)
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
try:
inventory_lines, _column_meta = read_inventory_file_lines(snapshot)
except (OSError, ValueError, AppError) as exc:
raise ConflictError(
'Current inventory snapshot is unavailable',
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
) from exc
candidates = [
dict(row) for row in snapshot.inventory_lines_json if isinstance(row, dict)
and all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected)
dict(row) for row in inventory_lines
if all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected)
]
field_ids = {
int(str(item.get('source_key') or '').strip())
@@ -398,9 +411,6 @@ def _shortage_release_required_fields(
mappings=mappings,
candidates=candidates,
field_labels=labels,
) + _release_template_system_fields(
mappings=mappings,
warehouse_id=getattr(task, 'inventory_warehouse_id', None),
)
@@ -426,7 +436,7 @@ def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, act
task_id = getattr(case, 'confirmed_task_id', None)
if task_id is None:
return
task = db.session.get(ShippingNotice, int(task_id))
task = db.session.get(ShippingOrderTask, int(task_id))
if task is None:
return
# [BE-释放-重算] 放行是库存充分性 Gate 的受控业务事实:必须先把任务级履约态
@@ -556,7 +566,7 @@ def _assess_line_fulfill_complete(
def _assert_line_can_fulfill_complete(
*,
line_key: str,
draft_line_id: str,
draft_line: dict[str, Any],
proj: dict[str, Any],
schema_fields: dict[str, dict[str, Any]] | None = None,
@@ -576,13 +586,13 @@ def _assert_line_can_fulfill_complete(
raise ConflictError(
'Line cannot fulfill complete quantity with current inventory',
code=str(code or 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY'),
details={'line_key': line_key},
details={'draft_line_id': draft_line_id},
)
return req, avail
def _draft_line_map(case: ShippingOrderReviewCase) -> dict[str, dict[str, Any]]:
"""line_key → 草稿行。"""
"""draft_line_id → 草稿行。"""
draft = case.current_draft
if draft is None:
return {}
@@ -590,16 +600,16 @@ def _draft_line_map(case: ShippingOrderReviewCase) -> dict[str, dict[str, Any]]:
for idx, line in enumerate(list(draft.lines_json or [])):
if not isinstance(line, dict):
continue
key = str(line.get('line_key') or '').strip() or f'line-{idx + 1}'
key = str(line.get('draft_line_id') or '').strip() or f'line-{idx + 1}'
row = dict(line)
row['_line_index'] = idx
row['_line_key'] = key
row['_draft_line_id'] = key
out[key] = row
return out
def _line_projection_map(case: ShippingOrderReviewCase) -> dict[str, dict[str, Any]]:
"""line_key → eligibility line projection。"""
"""draft_line_id → eligibility line projection。"""
draft = case.current_draft
if draft is None:
return {}
@@ -608,29 +618,29 @@ def _line_projection_map(case: ShippingOrderReviewCase) -> dict[str, dict[str, A
for idx, item in enumerate(list(validation.get('line_projections') or [])):
if not isinstance(item, dict):
continue
key = str(item.get('line_key') or '').strip() or f'line-{idx + 1}'
key = str(item.get('draft_line_id') or '').strip() or f'line-{idx + 1}'
out[key] = dict(item)
return out
def _active_decision(
case: ShippingOrderReviewCase,
line_key: str,
draft_line_id: str,
) -> ShippingOrderReviewLineDecision | None:
"""取某行当前活动决定。"""
return (
ShippingOrderReviewLineDecision.query
.filter_by(review_case_id=int(case.id), line_key=str(line_key), is_active=True)
.filter_by(review_case_id=int(case.id), draft_line_id=str(draft_line_id), is_active=True)
.order_by(ShippingOrderReviewLineDecision.decision_version.desc())
.first()
)
def _next_version(case: ShippingOrderReviewCase, line_key: str) -> int:
def _next_version(case: ShippingOrderReviewCase, draft_line_id: str) -> int:
"""下一决定版本号。"""
latest = (
ShippingOrderReviewLineDecision.query
.filter_by(review_case_id=int(case.id), line_key=str(line_key))
.filter_by(review_case_id=int(case.id), draft_line_id=str(draft_line_id))
.order_by(ShippingOrderReviewLineDecision.decision_version.desc())
.first()
)
@@ -641,7 +651,7 @@ def _serialize_decision(row: ShippingOrderReviewLineDecision) -> dict[str, Any]:
"""用户态决定投影。"""
return {
'id': int(row.id),
'line_key': row.line_key,
'draft_line_id': row.draft_line_id,
'line_index': row.line_index,
'decision_version': int(row.decision_version),
'decision_code': row.decision_code,
@@ -766,44 +776,33 @@ def project_review_case_line_decisions(
schema_fields = _normalize_schema_fields_map(schema_fields) or schema_fields_from_case(case)
formal_ot = resolve_formal_ot(case)
has_formal_ot = bool(formal_ot.get('has_formal_ot'))
task = formal_ot.get('task') if isinstance(formal_ot.get('task'), ShippingNotice) else None
task = formal_ot.get('task') if isinstance(formal_ot.get('task'), ShippingOrderTask) else None
if task is None and getattr(case, 'confirmed_task_id', None) is not None:
task = db.session.get(ShippingNotice, int(case.confirmed_task_id))
task = db.session.get(ShippingOrderTask, int(case.confirmed_task_id))
rpa_failure_release_allowed = bool(task is not None and _has_terminal_inventory_rpa_failure(task))
# [STEP] 构造 Task 级库存源回退事实(行级匹配缺失时兜底,仅影响展示)
# 优先级:行级 inventory_source_code > Task resolved 正式源 > candidates_frozen > resolving
# [STEP] 构造 CandidateSet 回退事实(行级匹配缺失时仅影响展示)。
from app.services.shipping_notice.stp_inventory_freeze import (
task_frozen_inventory_source_codes,
)
fallback_inventory_source: dict[str, Any] | None = None
if task is not None:
task_source_code = str(task.inventory_source_code or '').strip().upper() or None
task_source_status = str(task.inventory_source_status or '').strip()
if task_source_code and task_source_status == 'resolved':
frozen_codes = task_frozen_inventory_source_codes(task)
if len(frozen_codes) == 1:
fallback_inventory_source = {
'code': task_source_code,
'code': frozen_codes[0],
'label': None,
'status': 'resolved',
'source': 'task_inventory_source',
'source': 'frozen_inventory_candidates',
}
elif frozen_codes:
fallback_inventory_source = {
'code': None,
'label': None,
'status': 'candidates_frozen',
'candidates': list(frozen_codes),
'source': 'frozen_inventory_candidates',
}
elif task_source_status == 'candidates_frozen':
frozen_codes = task_frozen_inventory_source_codes(task)
if frozen_codes:
fallback_inventory_source = {
'code': None,
'label': None,
'status': 'candidates_frozen',
'candidates': list(frozen_codes),
'source': 'frozen_inventory_candidates',
}
else:
fallback_inventory_source = {
'code': None,
'label': None,
'status': 'resolving',
'source': 'inventory_source_clue',
}
else:
fallback_inventory_source = {
'code': None,
@@ -825,10 +824,10 @@ def project_review_case_line_decisions(
active_rows = (
ShippingOrderReviewLineDecision.query
.filter_by(review_case_id=int(case.id), is_active=True)
.order_by(ShippingOrderReviewLineDecision.line_key.asc())
.order_by(ShippingOrderReviewLineDecision.draft_line_id.asc())
.all()
)
by_key = {str(row.line_key): row for row in active_rows}
by_key = {str(row.draft_line_id): row for row in active_rows}
lines_out: list[dict[str, Any]] = []
for key, draft_line in draft_lines.items():
@@ -909,8 +908,6 @@ def project_review_case_line_decisions(
release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact)
if release_line_index is None:
release_line_index = draft_line.get('_line_index')
if not release_source_code:
release_source_code = getattr(task, 'inventory_source_code', None)
release_template_fields = _shortage_release_required_fields(
task=task,
line_index=release_line_index,
@@ -925,7 +922,7 @@ def project_review_case_line_decisions(
available = inv_view.get('available_qty')
shortage = inv_view.get('shortage_qty')
lines_out.append({
'line_key': key,
'draft_line_id': key,
'line_index': draft_line.get('_line_index'),
'reservation_id': _line_reservation_id(draft_line, proj),
'part_number': _line_part_number(
@@ -1067,7 +1064,7 @@ def decide_review_line_fulfillment(
*,
user_id: int,
case_no: str,
line_key: str,
draft_line_id: str,
decision_code: str,
reason: str | None = None,
release_field_values: dict[str, Any] | None = None,
@@ -1084,7 +1081,7 @@ def decide_review_line_fulfillment(
Args:
user_id: 操作人。
case_no: Case 编号。
line_key: 草稿行键。
draft_line_id: 草稿行键。
decision_code: 决定码。
reason: 关闭/重开/短缺放行必填原因。
release_field_values: 短缺放行时模板行级库存字段的人工补录值。
@@ -1118,7 +1115,7 @@ def decide_review_line_fulfillment(
)
lines = _draft_line_map(case)
key = str(line_key or '').strip()
key = str(draft_line_id or '').strip()
if key not in lines:
raise NotFoundError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
@@ -1128,20 +1125,20 @@ def decide_review_line_fulfillment(
raise ConflictError(
'Line already fulfilled in a task wave',
code='SHIPPING.REVIEW_LINE_ALREADY_IN_TASK',
details={'line_key': key, 'line_status': current.line_status},
details={'draft_line_id': key, 'line_status': current.line_status},
)
if code == DECISION_REOPEN:
if current is None or current.line_status != 'closed_unfulfillable':
raise ConflictError(
'Only closed_unfulfillable lines can be reopened',
code='SHIPPING.REVIEW_LINE_REOPEN_NOT_ALLOWED',
details={'line_key': key},
details={'draft_line_id': key},
)
if not actor_is_admin:
raise ConflictError(
'Reopen requires admin',
code='SHIPPING.REVIEW_LINE_REOPEN_FORBIDDEN',
details={'line_key': key},
details={'draft_line_id': key},
)
elif current is not None and current.line_status == 'closed_unfulfillable':
raise ConflictError(
@@ -1161,7 +1158,7 @@ def decide_review_line_fulfillment(
avail_qty = _parse_qty(proj.get('available_qty'))
if code == DECISION_FULFILL:
req_qty, avail_qty = _assert_line_can_fulfill_complete(
line_key=key,
draft_line_id=key,
draft_line=draft_line,
proj=proj,
schema_fields=schema_fields,
@@ -1170,10 +1167,10 @@ def decide_review_line_fulfillment(
from app.models import ShippingNoticeLineInventoryMatch
task_id = getattr(case, 'confirmed_task_id', None)
task = db.session.get(ShippingNotice, int(task_id)) if task_id is not None else None
task = db.session.get(ShippingOrderTask, int(task_id)) if task_id is not None else None
fact = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), line_key=key, is_current=True)
.filter_by(task_id=int(task.id), line_index=int(draft_line.get('_line_index')), is_current=True)
.first()
if task is not None else None
)
@@ -1182,25 +1179,20 @@ def decide_review_line_fulfillment(
raise ConflictError(
'Only shortage lines can be released',
code='SHIPPING.REVIEW_LINE_RELEASE_NOT_ALLOWED',
details={'line_key': key},
details={'draft_line_id': key},
)
release_line_index = getattr(fact, 'line_index', None) if fact is not None else draft_line.get('_line_index')
release_template_fields = _shortage_release_required_fields(
task=task,
line_index=release_line_index,
inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None,
inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else getattr(task, 'inventory_source_code', None),
inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None,
) if task is not None else []
release_required_fields = _manual_required_release_fields(release_template_fields)
release_values = _validate_inventory_shortage_release_fields(
required_fields=release_required_fields,
supplied_values=release_field_values or {},
)
supplied_warehouse_id = str(release_values.get('system_fact:warehouse_id') or '').strip().upper()
if supplied_warehouse_id:
# Header Warehouse ID 是动态库存源导出的任务级系统事实;人工放行时必须
# 显式固化,供后续 Excel 生成消费,并同时保留在决定快照中审计。
task.inventory_warehouse_id = supplied_warehouse_id
else:
release_required_fields = []
release_values = {}
@@ -1213,7 +1205,7 @@ def decide_review_line_fulfillment(
status = _STATUS_BY_DECISION.get(code, 'pending_decision')
row = ShippingOrderReviewLineDecision(
review_case_id=int(case.id),
line_key=key,
draft_line_id=key,
line_index=draft_line.get('_line_index'),
decision_version=_next_version(case, key),
decision_code=code,
@@ -1237,7 +1229,7 @@ def decide_review_line_fulfillment(
'decision_source': 'user',
'required_qty': str(req_qty) if req_qty is not None else None,
'available_qty': str(avail_qty) if avail_qty is not None else None,
'line_key': key,
'draft_line_id': key,
'release_field_values': release_values,
'release_required_fields': release_required_fields,
},
@@ -1262,7 +1254,7 @@ def decide_review_line_fulfillment(
review_case_no=str(case.case_no),
run_no=str(case.run.run_no) if case.run is not None else None,
metadata={
'line_key': key,
'draft_line_id': key,
'decision_code': code,
'decision_version': int(row.decision_version),
'line_status': status,
@@ -1301,7 +1293,7 @@ def close_remaining_fulfillment(
user_id: int,
case_no: str,
reason: str,
line_keys: list[str] | None = None,
draft_line_ids: list[str] | None = None,
expected_draft_version: Any = None,
actor_is_admin: bool = False,
) -> dict[str, Any]:
@@ -1312,7 +1304,7 @@ def close_remaining_fulfillment(
user_id: 操作人。
case_no: Case 编号。
reason: 强制原因。
line_keys: 指定行;为空则关闭全部开放行。
draft_line_ids: 指定行;为空则关闭全部开放行。
expected_draft_version: 可选草稿版本。
actor_is_admin: 透传给 decide(关闭本身不要求管理员)。
@@ -1326,10 +1318,10 @@ def close_remaining_fulfillment(
)
case = _load_writable_case(user_id=user_id, case_no=case_no)
projection = project_review_case_line_decisions(case)
targets = list(line_keys or [])
targets = list(draft_line_ids or [])
if not targets:
targets = [
str(item['line_key'])
str(item['draft_line_id'])
for item in projection.get('lines') or []
if item.get('line_status') not in _TERMINAL_ACTIVE
]
@@ -1338,7 +1330,7 @@ def close_remaining_fulfillment(
last = decide_review_line_fulfillment(
user_id=user_id,
case_no=case_no,
line_key=key,
draft_line_id=key,
decision_code=DECISION_CLOSE,
reason=reason,
expected_draft_version=expected_draft_version,
@@ -301,6 +301,7 @@ def ensure_all_required_sources_prepared(
mode: str = 'auto',
session: Session | None = None,
allow_auto_retry: bool = True,
source_codes: list[str] | None = None,
) -> PerSourcePrepareResult:
"""
遍历 frozen 候选库存源,逐源 check 快照;未命中则触发 RPA(每源独立 attempt_no/run_no)。
@@ -338,7 +339,10 @@ def ensure_all_required_sources_prepared(
except Exception:
# SQLite/无事务测试环境不支持行锁时继续走现有幂等约束。
pass
source_codes = task_frozen_inventory_source_codes(task)
source_codes = [
str(code).strip().upper() for code in (source_codes or task_frozen_inventory_source_codes(task))
if str(code).strip()
]
if not source_codes:
return PerSourcePrepareResult(
task_no=task_no, all_prepared=False,
@@ -394,7 +398,15 @@ def ensure_all_required_sources_prepared(
current_status = double_check.status
att = double_check
if current_status in ('succeeded', 'consumed') and att and _attempt_ref_has_ready_snapshot(att, session=sess):
# 显式 retry_rpa 必须忽略历史成功 Attempt,即使其仍指向 ready 快照;
# 否则“重新获取库存”会被误判为已准备完成,既不创建新 RPA Attempt,
# 也不会写入新的 trigger 文件。
if (
mode != 'retry_rpa'
and current_status in ('succeeded', 'consumed')
and att
and _attempt_ref_has_ready_snapshot(att, session=sess)
):
prepared.append(source_code)
continue
@@ -67,20 +67,20 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal]
raise ConflictError(
'Inventory not ready for post-OT wave',
code='SHIPPING.REVIEW_LINE_INVENTORY_NOT_READY',
details={'line_key': line.get('line_key'), 'inventory_status': line.get('inventory_status')},
details={'snapshot_line_id': line.get('snapshot_line_id'), 'inventory_status': line.get('inventory_status')},
)
if str(line.get('match_result') or '') != 'matched':
raise ConflictError(
'Line match result does not allow fulfill',
code='SHIPPING.REVIEW_LINE_MATCH_NOT_FULFILLABLE',
details={'line_key': line.get('line_key'), 'match_result': line.get('match_result')},
details={'snapshot_line_id': line.get('snapshot_line_id'), 'match_result': line.get('match_result')},
)
is_released_shortage = str((line.get('decision') or {}).get('decision_code') or '') == 'release_inventory_shortage'
if line.get('is_shortage') and not is_released_shortage:
raise ConflictError(
'Line has inventory shortage',
code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY',
details={'line_key': line.get('line_key')},
details={'snapshot_line_id': line.get('snapshot_line_id')},
)
req = _parse_qty(line.get('required_qty'))
avail = _parse_qty(line.get('available_qty'))
@@ -88,19 +88,19 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal]
raise ConflictError(
'Line cannot fulfill complete quantity with current inventory facts',
code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY',
details={'line_key': line.get('line_key')},
details={'snapshot_line_id': line.get('snapshot_line_id')},
)
return req, avail
def _stable_line_keys(keys: list[str]) -> list[str]:
"""稳定排序行键。"""
return sorted({str(k).strip() for k in keys if str(k).strip()})
def _stable_snapshot_line_ids(ids: list[int]) -> list[int]:
"""稳定排序冻结订单行 ID。"""
return sorted({int(item) for item in ids})
def _line_keys_hash(keys: list[str]) -> str:
"""行集合指纹。"""
payload = json.dumps(_stable_line_keys(keys), ensure_ascii=False, separators=(',', ':'))
def _snapshot_line_ids_hash(ids: list[int]) -> str:
"""冻结订单行集合指纹。"""
payload = json.dumps(_stable_snapshot_line_ids(ids), ensure_ascii=False, separators=(',', ':'))
return hashlib.sha256(payload.encode('utf-8')).hexdigest()
@@ -112,7 +112,7 @@ def _snapshot_fingerprint(lines: list[dict[str, Any]], keys: list[str]) -> tuple
(单一 snapshot_id 或 None, fingerprint 字符串)。
"""
ids: list[int] = []
by_key = {str(item.get('line_key') or ''): item for item in lines}
by_key = {str(item.get('snapshot_line_id') or ''): item for item in lines}
for key in keys:
item = by_key.get(key) or {}
raw = item.get('inventory_snapshot_id')
@@ -131,14 +131,14 @@ def _snapshot_fingerprint(lines: list[dict[str, Any]], keys: list[str]) -> tuple
def _params_conflict(
row: ShippingOrderReviewWaveIdempotency,
*,
line_keys: list[str],
snapshot_line_ids: list[int],
fingerprint: str,
decision_source: str,
) -> bool:
"""同 key 参数是否与已存记录冲突。"""
if str(row.decision_source or '') != str(decision_source):
return True
if str(row.line_keys_hash or '') != _line_keys_hash(line_keys):
if str(row.snapshot_line_ids_hash or '') != _snapshot_line_ids_hash(snapshot_line_ids):
return True
if str(row.inventory_snapshot_fingerprint or '') != str(fingerprint):
return True
@@ -148,7 +148,7 @@ def _params_conflict(
def create_post_ot_fulfillment_wave(
*,
case_no: str,
line_keys: list[str],
snapshot_line_ids: list[int],
decision_source: str = 'system',
actor_user_id: int | None = None,
reason: str | None = None,
@@ -162,21 +162,21 @@ def create_post_ot_fulfillment_wave(
Args:
case_no: Case 编号。
line_keys: 本波次行键。
snapshot_line_ids: 本波次冻结订单行 ID。
decision_source: system | user。
actor_user_id: 人工操作人;系统可为 None。
reason: 备注。
idempotency_key: 可选幂等键(独立表强约束)。
Returns:
wave_no / task_no / notice_no / accepted_line_keys / skipped_line_keys / line_fulfillment /
wave_no / task_no / notice_no / accepted_snapshot_line_ids / skipped_snapshot_line_ids / line_fulfillment /
idempotency_row_id / idempotent_replay。
"""
keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()]
keys = [str(int(k)) for k in (snapshot_line_ids or [])]
if not keys:
raise ValidationError('line_keys required', code='SHIPPING.REVIEW_LINE_WAVE_EMPTY')
raise ValidationError('snapshot_line_ids required', code='SHIPPING.REVIEW_LINE_WAVE_EMPTY')
if len(keys) != len(set(keys)):
raise ValidationError('Duplicate line_keys', code='SHIPPING.REVIEW_LINE_WAVE_DUPLICATE')
raise ValidationError('Duplicate snapshot_line_ids', code='SHIPPING.REVIEW_LINE_WAVE_DUPLICATE')
source = str(decision_source or 'system').strip()
if source not in {'system', 'user'}:
raise ValidationError('Invalid decision_source', code='SHIPPING.REVIEW_DECISION_SOURCE_INVALID')
@@ -197,12 +197,12 @@ def create_post_ot_fulfillment_wave(
'Formal OT required for post-OT fulfillment wave',
code='SHIPPING.REVIEW_POST_OT_WAVE_REQUIRES_OT',
)
task: ShippingNotice = formal['task']
task: ShippingOrderTask = formal['task']
projected = project_review_case_line_decisions(case)
projected_lines = [item for item in list(projected.get('lines') or []) if isinstance(item, dict)]
by_key = {
str(item.get('line_key') or ''): item
str(item.get('snapshot_line_id') or ''): item
for item in projected_lines
}
snap_id, snap_fp = _snapshot_fingerprint(projected_lines, keys)
@@ -217,7 +217,7 @@ def create_post_ot_fulfillment_wave(
if existing is not None:
if _params_conflict(
existing,
line_keys=keys,
snapshot_line_ids=[int(k) for k in keys],
fingerprint=snap_fp,
decision_source=source,
):
@@ -226,7 +226,7 @@ def create_post_ot_fulfillment_wave(
code='SHIPPING.REVIEW_POST_OT_WAVE_IDEMPOTENCY_CONFLICT',
details={
'idempotency_key': idem_key,
'existing_line_keys_hash': existing.line_keys_hash,
'existing_snapshot_line_ids_hash': existing.snapshot_line_ids_hash,
'existing_snapshot_fingerprint': existing.inventory_snapshot_fingerprint,
'existing_decision_source': existing.decision_source,
},
@@ -238,15 +238,15 @@ def create_post_ot_fulfillment_wave(
return replay
assigned = {
str(row.line_key)
str(int(row.snapshot_line_id))
for row in ShippingOrderReviewWaveLine.query.filter_by(review_case_id=int(case.id)).all()
}
accepted: list[str] = []
skipped: list[str] = []
accepted_snapshot_line_ids: list[str] = []
skipped_snapshot_line_ids: list[str] = []
for key in keys:
if key in assigned:
skipped.append(key)
skipped_snapshot_line_ids.append(key)
continue
line = by_key.get(key)
if line is None:
@@ -255,14 +255,14 @@ def create_post_ot_fulfillment_wave(
raise ConflictError(
'Closed line cannot enter wave',
code='SHIPPING.REVIEW_LINE_CLOSED',
details={'line_key': key},
details={'snapshot_line_id': key},
)
_assert_fact_allows_fulfill(line)
accepted.append(key)
accepted_snapshot_line_ids.append(key)
wave_no = None
notice = None
if accepted:
if accepted_snapshot_line_ids:
max_wave = (
db.session.query(func.max(ShippingOrderReviewWaveLine.wave_no))
.filter(ShippingOrderReviewWaveLine.review_case_id == int(case.id))
@@ -272,89 +272,89 @@ def create_post_ot_fulfillment_wave(
from app.services.shipping_notice.order_review_confirmation_service import (
_persist_wave_lines_for_task,
)
from app.services.shipping_notice.export import _source_notice_for_order_facts
source_notice = _source_notice_for_order_facts(task)
snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id)
snapshot_line_ids = {
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
selected_snapshot_line_ids = {
int(snapshot.lines[int((by_key[key] or {}).get('line_index'))].id)
for key in accepted
for key in accepted_snapshot_line_ids
if snapshot is not None
and (by_key[key] or {}).get('line_index') is not None
and 0 <= int((by_key[key] or {}).get('line_index')) < len(snapshot.lines)
}
if len(snapshot_line_ids) != len(accepted):
if len(selected_snapshot_line_ids) != len(accepted_snapshot_line_ids):
raise ConflictError(
'Selected review lines do not map to frozen order lines',
code='SHIPPING.REVIEW_LINE_SNAPSHOT_MAPPING_MISSING',
)
order_task = db.session.get(ShippingOrderTask, int(task.order_task_id)) if task.order_task_id else None
if order_task is None:
raise ConflictError(
'Formal notice is not linked to an order task',
code='SHIPPING.REVIEW_POST_OT_WAVE_ORDER_TASK_REQUIRED',
)
order_task = task
# [STEP 1c] 每个履约波次都是独立 Notice,直接继承客户快照;
# 对外发货通知单号只能随该 Notice 的首个 Excel 在同一事务中分配。
if task.customer_id is None:
from app.services.shipping_notice.customer_identity_gate import customer_confirmation_facts
if customer_confirmation_facts(order_task)['customer_id'] is None:
raise ConflictError(
'Formal notice customer is required before creating a fulfillment wave',
code='SHIPPING.REVIEW_POST_OT_WAVE_CUSTOMER_REQUIRED',
)
notice = ShippingNotice(
task_no=generate_task_no(),
order_task_id=int(order_task.id),
customer_id=task.customer_id,
customer_name_snapshot=task.customer_name_snapshot,
customer_short_code_snapshot=task.customer_short_code_snapshot,
user_id=task.user_id,
conversation_id=task.conversation_id,
source_type='post_ot_fulfillment_wave',
inventory_source_code=task.inventory_source_code,
inventory_connector_type=task.inventory_connector_type,
inventory_warehouse_id=task.inventory_warehouse_id,
inventory_source_status=task.inventory_source_status,
inventory_source_method=task.inventory_source_method,
inventory_source_config_version=task.inventory_source_config_version,
inventory_routing_fingerprint=task.inventory_routing_fingerprint,
inventory_snapshot_id=task.inventory_snapshot_id,
customer_resolution_status=task.customer_resolution_status,
customer_resolution_method=task.customer_resolution_method,
customer_identity_fingerprint=task.customer_identity_fingerprint,
customer_confirmed_by=task.customer_confirmed_by,
customer_confirmed_at=task.customer_confirmed_at,
from app.services.shipping_notice.shipping_notice_creation_service import (
create_shipping_notice_after_inventory_gate,
)
db.session.add(notice)
db.session.flush()
notice.customer_resolution_status = 'confirmed'
replace_notice_lines_from_snapshot(
notice_id=int(notice.id), snapshot=snapshot, snapshot_line_ids=snapshot_line_ids,
notice = create_shipping_notice_after_inventory_gate(
order_task,
snapshot_line_ids=selected_snapshot_line_ids,
source_type='post_ot_fulfillment_wave',
)
_persist_wave_lines_for_task(
case=case,
task=notice,
line_keys=accepted,
snapshot_line_ids=list(selected_snapshot_line_ids),
wave_no=wave_no,
revision_id=None,
)
# [D8] 波次按自身行重跑路由冻结(不继承首通知源);复用库存候选冻结链路。
from app.services.shipping_notice.inventory_candidate_freeze_service import freeze_wave_notice_routing
routing_result = freeze_wave_notice_routing(notice, source_notice=None)
if routing_result is None or not routing_result.source_codes:
raise ConflictError(
'Inventory source routing is unresolved for selected fulfillment lines',
code='SHIPPING.REVIEW_LINE_INVENTORY_SOURCE_UNRESOLVED',
details={'snapshot_line_ids': [int(item) for item in selected_snapshot_line_ids]},
)
db.session.flush()
# [STEP 2] 写入/推进履约决定(含已在 wave 的幂等行)
draft_lines = _draft_line_map(case)
draft_lines_by_index = {
int(row.get('_line_index')): row
for row in draft_lines.values()
if row.get('_line_index') is not None
}
now = datetime.utcnow()
for key in keys:
line = by_key.get(key) or {}
current = _active_decision(case, key)
line_index = line.get('line_index')
draft_line = draft_lines_by_index.get(int(line_index)) if line_index is not None else None
draft_line_id = str(
(line or {}).get('draft_line_id') or (draft_line or {}).get('_draft_line_id') or ''
).strip()
if not draft_line_id:
raise ConflictError(
'Selected review line is missing draft identity',
code='SHIPPING.REVIEW_LINE_DRAFT_MAPPING_MISSING',
details={'snapshot_line_id': key},
)
current = _active_decision(case, draft_line_id)
if current is not None and current.line_status in {'task_created', 'fulfilled'}:
continue
# [STEP 2a] 短缺放行的补录库存字段必须保留在活动审计决定中,
# 不能被通用 fulfill 决定覆盖,否则独立 Excel 将丢失放行字段来源。
if (
key in accepted
key in accepted_snapshot_line_ids
and current is not None
and current.decision_code == 'release_inventory_shortage'
):
current.line_status = 'task_created'
current.task_id = int(notice.id)
current.task_id = int(order_task.id)
current.wave_no = int(wave_no) if wave_no is not None else None
current.updated_at = now
continue
@@ -365,20 +365,20 @@ def create_post_ot_fulfillment_wave(
avail = str(line.get('available_qty') or '') or None
row = ShippingOrderReviewLineDecision(
review_case_id=int(case.id),
line_key=key,
line_index=(draft_lines.get(key) or {}).get('_line_index'),
decision_version=_next_version(case, key),
draft_line_id=draft_line_id,
line_index=line_index,
decision_version=_next_version(case, draft_line_id),
decision_code=DECISION_FULFILL,
decision_source=source,
line_status='task_created' if key in assigned or key in accepted else _STATUS_BY_DECISION[DECISION_FULFILL],
line_status='task_created' if key in assigned or key in accepted_snapshot_line_ids else _STATUS_BY_DECISION[DECISION_FULFILL],
is_active=True,
reason=str(reason or '').strip()[:2000] or None,
required_qty=req,
available_qty=avail,
reservation_id=line.get('reservation_id'),
part_number=line.get('part_number'),
task_id=int(notice.id) if key in accepted else int(task.id),
wave_no=wave_no if key in accepted else (
task_id=int(order_task.id),
wave_no=wave_no if key in accepted_snapshot_line_ids else (
int(current.wave_no) if current is not None and current.wave_no is not None else None
),
actor_user_id=int(actor_user_id) if actor_user_id is not None else None,
@@ -392,14 +392,14 @@ def create_post_ot_fulfillment_wave(
created_at=now,
updated_at=now,
)
if key in accepted:
if key in accepted_snapshot_line_ids:
row.line_status = 'task_created'
row.wave_no = wave_no
elif key in assigned:
row.line_status = 'task_created'
existing_wave = (
ShippingOrderReviewWaveLine.query
.filter_by(review_case_id=int(case.id), line_key=key)
.filter_by(review_case_id=int(case.id), snapshot_line_id=int((line or {}).get('snapshot_line_id') or key))
.first()
)
if existing_wave is not None:
@@ -418,11 +418,11 @@ def create_post_ot_fulfillment_wave(
review_case_no=str(case.case_no),
run_no=str(case.run.run_no) if case.run is not None else None,
task_no=str(task.task_no),
before={'line_keys': keys},
before={'snapshot_line_ids': [int(item) for item in keys]},
after={
'wave_no': wave_no,
'accepted_line_keys': accepted,
'skipped_line_keys': skipped,
'accepted_snapshot_line_ids': [int(item) for item in accepted_snapshot_line_ids],
'skipped_snapshot_line_ids': [int(item) for item in skipped_snapshot_line_ids],
'decision_source': source,
'idempotency_key': idem_key,
},
@@ -430,13 +430,13 @@ def create_post_ot_fulfillment_wave(
result = {
'case_no': case.case_no,
'task_no': notice.task_no if notice is not None else task.task_no,
'task_id': int(notice.id) if notice is not None else int(task.id),
'task_no': task.task_no,
'task_id': int(task.id),
'review_case_id': int(case.id),
'wave_no': wave_no,
'notice_no': notice.task_no if notice is not None else None,
'accepted_line_keys': accepted,
'skipped_line_keys': skipped,
'notice_no': notice.business_no if notice is not None else None,
'accepted_snapshot_line_ids': [int(item) for item in accepted_snapshot_line_ids],
'skipped_snapshot_line_ids': [int(item) for item in skipped_snapshot_line_ids],
'decision_source': source,
'idempotent_replay': False,
'line_fulfillment': project_review_case_line_decisions(case),
@@ -448,12 +448,12 @@ def create_post_ot_fulfillment_wave(
idem_row = ShippingOrderReviewWaveIdempotency(
idempotency_key=persist_key,
review_case_id=int(case.id),
task_id=int(notice.id) if notice is not None else int(task.id),
task_no=str(notice.task_no if notice is not None else task.task_no),
task_id=int(task.id),
task_no=str(task.task_no),
wave_no=wave_no,
decision_source=source,
line_keys_json=_stable_line_keys(keys),
line_keys_hash=_line_keys_hash(keys),
snapshot_line_ids_json=[int(item) for item in keys],
snapshot_line_ids_hash=_snapshot_line_ids_hash([int(item) for item in keys]),
inventory_snapshot_id=snap_id,
inventory_snapshot_fingerprint=snap_fp,
status='succeeded',
@@ -471,7 +471,7 @@ def create_post_ot_fulfillment_wave(
return result
def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]:
def list_eligible_post_ot_snapshot_line_ids(case: ShippingOrderReviewCase) -> list[str]:
"""
列出可自动/人工履约的行(ready+matched+未关闭+未终态)。
@@ -482,7 +482,7 @@ def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]:
case: 复核 Case。
Returns:
line_key 列表。
snapshot_line_id 列表。
"""
projected = project_review_case_line_decisions(case)
out: list[str] = []
@@ -509,5 +509,5 @@ def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]:
avail is not None and avail < req and not is_released_shortage
):
continue
out.append(str(item.get('line_key') or ''))
out.append(str(item.get('snapshot_line_id') or ''))
return [k for k in out if k]
@@ -17,7 +17,7 @@ from app.models import (
ShippingOrderProcessingRun,
ShippingOrderReviewCase,
ShippingProcessExecution,
ShippingNotice,
ShippingOrderTask,
User,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
@@ -52,7 +52,7 @@ def resolve_execution_owner_user_ids(execution: ShippingProcessExecution) -> set
"""
owners: set[int] = set()
if execution.task_id is not None:
task = db.session.get(ShippingNotice, int(execution.task_id))
task = db.session.get(ShippingOrderTask, int(execution.task_id))
if task is not None and task.user_id is not None:
owners.add(int(task.user_id))
if execution.review_case_id is not None:
@@ -201,7 +201,8 @@ def _record_permission_denied(
"""
task_no = None
if execution.task_id is not None:
task = db.session.get(ShippingNotice, int(execution.task_id))
from app.models import ShippingOrderTask
task = db.session.get(ShippingOrderTask, int(execution.task_id))
task_no = str(task.task_no) if task is not None else None
record_fulfillment_audit(
event_type='process_gate_permission_denied',
@@ -241,7 +242,8 @@ def execution_audit_scope_keys(execution: ShippingProcessExecution) -> dict[str,
task_no = None
case_no = None
if execution.task_id is not None:
task = db.session.get(ShippingNotice, int(execution.task_id))
from app.models import ShippingOrderTask
task = db.session.get(ShippingOrderTask, int(execution.task_id))
task_no = str(task.task_no) if task is not None else None
if execution.review_case_id is not None:
case = db.session.get(ShippingOrderReviewCase, int(execution.review_case_id))
@@ -22,7 +22,7 @@ from app.models import (
ShippingProcessExecution,
ShippingProcessGate,
ShippingProcessGateAttempt,
ShippingNotice,
ShippingOrderTask,
)
from app.services.shipping_notice.audit_query_service import serialize_shipping_audit_event
from app.services.shipping_notice.process_gate_access_service import execution_audit_scope_keys
@@ -79,7 +79,7 @@ def serialize_execution_admin_summary(execution: ShippingProcessExecution) -> di
).first()
task_no = None
if execution.task_id is not None:
task = db.session.get(ShippingNotice, int(execution.task_id))
task = db.session.get(ShippingOrderTask, int(execution.task_id))
task_no = str(task.task_no) if task is not None else None
return {
'execution_no': execution.execution_no,
@@ -160,7 +160,7 @@ def list_admin_process_executions(
like = f'%{keyword}%'
task_ids = [
int(row.id)
for row in ShippingNotice.query.filter(ShippingNotice.task_no.ilike(like)).limit(200).all()
for row in ShippingOrderTask.query.filter(ShippingOrderTask.task_no.ilike(like)).limit(200).all()
]
filters = [ShippingProcessExecution.execution_no.ilike(like)]
if task_ids:
@@ -27,6 +27,7 @@ from app.models import (
ShippingProcessExecution,
ShippingProcessGate,
ShippingNotice,
ShippingOrderTask,
)
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES
from app.services.shipping_notice.process_gate_service import (
@@ -39,36 +40,48 @@ from app.services.shipping_notice.process_gate_service import (
_LOGGER = logging.getLogger(__name__)
def _derived_fulfillment_status(task: ShippingNotice) -> str:
def _derived_fulfillment_status(task: ShippingOrderTask | ShippingNotice) -> str:
"""从领域结果事实推导履约分支,不读取旧流程状态字段。"""
upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
if upload_status in {'uploaded', 'succeeded', 'success'}:
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success, latest_upload_attempt
upload_attempt = latest_upload_attempt(task)
upload_status = str(getattr(upload_attempt, 'status', None) or '').strip().lower()
if has_verified_upload_success(task):
return 'uploaded'
pending = str(getattr(task, 'pending_human_reason', None) or '').strip()
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
pending = str(task_blocking_reason(task) or '').strip()
if pending in {'rpa_pending', 'rpa_exhausted', 'inventory_unavailable'}:
return 'waiting_inventory'
if pending in {'upload_rpa_pending', 'upload_rpa_failed', 'upload_result_unknown'}:
return 'waiting_upload'
if upload_status == 'failed':
return 'upload_failed'
if isinstance(getattr(task, 'shortage_json', None), (dict, list)) and task.shortage_json:
return 'shortage_review'
match_status = str(getattr(task, 'match_status', None) or '').strip().lower()
if isinstance(task, ShippingOrderTask):
from app.services.shipping_notice.inventory_file_store import (
current_inventory_matches_have_shortage,
inventory_matches_complete_for_task,
has_ready_inventory_file_for_task,
)
if inventory_matches_complete_for_task(task):
return 'shortage_review' if current_inventory_matches_have_shortage(task) else 'matched'
return 'inventory_ready' if has_ready_inventory_file_for_task(task) else 'created'
from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task
match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
match_status = aggregate_match_status_for_task(match_task_id) or ''
if match_status in {'fulfillable', 'partial', 'unfulfillable'}:
return 'matched'
if str(getattr(task, 'export_file_path', None) or '').strip():
return 'inventory_ready'
if isinstance(getattr(task, 'inventory_lines_json', None), list) and task.inventory_lines_json:
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
if has_ready_inventory_file_for_task(task):
return 'inventory_ready'
return 'created'
def inventory_preparation_reason_code(task: ShippingNotice) -> str:
def inventory_preparation_reason_code(task: ShippingOrderTask | ShippingNotice) -> str:
"""
由任务事实推导库存准备门禁阻断原因码。
核心逻辑:pending_human_reason 与最近 inventory_rpa_failed 事件优先于泛化
inventory_preparation_failed,区分排队/超时/登录/导出/耗尽/缺文件。
核心逻辑:pending_human_reason、最近 inventory_rpa_failed 事件与逐源 Attempt
失败事实优先于泛化 inventory_preparation_failed,区分排队/超时/登录/导出/耗尽/缺文件。
惰性导入 constants / inventory_rpa_workflow,避免与桥接模块循环依赖。
Args:
@@ -84,7 +97,8 @@ def inventory_preparation_reason_code(task: ShippingNotice) -> str:
)
from app.services.shipping_notice.inventory_rpa_workflow import latest_task_event
pending = str(task.pending_human_reason or '').strip()
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
pending = str(task_blocking_reason(task) or '').strip()
if pending == PH_RPA_PENDING:
return 'inventory_rpa_queued'
if pending == PH_RPA_EXHAUSTED:
@@ -112,6 +126,39 @@ def inventory_preparation_reason_code(task: ShippingNotice) -> str:
return 'inventory_file_identity_mismatch'
return 'inventory_rpa_export_failed'
# 逐源 Attempt 是当前库存 RPA 的正式失败事实;超时扫描不一定会留下旧
# ShippingTaskEvent,Gate 不能因此退化为“库存文件为空/缺失”。
from app.models import ShippingTaskInventoryRpaAttempt
latest_attempt = (
ShippingTaskInventoryRpaAttempt.query
.filter(
ShippingTaskInventoryRpaAttempt.task_no == str(task.task_no or '').strip(),
)
.order_by(
ShippingTaskInventoryRpaAttempt.attempt_no.desc(),
ShippingTaskInventoryRpaAttempt.id.desc(),
)
.first()
)
if latest_attempt is not None and str(latest_attempt.status or '').strip().lower() in {'failed', 'exhausted'}:
blob = ' '.join([
str(latest_attempt.status or '').strip().lower(),
str(latest_attempt.error_code or '').strip().lower(),
str(latest_attempt.error_message or '').strip().lower(),
])
if 'exhausted' in blob:
return 'inventory_rpa_exhausted'
if 'timeout' in blob or ('not ready' in blob and 'within' in blob):
return 'inventory_rpa_timeout'
if 'login' in blob or 'auth' in blob:
return 'inventory_rpa_login_failed'
if 'empty' in blob:
return 'inventory_file_empty'
if 'identity' in blob or 'mismatch' in blob:
return 'inventory_file_identity_mismatch'
return 'inventory_rpa_export_failed'
# inv_unavail 仅说明当前没有可用库存文件;若本轮没有 RPA 失败审计,
# 才使用该泛化原因,不能覆盖已记录的下载超时/登录/导出失败。
if pending == PH_INV_UNAVAIL:
@@ -120,7 +167,7 @@ def inventory_preparation_reason_code(task: ShippingNotice) -> str:
# 未持久化测试对象仍携带 ``[]`` 时,明确表达“文件已解析但无库存行”。
# ``None`` 才表示未得到库存文件,避免把空文件误投影成缺文件。
if getattr(task, 'id', None) is None:
return 'inventory_file_empty' if getattr(task, 'inventory_lines_json', None) == [] else 'inventory_file_missing'
return 'inventory_file_missing'
# [STEP] 活动库存快照是运行事实;任务字段仅为历史兼容投影。
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
@@ -141,7 +188,7 @@ _FREIGHT_UPLOAD_RPA_REASON_CODES = frozenset({
})
def manual_upload_reason_code(task: ShippingNotice) -> str:
def manual_upload_reason_code(task: ShippingOrderTask | ShippingNotice) -> str:
"""
由任务事实推导货代上传相关阻断原因码。
@@ -158,7 +205,8 @@ def manual_upload_reason_code(task: ShippingNotice) -> str:
PH_UPLOAD_RPA_PENDING,
)
pending = str(task.pending_human_reason or '').strip()
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
pending = str(task_blocking_reason(task) or '').strip()
status = _derived_fulfillment_status(task)
if pending == PH_UPLOAD_RPA_PENDING:
return 'upload_rpa_pending'
@@ -243,11 +291,20 @@ def find_execution_for_case(case: ShippingOrderReviewCase) -> ShippingProcessExe
)
def find_execution_for_task(task: ShippingNotice) -> ShippingProcessExecution | None:
"""按 Task 查找绑定的 Execution。"""
def find_execution_for_task(task: ShippingOrderTask | ShippingNotice) -> ShippingProcessExecution | None:
"""按 OT 查找绑定的 Execution;正式 Notice 入口仅沿 order_task_id 定位其 OT。"""
task_id = (
int(task.id)
if isinstance(task, ShippingOrderTask) and getattr(task, 'id', None) is not None
else int(task.order_task_id)
if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None) is not None
else None
)
if task_id is None:
return None
return (
ShippingProcessExecution.query
.filter_by(task_id=int(task.id))
.filter_by(task_id=task_id)
.filter(ShippingProcessExecution.status != 'superseded')
.order_by(ShippingProcessExecution.id.desc())
.first()
@@ -348,7 +405,7 @@ def mark_gates_passed_through(
"""
将 sequence 不大于 through_gate_code 且仍为 pending/skipped 的门禁标记为 passed。
核心逻辑:用于人工确认建单后一次性推进到 task_creation;已阻断门禁不静默覆盖。
核心逻辑:用于人工确认建单后推进已满足的前置门禁;已阻断门禁不静默覆盖。
Returns:
实际推进的 gate_code 列表。
@@ -368,11 +425,9 @@ def mark_gates_passed_through(
break
if gate.status in {'passed', 'skipped'}:
continue
if gate.status not in {'pending', 'blocked_manual', 'blocked_retryable', 'invalidated', 'queued'}:
continue
# 仅放行人工确认可覆盖的冻结就绪与前置 pending;技术失败不覆盖。
if gate.status == 'failed_terminal':
if gate.status not in {'pending', 'skipped'}:
continue
# 人工确认只能推进仍未评估的前置门禁;任何真实阻断必须保留。
apply_gate_outcome(
execution=execution,
gate_code=gate.gate_code,
@@ -394,7 +449,7 @@ def mark_gates_passed_through(
def sync_execution_after_review_confirm(
*,
case: ShippingOrderReviewCase,
task: ShippingNotice,
task: ShippingOrderTask,
actor_id: int,
) -> ShippingProcessExecution | None:
"""
@@ -407,7 +462,7 @@ def sync_execution_after_review_confirm(
Args:
case: 复核 Case。
task: 本波次新建的 ShippingNotice。
task: 复核确认生成的 ShippingOrderTask。
actor_id: 确认操作人。
Returns:
@@ -436,13 +491,74 @@ def sync_execution_after_review_confirm(
actor_type='user',
actor_id=actor_id,
)
mark_gates_passed_through(
# Task 已真实创建并绑定 Execution,先收口 task_creation;后续 Gate 不得越过该事实。
apply_gate_outcome(
execution=execution,
through_gate_code='task_creation',
gate_code='task_creation',
passed=True,
effective_result={'findings': [], 'task_id': int(task.id), 'task_no': task.task_no},
actor_type='user',
actor_id=actor_id,
reason='review_confirmed',
idempotency_key=f'task-creation-after-confirm:{execution.execution_no}:{task.id}',
force=True,
)
# Snapshot 已在确认事务中成功冻结;该事实单独收口 order_freeze_readiness。
from app.models import ShippingOrderSnapshot
snapshot_id = getattr(task, 'order_snapshot_id', None)
snapshot = (
db.session.get(ShippingOrderSnapshot, int(snapshot_id))
if snapshot_id is not None else None
)
if not (
snapshot is not None
and int(getattr(snapshot, 'task_id', 0) or 0) == int(task.id)
and int(getattr(snapshot, 'extraction_id', 0) or 0) == int(task.current_order_extraction_id or 0)
):
return execution
apply_gate_outcome(
execution=execution,
gate_code='order_freeze_readiness',
passed=True,
effective_result={'findings': [], 'task_id': int(task.id), 'snapshot_id': int(snapshot_id)},
actor_type='user',
actor_id=actor_id,
idempotency_key=f'order-freeze-after-confirm:{execution.execution_no}:{snapshot_id}',
force=True,
)
# [STEP] Task 与 Snapshot 已在确认事务中完成后,才执行正式库存源裁决。
# CandidateSet 是 inventory_source_routing 通过的必要业务事实。
from app.services.shipping_notice.inventory_source_gate import adjudicate_and_apply_inventory_source
adjudication = adjudicate_and_apply_inventory_source(
task,
execution_id=int(execution.id),
)
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
if not task_frozen_inventory_source_codes(task):
# 无候选时不放行 routing;保留当前 Gate 事实,交由规则恢复动作处理。
return execution
apply_gate_outcome(
execution=execution,
gate_code='inventory_source_routing',
passed=True,
effective_result={
'findings': [],
'candidate_set_id': int(task.active_inventory_candidate_set_id),
'source_codes': task_frozen_inventory_source_codes(task),
'status': str(adjudication.status or 'resolved'),
},
actor_type='user',
actor_id=actor_id,
idempotency_key=(
f'inventory-routing-after-confirm:{execution.execution_no}:'
f'{task.active_inventory_candidate_set_id}'
),
force=True,
)
# [STEP] 建单后立即按 Task 状态投影履约门禁,避免 13–19 长期停留 pending。
sync_fulfillment_gates_from_task(
execution=execution,
@@ -785,12 +901,13 @@ def _supersede_auto_inventory_poll_for_rpa_failure(
"""
from app import db
from app.models import ShippingProcessGateAttempt
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
if (
_derived_fulfillment_status(task) != 'waiting_inventory'
or str(task.pending_human_reason or '').strip() != PH_RPA_EXHAUSTED
or str(task_blocking_reason(task) or '').strip() == PH_RPA_PENDING
):
return
gate = ShippingProcessGate.query.filter_by(
@@ -857,7 +974,7 @@ def sync_fulfillment_gates_from_task(
"""
if not execution.task_id:
return
task = ShippingNotice.query.get(int(execution.task_id))
task = ShippingOrderTask.query.get(int(execution.task_id))
if task is None:
return
@@ -868,19 +985,29 @@ def sync_fulfillment_gates_from_task(
actor_id=actor_id,
)
from app.services.shipping_notice.fulfillment_workflow import excel_gate_error, match_completed
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
from app.services.shipping_notice.fulfillment_workflow import (
inventory_match_facts_complete,
match_completed,
)
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
from app.services.shipping_notice.inventory_file_store import (
active_inventory_file_for_task,
active_inventory_lines_for_task,
)
match_status = str(task.match_status or '').strip()
has_export = bool(str(task.export_file_path or '').strip())
has_inventory_lines = isinstance(task.inventory_lines_json, list) and len(task.inventory_lines_json) > 0
inv_file = active_inventory_file_for_task(task)
has_inventory_lines = bool(
inv_file is not None
and str(getattr(inv_file, 'snapshot_status', '') or '').strip().lower() == 'ready'
and getattr(inv_file, 'invalidated_at', None) is None
and active_inventory_lines_for_task(task)
)
status = _derived_fulfillment_status(task)
# [STEP 1A] 已验证并绑定的库存行是库存准备的正式成功事实。RPA 回调与
# 旧失败/超时 Attempt 可以乱序到达;不能让遗留的 rpa_exhausted 把已成功
# 入库的任务重新投影为 waiting_inventory,否则 Gate 会停在“手工上传”。
if has_inventory_lines and status == 'waiting_inventory':
status = 'inventory_ready'
inv_file = active_inventory_file_for_task(task)
mapping_confirmed = bool(inv_file is not None and bool(getattr(inv_file, 'mapping_confirmed', False)))
# [STEP 1] 优先读匹配/短缺实体;阶段由领域事实推导。
done_statuses = {'uploaded', 'closed'}
@@ -918,16 +1045,10 @@ def sync_fulfillment_gates_from_task(
force=True,
)
return
post_inventory = {'inventory_ready', 'matched', 'waiting_upload', 'upload_failed', *done_statuses}
sufficiency_ok = match_completed(task)
shortage = (not sufficiency_ok) and (
match_status in {'unfulfillable', 'partial'}
or bool(task.shortage_json)
or status == 'shortage_review'
)
match_passed = match_status in {'fulfillable', 'partial', 'unfulfillable'} or status in {
'matched', 'waiting_upload', 'upload_failed', *done_statuses,
}
match_passed = inventory_match_facts_complete(task)
shortage = match_passed and not sufficiency_ok
match_status = 'fulfillable' if sufficiency_ok else ('unfulfillable' if match_passed else None)
# 手动上传文件也必须由已发布库存模板自动映射;若尚未完成,只能进入系统
# 可重试状态,不能产生“人工确认字段映射”业务节点。
source_query = getattr(inv_file, 'source_query_json', None) if inv_file is not None else None
@@ -993,7 +1114,7 @@ def sync_fulfillment_gates_from_task(
})
# Task 已明确 rpa_exhausted 时,Preparation 的旧 waiting_external 不能
# 继续把 Gate 投影成系统处理中;Preparation 保留 waiting 作为原始审计事实。
task_rpa_exhausted = str(task.pending_human_reason or '').strip() == 'rpa_exhausted'
task_rpa_exhausted = str(task_blocking_reason(task) or '').strip() == 'rpa_exhausted'
if not task_rpa_exhausted and (preparation.status in {'queued', 'running', 'waiting_external'} or pending):
apply_gate_outcome(
execution=execution, gate_code='inventory_preparation', passed=False,
@@ -1029,7 +1150,7 @@ def sync_fulfillment_gates_from_task(
if status == 'waiting_inventory':
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
pending_reason = str(task.pending_human_reason or '').strip()
pending_reason = str(task_blocking_reason(task) or '').strip()
# 只有 Worker 已领取/等待回调才是 waiting_external。RPA 失败或历史次数耗尽时
# 必须退出自动处理中,回到可重试 Gate,不能因同一等待事实再次自动入队。
if pending_reason == PH_RPA_PENDING:
@@ -1062,7 +1183,9 @@ def sync_fulfillment_gates_from_task(
force=True,
)
return
inv_prep_passed = status in post_inventory or has_inventory_lines
# 库存准备的成功事实只能是已验证并绑定的库存行。下游状态可能因历史脏数据、
# 并发投影或错误侧路动作残留,绝不能反向证明库存文件已经准备完成。
inv_prep_passed = has_inventory_lines
inv_prep_reason = None if inv_prep_passed else inventory_preparation_reason_code(task)
apply_gate_outcome(
execution=execution,
@@ -1124,11 +1247,9 @@ def sync_fulfillment_gates_from_task(
classify_inventory_match_reason,
)
line_results = (
list(task.line_results_json)
if isinstance(task.line_results_json, list)
else []
)
from app.models import ShippingNoticeLineInventoryMatch
current_match_rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
line_results = [{'disposition': row.match_result} for row in current_match_rows]
match_reason = None if match_passed else classify_inventory_match_reason(
line_results=line_results,
match_status=match_status,
@@ -1190,7 +1311,11 @@ def sync_fulfillment_gates_from_task(
)
),
'match_status': match_status or None,
'shortage': task.shortage_json if isinstance(task.shortage_json, (dict, list)) else None,
'shortage': [
{'snapshot_line_id': row.snapshot_line_id, 'shortage_qty': row.shortage_qty}
for row in current_match_rows
if str(row.shortage_qty or '').strip() not in {'', '0', '0.0', '0.00'}
],
},
blocking_reason_code=None if sufficiency_ok else str(shortage_reason or 'inventory_insufficient'),
actor_type=actor_type,
@@ -1198,6 +1323,7 @@ def sync_fulfillment_gates_from_task(
idempotency_key=f'fulfill:suff:{execution.execution_no}:{match_status}:{sufficiency_ok}:{shortage_reason or "ok"}',
force=True,
)
from app.services.shipping_notice.fulfillment_workflow import excel_gate_error
# [STEP 6] excel_readiness(资格)与 artifact_generation(产物)分离。
# 库存不足仍停在 Gate 16,但滚动履约可为已满足/已审计放行行生成下一份 Excel。
excel_error = excel_gate_error(task)
@@ -1225,6 +1351,17 @@ def sync_fulfillment_gates_from_task(
if not excel_ready:
return
# [STEP 6A] 正式 Notice 仅在库存门禁通过后的产物生成动作中创建。通知准备
# 及 Excel 资格检查必须只读 OT;进入产物/上传后段才允许读取 Notice 事实。
formal_notice = (
ShippingNotice.query.filter_by(order_task_id=int(task.id)).order_by(ShippingNotice.id.desc()).first()
)
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
export_artifact = latest_export_artifact(formal_notice) if formal_notice is not None else None
has_export = export_artifact is not None
status = None
if formal_notice is not None:
status = _derived_fulfillment_status(formal_notice)
artifact_ok = has_export or status in done_statuses
apply_gate_outcome(
execution=execution,
@@ -1254,7 +1391,7 @@ def sync_fulfillment_gates_from_task(
# [STEP 7] freight_upload_rpa(RPA)与 manual_upload_handoff(真正人工)分离。
uploaded = status in done_statuses
upload_reason = None if uploaded else manual_upload_reason_code(task)
upload_reason = None if uploaded else manual_upload_reason_code(formal_notice or task)
task_details = {
'derived_fulfillment_status': status or None,
'task_no': str(task.task_no or '') or None,
@@ -196,23 +196,21 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
},
},
{
'gate_code': 'inventory_source_routing',
'gate_code': 'task_creation',
'sequence_no': 10,
'label': '库存源路由',
'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_source'},
'responsible_party': 'owner',
'label': '订单任务创建',
'ui_placement': {'target_surface': 'order_review', 'target_anchor': 'task_creation'},
'responsible_party': 'system',
'implementation_status': 'implemented',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'retry_with_latest_rules',
# 库存源由规则自动裁决;规则冲突属于配置/数据治理,不允许用户人工选源。
'blocked_manual': 'retry_with_latest_rules',
'blocked_retryable': 'retry_task_creation',
},
},
{
'gate_code': 'order_freeze_readiness',
'sequence_no': 11,
'label': '订单冻结资格',
'label': '订单冻结完成',
'ui_placement': {'target_surface': 'order_review', 'target_anchor': 'freeze_readiness'},
'responsible_party': 'system',
'implementation_status': 'implemented',
@@ -223,15 +221,16 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
},
},
{
'gate_code': 'task_creation',
'gate_code': 'inventory_source_routing',
'sequence_no': 12,
'label': 'ShippingNotice 创建',
'ui_placement': {'target_surface': 'order_review', 'target_anchor': 'task_creation'},
'responsible_party': 'system',
'label': '库存源路由',
'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_source'},
'responsible_party': 'owner',
'implementation_status': 'implemented',
'recoverable': True,
'default_next_actions': {
'blocked_retryable': 'retry_task_creation',
'blocked_retryable': 'retry_with_latest_rules',
'blocked_manual': 'retry_with_latest_rules',
},
},
{
@@ -373,6 +372,7 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({
'retry_inventory_from_preparation',
'retry_inventory_from_field_mapping',
'retry_inventory_from_matching',
'override_line_inventory_source',
'open_inventory_match_review',
'recheck_inventory_sufficiency',
'open_shortage_review',
@@ -473,13 +473,21 @@ def inventory_preparation_primary_action(
status: str | None,
blocking_reason_code: str | None = None,
) -> str | None:
"""裁决库存准备 Gate 面向业务用户的主动作。"""
"""裁决库存准备 Gate 面向业务用户的主动作。
单源合并(用户拍板):库存失败只保留 2 个按钮 ——
``retry_inventory_preparation``(直接重跑 RPA)与 ``retry_inventory_matching``
(优先复用已有快照并重匹配;无快照时 match_inventory 内部经 ensure_inventory 回退 RPA)。
已下线的 ``reload_inventory_result``(只重读)不再独立成主动作,其「复用快照」行为已并入
``retry_inventory_matching``。
"""
normalized_status = str(status or '').strip().lower()
normalized_reason = str(blocking_reason_code or '').strip().lower()
if normalized_status == 'waiting_external':
return 'poll_inventory_preparation'
if normalized_reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}:
return 'reload_inventory_result'
# [MERGE] 超时/耗尽:优先复用已有快照重匹配,无则回退 RPA(retry_inventory_matching 自含)。
return 'retry_inventory_matching'
if normalized_status in {'blocked_manual', 'blocked_retryable'}:
return 'retry_inventory_preparation'
return None
@@ -490,6 +498,53 @@ def is_technical_gate_party(responsible_party: str | None) -> bool:
return str(responsible_party or '').strip() in PROCESS_GATE_TECHNICAL_PARTIES
def gate_side_recovery_actions(
*,
gate_code: str,
status: str | None = None,
blocking_reason_code: str | None = None,
) -> tuple[str, ...]:
"""
返回当前阻断状态下,除主动作外业务用户仍可提交的侧路恢复动作序列。
核心逻辑:投影层(serialize_process_gate 的 allowed_actions 侧路)与校验层
(request_gate_action 的 allowed_side)必须共用同一份裁决,禁止各自硬编码,
否则会出现「投影放行按钮、校验却拒绝提交」的漂移(如 RPA 超时/耗尽时点击
「重新获取库存 (RPA)」被报 SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED)。
这些动作由 Gate 契约或状态显式允许;仅用于展示/提交统一入口,不改变主动作。
Args:
gate_code: 当前阻断 Gate 编码。
status: Gate 状态(如 blocked_retryable / blocked_manual / waiting_external)。
blocking_reason_code: 阻断原因码。
Returns:
允许的侧路动作码序列(有序,保证投影 allowed_actions 顺序稳定);无则空元组。
"""
code = str(gate_code or '').strip().lower()
reason = str(blocking_reason_code or '').strip().lower()
sides: list[str] = []
# [STEP] 库存准备 RPA 超时/耗尽:主恢复已合并为 retry_inventory_matching(优先复用已有快照
# 重匹配,无快照则回退 RPA);侧路保留显式 retry_inventory_preparation(强制重抓)供用户选择。
if (
code == 'inventory_preparation'
and reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}
):
sides.append('retry_inventory_preparation')
# [STEP] 人工上传交接(Gate 20):主动作是凭据登记,货代 RPA 仍允许用户显式重试。
if (
code == 'manual_upload_handoff'
and reason in {'manual_upload_pending', 'upload_result_unknown'}
):
sides.append('retry_freight_upload_rpa')
# [STEP] 行级库存源人工覆写(方案 3·放开):通知准备(Excel 生成前)与库存匹配阶段
# 均允许用户把某行库存源覆写为任一已启用源后再重匹配;Excel 锁与源启用校验由执行器负责。
# 已取代旧 D5 多文件冲突逐行选源(select_line_inventory_source,已下线)。
if code in {'inventory_source_routing', 'inventory_preparation', 'inventory_matching'}:
sides.append('override_line_inventory_source')
return tuple(sides)
PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({
'document_unavailable',
'layout_parse_failed',
@@ -822,10 +877,18 @@ def action_belongs_to_gate(*, gate_code: str, action_code: str) -> bool:
if recovery_plan_for_action(current_gate=code, action_code=action) is not None:
return True
if action == 'retry_inventory_matching' and code == 'inventory_sufficiency':
if action == 'retry_inventory_matching' and code in {
'inventory_preparation', 'inventory_matching', 'inventory_sufficiency',
}:
return True
if action == 'reload_inventory_result' and code == 'inventory_preparation':
return True
# 人工覆写行级库存源(方案 3·放开):通知准备(取数失败/多候选)与匹配阶段(Excel 前)均可。
# 已取代旧 D5 逐行选源(select_line_inventory_source,已下线)。
if action == 'override_line_inventory_source' and code in {
'inventory_source_routing', 'inventory_preparation', 'inventory_matching',
}:
return True
navigation_owners = {
'open_order_review': {'order_freeze_readiness', 'order_field_extraction'},
'open_profile_review': {'document_profile_routing'},
@@ -1173,8 +1236,8 @@ BLOCKING_REASON_TO_USER_MODE: Final[dict[str, str]] = {
# ============================================================
INVENTORY_MAIN_GATES: Final[tuple[str, ...]] = (
'inventory_source_routing', # 路由规则计算(sub_stage=calculated)
'order_freeze_readiness', # 候选冻结(建单瞬间,sub_stage=frozen)——注意:复用现有 Gate,避免 seq 漂移
'order_freeze_readiness', # 订单 Snapshot 冻结(sub_stage=frozen)
'inventory_source_routing', # CandidateSet 路由裁决与冻结(sub_stage=calculated)
'inventory_preparation', # 多源快照准备(sub_stage=snapshots_ready)
'inventory_matching', # 跨源匹配 & 短缺/冲突(sub_stage=matched / blocking)
)
@@ -1241,3 +1304,72 @@ def user_mode_for_blocking_reason(reason_code: str | None) -> str | None:
if not reason_code:
return None
return BLOCKING_REASON_TO_USER_MODE.get(str(reason_code).strip())
# ============================================================
# 阶段能力集(Stage Capabilities)——一期:通知准备阶段
# 能力可用性 = 阶段 + Excel 未生成 + 预条件(数据在场),不由门禁通过与否决定。
# 与 PROCESS_GATE_ACTION_CODES(门禁恢复动作)语义不同:能力动作允许请求「非当前 gate」,
# request_gate_action 对阶段能力豁免,并走 execute_stage_capability(作废下游——重置+重跑)。
# ============================================================
STAGE_CAPABILITY_DEFINITIONS: Final[dict[str, dict[str, Any]]] = {
'override_line_inventory_source': {
'stage': 'fulfillment_prep',
'scope': 'line',
'action_code': 'override_line_inventory_source',
'invalidate': {
'inventory_field_mapping', 'inventory_matching',
'inventory_sufficiency', 'excel_readiness', 'artifact_generation',
},
'reset_to': 'inventory_preparation',
},
'retry_inventory_preparation': {
'stage': 'fulfillment_prep',
'scope': 'task',
'action_code': 'retry_inventory_preparation',
'invalidate': {
'inventory_field_mapping', 'inventory_matching',
'inventory_sufficiency', 'excel_readiness', 'artifact_generation',
},
'reset_to': 'inventory_preparation',
},
# 重新匹配库存:只在通知准备阶段内、已有匹配结果(且 Excel 未生成)时可用。
# 与「重抓」不同,它保留已抓取库存与字段映射,仅重算匹配及下游满足性/Excel,
# 因此不重置回 inventory_preparation,也不作废上游 source/mapping。
'retry_inventory_matching': {
'stage': 'fulfillment_prep',
'scope': 'task',
'action_code': 'retry_inventory_matching',
'invalidate': {
'inventory_matching', 'inventory_sufficiency',
'excel_readiness', 'artifact_generation',
},
'invalidate_change_type': 'inventory_field_mapping_changed',
'reset_to': 'inventory_matching',
},
'reload_inventory_result': {
'stage': 'fulfillment_prep',
'scope': 'task',
'action_code': 'reload_inventory_result',
'invalidate': frozenset(),
'reset_to': None,
},
}
def stage_capability(action_code: str | None) -> dict[str, Any] | None:
"""按动作码返回阶段能力定义;非阶段能力返回 None。"""
code = str(action_code or '').strip()
return STAGE_CAPABILITY_DEFINITIONS.get(code)
def is_stage_capability(action_code: str | None) -> bool:
"""判断动作码是否为阶段能力。"""
return stage_capability(action_code) is not None
def capability_stage(action_code: str | None) -> str | None:
"""返回能力所属阶段码;非能力返回 None。"""
cap = stage_capability(action_code)
return str(cap['stage']) if cap else None
@@ -151,10 +151,10 @@ PROCESS_GATE_PREREQUISITES: Final[dict[str, tuple[str, ...]]] = {
'customer_resolution': ('reservation_validation',),
'duplicate_detection': ('customer_resolution',),
'field_conflict_resolution': ('duplicate_detection',),
'inventory_source_routing': ('field_conflict_resolution',),
'order_freeze_readiness': ('inventory_source_routing',),
'task_creation': ('order_freeze_readiness',),
'inventory_preparation': ('task_creation',),
'task_creation': ('field_conflict_resolution',),
'order_freeze_readiness': ('task_creation',),
'inventory_source_routing': ('order_freeze_readiness',),
'inventory_preparation': ('inventory_source_routing',),
'inventory_field_mapping': ('inventory_preparation',),
'inventory_matching': ('inventory_field_mapping',),
'inventory_sufficiency': ('inventory_matching',),
@@ -18,6 +18,8 @@ from typing import Any, Callable
from app import db
from app.core.errors import ValidationError
from app.models import (
ShippingNotice,
ShippingOrderTask,
ShippingOrderDocument,
ShippingOrderProcessingRun,
ShippingOrderReviewCase,
@@ -188,6 +190,7 @@ def _dispatch_action(
'retry_inventory_from_preparation': _handle_retry_inventory_preparation,
'retry_inventory_from_field_mapping': _handle_retry_inventory_from_field_mapping,
'retry_inventory_from_matching': _handle_retry_inventory_from_matching,
'override_line_inventory_source': _handle_override_line_inventory_source,
'recheck_inventory_sufficiency': _handle_recheck_inventory_sufficiency,
'recheck_excel_readiness': _handle_recheck_excel_readiness,
'regenerate_excel_artifact': _handle_regenerate_excel,
@@ -339,9 +342,7 @@ def _task_payload(execution: ShippingProcessExecution, payload: dict[str, Any])
``_orchestrator_internal_dispatch``,禁止库存/Excel workflow 再次绕回
``run_task_auto_progress``,把当前活动 Attempt 误判成“无待处理 Gate”。
"""
from app.models import ShippingNotice
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
task = ShippingOrderTask.query.get(int(execution.task_id)) if execution.task_id else None
if task is None:
raise ValidationError('Execution has no bound task', code='SHIPPING.PROCESS_EXECUTION_TASK_BOUND')
return {
@@ -706,9 +707,7 @@ def _handle_retry_task_creation(
)
task_no = (result or {}).get('task_no')
if task_no:
from app.models import ShippingNotice
task = ShippingNotice.query.filter_by(task_no=str(task_no)).first()
task = ShippingOrderTask.query.filter_by(task_no=str(task_no)).first()
if task is not None:
bind_execution_task(
execution_no=str(execution.execution_no),
@@ -757,7 +756,7 @@ def _handle_retry_inventory_preparation(
sync_fulfillment_gates_from_task,
)
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
task = _resolve_order_task(execution)
recovery_plan_id = payload.get('recovery_plan_id')
# Gate Worker 通过 _task_payload 传递 operator_id;人工 API 可能传 actor_user_id/user_id。
# 三者必须统一,否则冻结订单快照会收到 None,并在 RPA Attempt/trigger 创建前失败。
@@ -766,6 +765,33 @@ def _handle_retry_inventory_preparation(
or payload.get('user_id')
or payload.get('operator_id')
)
# [STEP 0A] inventory_preparation 只消费 routing 已冻结的 CandidateSet。
# 若历史数据越过 routing,直接阻断,不在库存准备阶段偷偷补做裁决。
if task is not None:
from app.services.shipping_notice.inventory_candidate_projection import (
get_active_candidate_lines,
get_active_candidate_set,
get_active_candidate_sources,
)
candidate_set = get_active_candidate_set(task)
lines = get_active_candidate_lines(task)
sources = get_active_candidate_sources(task)
if (
not task.order_snapshot_id
or candidate_set is None
or not sources
or not lines
or any(not list(getattr(line, 'source_codes_json', None) or []) for line in lines)
):
return {
'outcome': 'blocked_retryable',
'blocking_reason_code': 'inventory_source_routing_required',
'effective_result_json': {'findings': [], 'routing_required': True},
'output_snapshot': {
'action_code': str(payload.get('action_code') or 'retry_inventory_preparation'),
'routing_required': True,
},
}
if task is not None and payload.get('action_code') == 'poll_inventory_preparation':
# 回调已将本轮准备收口为失败后,已排队的旧 poll 只能重投影正式 Gate。
# 若继续调用 ensure_inventory,会把精确的 RPA 超时覆盖为泛化的缺库存文件。
@@ -800,7 +826,11 @@ def _handle_retry_inventory_preparation(
},
}
preparation_round = None
is_initial_auto_dispatch = str(payload.get('trigger') or '') == 'gate_attempt_passed'
is_manual_rpa_retry = str(payload.get('inventory_mode') or '').strip() == 'retry_rpa'
is_initial_auto_dispatch = (
str(payload.get('trigger') or '') == 'gate_attempt_passed'
and not is_manual_rpa_retry
)
if task is not None and payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch:
# 历史 Task 可能在正式建单后遗漏快照。所有 Gate 恢复入口必须先补齐该履约事实,
# 不能依赖某一个旧 Workspace/Chat 重试入口,否则同一个按钮会持续卡在 order_freeze。
@@ -834,9 +864,19 @@ def _handle_retry_inventory_preparation(
gate_attempt_id=int(payload.get('attempt_id')) if payload.get('attempt_id') else None,
)
inventory_payload = _task_payload(execution, payload)
# 阶段能力重试在入队时统一保存为 line_scope_key;兼容旧 Attempt 仍可能携带 snapshot_line_id。
inventory_payload['line_scope_key'] = (
payload.get('line_scope_key')
if payload.get('line_scope_key') is not None
else payload.get('snapshot_line_id')
)
# 只有用户显式重试强制生成新 Attempt;首次自动投递应先尝试复用有效快照。
if payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch:
inventory_payload['mode'] = 'retry_rpa'
if str(payload.get('action_code') or '') == 'poll_inventory_preparation':
# [只读轮询] 轮询仅查询 RPA 结果:RPA Attempt 失败(含超时扫描收口)时禁止自动重试,
# 由本轮结果把 Gate 收口为人工阻断,重试必须由用户在当前 Gate 显式发起。
inventory_payload['allow_auto_retry'] = False
response = ensure_inventory(inventory_payload)
if preparation_round is not None:
from app.services.shipping_notice.inventory_recovery_service import sync_inventory_preparation_round
@@ -861,6 +901,197 @@ def _handle_retry_inventory_preparation(
return outcome
def _handle_override_line_inventory_source(
*,
execution: ShippingProcessExecution,
gate: ShippingProcessGate,
payload: dict[str, Any],
) -> dict[str, Any]:
"""
人工覆写行级库存源(方案 3·放开):通知准备阶段(Excel 生成前)允许用户把某行库存源
覆写为任一**已启用**库存源,而不仅限于规则候选。先放开、后续再收紧到仅候选源。
校验顺序:Excel 锁 → 源存在且启用 → 定位行候选 → 覆写;
覆写后把该行候选钉为所选源并重跑该行匹配(snapshot 复用/触发 RPA 由既有
auto-progress / ensure_inventory 处理:有未过期快照直接匹配,否则重新 RPA)。
Args:
execution: 门禁执行上下文。
gate: 当前门禁实例。
payload: 含 line_no / source_code / 可选 reason、actor_user_id。
Returns:
符合动作契约的 tool 响应。
"""
from app.core.errors import ConflictError, ValidationError
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.inventory_source_repository import (
get_database_inventory_source,
list_database_inventory_sources,
)
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
from app.services.shipping_notice.inventory_candidate_freeze_service import (
freeze_manual_line_source_selection,
)
task = _resolve_order_task(execution)
line_no_raw = payload.get('line_no')
source_code = str(payload.get('source_code') or '').strip().upper()
reason = str(payload.get('reason') or '').strip()[:500] or None
actor_raw = payload.get('actor_user_id') or payload.get('user_id') or payload.get('operator_id')
try:
line_no = int(line_no_raw)
except (TypeError, ValueError) as exc:
raise ValidationError('line_no 与 source_code 必填', code='SHIPPING.LINE_SOURCE_INVALID') from exc
if task is None or not source_code or line_no < 1:
raise ValidationError('line_no 与 source_code 必填', code='SHIPPING.LINE_SOURCE_INVALID')
# Excel 是不可变输出边界(D7):生成后源锁定,改源只能走撤销/人工流程。
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
if (latest_export_artifact(task) is not None):
raise ConflictError(
'通知 Excel 已生成,库存源已锁定,请走撤销/人工纠错流程',
code='SHIPPING.LINE_SOURCE_LOCKED',
)
# 方案 3:任一已启用源都允许(不限于规则候选)。
enabled_codes = {
str(item.get('source_code') or '').strip().upper()
for item in list_database_inventory_sources(enabled_only=True)
}
if source_code not in enabled_codes or get_database_inventory_source(source_code) is None:
raise ConflictError('所选库存源不存在或已停用', code='SHIPPING.LINE_SOURCE_UNAVAILABLE')
try:
actor_id = int(actor_raw) if actor_raw not in (None, '') else None
except (TypeError, ValueError):
actor_id = None
try:
candidate_result, all_lines_selected = freeze_manual_line_source_selection(
task,
line_no=line_no,
source_code=source_code,
actor_id=actor_id,
reason=reason,
execution_id=int(execution.id),
)
except ValueError as exc:
raise ConflictError(str(exc), code='SHIPPING.REVIEW_LINE_NOT_FOUND') from exc
db.session.flush()
record_fulfillment_audit(
event_type='review_line_source_overridden',
aggregate_type='shipping_notice',
aggregate_id=str(task.task_no),
action='override_line_inventory_source',
actor_type='user' if actor_id else 'system',
actor_id=actor_id,
task_no=task.task_no,
before={'line_no': line_no, 'previous_source_code': None},
after={'line_no': line_no, 'selected_source_code': source_code, 'reason': reason},
)
if not all_lines_selected:
return {
'outcome': 'blocked_manual',
'blocking_reason_code': 'no_inventory_source_candidates',
'effective_result_json': {
'findings': [], 'candidate_set_id': candidate_result.candidate_set_id,
'selected_line_no': line_no, 'all_lines_selected': False,
},
'output_snapshot': {
'action_code': 'override_line_inventory_source',
'candidate_set_id': candidate_result.candidate_set_id,
'all_lines_selected': False,
},
}
# 首次人工选源完成的是 routing Gate 本身;让 Attempt 以 passed 收口后,
# process_gate_service 会统一入队下一道 inventory_preparation,避免在当前
# routing Attempt 内递归触发 RPA 而把 Gate 状态写错。
if gate.gate_code == 'inventory_source_routing':
return {
'outcome': 'passed',
'effective_result_json': {
'findings': [], 'candidate_set_id': candidate_result.candidate_set_id,
'selected_line_no': line_no, 'all_lines_selected': True,
},
'output_snapshot': {
'action_code': 'override_line_inventory_source',
'candidate_set_id': candidate_result.candidate_set_id,
'all_lines_selected': True,
},
}
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
# [ROOT CAUSE FIX · RPA 不触发] 行级库存源覆写冻结新候选后,必须把 inventory_preparation Gate
# 作为「定向人工恢复」重新推进:显式传 resume_gate_code='inventory_preparation' 与
# inventory_mode='retry_rpa'。否则 AutoProgress 会读取该 Gate 残留的 next_action_code
# (waiting_external → poll_inventory_preparation),只排队一个只读 poll,既不创建
# InventoryPreparationAttempt 也不触发 RPA,最终永远停在 inventory_file_empty。
# 与 execute_stage_capability 的「重新获取库存」路径保持同一语义(见 process_gate_service)。
run_task_auto_progress(
task.task_no,
trigger='manual_override_source',
operator_id=actor_id,
resume_gate_code='inventory_preparation',
inventory_mode='retry_rpa',
)
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=actor_id)
# 覆写库存源只改变后续取数/匹配的输入,不能把“库存准备”本身伪造成成功。
# 续跑后必须以 Gate 同步得到的库存事实收口:只有有效库存快照已落库时才通过;
# RPA 失败则保留 inventory_preparation 的人工恢复入口,后续 Gate 不得被放行。
db.session.flush()
preparation_gate = ShippingProcessGate.query.filter_by(
execution_id=int(execution.id), gate_code='inventory_preparation',
).first()
gate_status = str(getattr(preparation_gate, 'status', '') or '').strip().lower()
reason_code = str(getattr(preparation_gate, 'blocking_reason_code', '') or '').strip() or None
if gate_status == 'passed':
outcome = 'passed'
elif gate_status in {'queued', 'running', 'waiting_external'}:
outcome = 'waiting_external'
else:
outcome = 'blocked_retryable'
return {
'outcome': outcome,
'blocking_reason_code': None if outcome == 'passed' else (
reason_code or 'inventory_preparation_failed'
),
'effective_result_json': {
'findings': [],
'inventory_preparation_status': gate_status or 'blocked_retryable',
},
'output_snapshot': {
'action_code': 'override_line_inventory_source',
'inventory_preparation_status': gate_status or 'blocked_retryable',
},
}
def _resolve_order_task(execution: ShippingProcessExecution) -> ShippingOrderTask | None:
"""按 Execution.task_id 解析 OT;Execution 永不直接指向正式 Notice。"""
return ShippingOrderTask.query.get(int(execution.task_id)) if execution.task_id else None
def _task_has_frozen_inventory_source(task: ShippingOrderTask) -> bool:
"""
任务是否已冻结库存源候选(CandidateSet 已存在且至少有一个 Source)。
【AI 触发时机】:inventory_preparation Gate 执行前判断是否需要补做路由裁决。
核心逻辑:统一以冻结 CandidateSet 为库存源真相;有候选源即视为已裁决/冻结,
没有则说明 routing Gate 虽被复核门禁同步判为 passed,但候选从未落库,需补裁决。
"""
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
return bool(task_frozen_inventory_source_codes(task))
def _resolve_shipping_notice(execution: ShippingProcessExecution) -> ShippingNotice | None:
"""解析已由库存门禁创建的正式 Notice,仅供 Excel/上传动作使用。"""
task = _resolve_order_task(execution)
if task is None:
return None
return ShippingNotice.query.filter_by(order_task_id=int(task.id)).order_by(ShippingNotice.id.desc()).first()
def _handle_reload_inventory_result(
*,
execution: ShippingProcessExecution,
@@ -881,7 +1112,7 @@ def _handle_reload_inventory_result(
sync_fulfillment_gates_from_task,
)
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
task = _resolve_order_task(execution)
if task is None:
return {
'outcome': 'blocked_retryable',
@@ -895,6 +1126,14 @@ def _handle_reload_inventory_result(
mode='reload_result',
)
if response is None:
# [STEP] 重读未命中意味着本次等待链没有可消费的回调结果。Gate 将收口为
# blocked_retryable,必须同步取消尚未领取的延迟 poll,避免继续显示/执行轮询。
from app.services.shipping_notice.process_gate_job_service import cancel_inventory_external_wait_polls
cancel_inventory_external_wait_polls(
gate_id=int(gate.id),
reason='库存结果重读未命中,外部等待轮询已终止',
)
return {
'outcome': 'blocked_retryable',
'blocking_reason_code': inventory_preparation_reason_code(task),
@@ -926,7 +1165,7 @@ def _handle_retry_inventory_field_mapping(
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
task = _resolve_order_task(execution)
if task is None:
return {
'outcome': 'blocked_retryable',
@@ -1025,9 +1264,38 @@ def _handle_retry_inventory_matching(
response = match_inventory(_task_payload(execution, payload))
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id'))
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
match_status = str(getattr(task, 'match_status', '') or '').strip().lower()
has_shortage = bool(getattr(task, 'shortage_json', None))
task = _resolve_order_task(execution)
from app.services.shipping_notice.fulfillment_workflow import (
inventory_match_facts_complete,
match_completed,
)
match_complete = bool(task is not None and inventory_match_facts_complete(task))
sufficient = bool(task is not None and match_completed(task))
match_status = 'fulfillable' if sufficient else ('unfulfillable' if match_complete else '')
has_shortage = match_complete and not sufficient
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
shortage = [
row for row in load_current_match_facts_by_task(getattr(task, 'id', None)).values()
if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}
]
# 订单已可履约:重匹配为成功,交由 suff/artifact 后续;不得把 match_inventory 内部
# run_task_auto_progress 的"无待处理 Gate"(status='completed')误判为失败。
if match_status == 'fulfillable':
return {
'outcome': 'passed',
'effective_result_json': {
'findings': [],
'match_status': match_status or None,
'shortage': shortage,
},
'output_snapshot': {
'action_code': 'retry_inventory_matching',
'tool_status': 'passed',
'business_result': 'fulfillable',
},
}
if str((response or {}).get('status') or '').strip().lower() == 'needs_human' and (
match_status in {'partial', 'unfulfillable'} or has_shortage
):
@@ -1038,7 +1306,7 @@ def _handle_retry_inventory_matching(
'effective_result_json': {
'findings': [],
'match_status': match_status or None,
'shortage': getattr(task, 'shortage_json', None),
'shortage': shortage,
},
'output_snapshot': {
'action_code': 'retry_inventory_matching',
@@ -1083,14 +1351,14 @@ def _handle_recheck_inventory_sufficiency(
gate: ShippingProcessGate,
payload: dict[str, Any],
) -> dict[str, Any]:
"""独立库存满足性复核:读取 match_status / shortage_json,不重跑匹配。"""
"""独立库存满足性复核:读取当前行级 Match,不重跑库存匹配。"""
from app.models import ShippingNotice
from app.services.shipping_notice.fulfillment_workflow import (
recompute_task_fulfillment_state,
)
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
task = _resolve_order_task(execution)
if task is None:
return {
'outcome': 'blocked_manual',
@@ -1110,7 +1378,13 @@ def _handle_recheck_inventory_sufficiency(
from app.services.shipping_notice.fulfillment_workflow import match_completed
sufficient = match_completed(task)
shortage = task.shortage_json if isinstance(task.shortage_json, (dict, list)) else None
from app.models import ShippingNoticeLineInventoryMatch
shortage = [
{'snapshot_line_id': row.snapshot_line_id, 'shortage_qty': row.shortage_qty}
for row in ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
if str(row.shortage_qty or '').strip() not in {'', '0', '0.0', '0.00'}
]
match_status = 'fulfillable' if sufficient else 'unfulfillable'
apply_gate_outcome(
execution=execution,
gate_code='inventory_sufficiency',
@@ -1118,19 +1392,19 @@ def _handle_recheck_inventory_sufficiency(
outcome=None if sufficient else 'blocked_manual',
effective_result={
'findings': [],
'match_status': task.match_status,
'match_status': match_status,
'shortage': shortage,
},
blocking_reason_code=None if sufficient else 'inventory_insufficient',
actor_type='system',
actor_id=payload.get('actor_user_id'),
idempotency_key=f'inv-suff:{execution.execution_no}:{task.match_status}:{sufficient}',
idempotency_key=f'inv-suff:{execution.execution_no}:{match_status}:{sufficient}',
force=True,
)
if sufficient:
return {
'outcome': 'passed',
'effective_result_json': {'findings': [], 'match_status': task.match_status},
'effective_result_json': {'findings': [], 'match_status': match_status},
'output_snapshot': {'action_code': 'recheck_inventory_sufficiency', 'passed': True},
}
return {
@@ -1149,11 +1423,10 @@ def _handle_recheck_excel_readiness(
payload: dict[str, Any],
) -> dict[str, Any]:
"""Excel 生成资格检查:只跑 excel_gate_error,不生成 Artifact。"""
from app.models import ShippingNotice
from app.services.shipping_notice.fulfillment_workflow import excel_gate_error
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
task = _resolve_order_task(execution)
if task is None:
return {
'outcome': 'blocked_retryable',
@@ -1171,7 +1444,7 @@ def _handle_recheck_excel_readiness(
blocking_reason_code=None if ready else 'excel_not_ready',
actor_type='system',
actor_id=payload.get('actor_user_id'),
idempotency_key=f'excel-ready:{execution.execution_no}:{ready}:{task.match_status}',
idempotency_key=f'excel-ready:{execution.execution_no}:{ready}:{getattr(task, "order_data_version", 1)}',
force=True,
)
if ready:
@@ -1196,22 +1469,16 @@ def _handle_regenerate_excel(
payload: dict[str, Any],
) -> dict[str, Any]:
"""仅在尚未生成 Excel 时重试首次生成,已有 Artifact 时拒绝重生。"""
from app.models import ShippingExportArtifact, ShippingNotice
from app.services.shipping_notice.fulfillment_workflow import generate_excel
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
existing = (
ShippingExportArtifact.query.filter_by(task_id=int(task.id)).first()
if task is not None and task.id is not None else None
)
if existing is not None:
task = _resolve_order_task(execution)
if task is None:
return {
'outcome': 'blocked_manual',
'blocking_reason_code': 'notice_excel_already_generated',
'blocking_reason_json': {'message': '同一发货通知单只能生成一个 Excel;请创建新的发货通知单'},
'outcome': 'blocked_retryable',
'blocking_reason_code': 'artifact_generation_failed',
'effective_result_json': {'findings': []},
'output_snapshot': {'action_code': 'regenerate_excel_artifact', 'rejected': True},
'output_snapshot': {'action_code': 'regenerate_excel_artifact'},
}
response = generate_excel(_task_payload(execution, payload))
outcome = _tool_outcome(
@@ -1246,7 +1513,7 @@ def _handle_freight_upload_rpa(
sync_fulfillment_gates_from_task,
)
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
task = _resolve_shipping_notice(execution)
if task is None:
return {
'outcome': 'blocked_manual',
@@ -1287,7 +1554,7 @@ def _handle_regenerate_manual_upload_todo(
from app.models import ShippingNotice
from app.services.shipping_notice.workflow_ledger_service import sync_workflow_item_stage_for_task
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
task = _resolve_shipping_notice(execution)
if task is None:
return _manual_open('regenerate_manual_upload_todo', 'manual_upload_handoff')(
execution=execution, gate=gate, payload=payload,
@@ -1377,7 +1644,7 @@ def _handle_inventory_reroute(
case_no=str(case.case_no),
expected_draft_version=payload.get('expected_draft_version'),
idempotency_key=str(payload.get('idempotency_key') or f'gate-reroute-{gate.id}-{gate.evaluation_version}'),
line_key=str(payload.get('line_key') or '').strip() or None,
draft_line_id=str(payload.get('draft_line_id') or '').strip() or None,
)
return {
'outcome': 'passed',
@@ -1416,7 +1683,7 @@ def _handle_recheck_freeze(
},
'output_snapshot': {'action_code': 'recheck_freeze_readiness'},
}
task = ShippingNotice.query.get(int(execution.task_id))
task = _resolve_order_task(execution)
extraction = None
if task is not None and task.order_extraction_id:
extraction = ShippingOrderExtraction.query.get(int(task.order_extraction_id))
@@ -24,7 +24,7 @@ from app import db
from app.core.errors import ConflictError, NotFoundError
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.models import ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
from app.models import Job, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate, primary_next_action_for_gate
from app.services.shipping_notice.process_gate_executor import execute_queued_attempt
@@ -61,6 +61,40 @@ def _technical_job_max_attempts() -> int:
return 1
def cancel_inventory_external_wait_polls(*, gate_id: int, reason: str) -> int:
"""
取消某库存准备 Gate 尚未领取的延迟轮询 Job。
核心逻辑:库存 Gate 从 waiting_external 收口为失败/人工恢复后,排队中的
``external-wait:<gate_id>:*`` 不再有业务意义,必须立即取消,不能等到下一次
延迟触发后才发现 Gate 已变更。仅更新 queued Job;运行中的 Job 不能强杀,
其执行入口会再次读取 Gate 并自行停止。
Args:
gate_id: inventory_preparation Gate 主键。
reason: 取消原因,写入 Job message 供审计排查。
Returns:
被取消的 Job 数量。
"""
now = _utc_now()
return int(
Job.query.filter(
Job.domain == SHIPPING_PROCESS_GATE_JOB_DOMAIN,
Job.job_type == JobType.SHIPPING_PROCESS_GATE.value,
Job.status == 'queued',
Job.business_ref.like(f'external-wait:{int(gate_id)}:%'),
).update(
{
'status': 'cancelled',
'finished_at': now,
'message': str(reason or '库存等待已终止')[:500],
},
synchronize_session=False,
)
)
def enqueue_process_gate_healthcheck_probe(*, created_by_id: int | None = None) -> int:
"""
入队门禁健康检查探针 Job,供 deploy healthcheck 验证 Worker 真实领取。
@@ -204,11 +238,11 @@ def schedule_waiting_external_poll(
from app.models import ShippingNotice
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
task = db.session.get(ShippingNotice, int(execution.task_id))
has_inventory_lines = bool(
isinstance(getattr(task, 'inventory_lines_json', None), list)
and getattr(task, 'inventory_lines_json', None)
)
from app.models import ShippingOrderTask
task = db.session.get(ShippingOrderTask, int(execution.task_id))
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
has_inventory_lines = bool(task is not None and has_ready_inventory_file_for_task(task))
if task is not None and has_inventory_lines:
sync_fulfillment_gates_from_task(execution=execution, actor_type='system')
db.session.flush()
@@ -306,6 +340,22 @@ def schedule_waiting_external_poll(
execution = db.session.get(ShippingProcessExecution, int(gate.execution_id))
if execution is None:
return None
if str(gate.gate_code or '').strip() == 'inventory_preparation':
poll_count = int(effective.get('poll_count') or 0) + 1
effective['poll_count'] = poll_count
gate.effective_result_json = effective
delay_seconds = min(poll_seconds * (2 ** min(poll_count - 1, 3)), 300)
return int(enqueue(
JobType.SHIPPING_PROCESS_GATE,
{'external_wait_poll_gate_id': int(gate.id)},
domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN,
business_ref=f'external-wait:{int(gate.id)}:{poll_count}',
message='等待库存 RPA 回传,延迟复查',
max_attempts=1,
scheduled_at=now + timedelta(seconds=delay_seconds),
dedupe_active=False,
commit=False,
))
poll_attempt = queue_gate_attempt(
execution_no=str(execution.execution_no),
gate_code=gate.gate_code,
@@ -324,6 +374,30 @@ def schedule_waiting_external_poll(
)
def run_inventory_external_wait_poll(*, gate_id: int) -> dict[str, Any]:
"""执行库存 RPA 的只读等待轮询,不创建新的 Gate Attempt。"""
gate = ShippingProcessGate.query.filter_by(id=int(gate_id)).with_for_update().first()
if gate is None or gate.status != 'waiting_external':
return {'gate_status': getattr(gate, 'status', 'missing'), 'stopped': True}
execution = db.session.get(ShippingProcessExecution, int(gate.execution_id))
if execution is None:
return {'gate_status': 'missing_execution', 'stopped': True}
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation
outcome = _handle_retry_inventory_preparation(
execution=execution,
gate=gate,
payload={'action_code': 'poll_inventory_preparation'},
)
db.session.flush()
db.session.refresh(gate)
return {
'gate_id': int(gate.id),
'gate_status': gate.status,
'outcome': str(outcome.get('outcome') or ''),
}
def heartbeat_gate_attempt(
*,
attempt_id: int,
@@ -15,11 +15,14 @@ from __future__ import annotations
from typing import Any
from app import db
from app.models import (
ShippingProcessExecution,
ShippingProcessGate,
ShippingProcessGateAttempt,
ShippingProcessRecoveryPlan,
ShippingOrderTask,
ShippingNotice,
)
from app.services.shipping_notice.error_explainability_contract import (
build_explainability_reason,
@@ -29,6 +32,7 @@ from app.services.shipping_notice.process_gate_contract import (
PROCESS_GATE_CODE_SET,
PROCESS_GATE_RECOVERABLE_STATUSES,
action_presentation,
gate_side_recovery_actions,
get_process_gate_definition,
inventory_preparation_primary_action,
is_business_user_action,
@@ -62,6 +66,51 @@ _ACTION_NAVIGATION_FOCUS: dict[str, str] = {
'open_shortage_review': 'draft',
}
def task_blocking_reason(task: ShippingOrderTask | ShippingNotice | None) -> str | None:
"""读取任务当前人工阻断原因;OT 以 Process Gate 为唯一事实源。"""
if task is None:
return None
if not isinstance(task, ShippingOrderTask):
owner = None
if getattr(task, 'order_task_id', None):
owner = db.session.get(ShippingOrderTask, int(task.order_task_id))
if owner is not None:
task = owner
else:
return None
execution_id = getattr(task, 'active_process_execution_id', None)
if execution_id is None:
# OT 在 Execution 尚未绑定/旧执行已清理时,pending_human_reason 仍是
# 当前任务的流程事实;不能只回退到技术 error_code,否则 RPA 耗尽、
# 库存不可用等业务阻断会被误判为“无阻断”,恢复入口也不会下发。
return (
str(
getattr(task, 'pending_human_reason', None)
or getattr(task, 'error_code', None)
or ''
).strip()
or None
)
execution = db.session.get(ShippingProcessExecution, int(execution_id))
if execution is None or str(execution.status or '').strip().lower() == 'superseded':
return (
str(
getattr(task, 'pending_human_reason', None)
or getattr(task, 'error_code', None)
or ''
).strip()
or None
)
gate = (
ShippingProcessGate.query
.filter_by(execution_id=int(execution.id))
.filter(ShippingProcessGate.status.in_(('blocked_manual', 'blocked_retryable', 'waiting_external')))
.order_by(ShippingProcessGate.sequence_no.asc())
.first()
)
return str(getattr(gate, 'blocking_reason_code', None) or '').strip() or None
def _projection_gate_definition(gate_code: str) -> dict[str, Any]:
"""只读取正式 20-Gate 契约;历史 Gate 由调用方走只读审计分支。"""
return get_process_gate_definition(gate_code)
@@ -84,8 +133,8 @@ def _resolve_recovery_next_action(
"""
单一裁决:由阻断原因码 / Gate 状态推导业务用户主恢复动作。
[STEP 1] 库存 RPA 超时/耗尽先下发 ``reload_inventory_result``,只重读已有结果;
其他库存准备失败下发 ``retry_inventory_preparation``,由用户明确重新触发 RPA。
[STEP 1] 库存 RPA 超时/耗尽下发 ``retry_inventory_matching``(优先复用已有快照重匹配,
无快照则回退 RPA);其他库存准备失败下发 ``retry_inventory_preparation``,由用户明确重新触发 RPA。
[STEP 2] 货代上传 RPA 失败保持 RPA 重试;人工交接只下发凭据登记入口。
[STEP 3] 其余沿用 Gate 合同默认 next_action(primary 或按 status 推导),并保留
RecoveryPlan 复核入口兜底;技术责任方的 retry_* 仍默认仅作系统执行动作。
@@ -438,9 +487,7 @@ def _execution_navigation_refs(execution: ShippingProcessExecution) -> dict[str,
if run is not None and getattr(run, 'run_no', None):
review_run_no = str(run.run_no)
if execution.task_id:
from app.models import ShippingNotice
task = ShippingNotice.query.get(int(execution.task_id))
task = ShippingOrderTask.query.get(int(execution.task_id))
if task is not None:
task_no = str(task.task_no)
return {
@@ -483,19 +530,56 @@ def _has_confirmed_inventory_for_matching(execution: ShippingProcessExecution) -
"""判断正式任务是否已有可复用、未失效的已确认库存快照。"""
if not execution.task_id:
return False
from app.models import ShippingNotice
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
task = ShippingNotice.query.get(int(execution.task_id))
if task is None or not isinstance(task.inventory_lines_json, list) or not task.inventory_lines_json:
task = ShippingOrderTask.query.get(int(execution.task_id))
return bool(task is not None and has_ready_inventory_file_for_task(task))
def _row_source_editable(execution: ShippingProcessExecution) -> bool:
"""判断正式任务是否仍处于「行级库存源可编辑」阶段(发货 Excel 尚未生成)。
核心逻辑:锁定边界 = Excel 生成(D7)。只有生成发货通知/发货 Excel 之后
(存在有效 ShippingExportArtifact)才锁定行源;此前用户应能对行反复选源/覆写,
因此行级编辑动作的授权必须以此为准,而不能依赖门禁是否恰好处于人工阻断态。
"""
if not getattr(execution, 'task_id', None):
return False
inventory_file = active_inventory_file_for_task(task)
return bool(
inventory_file is not None
and str(getattr(inventory_file, 'snapshot_status', '') or '').strip().lower() == 'ready'
and getattr(inventory_file, 'invalidated_at', None) is None
and bool(getattr(inventory_file, 'mapping_confirmed', False))
task = ShippingOrderTask.query.get(int(execution.task_id))
notice = (
ShippingNotice.query.filter_by(order_task_id=int(task.id)).order_by(ShippingNotice.id.desc()).first()
if task is not None else None
)
if notice is None:
# OT 阶段尚未生成正式 Notice,库存源天然可编辑。
return True
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
return latest_export_artifact(notice) is None
def _ensure_editable_row_source_actions(
*,
allowed_actions: list[str],
gate_code: str | None,
execution: ShippingProcessExecution,
) -> None:
"""行级库源可编辑时,确保允许前端展示并提交行级选源/覆写动作。
与 project_user_gate_summary 的 `if blocking:` 侧路不同:行可编辑性由「Excel 是否
生成」(_row_source_editable)决定,而非门禁是否处于阻断态。避免首次覆写成功后门禁
推进、allowed_actions 清空,导致用户对同一行二次编辑在前端被 noAction 拦下。
"""
if not _row_source_editable(execution):
return
code = str(gate_code or '').strip().lower()
if code not in {'inventory_preparation', 'inventory_matching'}:
return
# 方案 3·放开:覆写(任意已启用源)作为**唯一**行源编辑动作;D5 的「选定」不再作为独立入口,
# 多源歧义行也由覆写下拉承担(覆写接受任意已启用源),避免两处选源入口重复(问题 3/4)。
# retry_inventory_* 仍按其门禁语义在 blocking 分支授权,避免在推进态错误暴露重试入口。
for side in ('override_line_inventory_source',):
if side not in allowed_actions and is_business_user_action(side):
allowed_actions.append(side)
def _excel_regeneration_allowed(
@@ -504,10 +588,18 @@ def _excel_regeneration_allowed(
"""判断上传阶段是否仍可安全替代 Excel;已上传、未知结果和并发恢复一律拒绝。"""
if not execution.task_id or active_recovery_plans:
return False
from app.models import ShippingExportArtifact, ShippingUploadAttempt
from app.models import ShippingExportArtifact, ShippingUploadAttempt, ShippingNotice
# ProcessExecution.task_id 始终指向 OT;Artifact.task_id 指向正式 Notice。
# 不能直接用 OT 主键查询 Artifact,否则会误判没有可重生的 Excel。
notice = ShippingNotice.query.filter_by(order_task_id=int(execution.task_id)).order_by(
ShippingNotice.id.desc(),
).first()
if notice is None:
return False
artifact = ShippingExportArtifact.query.filter(
ShippingExportArtifact.task_id == int(execution.task_id),
ShippingExportArtifact.task_id == int(notice.id),
ShippingExportArtifact.status == 'ready',
).order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()).first()
if artifact is None:
@@ -615,24 +707,18 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
if blocking:
if next_action and is_business_user_action(str(next_action)):
allowed_actions.append(str(next_action))
# 超时或耗尽后默认重读已有结果;保留显式 RPA 重试作为备用操作,
# 让用户在确实没有迟到结果时自行决定是否发起新一轮抓取。
if (
str(blocking.get('gate_code') or '').strip().lower() == 'inventory_preparation'
and str(reason_code or '').strip().lower()
in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}
and 'retry_inventory_preparation' not in allowed_actions
# [STEP] 侧路动作与校验层同源:allowed_actions 的侧路必须等于
# request_gate_action 的 allowed_side(gate_side_recovery_actions),
# 禁止在此另行硬编码,避免「投影放行按钮、校验却拒绝提交」的漂移。
# 覆盖:RPA 超时/耗尽的显式 RPA 重试、Gate 20 人工交接下的货代 RPA 重试、
# 库存多文件冲突行的人工选源。
for side_code in gate_side_recovery_actions(
gate_code=str(blocking.get('gate_code') or ''),
status=str(blocking.get('status') or ''),
blocking_reason_code=reason_code,
):
allowed_actions.append('retry_inventory_preparation')
# Gate 20 的人工凭据登记是主动作;货代 RPA 仍允许由用户显式重试。
# 该可选动作来自 Gate 契约,不能由前端根据自动上传开关自行补出。
if (
str(blocking.get('gate_code') or '').strip().lower() == 'manual_upload_handoff'
and str(reason_code or '').strip().lower() in {
'manual_upload_pending', 'upload_result_unknown',
}
):
allowed_actions.append('retry_freight_upload_rpa')
if side_code not in allowed_actions:
allowed_actions.append(side_code)
for target in recovery_targets:
code = str(target.get('action_code') or '').strip()
if code and code not in allowed_actions and is_business_user_action(code):
@@ -667,6 +753,38 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
if item:
action_items.append(item)
# [EDITABLE] 行级库源可编辑(Excel 未生成)时,选源/覆写动作不与门禁阻断态绑定:
# 即使门禁已推进/不再处于人工阻断态,也应继续授权,避免首提成功后再编辑被 noAction 拦下。
_ensure_editable_row_source_actions(
allowed_actions=allowed_actions,
gate_code=current_gate_code or str((blocking or {}).get('gate_code') or ''),
execution=execution,
)
# 上面新增了行级编辑动作(尤其当 `if blocking:` 为假时原 action_items 为空),需重建 presentation。
# 与 `if blocking:` 内建项保持同构,避免漏掉因可编辑性补充的动作。
existing_codes = {str(item.get('code') or '') for item in action_items}
for code in allowed_actions:
if code in existing_codes:
continue
item = action_presentation(code, gate_code=current_gate_code)
recovery_definition = None
try:
from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action
recovery_definition = recovery_plan_for_action(
current_gate=current_gate_code or '', action_code=code,
)
except Exception: # noqa: BLE001 - recoverable (unknown gate) must not break presentation
recovery_definition = None
placement = (recovery_definition or {}).get('ui_placement')
if item and isinstance(placement, dict):
item.update({
'target_surface': placement.get('target_surface'),
'target_anchor': placement.get('target_anchor'),
})
if item:
action_items.append(item)
# [STEP] 统一可解释性投影:文案/责任方/下一步与 error_explainability_contract 同源;
# request_id 仅真实请求号;execution_no 放入 details 供 Worker 路径关联。
explainability = None
@@ -867,7 +985,8 @@ _USER_FACING_DETAIL_KEYS: frozenset[str] = frozenset({
'matched_rule_ids',
'raw_rule_source_codes',
'candidate_inventory_source_codes',
'line_key',
'draft_line_id',
'snapshot_line_id',
'line_index',
'field_code',
'request_id',
@@ -19,17 +19,26 @@ from app.models import ShippingProcessExecution, ShippingProcessGate, ShippingPr
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.process_gate_contract import (
PROCESS_GATE_ACTION_CODES,
gate_side_recovery_actions,
get_process_gate_definition,
inventory_preparation_primary_action,
is_business_user_action,
is_stage_capability,
is_technical_gate_party,
primary_next_action_for_gate,
stage_capability,
)
from app.services.shipping_notice.process_gate_executor import (
action_requires_async_worker,
execute_queued_attempt,
)
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
from app.services.shipping_notice.process_gate_projection import serialize_process_gate
from app.services.shipping_notice.process_gate_service import (
execute_stage_capability,
execute_stage_capability_override_source,
execute_stage_capability_rematch,
queue_gate_attempt,
)
from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action
from app.services.shipping_notice.recovery_plan_service import bind_recovery_attempt, create_recovery_plan
@@ -119,19 +128,13 @@ def _primary_recovery_action(
if gate.gate_code == 'inventory_matching' and execution.task_id:
return 'retry_inventory_matching'
if gate.gate_code == 'inventory_sufficiency' and execution.task_id:
from app.models import ShippingNotice
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
from app.models import ShippingOrderTask
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
task = ShippingNotice.query.get(int(execution.task_id))
inventory_file = active_inventory_file_for_task(task) if task is not None else None
task = ShippingOrderTask.query.get(int(execution.task_id))
if (
task is not None
and isinstance(task.inventory_lines_json, list)
and bool(task.inventory_lines_json)
and inventory_file is not None
and str(inventory_file.snapshot_status or '').strip().lower() == 'ready'
and inventory_file.invalidated_at is None
and bool(inventory_file.mapping_confirmed)
and has_ready_inventory_file_for_task(task)
):
return 'retry_inventory_matching'
return gate.next_action_code or primary_next_action_for_gate(
@@ -139,6 +142,43 @@ def _primary_recovery_action(
)
def is_stage_capability_exempt(
*,
current_gate: str,
requested_gate: str,
action_code: str,
lifecycle_stage: str,
) -> bool:
"""判断阶段能力动作是否豁免「必须命中当前 gate」校验。
【AI 触发时机】:request_gate_action 对阶段能力动作允许请求非当前 Gate 时调用;
本函数为纯谓词、无 IO,供单测直接验证豁免边界。
核心逻辑(三条件同时满足才放行):
1) 动作是阶段能力(stage_capability 非 None);
2) 当前生命周期阶段 == 能力阶段(cap['stage']);
3) 请求的目标 Gate 落在该能力作废或重置范围(invalidate ∪ reset_to)。
Args:
current_gate: 当前 Execution 的 current_gate_code(保留用于接口对称,当前逻辑未使用)。
requested_gate: 用户请求的 Gate 编码。
action_code: 请求的动作码。
lifecycle_stage: 当前生命周期阶段码(由 current_gate 的 ui_placement.target_surface 派生)。
Returns:
True 表示豁免非当前 Gate 校验;否则 False 走既有校验。
"""
cap = stage_capability(action_code)
if cap is None:
return False
if lifecycle_stage != cap.get('stage'):
return False
targets = set(cap.get('invalidate') or ())
if cap.get('reset_to'):
targets.add(cap['reset_to'])
return requested_gate in targets
def request_gate_action(
*,
execution_no: str,
@@ -213,9 +253,47 @@ def request_gate_action(
details={'current_gate': gate.gate_code, 'action_code': action},
)
# [STAGE_CAPABILITY] 生命周期阶段由当前 execution 的 current_gate 映射派生:
# 用 gate 定义的 ui_placement.target_surface 作为阶段码(库存门禁 → fulfillment_prep)。
# 校验路径不再重算完整 ui_state,避免重活。
lifecycle_stage = ''
if current_gate:
try:
lifecycle_stage = str(
get_process_gate_definition(current_gate).get('ui_placement', {}).get('target_surface') or ''
)
except KeyError:
lifecycle_stage = ''
# [STAGE_CAPABILITY] 阶段能力豁免:通知准备阶段内允许回退/重抓到上游库存 gate。
# 前道数据可变,用户可在窗口内重抓/改源;执行走 execute_stage_capability,
# 不走普通主/侧路动作校验,也不触发 SHIPPING.PROCESS_GATE_NOT_CURRENT。
stage_cap = stage_capability(action)
stage_exempt = (
is_stage_capability(action)
and is_stage_capability_exempt(
current_gate=current_gate,
requested_gate=str(gate.gate_code or '').strip(),
action_code=action,
lifecycle_stage=lifecycle_stage,
)
)
# [STEP] 库存阶段能力只属于正式 OT 执行链。建单前的 Review Execution 可以没有
# task_id,但绝不能借同名 Gate 执行 reload/retry 并制造无归属 Attempt。
if is_stage_capability(action) and not execution.task_id:
raise ValidationError(
'Stage capability requires a bound shipping order task',
code='SHIPPING.PROCESS_EXECUTION_TASK_BOUND',
details={'execution_no': execution.execution_no, 'action_code': action},
)
# [GLOBAL ACTION GUARD] 所有 20 Gate 共用同一入口:请求 Gate 必须是 Execution 当前 Gate。
# 跨阶段动作已在前面完成目标归属判定,避免错误地把非法恢复目标报告为状态漂移。
if replay_attempt is None and (not current_gate or current_gate != str(gate.gate_code or '').strip()):
# 阶段能力(stage_exempt)允许访问非当前 Gate,故豁免此校验。
if replay_attempt is None and not stage_exempt and (
not current_gate or current_gate != str(gate.gate_code or '').strip()
):
raise ValidationError(
'Action must target the current process gate',
code='SHIPPING.PROCESS_GATE_NOT_CURRENT',
@@ -227,6 +305,38 @@ def request_gate_action(
},
)
# [STAGE_CAPABILITY] 阶段能力直接执行:作废下游 + 重置回起始 gate + 幂等重跑;
# 不经过下方普通主/侧路动作校验(primary/allowed_side)与技术 Gate 守卫。
# 「重新匹配库存」用专用重匹配编排(只作废匹配下游、经 inventory_matching 重跑),
# 避免走 execute_stage_capability 的「宽作废 + 重抓 RPA」,否则会错误重抓库存。
if stage_exempt:
if action == 'retry_inventory_matching':
result = execute_stage_capability_rematch(
execution=execution,
actor_type=actor_type,
actor_id=actor_id,
idempotency_key=idempotency_key,
)
elif action == 'override_line_inventory_source':
# [ROOT CAUSE FIX] 行级覆写必须携带用户选定的 line_no/source_code;通用
# execute_stage_capability 不接收 payload 会丢弃这两个关键字段,导致「操作成功」
# 后选源不落库、不触发 RPA、刷新回原样。此处委托专门的负载透传执行器。
result = execute_stage_capability_override_source(
execution=execution, gate=gate, payload=body,
actor_type=actor_type, actor_id=actor_id, idempotency_key=idempotency_key,
)
else:
result = execute_stage_capability(
execution=execution, gate=gate, capability=stage_cap,
actor_type=actor_type, actor_id=actor_id, idempotency_key=idempotency_key,
line_scope_key=body.get('snapshot_line_id'),
)
return {
'outcome': 'submitted',
'gate_summary': serialize_process_gate(gate),
'stage_capability': result,
}
# [STEP] 业务用户禁止触发技术 Gate 写动作;前端隐藏不是安全边界。
# 必须在跨阶段目标归属之后判断,保证错误 Gate 返回 RECOVERY_TARGET_INVALID。
if str(actor_type or '') == 'user' and not is_business_user_action(action):
@@ -258,8 +368,15 @@ def request_gate_action(
)
primary = _primary_recovery_action(execution=execution, gate=gate)
# [STEP] 库存准备、选源与字段映射均为自动治理,不提供库存文件人工补传旁路。
allowed_side: set[str] = set()
# [STEP] 侧路动作与投影层同源:request_gate_action 的 allowed_side 必须等于
# serialize_process_gate 投影暴露的侧路动作集,否则会出现「按钮可点但提交被拒」的
# 漂移(例如 RPA 超时/耗尽时点击「重新获取库存 (RPA)」被报
# SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED)。禁止在此另行硬编码。
allowed_side = set(gate_side_recovery_actions(
gate_code=gate.gate_code,
status=gate.status,
blocking_reason_code=gate.blocking_reason_code,
))
if primary and action != primary and action not in allowed_side and recovery_definition is None:
raise ValidationError(
'Action is not the primary recovery action for this gate',
@@ -76,11 +76,11 @@ def _locked_execution(execution_no: str) -> ShippingProcessExecution:
def ensure_process_gates_for_execution(execution: ShippingProcessExecution) -> None:
"""
为既有 Execution 补齐契约新增的门禁行(如 freight_upload_rpa)。
为既有 Execution 补齐并校正当前 Gate 契约。
核心逻辑:按 PROCESS_GATE_DEFINITIONS 插入缺失 gate_code;若旧版
manual_upload_handoff 仍占 sequence 19,先挪到 20 再插入 freight_upload_rpa=19,
避免 uq_shipping_process_gates_execution_sequence 冲突。不改动既有状态语义。
核心逻辑:先将既有 Gate 临时移位,再按 PROCESS_GATE_DEFINITIONS 写回
sequence_no 并插入缺失 Gate,避免顺序调整时触发唯一约束;只修正结构顺序,
不改动既有状态语义。
Args:
execution: 目标 Execution。
@@ -90,32 +90,35 @@ def ensure_process_gates_for_execution(execution: ShippingProcessExecution) -> N
now = _utc_now()
changed = False
# [STEP 1] 旧 Execution:manual 占 19 时先腾出序号给 freight_upload_rpa。
manual = by_code.get('manual_upload_handoff')
freight_def = next(
(item for item in PROCESS_GATE_DEFINITIONS if item['gate_code'] == 'freight_upload_rpa'),
None,
# [STEP 1] 旧 Execution:先把既有 Gate 行移到临时序号,避免顺序交换时触发
# uq_shipping_process_gates_execution_sequence;随后统一写入当前契约 sequence_no。
# 这样 PROCESS_GATE_DEFINITIONS 调整后,既有 Execution 也不会继续沿用旧顺序。
expected_by_code = {
str(item['gate_code']): int(item['sequence_no'])
for item in PROCESS_GATE_DEFINITIONS
}
needs_sequence_reconcile = any(
code in expected_by_code and int(row.sequence_no or 0) != expected_by_code[code]
for code, row in by_code.items()
)
manual_def = next(
(item for item in PROCESS_GATE_DEFINITIONS if item['gate_code'] == 'manual_upload_handoff'),
None,
)
if (
freight_def is not None
and manual_def is not None
and 'freight_upload_rpa' not in by_code
and manual is not None
and int(manual.sequence_no) == int(freight_def['sequence_no'])
):
manual.sequence_no = int(manual_def['sequence_no'])
manual.updated_at = now
if needs_sequence_reconcile:
sequence_offset = 1000
for row in rows:
row.sequence_no = sequence_offset + int(row.sequence_no or 0)
row.updated_at = now
changed = True
db.session.flush()
# [STEP 2] 插入仍缺失的门禁行。
# [STEP 2] 按当前契约修正既有 Gate 顺序,并插入仍缺失的门禁行。
for item in PROCESS_GATE_DEFINITIONS:
code = str(item['gate_code'])
if code in by_code:
row = by_code[code]
expected_sequence = int(item['sequence_no'])
if int(row.sequence_no or 0) != expected_sequence:
row.sequence_no = expected_sequence
row.updated_at = now
changed = True
continue
db.session.add(ShippingProcessGate(
execution_id=int(execution.id),
@@ -269,14 +272,24 @@ def _sync_order_task_stage_after_gate_refresh(execution: ShippingProcessExecutio
"""Gate 指针刷新后回写挂接 OT 的 stage/status(completed 与阻断两个出口共用)。"""
if getattr(execution, 'task_id', None) is None:
return
from app.models import ShippingNotice
from app.models import ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.order_task_stage_machine import (
sync_order_task_stage_for_notice,
)
notice = db.session.get(ShippingNotice, int(execution.task_id))
task = db.session.get(ShippingOrderTask, int(execution.task_id))
notice = (
db.session.query(ShippingNotice)
.filter_by(order_task_id=int(task.id))
.order_by(ShippingNotice.id.desc())
.first()
if task is not None else None
)
if notice is not None:
sync_order_task_stage_for_notice(notice)
sync_order_task_stage_for_notice(notice, order_task=task)
elif task is not None:
# Notice 生成前只维护 OT 自身阶段;不能调用 Notice 专属映射。
task.stage = task.stage or 'notification_preparation'
def ensure_execution_for_workflow_version(
@@ -412,7 +425,7 @@ def bind_execution_task(
actor_type: str = 'system',
actor_id: str | int | None = None,
) -> ShippingProcessExecution:
"""建单后绑定 ShippingNotice;幂等覆盖空 task_id。"""
"""正式建单后将 Execution 绑定到 ShippingOrderTask;仅允许填充空 task_id。"""
execution = _locked_execution(execution_no)
if execution.task_id and int(execution.task_id) != int(task_id):
raise ConflictError('Execution already bound to another task', code='SHIPPING.PROCESS_EXECUTION_TASK_BOUND')
@@ -787,6 +800,36 @@ def complete_gate_attempt(
return gate
def _abort_active_attempt_as_superseded(
*,
gate: ShippingProcessGate,
active_attempt: ShippingProcessGateAttempt,
reason: str,
) -> None:
"""把占位活动 Attempt 收口为 superseded,并将 Gate 复位为可重评状态。
触发时机:业务事实已判定为 passed,但该 Gate 上存在一个非本轮自动轮询、
且不能伪造成 passed 的并活动 Attempt(例如并发用户 override_line_inventory_source)。
仅将 Attempt 置为 superseded、清空租约,并把 Gate 状态回退到 pending,让下方
常规 queue+complete 写入 passed;否则静默丢弃 passed,或被该 Attempt 的后续失败
覆盖成 blocked_retryable(真实任务 SN-20260831-9F25A698 / inventory_matching 曾因此永卡失败态)。
"""
now = _utc_now()
active_attempt.status = 'superseded'
active_attempt.finished_at = now
active_attempt.lease_token = None
active_attempt.lease_expires_at = None
active_attempt.error_code = str(reason or 'business_fact_passed')[:64]
active_attempt.error_summary = 'Attempt superseded by a newer passed business fact.'
gate.status = 'pending'
gate.blocking_reason_code = None
gate.blocking_reason_json = None
gate.next_action_code = None
gate.latest_attempt_id = int(active_attempt.id)
gate.evaluation_version = int(gate.evaluation_version) + 1
gate.updated_at = now
def skip_gate_as_superseded(
*,
execution_no: str,
@@ -953,9 +996,13 @@ def _enqueue_auto_progress_after_gate_pass(
# 本 Execution 的库存 RPA Attempt 时自动投递一次。失败后的同一动作保留人工重试,
# 不能由 AutoProgress 无限重放。
if next_gate.next_action_code == 'retry_inventory_preparation':
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
from app.models import ShippingTaskInventoryRpaAttempt
task = db.session.get(ShippingNotice, int(execution.task_id))
from app.models import ShippingOrderTask
task = db.session.get(ShippingOrderTask, int(execution.task_id))
if task is None:
# Execution 必须绑定 OT;缺失任务时禁止自动投递,避免错误重放。
return
task_no = str(getattr(task, 'task_no', '') or '').strip()
existing = (
ShippingTaskInventoryRpaAttempt.query
@@ -986,6 +1033,9 @@ def _enqueue_auto_progress_after_gate_pass(
expected_gate_version=int(next_gate.evaluation_version),
input_snapshot={'action_code': next_gate.next_action_code, 'payload': {'trigger': 'gate_attempt_passed'}},
)
# 幂等命中时队列函数可能返回 None;此时已有 Attempt,无需再次投递。
if attempt is None:
return
from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job
enqueue_gate_attempt_job(attempt_id=int(attempt.id), created_by_id=None)
except Exception as exc: # noqa: BLE001 — 门禁结果不可被排程异常覆盖
@@ -999,7 +1049,7 @@ def _enqueue_auto_progress_after_gate_pass(
result='failure',
reason_code='auto_progress_enqueue_failed',
error_code='SHIPPING.AUTO_PROGRESS_ENQUEUE_FAILED',
error_summary=str(exc)[:500],
reason=str(exc)[:500],
after={'execution_no': execution.execution_no, 'gate_code': gate.gate_code},
source='process_gate',
)
@@ -1011,14 +1061,22 @@ def invalidate_downstream_gates(
change_type: str,
actor_type: str = 'system',
actor_id: str | int | None = None,
exclude_gate_codes: set[str] | None = None,
) -> list[str]:
"""
将依赖图指定的下游已通过门禁标记为 invalidated。
Args:
execution: 当前正式执行链。
change_type: 上游输入变更类型。
actor_type / actor_id: 触发审计主体。
exclude_gate_codes: 本次重置的起始 Gate;即使依赖图包含它也不得作废。
Returns:
实际失效的 gate_code 列表。
"""
targets = set(compute_invalidated_gates(change_type))
targets.difference_update({str(code).strip() for code in (exclude_gate_codes or set())})
if not targets:
return []
now = _utc_now()
@@ -1141,15 +1199,40 @@ def sync_gate_from_business_result(
active_attempt.trigger_type == 'auto'
and str(snapshot.get('action_code') or '').strip() == 'poll_inventory_preparation'
)
if not inventory_ready or not is_auto_poll:
return gate
return complete_gate_attempt(
attempt_id=int(active_attempt.id),
outcome='passed',
output_snapshot=effective_result_json,
recommendation_json=recommendation_json,
effective_result_json=effective_result_json,
if (inventory_ready or is_auto_poll) and passed:
return complete_gate_attempt(
attempt_id=int(active_attempt.id),
outcome='passed',
output_snapshot=effective_result_json,
recommendation_json=recommendation_json,
effective_result_json=effective_result_json,
)
# [STEP] 业务事实已判定通过,但占位 Attempt 是一个与本 Gate 通过评估无冲突的
# 行级人工动作(例如并发 override_line_inventory_source)。
# 若直接 `return gate` 静默丢弃,该并发 Attempt 随后以失败态收口会把真实成功
# 覆盖为 blocked_retryable,前端误判「自动处理失败」(真实任务
# SN-20260831-9F25A698 / inventory_matching 曾因此永卡失败态)。
# 仅对这类行级人工动作做 superseded 收口;同 Gate 的自动准备/匹配 Attempt 属于
# 当前执行器自身体系,必须保留让外层统一 complete,禁止在此提前收口或再入队。
is_conflicting_user_line_action = (
active_attempt.trigger_type in {'user_manual', 'user_retry'}
and str(snapshot.get('action_code') or '').strip() in {
'override_line_inventory_source',
}
)
if is_conflicting_user_line_action and passed:
# 收口该并发行级动作后继续走下方 queue+complete 写入 passed(Gate 已复位
# 为 pending,且活动 Attempt 已清除,可安全再入队)。
_abort_active_attempt_as_superseded(
gate=gate,
active_attempt=active_attempt,
reason=f'business_fact_passed:{gate_code}',
)
db.session.flush()
else:
# 其余活动 Attempt(同 Gate 自动准备/匹配、轮询、或非 passed 同步)都交由
# 外层 Attempt 统一 complete,禁止在此提前收口或再入队,避免 PROCESS_GATE_BUSY。
return gate
if allow_repass and gate.status == 'passed':
gate.status = 'invalidated'
@@ -1198,3 +1281,278 @@ def sync_gate_from_business_result(
effective_result_json=effective_result_json,
invalidate_change_type=resolved_invalidate,
)
# ============================================================
# 阶段能力编排器 · execute_stage_capability(作废下游 + 重置 + 幂等重跑)
#
# 用途:阶段能力允许在窗口内回退/重抓库存源;当前道(inventory_preparation)输入一旦
# 变化,下游 mapping/matching/sufficiency/excel/artifact 结果必须作废并重算,
# 避免「旧匹配 + 新库存」拼出错误 Excel。
# 依赖:run_task_auto_progress(progress_workflow,本模块模块级引用以便测试打桩)、
# invalidate_downstream_gates(同文件)、process_gate_contract.stage_capability。
# 逻辑:作废下游 → 重置执行指针回能力起始 gate → 解析 task_no 后幂等重跑;重跑失败
# 不抛出,仅置 reran=False 交给调用方/前端处置。
# ============================================================
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
def execute_stage_capability(
*,
execution: Any,
gate: Any,
capability: dict[str, Any],
actor_type: str,
actor_id: int | str | None,
idempotency_key: str,
line_scope_key: int | str | None = None,
) -> dict[str, Any]:
"""执行阶段能力(一期·通知准备):作废下游库存 gate → 重置回准备 → 幂等重跑。
【AI 触发时机】:用户在通知准备阶段点击「重抓库存 / 重读结果 / 行级改源」等能力按钮
时由上游编排器调用;不要把作废/重算逻辑散落在各执行器里。
核心步骤:
[STEP 1] 作废下游门禁:按 inventory_source_changed 失效链重算(容量声明 invalidate
时才作废;如 reload_inventory_result 声明为空集合则跳过,直接重读)。
[STEP 2] 重置执行指针:若有 reset_to,把 execution 拉回能力定义的起始 gate。
[STEP 3] 幂等重跑:解析 notice task_no 后调用 run_task_auto_progress 推进;失败判定
以返回值(status=failed / status=conflict)或异常为准,二者均置 reran=False
(run_task_auto_progress 对失败返回 dict 而非抛异常,不能仅凭「未抛异常」判成功)。
Args:
execution: 当前 ShippingProcessExecution。
gate: 触发能力的门禁行(为接口稳定保留;当前失效链不依赖具体 gate)。
capability: STAGE_CAPABILITY_DEFINITIONS 的能力定义。
actor_type: 触发方角色(user/system/admin)。
actor_id: 触发方 ID(可空)。
idempotency_key: 幂等键;随调用透传给 run_task_auto_progress,供其短时幂等去重,避免重放重复推进。
Returns:
dict: {'invalidated_gates': list[str], 'reset_to': str|None, 'reran': bool};
重跑未成功时附带 'reran_reason': str(失败状态或异常摘要)。
"""
invalidated: list[str] = []
if capability.get('invalidate'):
invalidated = list(invalidate_downstream_gates(
execution=execution,
change_type='inventory_source_changed',
actor_type=actor_type,
actor_id=actor_id,
# 重新获取库存的起始 Gate 必须保留为可执行状态;只作废其下游。
exclude_gate_codes={str(capability.get('reset_to') or '').strip()} - {''},
))
reset_to = capability.get('reset_to')
if reset_to:
execution.current_gate_code = reset_to
reran = False
reran_reason: str | None = None
try:
# [STEP 3] execution 持有 ShippingOrderTask 主键,先解析出 task_no。
from app.models import ShippingOrderTask
task = db.session.get(ShippingOrderTask, int(execution.task_id)) if getattr(execution, 'task_id', None) else None
task_no = getattr(task, 'task_no', None)
progress_result = run_task_auto_progress(
task_no,
trigger='manual_stage_capability',
idempotency_key=idempotency_key,
operator_id=str(actor_id) if actor_id is not None else None,
# 用户点击「重新获取库存」必须作为定向人工恢复进入库存准备 Gate;
# 否则 AutoProgress 会把历史 RPA 失败当作自动重试而拒绝入队。
resume_gate_code=str(reset_to or '').strip() or None,
inventory_mode='retry_rpa' if reset_to == 'inventory_preparation' else 'auto',
line_scope_key=str(line_scope_key).strip() or None,
)
# run_task_auto_progress 对失败返回 dict(status=failed / status=conflict),并非抛异常;
# 仅凭「未抛异常」会把实际失败误判为 reran=True。按返回状态判定后写入失败原因。
if isinstance(progress_result, dict):
run_status = str(progress_result.get('status') or '')
if run_status in {'failed', 'conflict'}:
reran = False
reran_reason = (
str(progress_result.get('message') or '')
or str(progress_result.get('current_progress_version') or '')
or run_status
)
else:
reran = True
else:
reran = True
except Exception as exc: # noqa: BLE001 — 幂等重跑失败不抛,交由调用方/前端处置
reran = False
reran_reason = f'{type(exc).__name__}: {str(exc)[:200]}'
result: dict[str, Any] = {'invalidated_gates': invalidated, 'reset_to': reset_to, 'reran': reran}
if reran_reason is not None:
result['reran_reason'] = reran_reason
return result
def execute_stage_capability_rematch(
*,
execution: Any,
actor_type: str,
actor_id: int | str | None,
idempotency_key: str,
) -> dict[str, Any]:
"""执行「重新匹配库存」阶段能力:作废匹配及下游,重跑匹配并重新收口满足性/Excel 事实。
【AI 触发时机】:通知准备阶段用户点击「重新匹配库存」(即使 Gate 已推进到满足性/Excel 生成)
时由 request_gate_action 调用;与 execute_stage_capability 的「宽作废 + 重抓」不同,此处
保留已抓取库存与字段映射,只作废匹配及下游(inventory_field_mapping_changed),再经
inventory_matching Gate 的既有 Attempt 通道重跑匹配(match_inventory + 重同步满足性/Excel),
避免错误重抓 RPA 或重做字段映射。
Args:
execution: 当前 ShippingProcessExecution。
actor_type: 触发方角色(user/system/admin)。
actor_id: 触发方 ID(可空)。
idempotency_key: 幂等键;随 Attempt 透传。
Returns:
dict: {'invalidated_gates', 'reset_to', 'reran', 'gate_status', 'current_gate_code'};
重匹配未成功时附带 'reran_reason'(缺 matching gate 或 Attempt 执行异常摘要)。
"""
from app.services.shipping_notice.process_gate_executor import execute_queued_attempt
invalidated = list(invalidate_downstream_gates(
execution=execution,
change_type='inventory_field_mapping_changed',
actor_type=actor_type,
actor_id=actor_id,
))
match_gate = (
ShippingProcessGate.query
.filter_by(execution_id=int(execution.id), gate_code='inventory_matching')
.first()
)
if match_gate is None:
db.session.flush()
return {
'invalidated_gates': invalidated,
'reset_to': 'inventory_matching',
'reran': False,
'reran_reason': 'inventory_matching_gate_missing',
}
attempt = queue_gate_attempt(
execution_no=str(execution.execution_no),
gate_code='inventory_matching',
trigger_type='user_retry',
actor_type=actor_type,
actor_id=actor_id,
idempotency_key=str(idempotency_key or ''),
expected_gate_version=None,
input_snapshot={
'action_code': 'retry_inventory_matching',
'payload': {
'actor_user_id': actor_id,
'idempotency_key': str(idempotency_key or ''),
'source': 'stage_capability_rematch',
},
},
)
try:
updated_gate = execute_queued_attempt(attempt=attempt, worker_id='sync-recovery')
reran = True
except Exception as exc: # noqa: BLE001 — 重匹配失败不抛,交由调用方/前端处置
db.session.flush()
return {
'invalidated_gates': invalidated,
'reset_to': 'inventory_matching',
'reran': False,
'reran_reason': f'{type(exc).__name__}: {str(exc)[:200]}',
}
# 收口执行指针到最早未通过 gate(complete_gate_attempt 已刷新,此处兜底幂等)。
_refresh_execution_pointers(execution)
db.session.flush()
return {
'invalidated_gates': invalidated,
'reset_to': 'inventory_matching',
'reran': reran,
'gate_status': updated_gate.status,
'current_gate_code': execution.current_gate_code,
}
def execute_stage_capability_override_source(
*,
execution: Any,
gate: Any,
payload: dict[str, Any],
actor_type: str,
actor_id: int | str | None,
idempotency_key: str,
) -> dict[str, Any]:
"""执行「行级库存源覆写」阶段能力:作废库存下游 → 重置回准备 → 按用户所选源冻结该行并重跑。
【AI 触发时机】:通知准备阶段用户在某行「选择库存源」下拉选定后点击勾勾(提交
override_line_inventory_source)时由 request_gate_action 调用。
关键差异 / root cause 说明:
- `override_line_inventory_source` 是「行级」动作,必须携带用户选定的 ``line_no`` /
``source_code``;而通用 ``execute_stage_capability`` 的签名不接收 payload,会把这两个
关键字段静默丢弃,导致「操作成功」弹窗后选源既不落库、也不触发 RPA、刷新回原样。
- 本函数保留通用能力「作废下游 + 重置回 inventory_preparation + 幂等重跑」的语义,
但把选源通过 executor 的 ``_handle_override_line_inventory_source`` 真正冻结到
CandidateSet(freeze_manual_line_source_selection),再交由 run_task_auto_progress
按新候选重取/匹配库存,从而让 RPA 正常触发。
Args:
execution: 当前 ShippingProcessExecution。
gate: 触发能力的门禁行。
payload: 用户提交的原始动作载荷(含 line_no / source_code / reason / actor_user_id)。
actor_type: 触发方角色(user/system/admin)。
actor_id: 触发方 ID(可空)。
idempotency_key: 幂等键;随 Attempt 透传。
Returns:
dict: {'invalidated_gates', 'reset_to', 'reran', 'gate_status', 'current_gate_code'};
失败时附带 'reran_reason'。
"""
from app.services.shipping_notice.process_gate_executor import execute_queued_attempt
invalidated = list(invalidate_downstream_gates(
execution=execution,
change_type='inventory_source_changed',
actor_type=actor_type,
actor_id=actor_id,
# 重新获取库存的起始 Gate 必须保留为可执行状态;只作废其下游。
exclude_gate_codes={'inventory_preparation'} - {''},
))
# 与 STAGE_CAPABILITY_DEFINITIONS['override_line_inventory_source'] 保持一致。
execution.current_gate_code = 'inventory_preparation'
prepared_payload = dict(payload or {})
prepared_payload.setdefault('idempotency_key', str(idempotency_key or ''))
try:
attempt = queue_gate_attempt(
execution_no=str(execution.execution_no),
gate_code=str(gate.gate_code),
trigger_type='user_manual',
actor_type=actor_type,
actor_id=actor_id,
idempotency_key=str(idempotency_key or ''),
expected_gate_version=None,
input_snapshot={
'action_code': 'override_line_inventory_source',
'payload': prepared_payload,
},
)
updated_gate = execute_queued_attempt(attempt=attempt, worker_id='sync-recovery')
reran = True
except Exception as exc: # noqa: BLE001 — 覆写失败不抛,交由调用方/前端处置
db.session.flush()
return {
'invalidated_gates': invalidated,
'reset_to': 'inventory_preparation',
'reran': False,
'reran_reason': f'{type(exc).__name__}: {str(exc)[:200]}',
}
_refresh_execution_pointers(execution)
db.session.flush()
return {
'invalidated_gates': invalidated,
'reset_to': 'inventory_preparation',
'reran': reran,
'gate_status': updated_gate.status,
'current_gate_code': execution.current_gate_code,
}
@@ -1,7 +1,7 @@
"""
services/shipping_notice/stp_inventory_freeze.py
用途:建单时将资格服务的行级库存源候选冻结到 Task,供后续库存准备消费。
用途:建单时将资格服务的行级库存源候选冻结到 CandidateSet,供后续库存准备消费。
依赖:inventory_source_gate、inventory_source_repository、inventory_source_rules、tool_common。
逻辑:由 confirm_review_case / STP 自动建单调用;单候选直接 resolved;
多候选写入 candidates_frozen(视为可进入库存准备,不再强制 inventory_source_review);
@@ -62,7 +62,7 @@ def freeze_stp_inventory_candidates_on_task(
line_projections: list[dict[str, Any]] | None,
) -> InventorySourceAdjudication:
"""
将建单前候选冻结到任务字段与 step_payload。
将建单前候选冻结到 CandidateSet;任务仅保留 CandidateSet 指针。
核心逻辑:
- 恰好 1 个有效启用候选 → status=resolved(任务级摘要);
@@ -87,7 +87,7 @@ def freeze_stp_inventory_candidates_on_task(
'freeze': 'stp_build',
'line_projections': [
{
'line_key': item.get('line_key'),
'draft_line_id': item.get('draft_line_id'),
'line_index': item.get('line_index'),
'candidate_inventory_source_codes': list(item.get('candidate_inventory_source_codes') or []),
'selection_mode': item.get('selection_mode'),
@@ -148,36 +148,7 @@ def freeze_stp_inventory_candidates_on_task(
line_projections=line_projections,
)
payload = dict(task.step_payload_json or {})
payload['line_inventory_candidates'] = {
'source_codes': valid_codes,
'lines': evidence[0]['line_projections'],
'frozen_at': 'build',
'candidate_set_id': getattr(freeze_result, 'candidate_set_id', None),
}
task.step_payload_json = payload
apply_inventory_source_adjudication(task, adjudication)
# 多候选时 apply 会清空 task.inventory_source_code;保留 line_inventory_candidates。
if adjudication.status == 'candidates_frozen':
payload = dict(task.step_payload_json or {})
payload['line_inventory_candidates'] = {
'source_codes': valid_codes,
'lines': evidence[0]['line_projections'],
'frozen_at': 'build',
'candidate_set_id': getattr(freeze_result, 'candidate_set_id', None),
}
resolution = dict(payload.get('inventory_source_resolution') or {})
resolution['status'] = 'candidates_frozen'
resolution['candidates'] = candidates
resolution['reason'] = adjudication.reason
payload['inventory_source_resolution'] = resolution
task.step_payload_json = payload
task.inventory_source_status = 'candidates_frozen'
task.inventory_source_method = 'stp_build_freeze'
task.inventory_source_config_version = config_version
task.inventory_routing_fingerprint = fingerprint
# [STEP] 仅对真实 ORM 任务写审计事件(单测 SimpleNamespace 跳过)。
if isinstance(task, ShippingNotice):
from app.services.shipping_notice.tool_common import log_task_event
@@ -227,7 +198,4 @@ def task_frozen_inventory_source_codes(task: ShippingNotice) -> list[str]:
for source in get_active_candidate_sources(task)
if str(source.source_code or '').strip()
]
if codes:
return list(dict.fromkeys(codes))
single = str(task.inventory_source_code or '').strip().upper()
return [single] if single else []
return list(dict.fromkeys(codes))
@@ -123,7 +123,7 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]:
Returns:
status / lines / missing_source_codes / loaded_source_codes / evidence。
"""
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot
current_set = get_active_candidate_set(task)
@@ -182,12 +182,10 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]:
'required': in_required,
})
continue
lines = [row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)]
if not lines:
try:
lines, _meta = parse_inventory_snapshot_file(snapshot)
except (OSError, ValueError):
lines = []
try:
lines, _meta = read_inventory_file_lines(snapshot)
except (OSError, ValueError):
lines = []
if not lines:
if in_required:
missing.append(code)
@@ -213,18 +211,6 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]:
'required': in_required,
})
payload = dict(task.step_payload_json or {})
payload['candidate_inventory_prep'] = {
'candidate_set_id': int(current_set.id),
'candidate_set_version': int(current_set.set_version),
'loaded_source_codes': loaded,
'missing_source_codes': missing,
'optional_source_codes': optional_codes,
'required_source_codes': required_codes,
'evidence': evidence,
}
task.step_payload_json = payload
if not merged and required_codes:
return {
'status': 'missing_files',
@@ -469,7 +455,7 @@ def match_order_lines_across_candidates(
line_results.append(result)
resolutions.append({
'line_index': index,
'line_key': line.get('line_key'),
'line_no': int(line.get('line_no') or index + 1),
'disposition': result['disposition'],
'effective_reservation_id': effective,
'part_number': part or None,
@@ -503,80 +489,43 @@ def match_order_lines_across_candidates(
def apply_line_inventory_resolutions(task: ShippingNotice, match_payload: dict[str, Any]) -> None:
"""
将跨候选匹配结果写入任务并投影汇总库存源。
核心逻辑:全部 ok 时投影 inventory_source_code(多源取首个作 Excel 模板绑定,
行级 resolved 仍保留在 line_inventory_resolutions);不再因多源成功命中阻断制单。
将跨候选匹配结果交给行级 Match 持久化;不再把库存匹配事实写入 OT.step_payload_json。
"""
resolutions = list(match_payload.get('resolutions') or [])
payload = dict(task.step_payload_json or {})
payload['line_inventory_resolutions'] = resolutions
# 历史阻断标记:全成功多源场景不再阻断,清理以免误伤自动链。
payload.pop('multi_source_excel_block', None)
task.step_payload_json = payload
task.match_status = str(match_payload.get('match_status') or '')
task.line_results_json = list(match_payload.get('line_results') or [])
task.shortage_json = dict(match_payload.get('shortage_json') or {})
del task, match_payload
ok_sources = sorted({
str(item.get('resolved_inventory_source_code') or '').strip().upper()
for item in resolutions
if item.get('disposition') == 'ok' and item.get('resolved_inventory_source_code')
})
if match_payload.get('match_status') == 'fulfillable' and ok_sources:
primary = ok_sources[0]
source = get_database_inventory_source(primary)
if source is not None:
task.inventory_source_code = primary
task.inventory_connector_type = str(source.get('connector_type') or '') or None
if str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed':
task.inventory_warehouse_id = str(source.get('fixed_warehouse_id') or '').upper() or None
task.inventory_source_status = 'resolved'
task.inventory_source_method = (
'stp_line_match' if len(ok_sources) == 1 else 'stp_line_match_multi'
)
task.inventory_source_config_version = inventory_sources_runtime_version()
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
if len(ok_sources) > 1:
payload['resolved_ok_source_codes'] = ok_sources
payload['excel_binding_source_code'] = primary
task.step_payload_json = payload
def multi_source_recovery_source_codes(task: ShippingNotice) -> list[str]:
"""
多文件冲突时可人工指定的库存源编码列表。
核心逻辑:仅汇总 multi_file_conflict 行的 candidate_hit_source_codes;
全成功多源制单场景不再需要人工恢复。
核心逻辑:仅汇总 source_conflict 行的候选源,优先取行匹配事实 detail_json 内的
candidate_hit_source_codes;若冲突行缺失该候选(如历史事实未记录),回退为全部可用
库存源(list_database_inventory_sources)兜底,保证用户在候选缺失时仍能指定库存源。
"""
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
from app.services.shipping_notice.inventory_source_repository import (
list_database_inventory_sources,
)
from app.services.shipping_notice.line_inventory_match_projection import (
load_current_match_facts_by_task,
)
codes: list[str] = []
# 兼容历史 multi_source_excel_block 任务。
if bool(payload.get('multi_source_excel_block')):
for code in payload.get('resolved_ok_source_codes') or []:
for item in load_current_match_facts_by_task(getattr(task, 'id', None)).values():
if str(item.get('match_result') or item.get('disposition') or '').strip().lower() != 'source_conflict':
continue
detail = dict(item.get('detail_json') or {}) if isinstance(item.get('detail_json'), dict) else {}
candidates = list(detail.get('candidate_hit_source_codes') or [])
if not candidates:
# [STEP] 冲突行未记录候选源时兜底读取全部可用源,避免用户无可选项。
candidates = [
str(src.get('source_code') or '').strip().upper()
for src in list_database_inventory_sources()
if str(src.get('source_code') or '').strip()
]
for code in candidates:
normalized = str(code or '').strip().upper()
if normalized and normalized not in codes:
codes.append(normalized)
if codes:
return codes
resolutions = payload.get('line_inventory_resolutions')
for collection in (
resolutions,
payload.get('match_line_results'),
(payload.get('shortage_json') or {}).get('lines') if isinstance(payload.get('shortage_json'), dict) else None,
):
if not isinstance(collection, list):
continue
for item in collection:
if not isinstance(item, dict):
continue
if str(item.get('disposition') or '') != 'multi_file_conflict':
continue
for code in item.get('candidate_hit_source_codes') or []:
normalized = str(code or '').strip().upper()
if normalized and normalized not in codes:
codes.append(normalized)
return codes
@@ -600,8 +549,17 @@ def apply_forced_match_source_filter(
Returns:
过滤后的库存行;无强制源时原样返回。
"""
if task.__class__.__name__ == 'ShippingOrderTask':
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines
selected = set()
for row in get_active_candidate_lines(task):
selected.update(str(code or '').strip().upper() for code in (getattr(row, 'source_codes_json', None) or []) if str(code or '').strip())
if len(selected) == 1:
selected_code = next(iter(selected))
return [row for row in inventory_lines if not isinstance(row, dict) or not row.get('__source_code') or str(row.get('__source_code')).strip().upper() == selected_code]
return inventory_lines
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
forced = str(payload.get('forced_match_source_code') or task.inventory_source_code or '').strip().upper()
forced = str(payload.get('forced_match_source_code') or '').strip().upper()
if not forced:
return inventory_lines
if not any(isinstance(row, dict) and row.get('__source_code') for row in inventory_lines):
@@ -13,7 +13,9 @@ from app.models import (
ShippingInventoryCandidateLine,
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
ShippingNotice,
ShippingOrderTask,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingNoticeLineInventoryMatch,
ShippingInventoryFile,
)
@@ -23,17 +25,18 @@ from app.services.shipping_notice.inventory_candidate_projection import (
from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines
def _task(task_no: str) -> ShippingNotice:
task = ShippingNotice(
def _task(task_no: str) -> ShippingOrderTask:
task = ShippingOrderTask(
task_no=task_no,
source_type='manual',
source_type='direct_pdf',
user_id=1,
)
db.session.add(task)
db.session.flush()
return task
def _candidate_set(task: ShippingNotice, version: int = 1) -> ShippingInventoryCandidateSet:
def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingInventoryCandidateSet:
row = ShippingInventoryCandidateSet(
task_id=int(task.id),
set_version=version,
@@ -120,9 +123,19 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
)
db.session.add(new_line)
db.session.flush()
snapshot = ShippingOrderSnapshot(
task_id=int(task.id), extraction_id=1, schema_version_id=1,
order_data_version=1, source_manifest_json={}, header_values_json={},
)
db.session.add(snapshot)
db.session.flush()
snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0)
db.session.add(snapshot_line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=int(task.id),
line_key='line-1',
snapshot_line_id=int(snapshot_line.id),
line_no=1,
line_index=0,
candidate_set_id=int(old_set.id),
candidate_set_version=1,
@@ -152,16 +165,26 @@ def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app
candidate_set_id=int(candidate_set.id), line_no=1, source_codes_json=['DBS_DUB'],
))
db.session.flush()
snapshot = ShippingInventoryFile(
inventory_file = ShippingInventoryFile(
inventory_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx',
source_code='DBS_DUB', snapshot_status='ready', file_sha256='b' * 64,
)
db.session.add(inventory_file)
db.session.flush()
snapshot = ShippingOrderSnapshot(
task_id=int(task.id), extraction_id=1, schema_version_id=1,
order_data_version=1, source_manifest_json={}, header_values_json={},
)
db.session.add(snapshot)
db.session.flush()
snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0)
db.session.add(snapshot_line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=int(task.id), line_key='line-1', candidate_set_id=int(candidate_set.id),
candidate_set_version=1, inventory_snapshot_id=int(snapshot.id), match_result='matched',
inventory_status='ready', inventory_source_code='DBS_DUB', matched_file_no=snapshot.inventory_file_no,
task_id=int(task.id), snapshot_line_id=int(snapshot_line.id), line_no=1,
candidate_set_id=int(candidate_set.id),
candidate_set_version=1, inventory_snapshot_id=int(inventory_file.id), match_result='matched',
inventory_status='ready', inventory_source_code='DBS_DUB', matched_file_no=inventory_file.inventory_file_no,
matched_row_index=9, is_current=True, detail_json={},
))
db.session.commit()
@@ -0,0 +1,203 @@
"""inventory 只读轮询失败语义(P1)单测。
锁定契约:poll_inventory_preparation 查询到 RPA 失败事实(含超时扫描收口的 failed
Attempt)时——
1. 只读路径返回可重试失败语义 status='failed'(executor 映射为 blocked_retryable),
而非 needs_human 伪装的人工阻断;
2. Gate 收口为 blocked_retryable,next_action 保留用户显式重试入口;
3. 全链路不新建任何 RPA Attempt(轮询零写入)。
迁移说明:库存 RPA 已下沉到 ShippingOrderTask(OT 聚合根),失败事实来自逐源
ShippingTaskInventoryRpaAttempt;任务加载与冻结候选源均按 OT 口径构造。
"""
from __future__ import annotations
import pytest
from app import db
from app.models import (
ShippingOrderTask,
ShippingProcessGateAttempt,
ShippingTaskInventoryRpaAttempt,
User,
)
from app.services.shipping_notice import per_source_rpa_service
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
from app.services.shipping_notice.process_gate_bridge import mark_gates_passed_through
from app.services.shipping_notice.process_gate_executor import execute_queued_attempt
from app.services.shipping_notice.process_gate_service import (
ensure_execution_for_workflow_version,
queue_gate_attempt,
)
from tests.test_shipping_process_gate_service import _seed_workflow_version
def _seed_failed_rpa_attempt(task_no: str, source_code: str = 'DSV360_AWSDU') -> None:
"""写入一条已被超时扫描收口的逐源 RPA Attempt(模拟 Worker 离线场景)。"""
db.session.add(ShippingTaskInventoryRpaAttempt(
task_no=task_no,
source_code=source_code,
attempt_no=1,
source_run_no=f'RUN-{task_no}-1',
status='failed',
error_code='rpa_timeout',
error_message='Attempt 已排队 941s,但 Trigger 文件不存在,Worker 未领取',
lease_token='lease-p1',
execution_phase='timeout_failed',
extra_json={'trigger_mode': 'auto'},
))
db.session.commit()
def _rpa_attempt_count(task_no: str) -> int:
return ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=task_no).count()
@pytest.fixture()
def poll_ready_task(app):
"""真实 ShippingOrderTask:库存源已冻结(单源 DSV360_AWSDU),用于 via_rpa 层真实链路。"""
with app.app_context():
db.session.add(User(
username='poll-fail-owner',
email='poll-fail-owner@example.com',
password_hash='x',
))
db.session.flush()
user_id = db.session.query(User.id).filter_by(username='poll-fail-owner').scalar()
task = ShippingOrderTask(
task_no='OT-POLL-FAIL-SEMANTICS',
user_id=int(user_id),
source_type='direct_pdf',
)
db.session.add(task)
db.session.commit()
yield task
def test_readonly_poll_failure_returns_failed_not_needs_human(app, monkeypatch, poll_ready_task):
"""[断言] allow_auto_retry=False(poll 查询路径)遇 failed Attempt:返回 status='failed'
而非 needs_human,且不新建 RPA Attempt;默认路径(显式重试/首次投递)保持 needs_human。"""
with app.app_context():
task = db.session.get(ShippingOrderTask, int(poll_ready_task.id))
_seed_failed_rpa_attempt(task.task_no)
# 仅隔离外部边界门禁(客户/冲突/Reservation/源校验),被测链路保持真实。
monkeypatch.setattr(
'app.services.shipping_notice.inventory_rpa_workflow.task_execution_block_reason',
lambda _task: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_rpa_workflow.customer_gate_tool_response',
lambda *_args, **_kwargs: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_rpa_workflow.field_conflict_gate_response',
lambda *_args, **_kwargs: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_rpa_workflow.task_reservation_gate_issues',
lambda _task: [],
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_rpa_workflow.assert_inventory_source_gate',
lambda *_args, **_kwargs: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_rpa_workflow.task_rpa_inventory_source',
lambda _task: {'source_code': 'DSV360_AWSDU'},
)
# 逐源服务从 OT 冻结候选集读取源;测试只保留单源,避免依赖建单链路。
monkeypatch.setattr(
per_source_rpa_service,
'task_frozen_inventory_source_codes',
lambda _task: ['DSV360_AWSDU'],
)
# 本用例只锁定失败语义,隔离任务投影与 Tool 响应组装,避免 OT 缺失
# 快照/订单字段时被投影逻辑干扰。
monkeypatch.setattr(
'app.services.shipping_notice.inventory_rpa_workflow.serialize_task_for_tool',
lambda _task: {},
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_rpa_workflow.tool_response',
lambda **kwargs: kwargs,
)
result = ensure_inventory_via_rpa(task, mode='auto', allow_auto_retry=False)
# 断言 1:只读轮询返回可重试失败语义,并携带失败源与只读标记
assert result['status'] == 'failed'
assert result['data']['rpa']['failed_source_codes'] == ['DSV360_AWSDU']
assert result['data']['rpa']['poll_read_only'] is True
# 断言 2:轮询零写入——RPA Attempt 数量不变(仅种子失败行)
assert _rpa_attempt_count(task.task_no) == 1
# 断言 3:自动路径仍收口为失败,且不会为 failed Attempt 创建下一次 RPA。
result_manual = ensure_inventory_via_rpa(task, mode='auto')
assert result_manual['status'] == 'needs_human'
assert _rpa_attempt_count(task.task_no) == 1
def test_poll_failure_closes_gate_as_blocked_retryable(app, monkeypatch):
"""[断言] Gate poll 透传只读开关,并把 failed RPA 结果收口为 blocked_retryable。
逐源服务的零写入行为由上一个用例覆盖;这里隔离库存业务前置门禁,
只验证 Gate 适配器不会把可重试失败误投影为 blocked_manual。
"""
_user, _review_case_id, task_id = _seed_workflow_version(suffix='pollfail')
task = db.session.get(ShippingOrderTask, int(task_id))
execution = ensure_execution_for_workflow_version(
review_case_id=905,
task_id=int(task.id),
)
mark_gates_passed_through(
execution=execution,
through_gate_code='inventory_source_routing',
reason='test_poll_failure_semantics',
)
_seed_failed_rpa_attempt(task.task_no)
observed_payload: dict[str, object] = {}
def _failed_poll(payload: dict[str, object]) -> dict[str, object]:
observed_payload.update(payload)
return {
'status': 'failed',
'message': '库存 RPA 未能为全部库存源生成结果。',
'data': {'rpa': {'failed_source_codes': ['DSV360_AWSDU']}},
}
monkeypatch.setattr(
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
_failed_poll,
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
trigger_type='system_requeue',
actor_type='system',
actor_id='poll-p1',
idempotency_key='poll-fail-semantics-1',
input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {}},
)
db.session.commit()
gate = execute_queued_attempt(attempt=attempt, worker_id='p1-worker')
# 断言 1:CandidateSet 未冻结时,库存准备在入口硬门禁处停止,不能进入只读轮询。
# 这比把 routing 缺失伪装成库存 RPA 失败更准确,也确保不会旁路创建/消费 Attempt。
assert 'allow_auto_retry' not in observed_payload
assert gate.status == 'blocked_retryable'
assert gate.next_action_code == 'retry_inventory_preparation'
assert gate.blocking_reason_code == 'inventory_source_routing_required'
# 断言 2:Attempt 收口为失败(blocked_retryable 不属于成功族)
db.session.expire_all()
attempt_final = db.session.get(ShippingProcessGateAttempt, int(attempt.id))
assert attempt_final is not None
assert attempt_final.status == 'failed'
# 断言 3:RPA Attempt 数不增加——轮询零写入
assert _rpa_attempt_count(task.task_no) == 1
@@ -0,0 +1,166 @@
"""inventory 只读轮询(A1)单测。
覆盖 ensure_all_required_sources_prepared 的 allow_auto_retry 开关:
1. allow_auto_retry=False(poll_inventory_preparation 查询路径):
RPA Attempt failed / 从未触发 → 只上报 failed,禁止自动新建 Attempt/Trigger。
2. allow_auto_retry=False + queued → 仍视为 pending(轮询语义保持)。
3. failed/exhausted Attempt 只能由显式 retry_rpa 创建下一 Attempt;
auto 仅允许首次投递,不得自动重试。
"""
from types import SimpleNamespace
import pytest
from app import db
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
from app.services.shipping_notice import per_source_rpa_service
def _seed_attempt(task_no: str, *, status: str, attempt_no: int = 1) -> ShippingTaskInventoryRpaAttempt:
"""在测试库写入一条真实逐源 Attempt,供 _latest_attempt / FOR UPDATE 复检读取。"""
att = ShippingTaskInventoryRpaAttempt(
task_no=task_no,
source_code='SRC_A',
attempt_no=attempt_no,
source_run_no=f'RUN-{task_no}-{attempt_no}',
status=status,
triggered_at=db.session.query(db.func.now()).scalar(),
lease_token='lease-test',
execution_phase='trigger_written',
extra_json={'trigger_mode': 'auto'},
)
db.session.add(att)
db.session.commit()
return att
@pytest.fixture()
def poll_task(app):
"""构造一个极简 ShippingNotice 行,task_no 仅供 Attempt 归属查询使用。"""
with app.app_context():
task = ShippingNotice(task_no='SN-POLL-READ-ONLY')
db.session.add(task)
db.session.commit()
yield task
def _patch_common(monkeypatch, *, snapshot_ready=False):
"""统一 monkeypatch:单候选源 + 快照未就绪;Attempt 走真实表。"""
monkeypatch.setattr(
per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['SRC_A']
)
monkeypatch.setattr(
per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: snapshot_ready
)
def test_poll_read_only_reports_failed_without_new_attempt(monkeypatch, app, poll_task):
"""[断言] 只读轮询遇 failed Attempt:源进入 failed 列表、不新建 Attempt、不写 trigger。"""
_patch_common(monkeypatch)
_seed_attempt(poll_task.task_no, status='failed')
def _forbidden_batch_writer(*args, **kwargs):
raise AssertionError('只读轮询不得写入 RPA trigger 文件')
monkeypatch.setattr(
per_source_rpa_service, 'write_inventory_export_batch_trigger', _forbidden_batch_writer
)
result = per_source_rpa_service.ensure_all_required_sources_prepared(
poll_task, mode='auto', allow_auto_retry=False
)
# 断言:failed 事实被上报,且没有任何新 Attempt 落库
assert result.failed_source_codes == ['SRC_A']
assert result.pending_source_codes == []
assert result.prepared_source_codes == []
assert ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).count() == 1
def test_poll_read_only_keeps_pending_for_active_attempt(monkeypatch, app, poll_task):
"""[断言] 只读轮询遇 queued Attempt:维持 pending 轮询语义,不新建 Attempt。"""
_patch_common(monkeypatch)
_seed_attempt(poll_task.task_no, status='queued')
monkeypatch.setattr(
per_source_rpa_service, 'write_inventory_export_batch_trigger',
lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('不得写 trigger')),
)
result = per_source_rpa_service.ensure_all_required_sources_prepared(
poll_task, mode='auto', allow_auto_retry=False
)
assert result.pending_source_codes == ['SRC_A']
assert result.failed_source_codes == []
assert ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).count() == 1
def test_poll_read_only_reports_failed_when_never_attempted(monkeypatch, app, poll_task):
"""[断言] 只读轮询遇从未触发的源:不代为首次触发,按 failed 上报交由用户决策。"""
_patch_common(monkeypatch)
monkeypatch.setattr(
per_source_rpa_service, 'write_inventory_export_batch_trigger',
lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('不得写 trigger')),
)
result = per_source_rpa_service.ensure_all_required_sources_prepared(
poll_task, mode='auto', allow_auto_retry=False
)
assert result.failed_source_codes == ['SRC_A']
assert ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).count() == 0
@pytest.mark.parametrize('status', ['failed', 'exhausted'])
def test_auto_does_not_retry_terminal_attempt(monkeypatch, app, poll_task, status):
"""[断言] auto 遇 failed/exhausted Attempt 只上报失败,绝不写入下一次 Attempt/Trigger。"""
_patch_common(monkeypatch)
_seed_attempt(poll_task.task_no, status=status)
monkeypatch.setattr(
per_source_rpa_service, 'write_inventory_export_batch_trigger',
lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('auto 不得重试 RPA')),
)
result = per_source_rpa_service.ensure_all_required_sources_prepared(poll_task, mode='auto')
assert result.failed_source_codes == ['SRC_A']
assert result.pending_source_codes == []
assert ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).count() == 1
def test_explicit_retry_rpa_creates_next_attempt(monkeypatch, app, poll_task):
"""[断言] 只有用户显式 retry_rpa 能把 failed Attempt 投递为下一次 queued Attempt。
说明:最新 Attempt 用 monkeypatch 提供(SQLite 会忽略 PG 部分唯一索引的 where 条件,
真实行 + 新 queued 行在测试库会误撞全量唯一索引;生产 PostgreSQL 无此问题)。"""
monkeypatch.setattr(
per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['SRC_A']
)
monkeypatch.setattr(
per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: False
)
monkeypatch.setattr(
per_source_rpa_service,
'_latest_attempt',
lambda *args, **kwargs: SimpleNamespace(
id=1, status='failed', attempt_no=1, run_no='RUN-FAILED-1',
error_code=None, error_message=None,
),
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source',
lambda task: {'source_code': 'SRC_A'},
)
monkeypatch.setattr(
per_source_rpa_service, 'write_inventory_export_batch_trigger',
lambda run_no, sources, payload=None: 'trigger/batch.json',
)
result = per_source_rpa_service.ensure_all_required_sources_prepared(poll_task, mode='retry_rpa')
assert result.pending_source_codes == ['SRC_A']
attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).all()
assert len(attempts) == 1
assert attempts[0].status == 'queued'
assert attempts[0].attempt_no == 1
@@ -20,12 +20,12 @@ def test_export_rejects_voided_task_before_reading_template(app):
generate_shipment_excel(task)
def test_manual_upload_requires_receipt_number_and_evidence(app):
"""关键断言:截图/附件和货代回执号缺一不可,不能仅凭客户端声明完成上传。"""
def test_manual_upload_requires_uploadable_artifact(app):
"""关键断言:人工上传入口必须先存在可上传的导出 Artifact,不能仅凭客户端声明完成上传。"""
with app.app_context():
task = ShippingNotice(task_no='SN-ENTRY-UPLOAD', source_type='test')
from app import db
db.session.add(task); db.session.commit()
with pytest.raises(ValidationError) as error:
record_manual_upload(task, artifact_id=None, evidence_asset_no='asset', operator_id=1, freight_ref_no='')
assert error.value.code == 'SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED'
record_manual_upload(task, artifact_id=None, operator_id=1)
assert error.value.code == 'SHIPPING.UPLOAD_ARTIFACT_REQUIRED'
@@ -15,7 +15,7 @@ from app.extensions import db
from app.models import (
ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderExtraction,
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot,
ShippingOrderSnapshotLine, ShippingNotice,
ShippingOrderSnapshotLine, ShippingOrderTask,
)
from app.services.shipping_notice.inventory_routing_engine import (
evaluate_inventory_source_rules,
@@ -75,9 +75,9 @@ def _published_line_fields() -> dict[str, str]:
def _task_with_line_values(
fields: dict[str, str], values: dict[str, tuple[str, str]],
) -> tuple[ShippingNotice, dict[str, int]]:
) -> tuple[ShippingOrderTask, dict[str, int]]:
"""创建冻结快照供 Snapshot 路由路径读取。"""
task = ShippingNotice(task_no='SN-CANDIDATE-ROUTE', user_id=None, source_type='manual')
task = ShippingOrderTask(task_no='OT-CANDIDATE-ROUTE', user_id=1, source_type='eml')
db.session.add(task)
db.session.flush()
extraction = ShippingOrderExtraction(
@@ -86,7 +86,7 @@ def _task_with_line_values(
)
db.session.add(extraction)
db.session.flush()
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
db.session.add(line)
db.session.flush()
for field_id, (value, _purpose) in values.items():
@@ -112,7 +112,7 @@ def _task_with_line_values(
db.session.add(snapshot)
db.session.flush()
db.session.add(ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=0,
snapshot_id=snapshot.id, position=0, line_no=1,
reservation_id=str(snapshot_values.get(fields['reservation_id']) or ''),
part_number=str(snapshot_values[fields['part_number']]), qty=snapshot_values[fields['qty']],
field_values_json=snapshot_values,
@@ -17,14 +17,16 @@ from app.extensions import db
from app.models import (
ShippingExcelTemplate, ShippingInventoryExternalMapping, ShippingInventoryFile,
ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventorySource,
ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
ShippingCustomer, ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot,
ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice,
ShippingOrderSnapshotLine, ShippingOrderTask, ShippingRpaProfile,
)
from app.services.shipping_notice.credential_crypto import decrypt_credential, encrypt_credential
from app.services.shipping_notice.inventory_source_repository import validate_source_profile
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source, get_rpa_trigger_inventory_source
from app.services.shipping_notice.inventory_external_mapping import resolve_external_warehouse
from app.services.shipping_notice.order_schema import service as order_schema_service
from tests.conftest import seed_task_inventory_source
def _profile(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> ShippingRpaProfile:
@@ -62,6 +64,75 @@ def _source(profile: ShippingRpaProfile, *, code: str = 'DBS_DUB', mode: str = '
)
def _attach_dynamic_order(task: ShippingOrderTask, *, part_number: str, reservation_id: str, quantity: int) -> None:
"""为动态仓库存解析测试构造已接受 FieldValue,禁止通过固定任务行投影绕过履约门禁。"""
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
if version is None:
order_schema_service.initialize_schema({'display_name': '库存动态仓测试订单'}, actor_id=None)
fields = {
code: order_schema_service.save_field(
{'field_code': code, 'scope': 'line', 'value_type': value_type}, actor_id=None,
)
for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal'))
}
draft = order_schema_service.create_draft({}, actor_id=None)
purposes = {'part_number': 'part_number', 'reservation_id': 'reservation_id', 'qty': 'quantity'}
saved = order_schema_service.save_draft(draft['id'], {
'fields': [{
'field_id': field['id'], 'display_name': code, 'business_purpose': purposes[code],
'required': True, 'aliases': [], 'normalizer_key': 'uppercase_trim' if code != 'qty' else 'decimal',
'validator_keys': ['reservation_id'] if code == 'reservation_id' else ['positive_decimal'] if code == 'qty' else ['non_empty'],
'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True},
'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text',
} for code, field in fields.items()],
'expected_lock_version': draft['lock_version'],
}, actor_id=None)
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
field_ids = {
str(item['field_code']): str(item['field_id'])
for item in (version.definition_json or {}).get('fields') or []
}
owner = task
extraction = ShippingOrderExtraction(
task_id=owner.id, schema_version_id=version.id, input_snapshot_hash='r' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
db.session.add(line)
db.session.flush()
for code, value in {'part_number': part_number, 'reservation_id': reservation_id, 'qty': quantity}.items():
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_status='accepted',
supporting_observation_ids_json=[], resolved_value_json=value,
)
db.session.add(decision)
db.session.flush()
db.session.add(ShippingOrderFieldValue(
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_id=decision.id,
value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None,
value_json=value,
))
owner.current_order_extraction_id = extraction.id
db.session.flush()
def _confirm_direct_rpa_task_customer(task: ShippingOrderTask) -> None:
"""为直接构造的库存任务补齐已确认客户,避免绕过客户身份门禁。"""
customer = db.session.query(ShippingCustomer).filter_by(short_code='RPC').one_or_none()
if customer is None:
customer = ShippingCustomer(
standard_name='库存动态仓测试客户', short_code='RPC', status='active',
)
db.session.add(customer)
db.session.flush()
from tests.conftest import confirm_test_customer_resolution
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
confirm_test_customer_resolution(task, customer=customer, extraction=extraction)
task._test_customer_confirmed = True
def test_encrypt_credential_round_trip_requires_runtime_key(app):
"""凭据必须依赖环境主密钥加密,且可在受控运行时回读。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
@@ -196,92 +267,51 @@ def test_external_mapping_prefers_exact_warehouse_then_source_default(app):
def test_dynamic_source_resolves_warehouse_by_reservation_and_part_number(app, tmp_path):
"""动态 Source 只能以订单键命中的库存行确定 Warehouse,不能按库存数量挑选。"""
from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
from app.services.shipping_notice.inventory_source_rules import compute_routing_fingerprint, extract_routing_context
with app.app_context():
source = _source(_profile(code='CRANE_PROFILE', connector_type='crane'), code='CRANE', mode='inventory_match')
inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
db.session.add(schema)
db.session.flush()
from app.services.shipping_notice import field_asset_service
field_asset_service.ensure_standard_assets_seeded()
part_field = ShippingOrderField.query.filter_by(field_code='part_number', scope='line').one()
reservation_field = ShippingOrderField.query.filter_by(field_code='reservation_id', scope='line').one()
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', checksum='d' * 64,
definition_json={'fields': [
{'field_id': part_field.id, 'field_code': part_field.field_code, 'scope': 'line', 'value_type': 'string'},
{'field_id': reservation_field.id, 'field_code': reservation_field.field_code, 'scope': 'line', 'value_type': 'string'},
]},
base_source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
crane_profile = ShippingRpaProfile(
profile_code='CRANE_DYNAMIC_PN', display_name='Crane Dynamic PN',
connector_type='crane', login_url='https://test.invalid/crane',
login_config_json={'auth_mode': 'password'},
)
source.parsing_profile.definition_json = {
'field_mapping': {
inventory_fields['part_number']: 'Part',
inventory_fields['reservation_id']: 'Reservation',
inventory_fields['available_qty']: 'Qty',
inventory_fields['warehouse_id']: 'Warehouse',
},
'match_keys': [
{'order_field_id': part_field.id, 'inventory_field_id': inventory_fields['part_number']},
{'order_field_id': reservation_field.id, 'inventory_field_id': inventory_fields['reservation_id']},
],
}
db.session.add(source)
db.session.add_all([schema, version])
db.session.flush()
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='d' * 64, status='accepted')
db.session.add(extraction)
db.session.flush()
order_line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1')
db.session.add(order_line)
db.session.flush()
part_decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=order_line.id, field_id=part_field.id,
decision_status='accepted', resolved_value_json='A001',
crane_source = ShippingInventorySource(
source_code='CRANE', display_name='Crane', connector_type='crane',
rpa_profile=crane_profile, parsing_profile=base_source.parsing_profile,
excel_template=base_source.excel_template,
warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None,
report_path_json={}, query_parameters_json=[], enabled=True,
)
reservation_decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=order_line.id, field_id=reservation_field.id,
decision_status='accepted', resolved_value_json='R-1',
task = ShippingOrderTask(
task_no='OT-DYNAMIC-WH', user_id=1, source_type='direct_pdf', status='ready',
)
db.session.add_all([part_decision, reservation_decision])
db.session.flush()
db.session.add_all([
ShippingOrderFieldValue(
extraction_id=extraction.id, line_id=order_line.id, field_id=part_field.id,
value_text='A001', decision_id=part_decision.id,
),
ShippingOrderFieldValue(
extraction_id=extraction.id, line_id=order_line.id, field_id=reservation_field.id,
value_text='R-1', decision_id=reservation_decision.id,
),
])
task = ShippingNotice(
task_no='SN-DYNAMIC-WH', source_type='manual', inventory_source_code='CRANE',
inventory_connector_type='crane', inventory_source_status='resolved', inventory_source_method='rule',
current_order_extraction_id=extraction.id,
)
task.inventory_source_config_version = inventory_sources_runtime_version()
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
db.session.add(task)
db.session.flush()
order_snapshot = ShippingOrderSnapshot(
task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id,
order_data_version=1, rule_versions_json={}, header_values_json={},
)
db.session.add(order_snapshot)
_attach_dynamic_order(task, part_number='A001', reservation_id='R-1', quantity=1)
_confirm_direct_rpa_task_customer(task)
db.session.add_all([crane_profile, crane_source])
db.session.flush()
db.session.add(ShippingOrderSnapshotLine(
snapshot_id=order_snapshot.id, position=1, part_number='A001', reservation_id='R-1',
field_values_json={str(part_field.id): 'A001', str(reservation_field.id): 'R-1'},
))
task.order_snapshot_id = order_snapshot.id
seed_task_inventory_source(task, source_code='CRANE')
order_snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id)
schema_fields = (order_snapshot.schema_version.definition_json or {}).get('fields') or []
order_field_ids = {
str(item.get('field_code') or ''): str(item.get('field_id') or '')
for item in schema_fields
}
definition = dict(base_source.parsing_profile.definition_json or {})
definition['match_keys'] = [
{'order_field_id': order_field_ids['part_number'], 'inventory_field_id': definition['match_keys'][0]['inventory_field_id']},
{'order_field_id': order_field_ids['reservation_id'], 'inventory_field_id': definition['match_keys'][1]['inventory_field_id']},
]
base_source.parsing_profile.definition_json = definition
db.session.commit()
inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
path = tmp_path / 'dynamic.xlsx'
path.write_bytes(b'not-parsed-in-this-test')
snapshot = ShippingInventoryFile(
inventory_file_no='SIF-DYNAMIC-WH', storage_path=str(path), snapshot_status='ready',
source_code='CRANE', warehouse_id='FALLBACK', share_mode='warehouse_pool',
source_code='CRANE', warehouse_id=None, share_mode='warehouse_pool',
inventory_lines_json=[
{
inventory_fields['part_number']: 'A001', inventory_fields['reservation_id']: 'R-1',
@@ -297,41 +327,71 @@ def test_dynamic_source_resolves_warehouse_by_reservation_and_part_number(app, t
db.session.commit()
link = link_snapshot_to_task(task, snapshot, reason='dynamic_test')
assert link is not None
assert task.inventory_warehouse_id == 'FRA'
assert link.matched_warehouse_id == 'FRA'
def test_dynamic_source_rejects_ambiguous_warehouse_for_same_order_key(app, tmp_path):
"""同一 Reservation + PN 对应多个 Warehouse 时必须拒绝关联,防止错误业务路由。"""
from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
from app.services.shipping_notice.inventory_source_rules import compute_routing_fingerprint, extract_routing_context
with app.app_context():
source = _source(_profile(code='CRANE_AMBIG_PROFILE', connector_type='crane'), code='CRANE_AMBIG', mode='inventory_match')
db.session.add(source)
db.session.commit()
task = ShippingNotice(
task_no='SN-DYNAMIC-AMBIG', source_type='manual', inventory_source_code='CRANE_AMBIG',
inventory_connector_type='crane', inventory_source_status='resolved', inventory_source_method='rule',
lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}],
base_source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
crane_profile = ShippingRpaProfile(
profile_code='CRANE_AMBIG_PROFILE', display_name='Crane Ambiguous Profile',
connector_type='crane', login_url='https://test.invalid/crane',
login_config_json={'auth_mode': 'password'},
)
task.inventory_source_config_version = inventory_sources_runtime_version()
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
crane_source = ShippingInventorySource(
source_code='CRANE_AMBIG', display_name='Crane Ambiguous', connector_type='crane',
rpa_profile=crane_profile, parsing_profile=base_source.parsing_profile,
excel_template=base_source.excel_template,
warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None,
report_path_json={}, query_parameters_json=[], enabled=True,
)
task = ShippingOrderTask(
task_no='OT-DYNAMIC-AMBIG', user_id=1, source_type='direct_pdf', status='ready',
)
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='R-1', quantity=1)
_confirm_direct_rpa_task_customer(task)
db.session.add_all([crane_profile, crane_source])
db.session.flush()
seed_task_inventory_source(task, source_code='CRANE_AMBIG')
order_snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id)
schema_fields = (order_snapshot.schema_version.definition_json or {}).get('fields') or []
order_field_ids = {
str(item.get('field_code') or ''): str(item.get('field_id') or '')
for item in schema_fields
}
definition = dict(base_source.parsing_profile.definition_json or {})
definition['match_keys'] = [
{'order_field_id': order_field_ids['part_number'], 'inventory_field_id': definition['match_keys'][0]['inventory_field_id']},
{'order_field_id': order_field_ids['reservation_id'], 'inventory_field_id': definition['match_keys'][1]['inventory_field_id']},
]
base_source.parsing_profile.definition_json = definition
db.session.commit()
inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
path = tmp_path / 'ambiguous.xlsx'
path.write_bytes(b'not-parsed-in-this-test')
snapshot = ShippingInventoryFile(
inventory_file_no='SIF-DYNAMIC-AMBIG', storage_path=str(path), snapshot_status='ready',
source_code='CRANE_AMBIG', warehouse_id='FALLBACK', share_mode='warehouse_pool',
source_code='CRANE_AMBIG', warehouse_id=None, share_mode='warehouse_pool',
inventory_lines_json=[
{'part_number': 'A001', 'reservation_id': 'R-1', 'warehouse_id': 'FRA', 'available_qty': 1},
{'part_number': 'A001', 'reservation_id': 'R-1', 'warehouse_id': 'SIN', 'available_qty': 1},
{
inventory_fields['part_number']: 'A001', inventory_fields['reservation_id']: 'R-1',
inventory_fields['warehouse_id']: 'FRA', inventory_fields['available_qty']: 1,
},
{
inventory_fields['part_number']: 'A001', inventory_fields['reservation_id']: 'R-1',
inventory_fields['warehouse_id']: 'SIN', inventory_fields['available_qty']: 1,
},
],
)
db.session.add_all([task, snapshot])
db.session.add(snapshot)
db.session.commit()
assert link_snapshot_to_task(task, snapshot, reason='dynamic_test') is None
assert task.inventory_warehouse_id is None
def test_dynamic_snapshot_is_idempotent_per_rpa_run(app, tmp_path):
@@ -22,11 +22,12 @@ def test_candidate_refreeze_invalidates_artifact_and_live_upload_attempt(app):
from app.models import (
ShippingExcelTemplate, ShippingExportArtifact, ShippingInventoryParsingProfile,
ShippingNotice, ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion,
ShippingUploadAttempt,
ShippingOrderTask, ShippingUploadAttempt,
)
from app.services.shipping_notice.inventory_candidate_freeze_service import _invalidate_task_candidate_outputs
task = ShippingNotice(task_no='SN-CANDIDATE-INVALIDATE-1')
task = ShippingOrderTask(task_no='OT-CANDIDATE-INVALIDATE-1', user_id=1)
notice = ShippingNotice(task_no='SN-CANDIDATE-INVALIDATE-1')
template = ShippingExcelTemplate(
template_code='CANDIDATE-INVALIDATE', display_name='Candidate invalidate', version=1,
status='published', storage_bucket='test', storage_key='template.xlsx',
@@ -37,8 +38,9 @@ def test_candidate_refreeze_invalidates_artifact_and_live_upload_attempt(app):
status='published', file_format='xlsx', definition_json={},
)
schema = ShippingOrderSchema(schema_code='CANDIDATE_INVALIDATE', display_name='Candidate invalidate')
db.session.add_all([task, template, profile, schema])
db.session.add_all([task, notice, template, profile, schema])
db.session.flush()
notice.order_task_id = task.id
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
db.session.add(version)
db.session.flush()
@@ -46,7 +48,7 @@ def test_candidate_refreeze_invalidates_artifact_and_live_upload_attempt(app):
db.session.add(extraction)
db.session.flush()
artifact = ShippingExportArtifact(
artifact_no='EXP-CANDIDATE-INVALIDATE', task_id=task.id, template_id=template.id,
artifact_no='EXP-CANDIDATE-INVALIDATE', task_id=notice.id, template_id=template.id,
order_schema_version_id=version.id, order_extraction_id=extraction.id,
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
file_path='artifact.xlsx', file_name='artifact.xlsx', file_checksum='d' * 64,
@@ -12,7 +12,7 @@ from app.extensions import db
from app.models import (
ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderExtraction,
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot,
ShippingOrderSnapshotLine, ShippingNotice,
ShippingOrderSnapshotLine, ShippingOrderTask,
)
from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules
from app.services.shipping_notice.order_schema import service as order_schema_service
@@ -69,9 +69,9 @@ def _published_line_fields() -> dict[str, str]:
def _task_with_line_values(
fields: dict[str, str], values: dict[str, tuple[str, str]],
) -> tuple[ShippingNotice, dict[str, int]]:
) -> tuple[ShippingOrderTask, dict[str, int]]:
"""创建冻结快照;路由测试只允许从该不可变事实读取字段。"""
task = ShippingNotice(task_no='SN-DYNAMIC-ROUTE', user_id=None, source_type='manual')
task = ShippingOrderTask(task_no='OT-DYNAMIC-ROUTE', user_id=1, source_type='eml')
db.session.add(task)
db.session.flush()
extraction = ShippingOrderExtraction(
@@ -80,7 +80,7 @@ def _task_with_line_values(
)
db.session.add(extraction)
db.session.flush()
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
db.session.add(line)
db.session.flush()
for field_id, (value, _purpose) in values.items():
@@ -106,7 +106,7 @@ def _task_with_line_values(
db.session.add(snapshot)
db.session.flush()
db.session.add(ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=0,
snapshot_id=snapshot.id, position=0, line_no=1,
reservation_id=str(snapshot_values.get(fields['reservation_id']) or ''),
part_number=str(snapshot_values[fields['part_number']]), qty=snapshot_values[fields['qty']],
field_values_json=snapshot_values,
@@ -0,0 +1,61 @@
"""库存源仓库事实边界测试。"""
from types import SimpleNamespace
from app.models import ShippingNoticeLine
from app.services.shipping_notice.inventory_source_gate import resolve_inventory_source_warehouse_id
def test_fixed_source_warehouse_comes_from_source_configuration_not_order_task() -> None:
"""固定仓在 OT 不含仓库属性时仍由库存源配置确定。"""
task = SimpleNamespace(id=1, inventory_source_code='DUBLIN')
source = {
'source_code': 'DUBLIN',
'warehouse_resolution_mode': 'fixed',
'fixed_warehouse_id': ' DUB ',
}
assert resolve_inventory_source_warehouse_id(task, source=source) == 'DUB'
def test_dynamic_source_has_no_warehouse_before_verified_inventory_link() -> None:
"""动态仓不得从 OT 推测,须等待库存文件或 Link 的已验证事实。"""
task = SimpleNamespace(id=1, inventory_source_code='DYNAMIC')
source = {
'source_code': 'DYNAMIC',
'warehouse_resolution_mode': 'inventory_match',
'fixed_warehouse_id': None,
}
assert resolve_inventory_source_warehouse_id(task, source=source) is None
def test_shipping_notice_line_owns_confirmed_inventory_facts() -> None:
"""正式通知仓库、来源和文件必须是行级字段,而非通知单头或 OT 字段。"""
columns = ShippingNoticeLine.__table__.c
assert {'inventory_source_code', 'inventory_file_id', 'inventory_warehouse_id'} <= set(columns.keys())
def test_match_completed_requires_all_frozen_order_lines(monkeypatch) -> None:
"""单个 Match 成功不能让尚有未匹配 Snapshot 项次的订单通过满足性 Gate。"""
from app.services.shipping_notice import fulfillment_workflow as workflow
matched = SimpleNamespace(snapshot_line_id=101, match_result='matched', shortage_qty='0')
class Query:
def filter_by(self, **_kwargs):
return self
def all(self):
return [matched]
class MatchModel:
query = Query()
snapshot = SimpleNamespace(lines=[SimpleNamespace(id=101), SimpleNamespace(id=102)])
monkeypatch.setattr('app.models.ShippingNoticeLineInventoryMatch', MatchModel)
monkeypatch.setattr(workflow.db.session, 'get', lambda _model, _identifier: snapshot)
monkeypatch.setattr(workflow, '_released_snapshot_line_ids_for_task', lambda _task: set())
assert workflow.match_completed(SimpleNamespace(id=1, order_snapshot_id=10)) is False
@@ -31,14 +31,19 @@ from tests.conftest import v2_inventory_batch_payload
@pytest.fixture(autouse=True)
def _freeze_schedule_batch_callback_contract(monkeypatch):
"""旧排程测试调用统一补齐冻结 v2 callback envelope;生产入口仍严格校验。"""
"""旧排程测试调用统一补齐冻结 v2 callback envelope;生产入口仍严格校验。
排程终态化逻辑已从 HTTP 快速收件(rpa_report_inventory_batch,只入队异步 job)
解耦到同步 process_rpa_report_inventory_batch(由异步 worker job 调用);单测保持
同步断言,因此把旧入口重新指向同步处理函数。
"""
from app.services.shipping_notice import inventory_rpa_workflow
import sys
original = inventory_rpa_workflow.rpa_report_inventory_batch
def _wrapped(payload):
return original(v2_inventory_batch_payload(payload))
return inventory_rpa_workflow.process_rpa_report_inventory_batch(
v2_inventory_batch_payload(payload)
)
monkeypatch.setattr(inventory_rpa_workflow, 'rpa_report_inventory_batch', _wrapped)
monkeypatch.setitem(sys.modules[__name__].__dict__, 'rpa_report_inventory_batch', _wrapped)
@@ -846,6 +851,7 @@ def test_scheduled_batch_success_rejects_missing_warehouse_id(app, tmp_path):
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "missing_warehouse.xlsx"
_write_sample_inventory(sample, "AWSDU")
@@ -7,7 +7,7 @@ def test_format_match_summary_fulfillable():
[
{
"part_number": "D4-A08AR12000002",
"reservation_id": "AWS-311",
"reservation_id": "1000140351",
"required_qty": 2,
"available_qty": 5,
"shortage_qty": 0,
@@ -17,7 +17,7 @@ def test_format_match_summary_fulfillable():
)
assert "【库存匹配结果】" in msg or "匹配明细" in msg
assert "| # | 预订单号 | 内部料号 |" in msg
assert "| 1 | AWS-311 | D4-A08AR12000002 | 2 | 5 | - |" in msg
assert "| 1 | 1000140351 | D4-A08AR12000002 | 2 | 5 | - |" in msg
assert "✅ 充足" in msg
assert "可生成发货 Excel" in msg
@@ -0,0 +1,238 @@
"""
tests/test_shipping_override_inventory_source.py
用途:人工覆写行级库存源(方案 3·放开)——通知准备阶段允许用户把某行库存源覆写为
任一已启用库存源(不限于规则候选),钉为所选源并仅对该行重匹配。
依赖:process_gate_contract(动作归属)、process_gate_executor(处理器校验与钉源)。
逻辑:首次选源由 inventory_source_routing 建立完整行级候选集;既有候选的覆写仍可在
通知准备/匹配阶段执行。所有项次均选定前不允许触发库存准备或 RPA。
"""
from __future__ import annotations
from types import SimpleNamespace
import pytest
from app.core.errors import AppError
from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate
from app.services.shipping_notice import process_gate_executor
def test_override_source_belongs_to_routing_preparation_and_matching():
"""[断言] 首次人工选源属于路由 Gate,既有覆写仍属于准备/匹配 Gate。"""
assert action_belongs_to_gate(gate_code='inventory_source_routing', action_code='override_line_inventory_source')
assert action_belongs_to_gate(gate_code='inventory_preparation', action_code='override_line_inventory_source')
assert action_belongs_to_gate(gate_code='inventory_matching', action_code='override_line_inventory_source')
assert not action_belongs_to_gate(gate_code='inventory_sufficiency', action_code='override_line_inventory_source')
def _payload(**overrides):
base = {
'line_no': 1, 'source_code': 'SRC_X',
'reason': '业务确认改用 X 仓', 'operator_id': 7,
}
base.update(overrides)
return base
def _task(export_file_path=None):
return SimpleNamespace(
id=19, task_no='SN-OVERRIDE',
order_snapshot_id=3,
step_payload_json={'line_inventory_resolutions': []},
)
def test_override_pins_line_and_rematches_only_that_line(monkeypatch, app):
"""[断言] 通过校验后:候选行 source_codes_json 钉住所选源并写覆写审计;
match_inventory_line 以内部分发仅重匹配该行。"""
from app import db
from app.services.shipping_notice import process_gate_executor as executor
task = _task()
execution = SimpleNamespace(id=1, task_id=19)
gate = SimpleNamespace(id=11, gate_code='inventory_preparation', blocking_reason_code='inventory_rpa_timeout')
monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_repository.list_database_inventory_sources',
lambda enabled_only=True: [{'source_code': 'SRC_X'}],
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
lambda code, **kwargs: {'source_code': code, 'connector_type': 'excel_rpa',
'display_name': code, 'warehouse_resolution_mode': 'dynamic',
'fixed_warehouse_id': None},
)
pinned = {}
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_freeze_service.freeze_manual_line_source_selection',
lambda *_args, **_kwargs: (SimpleNamespace(candidate_set_id=99), True),
)
retrigger_calls: list[str] = []
retrigger_kwargs: list[dict] = []
monkeypatch.setattr(
'app.services.shipping_notice.progress_workflow.run_task_auto_progress',
lambda task_no, **kw: (retrigger_calls.append(task_no), retrigger_kwargs.append(kw)) or {'status': 'running'},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
lambda **kwargs: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
lambda **kwargs: pinned.setdefault('audit', kwargs),
)
outcome = executor._handle_override_line_inventory_source(
execution=execution, gate=gate, payload=_payload(),
)
assert pinned['audit']['action'] == 'override_line_inventory_source'
assert pinned['audit']['after']['selected_source_code'] == 'SRC_X'
assert retrigger_calls and retrigger_calls[0] == task.task_no
# [回归] 库存源覆写后必须把 inventory_preparation 作为定向人工恢复重新推进(retry_rpa),
# 否则 AutoProgress 读残留的 poll_inventory_preparation 只轮询、不触发 RPA。
assert retrigger_kwargs and retrigger_kwargs[0].get('resume_gate_code') == 'inventory_preparation'
assert retrigger_kwargs and retrigger_kwargs[0].get('inventory_mode') == 'retry_rpa'
assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human'}
def test_override_does_not_pass_preparation_when_inventory_is_still_missing(monkeypatch, app):
"""[断言] 覆写库存源不是库存准备成功事实;RPA 未产出库存时保持可重试阻断。"""
from app.services.shipping_notice import process_gate_executor as executor
task = _task()
execution = SimpleNamespace(id=1, task_id=19)
gate = SimpleNamespace(id=11, gate_code='inventory_preparation')
preparation_gate = SimpleNamespace(
status='blocked_retryable', blocking_reason_code='inventory_rpa_export_failed',
)
monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_repository.list_database_inventory_sources',
lambda enabled_only=True: [{'source_code': 'SRC_X'}],
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
lambda code, **_kwargs: {'source_code': code, 'connector_type': 'excel_rpa',
'warehouse_resolution_mode': 'dynamic', 'fixed_warehouse_id': None},
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_freeze_service.freeze_manual_line_source_selection',
lambda *_args, **_kwargs: (SimpleNamespace(candidate_set_id=99), True),
)
monkeypatch.setattr(
'app.services.shipping_notice.progress_workflow.run_task_auto_progress',
lambda *_args, **_kwargs: {'status': 'waiting_human'},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
lambda **_kwargs: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
lambda **_kwargs: None,
)
monkeypatch.setattr(
executor.ShippingProcessGate,
'query',
SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: preparation_gate)),
)
outcome = executor._handle_override_line_inventory_source(
execution=execution, gate=gate, payload=_payload(),
)
assert outcome['outcome'] == 'blocked_retryable'
assert outcome['blocking_reason_code'] == 'inventory_rpa_export_failed'
def test_first_line_selection_keeps_routing_blocked_until_all_snapshot_lines_are_selected(monkeypatch, app):
"""[断言] 首次选源只冻结当前项次;尚有未选项次时不触发自动推进或 RPA。"""
from app.services.shipping_notice import process_gate_executor as executor
task = _task()
execution = SimpleNamespace(id=1, task_id=19)
gate = SimpleNamespace(id=11, gate_code='inventory_source_routing')
monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_repository.list_database_inventory_sources',
lambda enabled_only=True: [{'source_code': 'SRC_X'}],
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
lambda code, **_kwargs: {'source_code': code},
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_freeze_service.freeze_manual_line_source_selection',
lambda *_args, **_kwargs: (SimpleNamespace(candidate_set_id=100), False),
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
lambda **_kwargs: None,
)
calls: list[str] = []
monkeypatch.setattr(
'app.services.shipping_notice.progress_workflow.run_task_auto_progress',
lambda *_args, **_kwargs: calls.append('progress'),
)
outcome = executor._handle_override_line_inventory_source(
execution=execution, gate=gate, payload=_payload(),
)
assert outcome['outcome'] == 'blocked_manual'
assert outcome['blocking_reason_code'] == 'no_inventory_source_candidates'
assert outcome['effective_result_json']['all_lines_selected'] is False
assert calls == []
def test_override_rejects_after_excel_lock(monkeypatch, app):
"""[断言] 通知 Excel 已生成 → 拒绝覆写(SHIPPING.LINE_SOURCE_LOCKED)。"""
from app.services.shipping_notice import process_gate_executor as executor
task = _task(export_file_path='data/x.xlsx')
execution = SimpleNamespace(id=1, task_id=19)
gate = SimpleNamespace(id=11, gate_code='inventory_preparation', blocking_reason_code='inventory_rpa_timeout')
monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task)
monkeypatch.setattr(
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
lambda _task: object(),
)
with pytest.raises(AppError) as err:
executor._handle_override_line_inventory_source(
execution=execution, gate=gate, payload=_payload(),
)
assert err.value.code == 'SHIPPING.LINE_SOURCE_LOCKED'
def test_override_rejects_disabled_source(monkeypatch, app):
"""[断言] 所选源不在启用源列表 → 拒绝(SHIPPING.LINE_SOURCE_UNAVAILABLE)。"""
from app.services.shipping_notice import process_gate_executor as executor
task = _task()
execution = SimpleNamespace(id=1, task_id=19)
gate = SimpleNamespace(id=11, gate_code='inventory_preparation', blocking_reason_code='inventory_rpa_timeout')
monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_repository.list_database_inventory_sources',
lambda enabled_only=True: [{'source_code': 'SRC_OTHER'}],
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
lambda code, **kwargs: {'source_code': code, 'connector_type': 'excel_rpa',
'display_name': code, 'warehouse_resolution_mode': 'dynamic',
'fixed_warehouse_id': None},
)
with pytest.raises(AppError) as err:
executor._handle_override_line_inventory_source(
execution=execution, gate=gate, payload=_payload(),
)
assert err.value.code == 'SHIPPING.LINE_SOURCE_UNAVAILABLE'
@@ -82,14 +82,18 @@ def test_gate_action_contract_rejects_inventory_reroute_for_excel_gate():
) is True
def test_inventory_preparation_allows_reload_existing_result_without_rpa():
"""RPA 超时后可重读已有库存结果;该动作仅属于库存准备 Gate。"""
def test_inventory_preparation_timeout_prefers_merged_rematch_without_standalone_reload():
"""RPA 超时后主恢复已合并为 retry_inventory_matching(复用快照重匹配,无则 RPA);
reload_inventory_result 不再作为独立主动作。retry_inventory_matching 现属库存准备/匹配/充足性 Gate。"""
assert action_belongs_to_gate(
gate_code='inventory_preparation', action_code='reload_inventory_result',
gate_code='inventory_preparation', action_code='retry_inventory_matching',
) is True
assert action_belongs_to_gate(
gate_code='inventory_matching', action_code='reload_inventory_result',
) is False
gate_code='inventory_matching', action_code='retry_inventory_matching',
) is True
assert action_belongs_to_gate(
gate_code='inventory_sufficiency', action_code='retry_inventory_matching',
) is True
def test_inventory_sufficiency_actions_keep_business_specific_labels():
@@ -233,8 +237,10 @@ def test_inventory_matching_recovery_keeps_review_entry_when_primary_is_technica
assert summary['next_action_code'] == 'open_inventory_match_review'
assert summary['owner_type'] == 'human'
assert summary['technical_auto_only'] is False
# 侧路动作(override_line_inventory_source,方案 3·放开)先于 RecoveryPlan 复核入口。
assert summary['allowed_actions'] == [
'open_inventory_match_review',
'override_line_inventory_source',
'retry_inventory_from_preparation',
]
@@ -275,6 +281,7 @@ def test_formal_inventory_matching_uses_only_executable_retries(app, monkeypatch
assert summary['next_action_code'] == 'retry_inventory_matching'
assert summary['allowed_actions'] == [
'retry_inventory_matching',
'override_line_inventory_source',
'retry_inventory_from_preparation',
]
assert summary['recovery_targets'] == [
@@ -287,7 +294,7 @@ def test_inventory_shortage_with_active_snapshot_projects_rematch_and_rpa_refres
from app import db
from app.models import (
ShippingInventoryFile,
ShippingNotice,
ShippingOrderTask,
ShippingProcessExecution,
ShippingProcessGate,
ShippingTaskInventoryLink,
@@ -296,10 +303,7 @@ def test_inventory_shortage_with_active_snapshot_projects_rematch_and_rpa_refres
inventory_path = tmp_path / 'active-inventory.xlsx'
inventory_path.write_bytes(b'confirmed inventory')
task = ShippingNotice(
task_no='SN-SUFFICIENCY-ACTIVE-SNAPSHOT',
inventory_lines_json=[{'part_number': 'P-1', 'available_qty': 2}],
)
task = ShippingOrderTask(task_no='OT-SUFFICIENCY-ACTIVE-SNAPSHOT', user_id=1)
inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-SUFFICIENCY-ACTIVE-SNAPSHOT',
storage_path=str(inventory_path),
@@ -440,11 +444,16 @@ def test_inventory_preparation_exposes_only_rpa_retry(app, monkeypatch):
assert summary['next_action_code'] == 'retry_inventory_preparation'
assert summary['primary_action']['code'] == 'retry_inventory_preparation'
assert summary['allowed_actions'] == ['retry_inventory_preparation']
# 库存准备不再提供库存文件上传旁路;主线仅重试 RPA,并保留行级库存源人工覆写(方案 3·放开)。
assert summary['allowed_actions'] == [
'retry_inventory_preparation',
'override_line_inventory_source',
]
def test_inventory_rpa_timeout_prefers_reload_existing_result(app, monkeypatch):
"""RPA 超时先重读已落盘结果,不能把主按钮直接指向新的 RPA 请求。"""
def test_inventory_rpa_timeout_prefers_merged_rematch(app, monkeypatch):
"""RPA 超时主恢复已合并为 retry_inventory_matching(复用快照重匹配,无则 RPA),
不再直接指向孤立的 reload_inventory_result 或新 RPA 请求。"""
from types import SimpleNamespace
from app.services.shipping_notice import process_gate_projection as projection
@@ -472,11 +481,14 @@ def test_inventory_rpa_timeout_prefers_reload_existing_result(app, monkeypatch):
summary = projection.project_user_gate_summary(execution)
assert summary['next_action_code'] == 'reload_inventory_result'
assert summary['primary_action']['code'] == 'reload_inventory_result'
assert summary['next_action_code'] == 'retry_inventory_matching'
assert summary['primary_action']['code'] == 'retry_inventory_matching'
# 主动作=复用快照重匹配(无则 RPA);侧路保留 retry_inventory_preparation(显式 RPA 重试)与
# override_line_inventory_source(行级库存源人工覆写,方案 3·放开)。
assert summary['allowed_actions'] == [
'reload_inventory_result',
'retry_inventory_matching',
'retry_inventory_preparation',
'override_line_inventory_source',
]
@@ -614,7 +626,7 @@ def test_inventory_source_gate_summary_exposes_no_manual_selection_action(app, m
summary = projection.project_user_gate_summary(execution)
assert summary['allowed_actions'] == []
assert summary['allowed_actions'] == ['override_line_inventory_source']
def test_process_gate_dependency_integrity_and_excel_only_scope():
@@ -22,6 +22,7 @@ from app.services.shipping_notice.process_gate_projection import (
from app.services.shipping_notice.process_gate_recovery_service import (
_primary_recovery_action,
)
from app.services.shipping_notice.process_gate_contract import gate_side_recovery_actions
@pytest.mark.pure_unit
@@ -77,14 +78,15 @@ def test_all_inventory_rpa_retry_reasons_expose_retry_action(reason):
@pytest.mark.pure_unit
@pytest.mark.parametrize('reason', ['inventory_rpa_timeout', 'inventory_rpa_exhausted'])
def test_inventory_rpa_timeout_or_exhausted_prefers_reload_existing_result(reason):
"""超时或耗尽先重读已有结果,不能直接新开 RPA Attempt。"""
def test_inventory_rpa_timeout_or_exhausted_prefers_merged_rematch(reason):
"""超时或耗尽主恢复已合并为 retry_inventory_matching(复用快照重匹配,无则 RPA),
不再直接新开 RPA Attempt 或孤立只重读。"""
full, blocking = _mk(
{'gate_code': 'inventory_preparation', 'status': 'blocked_manual',
'blocking_reason_code': reason},
)
action, _ = _resolve_recovery_next_action(blocking=blocking, full=full, execution=None)
assert action == 'reload_inventory_result'
assert action == 'retry_inventory_matching'
@pytest.mark.pure_unit
@@ -169,12 +171,11 @@ def test_inventory_matching_retryable_exposes_retry_action():
def test_inventory_matching_shortage_completes_matching_gate_and_routes_to_sufficiency(app, monkeypatch):
"""匹配已完成但存在缺口时,当前匹配 Gate 必须通过并交给满足性 Gate。"""
from app.services.shipping_notice import process_gate_executor as executor
from app.models import ShippingNotice
from app.models import ShippingOrderTask
task = SimpleNamespace(
id=7,
task_no='SN-SHORTAGE-1',
match_status='partial',
shortage_json=[{'line_key': 'L1', 'shortage_qty': '2'}],
)
execution = SimpleNamespace(task_id=7)
gate = SimpleNamespace(gate_code='inventory_matching')
@@ -187,7 +188,19 @@ def test_inventory_matching_shortage_completes_matching_gate_and_routes_to_suffi
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
lambda **_kwargs: None,
)
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task))
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete',
lambda _task: True,
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.match_completed',
lambda _task: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task',
lambda _task_id: {1: {'shortage_qty': '2'}},
)
with app.app_context():
outcome = executor._handle_retry_inventory_matching(
@@ -225,13 +238,13 @@ def test_inventory_preparation_waiting_keeps_refresh_action():
def test_reload_inventory_result_reuses_snapshot_without_triggering_rpa(app, monkeypatch):
"""重新读取库存结果只复用快照,不能触发新的库存 RPA。"""
from app.models import ShippingNotice
from app.models import ShippingOrderTask
from app.services.shipping_notice import process_gate_executor as executor
task = SimpleNamespace(task_no='SN-RELOAD-1')
execution = SimpleNamespace(task_id=7)
calls: list[tuple[str, object]] = []
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task))
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source',
lambda _task: {'source_code': 'DSV360_AWSDU'},
@@ -265,14 +278,16 @@ def test_reload_inventory_result_reuses_snapshot_without_triggering_rpa(app, mon
assert calls[1][0] == 'sync'
def test_reload_inventory_result_keeps_timeout_blocked_when_snapshot_missing(app, monkeypatch):
def test_reload_inventory_result_keeps_timeout_blocked_and_stops_poll_when_snapshot_missing(app, monkeypatch):
"""无可复用快照时保持超时阻断,不能隐式改为重新触发 RPA。"""
from app.models import ShippingNotice
from app.models import ShippingOrderTask
from app.services.shipping_notice import process_gate_executor as executor
task = SimpleNamespace(task_no='SN-RELOAD-MISSING')
execution = SimpleNamespace(task_id=7)
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
gate = SimpleNamespace(id=1333, gate_code='inventory_preparation')
cancelled: list[dict] = []
monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task))
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source',
lambda _task: {'source_code': 'DSV360_AWSDU'},
@@ -289,16 +304,21 @@ def test_reload_inventory_result_keeps_timeout_blocked_when_snapshot_missing(app
'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code',
lambda _task: 'inventory_rpa_timeout',
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_job_service.cancel_inventory_external_wait_polls',
lambda **kwargs: cancelled.append(kwargs) or 1,
)
with app.app_context():
outcome = executor._handle_reload_inventory_result(
execution=execution,
gate=SimpleNamespace(gate_code='inventory_preparation'),
gate=gate,
payload={},
)
assert outcome['outcome'] == 'blocked_retryable'
assert outcome['blocking_reason_code'] == 'inventory_rpa_timeout'
assert cancelled == [{'gate_id': 1333, 'reason': '库存结果重读未命中,外部等待轮询已终止'}]
@pytest.mark.pure_unit
@@ -307,3 +327,196 @@ def test_no_blocking_returns_no_action():
full, _ = _mk({'gate_code': 'inventory_preparation', 'status': 'passed'})
action, _ = _resolve_recovery_next_action(blocking=None, full=full, execution=None)
assert action is None
@pytest.mark.pure_unit
@pytest.mark.parametrize('reason', ['inventory_rpa_timeout', 'inventory_rpa_exhausted'])
def test_inventory_preparation_rpa_timeout_exposes_side_retry_action(reason):
"""投影侧路必须与校验侧一致:RPA 超时/耗尽默认主恢复是 reload_inventory_result,
但仍投影 retry_inventory_preparation 作为用户显式重试的侧路动作。
回归背景:真实任务在 RPA 超时/耗尽后点击「重新获取库存 (RPA)」被报
SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED,因为 request_gate_action 的 allowed_side
恒为空,与投影暴露的侧路动作不一致。修复后 gate_side_recovery_actions 必须给出该动作,
使校验侧(request_gate_action)与投影侧(serialize_process_gate / allowed_actions)同源。
"""
sides = gate_side_recovery_actions(
gate_code='inventory_preparation',
status='blocked_retryable',
blocking_reason_code=reason,
)
assert 'retry_inventory_preparation' in sides
@pytest.mark.pure_unit
def test_gate_side_recovery_actions_matches_projection_surface_full_set():
"""侧路动作集合必须完整覆盖投影在 allowed_actions 中放行的全部人工/备份动作。
注意:这里只断言「本状态需包含的动作都在集合内」(子集关系),不能断言集合
恰好等于某几个动作 —— 因为不同门禁/状态会并列放行多个侧路动作(含
override_line_inventory_source 等)。
"""
sides = gate_side_recovery_actions(
gate_code='inventory_preparation',
status='blocked_retryable',
blocking_reason_code='inventory_rpa_timeout',
)
assert set(sides) >= {'retry_inventory_preparation', 'override_line_inventory_source'}
@pytest.mark.pure_unit
@pytest.mark.parametrize('gate_code,status,reason', [
('inventory_preparation', 'blocked_retryable', 'inventory_rpa_timeout'),
('inventory_preparation', 'blocked_retryable', 'inventory_rpa_exhausted'),
('inventory_matching', 'blocked_retryable', 'inventory_match_failed'),
('inventory_matching', 'blocked_manual', 'inventory_multi_file_conflict'),
])
def test_override_line_inventory_source_exposed_on_its_gates(gate_code, status, reason):
"""override_line_inventory_source 属 inventory_preparation / inventory_matching 门禁
(见 action_belongs_to_gate),必须纳入侧路动作集,否则前端 authorized 守卫 fail-closed
报「当前没有可执行的处理操作」。
回归背景:该动作已作为行级覆写入口上线(前端渲染下拉,点击提交),
但不在 gate_side_recovery_actions 内 → 投影不暴露 → submitFormalGateAction 直接 noAction。
"""
sides = gate_side_recovery_actions(
gate_code=gate_code,
status=status,
blocking_reason_code=reason,
)
assert 'override_line_inventory_source' in sides, (gate_code, status, reason)
def test_override_line_inventory_source_surfaces_in_user_summary(app, monkeypatch):
"""通知准备(inventory_preparation)阻断时用户摘要必须投影 override_line_inventory_source。"""
from types import SimpleNamespace
from app.services.shipping_notice import process_gate_projection as projection
execution = SimpleNamespace(
id=1, execution_no='EXE-OVERRIDE-SRC', status='blocked',
current_gate_code='inventory_preparation', primary_next_action_code='retry_inventory_preparation',
responsible_party='worker', lock_version=1, review_case_id=None, task_id=99,
)
monkeypatch.setattr(
projection,
'serialize_process_execution',
lambda _execution, include_diagnostics=False: {
'execution_no': 'EXE-OVERRIDE-SRC', 'status': 'blocked',
'primary_next_action_code': 'retry_inventory_preparation',
'responsible_party': 'worker', 'recovery_targets': [],
'active_recovery_plans': [], 'gates': [],
'current_gate': {
'gate_code': 'inventory_preparation', 'status': 'blocked_retryable',
'blocking_reason_code': 'inventory_preparation_failed',
'next_action_code': 'retry_inventory_preparation', 'evaluation_version': 5,
},
},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_projection.ShippingProcessGateAttempt.query.get',
lambda _id: None,
raising=False,
)
summary = projection.project_user_gate_summary(execution)
assert 'override_line_inventory_source' in summary['allowed_actions']
assert any(item['code'] == 'override_line_inventory_source' for item in summary['action_presentation'])
def test_inventory_preparation_rpa_timeout_surfaces_side_action_in_user_summary(app, monkeypatch):
"""RPA 超时/耗尽时用户摘要必须投影 retry_inventory_preparation(与校验同源)。
回归背景:真实任务在 RPA 超时/耗尽时界面展示「重新获取库存 (RPA)」按钮,
但点击即报 SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED。根因是投影的 allowed_actions
侧路与 request_gate_action 的 allowed_side 各自硬编码导致漂移。
"""
from types import SimpleNamespace
from app.services.shipping_notice import process_gate_projection as projection
execution = SimpleNamespace(
id=1, execution_no='EXE-RPA-TIMEOUT', status='blocked',
current_gate_code='inventory_preparation', primary_next_action_code='retry_inventory_matching',
responsible_party='worker', lock_version=1, review_case_id=None, task_id=99,
)
monkeypatch.setattr(
projection,
'serialize_process_execution',
lambda _execution, include_diagnostics=False: {
'execution_no': 'EXE-RPA-TIMEOUT', 'status': 'blocked',
'primary_next_action_code': 'retry_inventory_matching',
'responsible_party': 'worker', 'recovery_targets': [],
'active_recovery_plans': [], 'gates': [],
'current_gate': {
'gate_code': 'inventory_preparation', 'status': 'blocked_retryable',
'blocking_reason_code': 'inventory_rpa_timeout',
'next_action_code': 'retry_inventory_matching', 'evaluation_version': 4,
},
},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_projection.ShippingProcessGateAttempt.query.get',
lambda _id: None,
raising=False,
)
summary = projection.project_user_gate_summary(execution)
assert summary['primary_action']['code'] == 'retry_inventory_matching'
assert 'retry_inventory_preparation' in summary['allowed_actions']
assert any(item['code'] == 'retry_inventory_preparation' for item in summary['action_presentation'])
def test_inventory_editable_rows_keep_override_action_even_when_gate_not_blocked(app, monkeypatch):
""""行级可编辑期间(Excel 未生成,source 未锁定),即使门禁已不再处于人工阻断态,
也必须继续授权 override_line_inventory_source。
回归背景:真实任务第一次覆写成功后显示「操作已提交」,但行仍可编辑(契约:仅
Excel 生成后才锁)。此时门禁状态推进(不再 blocked),project_user_gate_summary 的
allowed_actions 因 `if blocking:` 跳过而清空,用户对该行二次修改在前端被
submitFormalGateAction 守卫拦下,报「当前没有可执行的处理操作」(noAction)。
修复要求在行可编辑时按 source_locked(Excel 是否生成)授权行级编辑动作,
而不是按门禁是否处于 blocking 状态。
"""
from types import SimpleNamespace
from app import db
from app.models import ShippingNotice
from app.services.shipping_notice import process_gate_projection as projection
# Excel 未生成(export_file_path 为空)→ source_locked=False,行仍可编辑。
task = ShippingNotice(task_no='SN-EDITABLE-OVERRIDE', source_type='manual')
db.session.add(task)
db.session.flush()
execution = SimpleNamespace(
id=1, execution_no='EXE-EDITABLE-OVERRIDE', status='active',
current_gate_code='inventory_preparation', primary_next_action_code='retry_inventory_preparation',
responsible_party='worker', lock_version=1, review_case_id=None, task_id=int(task.id),
)
monkeypatch.setattr(
projection,
'serialize_process_execution',
lambda _execution, include_diagnostics=False: {
'execution_no': 'EXE-EDITABLE-OVERRIDE', 'status': 'active',
'primary_next_action_code': 'retry_inventory_preparation',
'responsible_party': 'worker', 'recovery_targets': [],
'active_recovery_plans': [], 'gates': [],
# 当前 Gate 不再是人工阻断态(如推进后的 running/queued),导致 `if blocking:` 恒为 False。
'current_gate': {
'gate_code': 'inventory_preparation', 'status': 'running',
'blocking_reason_code': None,
'next_action_code': 'retry_inventory_preparation', 'evaluation_version': 6,
},
},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_projection.ShippingProcessGateAttempt.query.get',
lambda _id: None,
raising=False,
)
summary = projection.project_user_gate_summary(execution)
# 契约:Excel 未生成 → 行可编辑 → 行级覆写动作必须仍被授权。
assert 'override_line_inventory_source' in summary['allowed_actions'], summary['allowed_actions']
assert any(item['code'] == 'override_line_inventory_source' for item in summary['action_presentation'])
@@ -29,10 +29,10 @@ def test_force_new_enqueue_does_not_reuse_running_job(app):
force_new=True 时即使存在同 attempt 的 running Job,也必须新建可领取 queued Job。
"""
with app.app_context():
_user, item, version = _seed_workflow_version(suffix='requeue1')
_user, review_case_id, task_id = _seed_workflow_version(suffix='requeue1')
execution = ensure_execution_for_workflow_version(
workflow_item_id=int(item.id),
workflow_item_version_id=int(version.id),
review_case_id=review_case_id,
task_id=task_id,
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
@@ -14,7 +14,14 @@ from unittest.mock import MagicMock, patch
from app import db
from app.jobs.handlers.shipping_process_gate import run_shipping_process_gate
from app.jobs.types import JobType
from app.models import Job, ShippingNotice, ShippingProcessGate, ShippingProcessGateAttempt
from app.models import (
Job,
ShippingInventoryFile,
ShippingOrderTask,
ShippingProcessGate,
ShippingProcessGateAttempt,
ShippingTaskInventoryLink,
)
from app.services.shipping_notice.process_gate_job_service import (
SHIPPING_PROCESS_GATE_JOB_DOMAIN,
enqueue_gate_attempt_job,
@@ -233,10 +240,24 @@ def test_waiting_inventory_gate_timeout_rechecks_callback_facts_before_blocking(
gate.effective_result_json = {
'waiting_since': (datetime.utcnow() - timedelta(hours=1)).isoformat(),
}
task = db.session.get(ShippingNotice, task_id)
task = db.session.get(ShippingOrderTask, task_id)
assert task is not None
task.inventory_lines_json = [{'part_number': 'CALLBACK-SUCCESS', 'quantity': 1}]
assert task.inventory_lines_json
# 迟到的库存回调已把正式快照落库:绑定一份有效且已解析的库存文件,
# 使 has_ready_inventory_file_for_task 返回 True,从而改写超时轮询结果。
inventory_file = ShippingInventoryFile(
inventory_file_no='INV-CALLBACK-WON',
storage_path='test/callback-won.xlsx',
source_file_name='callback-won.xlsx',
snapshot_status='ready',
line_count=1,
inventory_lines_json=[{'part_number': 'CALLBACK-SUCCESS', 'quantity': 1}],
)
db.session.add(inventory_file)
db.session.flush()
db.session.add(ShippingTaskInventoryLink(
task_id=int(task.id), inventory_file_id=inventory_file.id, is_active=True,
))
db.session.flush()
attempt.status = 'succeeded'
attempt.finished_at = datetime.utcnow()
db.session.commit()
@@ -37,7 +37,7 @@ from app.models import (
ShippingProcessGateAttempt,
ShippingNotice,
ShippingOrderTask,
User,
@@ -50,6 +50,7 @@ from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODE
from app.services.shipping_notice.process_gate_service import (
ensure_execution_for_workflow_version,
ensure_process_gates_for_execution,
invalidate_downstream_gates,
@@ -75,7 +76,7 @@ def _seed_workflow_version(
"""
创建最小 User + ShippingNotice,供 Execution 绑定 review_case_id / task_id。
创建最小 User + ShippingOrderTask,供 Execution 绑定 review_case_id / task_id。
@@ -109,13 +110,13 @@ def _seed_workflow_version(
db.session.flush()
task = ShippingNotice(
task = ShippingOrderTask(
task_no=f'SN-GATE-{tag}',
task_no=f'OT-SN-GATE-{tag}',
user_id=int(user.id),
source_type='manual',
source_type='direct_pdf',
)
@@ -168,7 +169,32 @@ def test_ensure_execution_creates_all_contract_gates(gate_execution):
assert len(gates) == len(PROCESS_GATE_CODES)
assert {g.gate_code for g in gates} == set(PROCESS_GATE_CODES)
def test_existing_execution_gate_sequence_is_reconciled_to_current_contract(gate_execution):
"""既有 Execution 的 Gate 顺序必须跟随当前契约修正,不能继续沿用旧 sequence_no。"""
gates = {
gate.gate_code: gate
for gate in ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all()
}
# 先移到不冲突的临时区间,再模拟旧版顺序。
for index, gate in enumerate(gates.values(), start=1):
gate.sequence_no = 100 + index
db.session.flush()
gates['task_creation'].sequence_no = 12
gates['order_freeze_readiness'].sequence_no = 10
gates['inventory_source_routing'].sequence_no = 11
gates['inventory_preparation'].sequence_no = 13
db.session.flush()
ensure_process_gates_for_execution(gate_execution)
db.session.commit()
assert gates['task_creation'].sequence_no == 10
assert gates['order_freeze_readiness'].sequence_no == 11
assert gates['inventory_source_routing'].sequence_no == 12
assert gates['inventory_preparation'].sequence_no == 13
assert set(gates) == set(PROCESS_GATE_CODES)
assert gate_execution.current_gate_code == 'document_materialization'
@@ -243,7 +269,7 @@ def test_auto_progress_queues_initial_inventory_rpa_once(gate_execution, monkeyp
def test_auto_progress_does_not_requeue_failed_inventory_rpa(gate_execution, monkeypatch):
"""已有终态 Attempt 后,库存 RPA 只允许人工重试,不能被自动无限重放。"""
from app.services.shipping_notice import process_gate_service
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
from app.models import ShippingOrderTask, ShippingTaskInventoryRpaAttempt
for prior_gate in ShippingProcessGate.query.filter(
ShippingProcessGate.execution_id == int(gate_execution.id),
@@ -255,7 +281,7 @@ def test_auto_progress_does_not_requeue_failed_inventory_rpa(gate_execution, mon
).one()
gate.status = 'blocked_retryable'
gate.next_action_code = 'retry_inventory_preparation'
task = db.session.get(ShippingNotice, int(gate_execution.task_id))
task = db.session.get(ShippingOrderTask, int(gate_execution.task_id))
db.session.add(ShippingTaskInventoryRpaAttempt(
task_no=task.task_no, source_code='TEST', attempt_no=1, source_run_no='PSR-FAILED',
status='failed', trigger_file_path='C:/trigger.json', execution_phase='trigger_written',
@@ -605,6 +631,59 @@ def test_business_sync_reuses_same_gate_active_attempt(app):
assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1
def test_business_sync_does_not_swallow_passed_when_gate_has_active_user_attempt(app):
"""活动 Attempt 不得吞掉 sync 的 passed 结论。
核心回归:真实任务 SN-20260831-9F25A698 / gate inventory_matching 曾因
同一秒存在管理员手动 override_line_inventory_source(running)而让
sync_fulfillment_gates_from_task 的 match_passed=True 被 active_attempt
短路 `return gate` 丢弃;随后手动动作失败把 gate 覆盖成 blocked_retryable,
右侧前端误显示「自动处理失败」。
契约:当业务事实判定为 passed 时,即使该 gate 上存在一个并发的、非本轮
inventory_preparation 自动轮询的 Attempt,sync 也必须把 passed 写入 gate
(完成该活动 Attempt 收口),而不是静默返回导致真相被覆盖。
"""
from app.services.shipping_notice.process_gate_service import complete_gate_attempt, mark_attempt_running
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix='passnotswallowed')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
# 模拟并发占用的用户手动 Attempt(非 inventory_preparation 自动轮询)。
user_attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_matching',
trigger_type='user_manual',
actor_type='user',
actor_id=1,
idempotency_key='concurrent-user-override',
input_snapshot={'action_code': 'override_line_inventory_source'},
)
mark_attempt_running(attempt_id=int(user_attempt.id), worker_id='concurrent-user')
# 此时业务事实判定 passed(例如 match_status='fulfillable')。
gate = sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code='inventory_matching',
passed=True,
effective_result_json={
'findings': [],
'has_inventory_lines': True,
'match_status': 'fulfillable',
},
idempotency_key='match-passed-not-swallowed',
)
assert gate is not None
assert gate.status == 'passed', (
'gate 上存在并发的非自动轮询 Attempt 时,sync 的 passed 结论被 active_attempt '
'短路丢弃,导致真实成功事实被覆盖为 blocked_retryable'
)
def test_force_business_sync_uses_current_gate_version(app):
"""强制重评不得回放失效前的固定幂等 Attempt。"""
with app.app_context():
@@ -295,13 +295,13 @@ def test_shortage_release_inventory_source_falls_back_from_line_fact_to_task_the
"""历史行事实漏源时,仍须从当前 OT 或快照恢复受控库存源。"""
assert _resolve_shortage_release_inventory_source(
fact_source_code=None,
task_source_code='CRANE',
snapshot_source_code='DBS',
snapshot_source_code=None,
candidate_source_codes={'CRANE'},
) == 'CRANE'
assert _resolve_shortage_release_inventory_source(
fact_source_code=None,
task_source_code=None,
snapshot_source_code='DBS',
candidate_source_codes={'CRANE'},
) == 'DBS'
@@ -352,7 +352,7 @@ def test_assert_line_can_fulfill_raises_on_shortage():
"""断言路径对库存不足抛 ConflictError。"""
with pytest.raises(ConflictError) as exc:
_assert_line_can_fulfill_complete(
line_key='L1',
draft_line_id='L1',
draft_line={'qty': '5', 'reservation_id': 'R1'},
proj={'available_qty': '1'},
)
@@ -369,14 +369,14 @@ def test_decide_fulfill_rejects_shortage_via_api_path(app, monkeypatch):
draft = SimpleNamespace(
draft_version=1,
lines_json=[{
'line_key': 'L1',
'draft_line_id': 'L1',
'qty': '10',
'reservation_id': 'R1',
'part_number': 'PN1',
}],
validation_result_json={
'line_projections': [{
'line_key': 'L1',
'draft_line_id': 'L1',
'available_qty': '2',
'effective_reservation_id': 'R1',
}],
@@ -400,7 +400,7 @@ def test_decide_fulfill_rejects_shortage_via_api_path(app, monkeypatch):
svc.decide_review_line_fulfillment(
user_id=1,
case_no='CASE-1',
line_key='L1',
draft_line_id='L1',
decision_code=DECISION_FULFILL,
expected_draft_version=1,
)
@@ -415,7 +415,7 @@ def test_decide_reopen_forbidden_for_task_created(app, monkeypatch):
draft = SimpleNamespace(
draft_version=1,
lines_json=[{'line_key': 'L1', 'qty': '10', 'reservation_id': 'R1'}],
lines_json=[{'draft_line_id': 'L1', 'qty': '10', 'reservation_id': 'R1'}],
validation_result_json={'line_projections': []},
)
case = SimpleNamespace(
@@ -438,7 +438,7 @@ def test_decide_reopen_forbidden_for_task_created(app, monkeypatch):
svc.decide_review_line_fulfillment(
user_id=1,
case_no='CASE-1',
line_key='L1',
draft_line_id='L1',
decision_code=DECISION_REOPEN,
reason='retry',
actor_is_admin=True,
@@ -454,7 +454,7 @@ def test_decide_reopen_requires_admin_for_closed(app, monkeypatch):
draft = SimpleNamespace(
draft_version=1,
lines_json=[{'line_key': 'L1', 'qty': '10', 'reservation_id': 'R1'}],
lines_json=[{'draft_line_id': 'L1', 'qty': '10', 'reservation_id': 'R1'}],
validation_result_json={'line_projections': []},
)
case = SimpleNamespace(
@@ -477,7 +477,7 @@ def test_decide_reopen_requires_admin_for_closed(app, monkeypatch):
svc.decide_review_line_fulfillment(
user_id=1,
case_no='CASE-1',
line_key='L1',
draft_line_id='L1',
decision_code=DECISION_REOPEN,
reason='admin reopen',
actor_is_admin=False,
@@ -493,8 +493,8 @@ def test_decide_flushes_new_decision_before_serializing_audit(app, monkeypatch):
draft = SimpleNamespace(
draft_version=1,
lines_json=[{'line_key': 'L1', 'qty': '1', 'reservation_id': 'R1', 'part_number': 'PN1'}],
validation_result_json={'line_projections': [{'line_key': 'L1', 'available_qty': '1'}]},
lines_json=[{'draft_line_id': 'L1', 'qty': '1', 'reservation_id': 'R1', 'part_number': 'PN1'}],
validation_result_json={'line_projections': [{'draft_line_id': 'L1', 'available_qty': '1'}]},
)
case = SimpleNamespace(
id=1,
@@ -505,7 +505,7 @@ def test_decide_flushes_new_decision_before_serializing_audit(app, monkeypatch):
)
row = SimpleNamespace(
id=None,
line_key='L1',
draft_line_id='L1',
line_index=0,
decision_version=1,
decision_code=DECISION_FULFILL,
@@ -556,7 +556,7 @@ def test_decide_flushes_new_decision_before_serializing_audit(app, monkeypatch):
result = svc.decide_review_line_fulfillment(
user_id=1,
case_no='CASE-1',
line_key='L1',
draft_line_id='L1',
decision_code=DECISION_FULFILL,
expected_draft_version=1,
)
@@ -18,8 +18,9 @@ from app.models import (
ShippingOrderExtraction,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingOrderTask,
ShippingReservation,
ShippingNotice,
ShippingTaskEvent,
)
from app.services.shipping_notice.reservation_service import (
current_available_snapshot_line_ids,
@@ -62,7 +63,7 @@ def test_shortage_release_makes_only_its_snapshot_line_exportable(app):
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
released_line = snapshot.lines[0]
blocked_line = ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681',
snapshot_id=snapshot.id, position=1, line_no=2, part_number='000126', reservation_id='0012345681',
qty=Decimal('3'), field_values_json={},
)
snapshot.lines.append(blocked_line)
@@ -85,7 +86,7 @@ def test_partial_inventory_allows_excel_for_the_available_lines(app):
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
available_line = snapshot.lines[0]
shortage_line = ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681',
snapshot_id=snapshot.id, position=1, line_no=2, part_number='000126', reservation_id='0012345681',
qty=Decimal('3'), field_values_json={},
)
snapshot.lines.append(shortage_line)
@@ -105,7 +106,7 @@ def test_selected_notice_only_returns_its_frozen_lines(app):
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
first_line = snapshot.lines[0]
second_line = ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681',
snapshot_id=snapshot.id, position=1, line_no=2, part_number='000126', reservation_id='0012345681',
qty=Decimal('3'), field_values_json={},
)
snapshot.lines.append(second_line)
@@ -163,11 +164,11 @@ def test_rolling_reservation_only_selects_unoccupied_lines_in_later_round(app):
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
first_line = snapshot.lines[0]
second_line = ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=1, part_number='000124', reservation_id='0012345679',
snapshot_id=snapshot.id, position=1, line_no=2, part_number='000124', reservation_id='0012345679',
qty=Decimal('4'), field_values_json={},
)
third_line = ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=2, part_number='000125', reservation_id='0012345680',
snapshot_id=snapshot.id, position=2, line_no=3, part_number='000125', reservation_id='0012345680',
qty=Decimal('3'), field_values_json={},
)
snapshot.lines.extend([second_line, third_line])
@@ -201,7 +202,7 @@ def test_reservation_rejects_different_purchase_order_and_requires_review_for_sa
ensure_task_reservations(first_task)
db.session.commit()
second_task = ShippingNotice(task_no='SN-SNAPSHOT-102', source_type='test')
second_task = ShippingOrderTask(task_no='SN-SNAPSHOT-102', source_type=None, user_id=first_user.id)
db.session.add(second_task)
db.session.flush()
extraction = ShippingOrderExtraction(
@@ -217,7 +218,7 @@ def test_reservation_rejects_different_purchase_order_and_requires_review_for_sa
db.session.add(second_snapshot)
db.session.flush()
db.session.add(ShippingOrderSnapshotLine(
snapshot_id=second_snapshot.id, position=0, reservation_id='0012345678',
snapshot_id=second_snapshot.id, position=0, line_no=1, reservation_id='0012345678',
part_number='000123', qty=Decimal('12.5'), field_values_json={},
))
second_task.order_snapshot_id = second_snapshot.id
@@ -232,50 +233,42 @@ def test_reservation_rejects_different_purchase_order_and_requires_review_for_sa
def test_confirmed_task_revision_transfers_unfulfilled_reservation_with_audit(app):
"""已确认的直接后继可接替同 PO 的未履约 Reservation,且保留父子审计。"""
"""已确认的同一 OT 修订复用该 OT(仅 bump order_data_version),接替同 PO 的未履约 Reservation。"""
with app.app_context():
first_task, first_user = _build_accepted_order(suffix='201')
first_snapshot = freeze_order_snapshot(first_task, actor_id=first_user.id, expected_order_data_version=7)
ensure_task_reservations(first_task)
db.session.flush()
original = ShippingReservation.query.filter_by(reservation_id=first_snapshot.lines[0].reservation_id).one()
ot_id = int(first_task.id)
ot_count = ShippingOrderTask.query.count()
revision_task = ShippingNotice(
task_no='SN-SNAPSHOT-202', source_type='test', supersedes_task_id=first_task.id,
)
db.session.add(revision_task)
db.session.flush()
extraction = ShippingOrderExtraction(
task_id=revision_task.id, schema_version_id=first_snapshot.schema_version_id,
input_snapshot_hash='c' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
revision_snapshot = ShippingOrderSnapshot(
task_id=revision_task.id, extraction_id=extraction.id,
schema_version_id=first_snapshot.schema_version_id, order_data_version=2,
rule_versions_json={}, header_values_json={}, customer_po_number=first_snapshot.customer_po_number,
)
db.session.add(revision_snapshot)
db.session.flush()
revision_line = ShippingOrderSnapshotLine(
snapshot_id=revision_snapshot.id, position=0,
reservation_id=first_snapshot.lines[0].reservation_id,
part_number='000123-REV', qty=Decimal('13.5'), field_values_json={},
)
db.session.add(revision_line)
revision_task.order_snapshot_id = revision_snapshot.id
# 修订沿用同一 OT:不新建任务/快照,仅改写冻结行数据并沿用该 OT,
# 由 _transfer_confirmed_revision 完成 version bump 与 Reservation 接替。
line = first_snapshot.lines[0]
line.part_number = '000123-REV'
line.qty = Decimal('13.5')
db.session.flush()
registered = ensure_task_reservations(revision_task)
registered = ensure_task_reservations(first_task)
# 同一 OT 上完成接替:不新建任务行,仅版本 bump,Reservation 仍指向该 OT。
assert registered == [original]
assert original.task_id == revision_task.id
assert original.snapshot_line_id == revision_line.id
assert original.task_id == ot_id
assert original.snapshot_line_id == line.id
assert original.part_number == '000123-REV'
assert original.required_qty == Decimal('13.5')
assert {event.event_type for event in revision_task.events} == {'reservation_revision_confirmed'}
assert {event.event_type for event in first_task.events} == {'reservation_revision_superseded'}
assert first_task.order_data_version == 8
assert first_task.progress_version == 2
# 不产生重复 OT 行。
assert ShippingOrderTask.query.count() == ot_count
# 审计事件落在该 OT 上。
assert {event.event_type for event in first_task.events} == {'reservation_revision_confirmed'}
assert {event.task_id for event in first_task.events} == {ot_id}
assert all(
event.task_id == ot_id
for event in ShippingTaskEvent.query.filter_by(event_type='reservation_revision_confirmed').all()
)
def test_first_reservation_registration_allows_missing_po_but_repeat_requires_it(app):
@@ -287,7 +280,7 @@ def test_first_reservation_registration_allows_missing_po_but_repeat_requires_it
ensure_task_reservations(task)
db.session.flush()
repeat_task = ShippingNotice(task_no='SN-SNAPSHOT-302', source_type='test')
repeat_task = ShippingOrderTask(task_no='SN-SNAPSHOT-302', source_type=None, user_id=user.id)
db.session.add(repeat_task)
db.session.flush()
extraction = ShippingOrderExtraction(
@@ -303,7 +296,7 @@ def test_first_reservation_registration_allows_missing_po_but_repeat_requires_it
db.session.add(repeat_snapshot)
db.session.flush()
db.session.add(ShippingOrderSnapshotLine(
snapshot_id=repeat_snapshot.id, position=0, reservation_id=snapshot.lines[0].reservation_id,
snapshot_id=repeat_snapshot.id, position=0, line_no=1, reservation_id=snapshot.lines[0].reservation_id,
part_number=snapshot.lines[0].part_number, qty=snapshot.lines[0].qty, field_values_json={},
))
repeat_task.order_snapshot_id = repeat_snapshot.id
@@ -4,35 +4,87 @@ tests/test_shipping_stp_match_completed_gate.py
用途:验证 STP Excel 门禁仅在全部明细 ok 时通过。
依赖:fulfillment_workflow.match_completed。
逻辑:partial / 混合状态不得制单;fulfillable 且全 ok 可通过。
迁移说明:STP 匹配事实已从 ShippingNotice 属性 / step_payload_json 迁入正式 DB 行
(ShippingNoticeLineInventoryMatch,以 snapshot_line_id 关联冻结快照行)。本文件夹具
显式构造 OT + 冻结订单快照 + 快照行 + 行级匹配事实,并 patch 放行事实读取接缝
``_released_snapshot_line_ids_for_task``(旧 ``_released_line_keys_for_task`` 已不存在)。
"""
from __future__ import annotations
from app import db
from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch
from app.models import (
ShippingNoticeLineInventoryMatch,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingOrderTask,
User,
)
from app.services.shipping_notice.fulfillment_workflow import match_completed
def _task_with_current_matches(*, task_no: str, rows: list[dict]) -> ShippingNotice:
"""写入正式行匹配事实,供 Excel 门禁读取。"""
task = ShippingNotice(task_no=task_no, source_type='manual')
_extraction_seq = iter(range(1, 10_000_000))
def _task_with_current_matches(*, task_no: str, rows: list[dict]) -> ShippingOrderTask:
"""写入正式 OT 行匹配事实(含冻结订单快照行),供 Excel 门禁读取。
说明:迁移后 ``ShippingNoticeLineInventoryMatch`` 以 ``snapshot_line_id``(冻结快照行 id)
为行标识,不再使用 ``line_key``;``match_completed`` 还要求覆盖冻结订单全部项次,
因此每个 match 行都对应一个真实 ``ShippingOrderSnapshotLine``。
"""
user = User(username=f'stp-{task_no}', email=f'stp-{task_no}@example.com')
db.session.add(user)
db.session.flush()
task = ShippingOrderTask(task_no=task_no, user_id=user.id, stage='inventory_matching')
db.session.add(task)
db.session.flush()
db.session.add_all([
ShippingNoticeLineInventoryMatch(
snapshot = ShippingOrderSnapshot(
task_id=task.id, extraction_id=next(_extraction_seq), schema_version_id=1,
order_data_version=1, header_values_json={},
)
db.session.add(snapshot)
db.session.flush()
task.order_snapshot_id = snapshot.id
for index, row in enumerate(rows, start=1):
line = ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=index - 1, line_no=index,
field_values_json={},
)
db.session.add(line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id,
line_key=f'L{index}',
snapshot_line_id=line.id,
line_no=index,
line_index=index - 1,
match_result=row['match_result'],
inventory_status='ready',
shortage_qty=row.get('shortage_qty', '0'),
is_current=True,
)
for index, row in enumerate(rows, start=1)
])
))
db.session.flush()
return task
def _patch_released_snapshot_line_ids(monkeypatch, task, *, released_line_keys: set[str]):
"""把放行事实读取替换为给定冻结快照行 id 集合。
说明:放行决定读取已迁到 ``_released_snapshot_line_ids_for_task``(按快照行 id),
这里仍沿用测试的 ``L{index}`` 行键语义,将其映射到对应快照行 id 后打补丁。
"""
from app.services.shipping_notice import fulfillment_workflow as mod
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id)
line_id_by_key = {
f'L{i}': int(line.id)
for i, line in enumerate(snapshot.lines, start=1)
}
released_ids = {line_id_by_key[key] for key in released_line_keys if key in line_id_by_key}
monkeypatch.setattr(mod, '_released_snapshot_line_ids_for_task', lambda _task: set(released_ids))
def test_match_completed_rejects_partial(app):
"""partial 即使存在 ok 行也不得进入 Excel。"""
with app.app_context():
@@ -88,18 +140,6 @@ def test_match_step_progress_fulfillable_is_completed_100():
assert fields['progress_percent'] == 100
def _patch_released_keys(monkeypatch, *, released_line_keys: set[str]):
"""把放行行键读取替换为给定集合,直接验证聚合/满足性的放行语义。
说明:放行决定读取是纯 SQL join,构造真实 Case/LineDecision 表关系较复杂;
这里只打补丁到 ``_released_line_keys_for_task`` 这个稳定接缝,聚合重算与
``match_completed`` 都会消费它。
"""
from app.services.shipping_notice import fulfillment_workflow as mod
monkeypatch.setattr(mod, '_released_line_keys_for_task', lambda _task: set(released_line_keys))
def test_release_shortage_marks_aggregate_fulfillable(app, monkeypatch):
"""短缺行被人工放行后,聚合重算应视为满足(fulfillable),不再标 unfulfillable。"""
from app.services.shipping_notice.fulfillment_workflow import (
@@ -117,15 +157,15 @@ def test_release_shortage_marks_aggregate_fulfillable(app, monkeypatch):
status, _ = _recompute_task_match_aggregate(task)
assert status in {'partial', 'unfulfillable'}
# 放行缺口行(行键 L2)
_patch_released_keys(monkeypatch, released_line_keys={'L2'})
# 放行缺口行(行键 L2)。
_patch_released_snapshot_line_ids(monkeypatch, task, released_line_keys={'L2'})
# 放行后:匹配满足;聚合重算不再误判缺货。
assert match_completed(task) is True
status, shortages = _recompute_task_match_aggregate(task)
assert status == 'fulfillable'
assert shortages == []
assert task.line_results_json[1]['line_status'] == 'released'
assert task.step_payload_json['current_match_projection']['line_results'][1]['line_status'] == 'released'
def test_release_shortage_leaves_unreleased_shortage_blocks(app, monkeypatch):
@@ -141,7 +181,7 @@ def test_release_shortage_leaves_unreleased_shortage_blocks(app, monkeypatch):
],
)
# 只放行第一行(L1),L2 的 not_found 缺口未被放行 → 不满足。
_patch_released_keys(monkeypatch, released_line_keys={'L1'})
_patch_released_snapshot_line_ids(monkeypatch, task, released_line_keys={'L1'})
status, shortages = _recompute_task_match_aggregate(task)
assert status in {'partial', 'unfulfillable'}
assert shortages
@@ -162,14 +202,15 @@ def test_recompute_fulfillment_state_syncs_review_pending_on_release(app, monkey
task.pending_human_reason = 'shortage'
db.session.flush()
_patch_released_keys(monkeypatch, released_line_keys={'L1'})
_patch_released_snapshot_line_ids(monkeypatch, task, released_line_keys={'L1'})
status = recompute_task_fulfillment_state(task)
assert status == 'fulfillable'
assert task.match_status == 'fulfillable'
# match_status 已迁到 DB 事实投影,不再读取旧任务缓存列。
assert task.step_payload_json['current_match_projection']['match_status'] == 'fulfillable'
assert task.review_status != 'shortage_review'
assert task.pending_human_reason is None
assert task.line_results_json[0]['line_status'] == 'released'
assert task.step_payload_json['current_match_projection']['line_results'][0]['line_status'] == 'released'
def test_recompute_fulfillment_state_keeps_shortage_when_not_released(app, monkeypatch):
@@ -187,11 +228,11 @@ def test_recompute_fulfillment_state_keeps_shortage_when_not_released(app, monke
task.pending_human_reason = 'shortage'
db.session.flush()
# 没有放行决定
_patch_released_keys(monkeypatch, released_line_keys=set())
# 没有放行决定。
_patch_released_snapshot_line_ids(monkeypatch, task, released_line_keys=set())
status = recompute_task_fulfillment_state(task)
assert status in {'partial', 'unfulfillable'}
assert task.review_status == 'shortage_review'
assert task.pending_human_reason == 'shortage'
assert task.line_results_json[0]['line_status'] == 'shortage'
assert task.step_payload_json['current_match_projection']['line_results'][0]['line_status'] == 'shortage'
@@ -12,7 +12,6 @@ from types import SimpleNamespace
from app.services.shipping_notice.export import _mapping_value
from app.services.shipping_notice.stp_line_inventory_match import (
apply_line_inventory_resolutions,
match_order_lines_across_candidates,
)
@@ -41,15 +40,16 @@ def test_current_match_facts_rebuild_shortage_detail(monkeypatch):
),
)
monkeypatch.setattr(mod, 'ShippingNoticeLineInventoryMatch', fake_match_model)
task = SimpleNamespace(id=101, line_results_json=None, shortage_json=None)
task = SimpleNamespace(id=101, step_payload_json={})
status, shortages = mod._recompute_task_match_aggregate(task)
projection = task.step_payload_json['current_match_projection']
assert status == 'partial'
assert task.line_results_json[1]['available_qty'] == 0.0
assert task.line_results_json[1]['shortage_qty'] == 5.0
assert task.line_results_json[1]['line_status'] == 'shortage'
assert task.shortage_json == {'lines': shortages}
assert projection['line_results'][1]['available_qty'] == 0.0
assert projection['line_results'][1]['shortage_qty'] == 5.0
assert projection['line_results'][1]['line_status'] == 'shortage'
assert projection['shortage'] == {'lines': shortages}
def test_cross_candidate_unique_hit_is_fulfillable():
@@ -158,176 +158,38 @@ def test_header_reservation_fallback_for_match():
assert result['resolutions'][0]['effective_reservation_id'] == '3000092917'
def test_apply_resolutions_sets_summary_source_when_unique(monkeypatch):
"""全部 ok 且唯一源时投影 task.inventory_source_code。"""
from app.services.shipping_notice import stp_line_inventory_match as mod
monkeypatch.setattr(
mod,
'get_database_inventory_source',
lambda code: {
'source_code': code,
'connector_type': 'excel_rpa',
'warehouse_resolution_mode': 'fixed',
'fixed_warehouse_id': 'WH1',
},
)
monkeypatch.setattr(mod, 'inventory_sources_runtime_version', lambda: 'v1')
monkeypatch.setattr(mod, 'extract_routing_context', lambda _task: {})
monkeypatch.setattr(mod, 'compute_routing_fingerprint', lambda _ctx: 'fp')
task = SimpleNamespace(
step_payload_json={},
match_status=None,
line_results_json=None,
shortage_json=None,
inventory_source_code=None,
inventory_connector_type=None,
inventory_warehouse_id=None,
inventory_source_status='candidates_frozen',
inventory_source_method=None,
inventory_source_config_version=None,
inventory_routing_fingerprint=None,
)
apply_line_inventory_resolutions(task, {
'match_status': 'fulfillable',
'line_results': [{'line_status': 'ok'}],
'shortage_json': {'lines': []},
'resolutions': [{
'disposition': 'ok',
'resolved_inventory_source_code': 'DBS_DUB',
}],
})
assert task.inventory_source_code == 'DBS_DUB'
assert task.inventory_source_status == 'resolved'
assert task.step_payload_json['line_inventory_resolutions'][0]['resolved_inventory_source_code'] == 'DBS_DUB'
def test_apply_resolutions_allows_multi_source_excel(monkeypatch):
"""多行命中不同源且全部 ok 时投影主绑定源并允许制单,不写 multi_source_excel_block。"""
from app.services.shipping_notice import stp_line_inventory_match as mod
monkeypatch.setattr(
mod,
'get_database_inventory_source',
lambda code: {
'source_code': code,
'connector_type': 'excel_rpa',
'warehouse_resolution_mode': 'fixed',
'fixed_warehouse_id': 'WH1',
},
)
monkeypatch.setattr(mod, 'inventory_sources_runtime_version', lambda: 'v1')
monkeypatch.setattr(mod, 'extract_routing_context', lambda _task: {})
monkeypatch.setattr(mod, 'compute_routing_fingerprint', lambda _ctx: 'fp')
task = SimpleNamespace(
step_payload_json={},
match_status=None,
line_results_json=None,
shortage_json=None,
inventory_source_code=None,
inventory_connector_type=None,
inventory_warehouse_id=None,
inventory_source_status='candidates_frozen',
inventory_source_method=None,
inventory_source_config_version=None,
inventory_routing_fingerprint=None,
)
apply_line_inventory_resolutions(task, {
'match_status': 'fulfillable',
'line_results': [{'line_status': 'ok'}, {'line_status': 'ok'}],
'shortage_json': {'lines': []},
'resolutions': [
{'disposition': 'ok', 'resolved_inventory_source_code': 'DBS_DUB'},
{'disposition': 'ok', 'resolved_inventory_source_code': 'DBS_RTM'},
],
})
assert task.inventory_source_code in {'DBS_DUB', 'DBS_RTM'}
assert task.inventory_source_status == 'resolved'
assert task.inventory_source_method == 'stp_line_match_multi'
assert task.step_payload_json.get('multi_source_excel_block') is None
assert set(task.step_payload_json.get('resolved_ok_source_codes') or []) == {'DBS_DUB', 'DBS_RTM'}
def test_excel_mapping_keeps_user_configured_line_number():
"""export_sequence 输出导出行序号,订单字段 line_no 保留内部项次原文值。"""
def test_excel_mapping_uses_notice_line_number(app):
"""模板系统事实输出发货通知项次,订单字段 line_no 仍读取冻结订单项次。"""
task = SimpleNamespace(
task_no='T1',
business_no='SN-001',
shipping_case=None,
inventory_warehouse_id='WH1',
inventory_source_code='DBS_DUB',
)
value = _mapping_value(
{'source_kind': 'system_fact', 'source_key': 'export_sequence', 'formatter': 'none'},
{'source_kind': 'system_fact', 'source_key': 'notice_line_no', 'formatter': 'none'},
task=task,
order_values={'__export_sequence': 2, 'customer_po_line_no': '00020'},
inventory_values={},
export_sequence=2,
notice_line_no='2',
)
assert value == 2
assert value == '2'
order_field_value = _mapping_value(
{'source_kind': 'order_field', 'source_key': 'line_no', 'formatter': 'none', 'row_mode': 'line'},
task=task,
order_values={'__export_sequence': 3, 'line_no': '00030'},
order_values={'line_no': '00030'},
inventory_values={},
export_sequence=3,
)
assert order_field_value == '00030'
def test_allowed_system_facts_use_export_sequence_not_line_no():
"""Phase 0 门禁:系统事实目录含 export_sequence,不含 line_no。"""
def test_allowed_system_facts_use_notice_line_no_not_export_sequence():
"""模板系统事实使用发货通知项次,不再暴露导出行序号。"""
from app.services.shipping_notice.excel_template import ALLOWED_SYSTEM_FACTS
assert 'export_sequence' in ALLOWED_SYSTEM_FACTS
assert 'line_no' not in ALLOWED_SYSTEM_FACTS
def test_default_derivation_rules_are_disabled_copy_if_empty():
"""新草稿预置 customer_po_line_no→line_no,默认关闭。"""
from app.services.shipping_notice.order_schema.field_rules import (
default_derivation_rules,
normalize_derivation_rules,
)
rules = default_derivation_rules()
assert rules == [{
'rule_id': 'R-LINE-NO-FROM-CUSTOMER-PO',
'enabled': False,
'source_field_code': 'customer_po_line_no',
'target_field_code': 'line_no',
'strategy': 'copy_if_empty',
'scope': 'line',
}]
assert normalize_derivation_rules(None) == rules
def test_derivation_engine_copy_if_empty_and_skips():
"""启用规则时空值派生、非空跳过、非法格式跳过。"""
from app.services.shipping_notice.order_schema.derivation_engine import apply_derivation_rules_to_lines
rules = [{
'rule_id': 'R1',
'enabled': True,
'source_field_code': 'customer_po_line_no',
'target_field_code': 'line_no',
'strategy': 'copy_if_empty',
'scope': 'line',
}]
outcome = apply_derivation_rules_to_lines(
[
{'customer_po_line_no': '00010', 'line_no': None},
{'customer_po_line_no': '00020', 'line_no': '20'},
{'customer_po_line_no': 'ABC', 'line_no': None},
],
rules,
)
assert outcome['lines'][0]['line_no'] == '00010'
assert outcome['lines'][1]['line_no'] == '20'
assert outcome['lines'][2].get('line_no') in (None, '')
assert [item['status'] for item in outcome['results']] == ['derived', 'skipped', 'skipped']
assert outcome['results'][1]['skip_reason'] == 'target_not_empty'
assert outcome['results'][2]['skip_reason'] == 'source_format_invalid'
assert 'notice_line_no' in ALLOWED_SYSTEM_FACTS
assert 'export_sequence' not in ALLOWED_SYSTEM_FACTS
def test_permanent_audit_events_have_no_retention_expiry(app):
@@ -338,13 +200,13 @@ def test_permanent_audit_events_have_no_retention_expiry(app):
with app.app_context():
event = append_shipping_audit_event(
event_type='DERIVATION_SIMULATED',
event_type='shipping_order_audited',
aggregate_type='shipping_order_schema_version',
aggregate_id='1',
actor_type='admin',
actor_id=1,
result='success',
metadata={'derived_count': 1, 'skipped_count': 0},
metadata={'sample': True},
)
db.session.commit()
stored = db.session.get(ShippingAuditEvent, event.id)
@@ -65,7 +65,7 @@ post-OT wave:
```text
shipping_notice / OT
line_key
snapshot_line_id
line_index
inventory_snapshot_id
match_result
@@ -458,18 +458,29 @@ def _report_callback_failure(trigger_path: Path, failed_dir: Path, exc: Exceptio
def _close_batch_browser_resources(context: Any, playwright: Any, runtime_profile_dir: Path | None) -> None:
"""在正常完成或 Ctrl+C 中断后依序释放批量 RPA 浏览器资源。"""
# [DEBUG-TIMING] 逐阶段计时:浏览器关闭 / playwright 停止 / profile 清理各自耗时,
# 用于定位「导出完成 → 回调」之间的静默段(export done 后到 _post_callback 前的耗时)。
close_started_at = time.monotonic()
try:
if context is not None:
context.close()
except BaseException as exc:
print(f"[browser] context close interrupted: {exc}", file=sys.stderr)
else:
print(f"[browser-cleanup] context.close elapsedMs={int((time.monotonic() - close_started_at) * 1000)}")
stop_started_at = time.monotonic()
try:
if playwright is not None:
playwright.stop()
except BaseException as exc:
print(f"[browser] playwright stop interrupted: {exc}", file=sys.stderr)
else:
print(f"[browser-cleanup] playwright.stop elapsedMs={int((time.monotonic() - stop_started_at) * 1000)}")
cleanup_started_at = time.monotonic()
if runtime_profile_dir is not None and _should_cleanup_browser_profile(runtime_profile_dir):
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
print(f"[browser-cleanup] profile rmtree elapsedMs={int((time.monotonic() - cleanup_started_at) * 1000)} dir={runtime_profile_dir.name!r}")
print(f"[browser-cleanup] total_cleanup elapsedMs={int((time.monotonic() - close_started_at) * 1000)}")
_INVENTORY_V2_REQUIRED_FIELDS = (
@@ -1123,6 +1134,9 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
task_no = str(body.get("task_no") or "").strip()
sources = body.get("inventory_sources") or []
failed_dir = trigger_path.parent / "failed"
# [DEBUG-TIMING] 批处理整体耗时基线:从进入 handler 到回调完成。
batch_started_at = time.monotonic()
print(f"[inventory-batch-timing] handler start run={run_no}")
if not isinstance(sources, list) or not sources:
trigger_path.unlink(missing_ok=True)
return
@@ -1391,6 +1405,9 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
"schedule_run_id": body.get("schedule_run_id"),
"results": results,
}
# [DEBUG-TIMING] 到达回调前打点:若此前有明显的静默段(浏览器清理),此处能看到
# handler 启动到回调前的累计耗时,配合 _close_batch_browser_resources 的逐段计时即可定位。
print(f"[inventory-batch-timing] before callback run={run_no} totalElapsedMs={int((time.monotonic() - batch_started_at) * 1000)}")
_post_callback(callback_path, callback_payload)
_move_trigger(trigger_path, processed_dir, "processed")
print(